Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extensions of the experimental.typedRoutes feature #1

Draft
wants to merge 2 commits into
base: canary
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dev/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PR.md
35 changes: 35 additions & 0 deletions dev/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
34 changes: 34 additions & 0 deletions dev/app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
47 changes: 47 additions & 0 deletions dev/app/examples/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { FC } from 'react'
import { PagesDir, AppDir, Link } from '../lib'

const PagesComponent: FC = () => {
const pagesRouter = PagesDir.useRouter()

/// Example with static path
pagesRouter.push({
path: '/todos',
})

/// Example with dynamic path
// TypeScript warns about the missing 'id' parameter
// @ts-expect-error
pagesRouter.push({
path: '/todos/[id]',
})

pagesRouter.push({
path: '/todos/[id]',
params: { id: 'hi' },
})

return null
}

const AppComponent: FC = () => {
const appRouter = AppDir.useRouter()

appRouter.push('/todos', {
query: { hello: 'world' },
hash: 'foo',
})

return null
}

const TodoLink: FC<{ id: string }> = ({ id }) => (
<Link
href={{
route: '/todos/[id]',
params: { id },
}}
>
Goto todo({id})
</Link>
)
4 changes: 4 additions & 0 deletions dev/app/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * as routers from './routers'
export * from './routers'

export { default as Link } from './link'
19 changes: 19 additions & 0 deletions dev/app/lib/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import NextLink, { type LinkProps } from 'next/link'
import type { Route, Path } from './utils'
import type { PoC_Routes } from 'next'

type Props<R extends PoC_Routes.AllRoutes, RouteInferTypes> = Omit<
LinkProps<RouteInferTypes>,
'href'
> &
(
| Pick<LinkProps<RouteInferTypes>, 'href'>
| {
href: { route: R } & Route.Data<Extract<R, Path.Type>>
}
)
const Link = <Route extends PoC_Routes.AllRoutes, RouteInferTypes>(
props: Props<Route, RouteInferTypes>
): JSX.Element => NextLink(props)

export default Link
76 changes: 76 additions & 0 deletions dev/app/lib/routers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { useRouter as useAppRouter } from 'next/navigation'
import { useRouter as usePagesRouter } from 'next/router'

import type { PoC_Routes, Route as NextRoute } from 'next'
import { type Route, createUrl } from './utils'

export namespace AppDir {
export function useRouter() {
const { push, replace, prefetch, ...router } = useAppRouter()

return {
...router,
push: <Path extends PoC_Routes.AllRoutes>(
hrefTemplate: Path,
options: Route.Data<Path> & Parameters<typeof push>[1]
) => push(createUrl(hrefTemplate, options), options),

replace: <Path extends PoC_Routes.AllRoutes>(
hrefTemplate: Path,
options: Route.Data<Path> & Parameters<typeof replace>[1]
) => replace(createUrl(hrefTemplate, options), options),

prefetch: <Path extends PoC_Routes.AllRoutes>(
hrefTemplate: Path,
options: Route.Data<Path>
) => prefetch(createUrl(hrefTemplate, options)),
} as const
}
}
export namespace PagesDir {
type RouteData<Path extends PoC_Routes.AllRoutes> = Route.Data<Path> & {
path: Path
}

export function useRouter() {
const { push, replace, prefetch, ...router } = usePagesRouter()

return {
...router,
push: <
Path extends PoC_Routes.AllRoutes,
As extends PoC_Routes.AllRoutes
>(
url: RouteData<Path> /* | Parameters<typeof push>[0] */,
as?: RouteData<As> /* | Parameters<typeof push>[1] */,
options?: Parameters<typeof push>[2]
) =>
push(
// 'path' in url ? createUrl(url.path, url) : url,
createUrl(url.path, url),
as === undefined ? undefined : createUrl(as.path, as),
options
),

replace: <
Path extends PoC_Routes.AllRoutes,
As extends PoC_Routes.AllRoutes
>(
url: RouteData<Path> /* | Parameters<typeof replace>[0] */,
as?: RouteData<As> /* | Parameters<typeof replace>[1] */,
options?: Parameters<typeof replace>[2]
) =>
replace(
// 'path' in url ? createUrl(url.path, url) : url,
createUrl(url.path, url),
as === undefined ? undefined : createUrl(as.path, as),
options
),

prefetch: <Path extends PoC_Routes.AllRoutes>(
hrefTemplate: Path,
options: Route.Data<Path>
) => prefetch(createUrl(hrefTemplate, options)),
} as const
}
}
98 changes: 98 additions & 0 deletions dev/app/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type { PoC_Routes, Route as NextRoute } from 'next'

/*
Utility namespaces
*/

export namespace Path {
export type Type = `/${string}`

export type Param<T extends string = string> = `[${T}]`

/** Takes in any string and returns a string that starts with a `"/"` */
export type fromString<T extends string> = T extends Path.Type ? T : `/${T}`
}

export namespace Route {
/** Parses the parameters from the given URL path string */
export type getParams<T extends Path.Type> =
T extends `${infer A}/[${infer Param}]${infer B}`
?
| (Param extends `...${string}`
? // If it's a catch-all it's allowed to be any string
string & {}
: Param)
// Recursively parse the path
| getParams<Path.fromString<`${A}${B}`>>
: never

export type Data<Path extends Path.Type> = {
query?: Record<string, string>
hash?: string
} & (Route.getParams<Path> extends never
? {}
: { params: Record<Route.getParams<Path>, string> })

/** A namespace containing utilities to filter */
export namespace Filters {
/** Filter the given `Paths` union to only contain static paths (= not containing route parameters) */
export type getStatic<Paths extends Path.Type> = keyof {
[P in Paths as Route.getParams<P> extends never ? P : never]: any
}

/** Filter the given `Paths` union to only contain dyanic paths (= paths with route parameters) */
export type getDynamic<Paths extends Path.Type> = Exclude<
Paths,
Filters.getStatic<Paths>
>
}
}

/*
Utility functions
*/

/** Takes in a File System Routing (FSR) `path` and returns a URL string.
*
* The function allows for both `app` and `pages` router paths to be passed.
*
* The `path` gets mutated with the given `data` to create the URL.
* - `data.params` is a record containing dynamic route segments.
* E.g. `{ id: '15' }` for `'/todos/[id]'`
* - `data.query` is a record containing the query parameters.
* E.g. `{ hello: 'world' }` for `'/todos'` becomes `'/todos?hello=world'`
* - `data.hash` is the hash value for the URL.
* E.g. `'section-1'` for `'/todos'` becomes `'/todos#section-1'`
*
* @example
* ```typescript
* const myUrl = createUrl('/todos/[id]', {
* params: { id: '15' },
* query: { hello: 'world' },
* hash: 'section-1',
* }) // '/todos/15?hello=world#section-1'
* ```
*/
export function createUrl<Path extends PoC_Routes.AllRoutes>(
path: Path,
data: Route.Data<Path>
) {
let url: string = path

if ('params' in data)
Object.entries<string>(data.params).forEach(
([key, value]) => (url = url.replaceAll(`[${key}]`, value))
)

const queryEntries =
data.query === undefined ? null : Object.entries(data.query)
if (queryEntries !== null)
queryEntries.forEach(
([key, value], index) =>
(url += `${index === 0 ? '?' : '&'}${key}=${encodeURI(value)}`)
)

if (data.hash !== undefined) url += `#${data.hash}`

return url as NextRoute<any>
}
10 changes: 10 additions & 0 deletions dev/app/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
externalDir: true,
appDir: true,
typedRoutes: true,
},
}

module.exports = nextConfig
20 changes: 20 additions & 0 deletions dev/app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@dev/app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/node": "20.5.9",
"@types/react": "18.2.21",
"@types/react-dom": "18.2.7",
"next": "link:../../packages/next",
"react": "link:../../node_modules/react",
"react-dom": "link:../../node_modules/react-dom",
"typescript": "5.2.2"
}
}
Loading