@mpen/rerouter 0.1.9 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -18
- package/cli/bin.test.ts +221 -0
- package/cli/bin.ts +342 -0
- package/cli/fixtures/bin/kitchen-sink.tsx +15 -0
- package/cli/fixtures/bin/optional.tsx +3 -0
- package/cli/fixtures/bin/pages/Home.tsx +3 -0
- package/cli/fixtures/bin/pages/KitchenSink.tsx +3 -0
- package/cli/fixtures/bin/pages/Login.tsx +3 -0
- package/cli/fixtures/bin/pages/Match.tsx +3 -0
- package/cli/fixtures/bin/pages/NotFound.tsx +3 -0
- package/cli/fixtures/bin/pages/Optional.tsx +3 -0
- package/cli/fixtures/bin/regexp-groups.tsx +11 -0
- package/cli/fixtures/bin/simple.tsx +1 -0
- package/cli/fixtures/bin/unnamed.tsx +4 -0
- package/cli/tsconfig.json +9 -0
- package/dist/acorn-k7ED_tOl.js +4968 -0
- package/dist/angular--Iqdw9UJ.js +4057 -0
- package/dist/babel-hfWAujRY.js +9878 -0
- package/dist/bin.d.ts +29 -0
- package/dist/bin.js +233 -0
- package/dist/estree-C1Zjnvlw.js +7266 -0
- package/dist/flow-BaD9LyIP.js +52912 -0
- package/dist/glimmer-CvCjW_1V.js +7541 -0
- package/dist/graphql-BdtzBuWh.js +1945 -0
- package/dist/html-DkZtUVbo.js +7137 -0
- package/dist/index.d.ts +278 -0
- package/dist/index.js +247 -0
- package/dist/markdown-Z8Vrc69e.js +6876 -0
- package/dist/meriyah-DeO4stuH.js +7590 -0
- package/dist/postcss-BmgGJ0E5.js +6777 -0
- package/dist/prettier-BT_F8kIx.js +15629 -0
- package/dist/routes-PW-bNm8e.js +135 -0
- package/dist/typescript-DtIxStjy.js +22936 -0
- package/dist/yaml-CWOPBY0q.js +5281 -0
- package/examples/App.tsx +80 -0
- package/examples/dist/BlogPost-c10d9w2p.js +1 -0
- package/examples/dist/FetchLoading-534mdrgz.js +1 -0
- package/examples/dist/FetchLoading-sbxbdkre.js +1 -0
- package/examples/dist/Home-a1258p25.js +1 -0
- package/examples/dist/KitchenSink-821mjg0h.js +1 -0
- package/examples/dist/Login-wywx6bp7.js +1 -0
- package/examples/dist/Match-1e72jm5w.js +1 -0
- package/examples/dist/NotFound-smxj24jw.js +1 -0
- package/examples/dist/SlowLoading-59xxmbfk.js +1 -0
- package/examples/dist/index-0d4kj0rv.js +2 -0
- package/examples/dist/index-3x197sbt.js +9 -0
- package/examples/dist/index-a2hkfx1n.js +9 -0
- package/examples/dist/index-d21me1mc.js +9 -0
- package/examples/dist/index-ktqdknsn.js +2 -0
- package/examples/dist/index-p53qxxzd.js +2 -0
- package/examples/dist/index.html +67 -0
- package/examples/index.html +67 -0
- package/examples/pages/BlogPost.tsx +17 -0
- package/examples/pages/FetchLoading.tsx +53 -0
- package/examples/pages/FetchLoadingItem.tsx +45 -0
- package/examples/pages/Home.tsx +3 -0
- package/examples/pages/KitchenSink.tsx +23 -0
- package/examples/pages/Login.tsx +3 -0
- package/examples/pages/Match.tsx +5 -0
- package/examples/pages/NotFound.tsx +3 -0
- package/examples/pages/SlowLoading.tsx +8 -0
- package/examples/routes.gen.ts +105 -0
- package/examples/routes.ts +40 -0
- package/examples/server/serve-dist.ts +33 -0
- package/examples/server/tsconfig.json +9 -0
- package/package.json +41 -31
- package/src/components/Link.test.tsx +139 -0
- package/src/components/Link.tsx +89 -0
- package/src/components/NavLink.test.tsx +119 -0
- package/src/components/NavLink.tsx +71 -0
- package/src/components/Router.test.tsx +183 -0
- package/src/components/Router.tsx +207 -0
- package/src/hooks/index.ts +1 -0
- package/src/hooks/useUrl.ts +22 -0
- package/src/index.ts +6 -0
- package/src/lib/mergeSearch.test.ts +37 -0
- package/src/lib/mergeSearch.ts +21 -0
- package/src/lib/routes.test.ts +67 -0
- package/src/lib/routes.ts +247 -0
- package/src/lib/url.ts +9 -0
- package/tsconfig.json +10 -0
- package/tsdown.config.ts +21 -0
- package/LICENSE +0 -21
- package/dist/bundle.cjs +0 -422
- package/dist/bundle.d.ts +0 -2
- package/dist/bundle.mjs +0 -420
- package/dist/dev.d.ts +0 -1
- package/dist/log.d.ts +0 -1
- package/dist/uri-template.d.ts +0 -56
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { startTransition, Suspense, useEffect, useMemo, useState, type ReactNode } from 'react'
|
|
2
|
+
import { useUrlPath } from '../hooks'
|
|
3
|
+
import {
|
|
4
|
+
normalizeRoutes,
|
|
5
|
+
type NormalizedRoute,
|
|
6
|
+
type Route,
|
|
7
|
+
type RouteComponent,
|
|
8
|
+
} from '../lib/routes'
|
|
9
|
+
|
|
10
|
+
const DEFAULT_LOADING_DELAY_MS = 400
|
|
11
|
+
const loadedRouteComponents = new WeakMap<Route['component'], RouteComponent<any>>()
|
|
12
|
+
const loadingRouteComponents = new WeakMap<Route['component'], Promise<RouteComponent<any>>>()
|
|
13
|
+
|
|
14
|
+
type RouteMatch = {
|
|
15
|
+
route: NormalizedRoute
|
|
16
|
+
params: Record<string, string | undefined>
|
|
17
|
+
pathname: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type RenderedRoute = RouteMatch & {
|
|
21
|
+
Component: RouteComponent<any>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function loadRouteComponent(component: Route['component']): Promise<RouteComponent<any>> {
|
|
25
|
+
const loaded = loadedRouteComponents.get(component)
|
|
26
|
+
if (loaded) return Promise.resolve(loaded)
|
|
27
|
+
|
|
28
|
+
let loading = loadingRouteComponents.get(component)
|
|
29
|
+
if (!loading) {
|
|
30
|
+
loading = component().then((module) => {
|
|
31
|
+
loadedRouteComponents.set(component, module.default)
|
|
32
|
+
loadingRouteComponents.delete(component)
|
|
33
|
+
return module.default
|
|
34
|
+
})
|
|
35
|
+
loadingRouteComponents.set(component, loading)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return loading
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function findRouteMatch(routes: readonly NormalizedRoute[], pathname: string): RouteMatch | null {
|
|
42
|
+
for (const route of routes) {
|
|
43
|
+
const params = route.matches(pathname)
|
|
44
|
+
if (!params) continue
|
|
45
|
+
return { route, params, pathname }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function getLoadedRoute(match: RouteMatch | null): RenderedRoute | null {
|
|
52
|
+
if (!match) return null
|
|
53
|
+
|
|
54
|
+
const Component = loadedRouteComponents.get(match.route.component)
|
|
55
|
+
if (!Component) return null
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
...match,
|
|
59
|
+
Component,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function scheduleTransition(cb: () => void): void {
|
|
64
|
+
queueMicrotask(() => {
|
|
65
|
+
startTransition(cb)
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function useRenderedRoute(
|
|
70
|
+
match: RouteMatch | null,
|
|
71
|
+
loadingDelayMs: number,
|
|
72
|
+
): { renderedRoute: RenderedRoute | null; showLoading: boolean } {
|
|
73
|
+
const [renderedRoute, setRenderedRoute] = useState(() => getLoadedRoute(match))
|
|
74
|
+
const [showLoading, setShowLoading] = useState(false)
|
|
75
|
+
const [loadError, setLoadError] = useState<unknown>(null)
|
|
76
|
+
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
if (!match) {
|
|
79
|
+
scheduleTransition(() => {
|
|
80
|
+
setRenderedRoute(null)
|
|
81
|
+
setShowLoading(false)
|
|
82
|
+
setLoadError(null)
|
|
83
|
+
})
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const loaded = getLoadedRoute(match)
|
|
88
|
+
if (loaded) {
|
|
89
|
+
scheduleTransition(() => {
|
|
90
|
+
setRenderedRoute(loaded)
|
|
91
|
+
setShowLoading(false)
|
|
92
|
+
setLoadError(null)
|
|
93
|
+
})
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let active = true
|
|
98
|
+
let timeout: ReturnType<typeof setTimeout> | undefined
|
|
99
|
+
|
|
100
|
+
scheduleTransition(() => {
|
|
101
|
+
setShowLoading(false)
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
if (loadingDelayMs <= 0) {
|
|
105
|
+
timeout = setTimeout(() => {
|
|
106
|
+
if (active) setShowLoading(true)
|
|
107
|
+
}, 0)
|
|
108
|
+
} else {
|
|
109
|
+
timeout = setTimeout(() => {
|
|
110
|
+
if (active) setShowLoading(true)
|
|
111
|
+
}, loadingDelayMs)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
loadRouteComponent(match.route.component)
|
|
115
|
+
.then((Component) => {
|
|
116
|
+
if (!active) return
|
|
117
|
+
if (timeout) clearTimeout(timeout)
|
|
118
|
+
|
|
119
|
+
startTransition(() => {
|
|
120
|
+
setRenderedRoute({ ...match, Component })
|
|
121
|
+
setShowLoading(false)
|
|
122
|
+
setLoadError(null)
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
.catch((error: unknown) => {
|
|
126
|
+
if (!active) return
|
|
127
|
+
setLoadError(error)
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
return () => {
|
|
131
|
+
active = false
|
|
132
|
+
if (timeout) clearTimeout(timeout)
|
|
133
|
+
}
|
|
134
|
+
}, [loadingDelayMs, match])
|
|
135
|
+
|
|
136
|
+
if (loadError) throw loadError
|
|
137
|
+
|
|
138
|
+
return { renderedRoute, showLoading }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Props for [`Router`]{@link Router}.
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```tsx
|
|
146
|
+
* <Router routes={routes} loading={<div>Loading...</div>} />
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
export interface RouterProps {
|
|
150
|
+
/**
|
|
151
|
+
* Route definitions to match against the current URL pathname.
|
|
152
|
+
*/
|
|
153
|
+
routes: readonly Route[]
|
|
154
|
+
/**
|
|
155
|
+
* Optional fallback rendered while a matched route component module is loading.
|
|
156
|
+
*/
|
|
157
|
+
loading?: ReactNode
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Delay before rendering [`RouterProps.loading`]{@link RouterProps#loading} for a suspended
|
|
161
|
+
* route, in milliseconds.
|
|
162
|
+
*
|
|
163
|
+
* @defaultValue `400`
|
|
164
|
+
*/
|
|
165
|
+
loadingDelayMs?: number
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Renders the first route that matches the current URL pathname.
|
|
170
|
+
*
|
|
171
|
+
* @param props - The router props.
|
|
172
|
+
* @returns The matched lazy route component, the loading fallback, or `null`.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* ```tsx
|
|
176
|
+
* import routes from './routes'
|
|
177
|
+
*
|
|
178
|
+
* function App() {
|
|
179
|
+
* return <Router routes={routes} loading={<div>Loading...</div>} loadingDelayMs={400} />
|
|
180
|
+
* }
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
export function Router({
|
|
184
|
+
routes,
|
|
185
|
+
loading = null,
|
|
186
|
+
loadingDelayMs = DEFAULT_LOADING_DELAY_MS,
|
|
187
|
+
}: RouterProps) {
|
|
188
|
+
const pathname = useUrlPath()
|
|
189
|
+
|
|
190
|
+
const normalizedRoutes = useMemo(() => normalizeRoutes(routes), [routes])
|
|
191
|
+
const match = useMemo(
|
|
192
|
+
() => findRouteMatch(normalizedRoutes, pathname),
|
|
193
|
+
[normalizedRoutes, pathname],
|
|
194
|
+
)
|
|
195
|
+
const { renderedRoute, showLoading } = useRenderedRoute(match, loadingDelayMs)
|
|
196
|
+
|
|
197
|
+
if (showLoading) return loading
|
|
198
|
+
if (!renderedRoute) return null
|
|
199
|
+
|
|
200
|
+
const { Component, params } = renderedRoute
|
|
201
|
+
|
|
202
|
+
return (
|
|
203
|
+
<Suspense fallback={loading}>
|
|
204
|
+
<Component {...(params as any)} />
|
|
205
|
+
</Suspense>
|
|
206
|
+
)
|
|
207
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useUrlPath, useUrlSearchParams } from './useUrl'
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useMemo, useSyncExternalStore } from 'react'
|
|
2
|
+
|
|
3
|
+
// Snapshot getters
|
|
4
|
+
const getPathname = () => window.location.pathname
|
|
5
|
+
const getSearch = () => window.location.search
|
|
6
|
+
|
|
7
|
+
function subscribe(cb: () => void): () => void {
|
|
8
|
+
const handler = () => cb()
|
|
9
|
+
window.addEventListener('popstate', handler)
|
|
10
|
+
return () => {
|
|
11
|
+
window.removeEventListener('popstate', handler)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function useUrlPath(): string {
|
|
16
|
+
return useSyncExternalStore(subscribe, getPathname, getPathname)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function useUrlSearchParams(): URLSearchParams {
|
|
20
|
+
const search = useSyncExternalStore(subscribe, getSearch, getSearch)
|
|
21
|
+
return useMemo(() => new URLSearchParams(search), [search])
|
|
22
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { mergeSearch } from './mergeSearch'
|
|
3
|
+
|
|
4
|
+
describe(mergeSearch.name, () => {
|
|
5
|
+
test('adds search params to a path without a query string', () => {
|
|
6
|
+
expect(mergeSearch('/matches', { page: 2, archived: false })).toBe(
|
|
7
|
+
'/matches?page=2&archived=false',
|
|
8
|
+
)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
test('overwrites matching params and keeps unrelated existing params', () => {
|
|
12
|
+
expect(mergeSearch('/matches?page=1&sort=asc', { page: 2 })).toBe(
|
|
13
|
+
'/matches?page=2&sort=asc',
|
|
14
|
+
)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
test('preserves hash fragments after the merged query string', () => {
|
|
18
|
+
expect(mergeSearch('/matches?page=1#details', { page: 2, tab: 'stats' })).toBe(
|
|
19
|
+
'/matches?page=2&tab=stats#details',
|
|
20
|
+
)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test('adds search params before a hash fragment when no query string exists', () => {
|
|
24
|
+
expect(mergeSearch('/matches#details', { tab: 'stats' })).toBe('/matches?tab=stats#details')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test('accepts URLSearchParams and tuple search params', () => {
|
|
28
|
+
expect(mergeSearch('/matches?filter=open', new URLSearchParams('filter=all'))).toBe(
|
|
29
|
+
'/matches?filter=all',
|
|
30
|
+
)
|
|
31
|
+
expect(mergeSearch('/matches', [['filter', 'open']])).toBe('/matches?filter=open')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('encodes merged params using URLSearchParams serialization', () => {
|
|
35
|
+
expect(mergeSearch('/matches?q=old', { q: 'hello world' })).toBe('/matches?q=hello+world')
|
|
36
|
+
})
|
|
37
|
+
})
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { SearchParamsInit } from '../components/Link'
|
|
2
|
+
|
|
3
|
+
export function mergeSearch(to: string, search: SearchParamsInit): string {
|
|
4
|
+
const hashIndex = to.indexOf('#')
|
|
5
|
+
const hash = hashIndex !== -1 ? to.slice(hashIndex) : ''
|
|
6
|
+
const pathAndQuery = hashIndex !== -1 ? to.slice(0, hashIndex) : to
|
|
7
|
+
|
|
8
|
+
const queryIndex = pathAndQuery.indexOf('?')
|
|
9
|
+
const path = queryIndex !== -1 ? pathAndQuery.slice(0, queryIndex) : pathAndQuery
|
|
10
|
+
const existingQuery = queryIndex !== -1 ? pathAndQuery.slice(queryIndex + 1) : ''
|
|
11
|
+
|
|
12
|
+
const params = new URLSearchParams(existingQuery)
|
|
13
|
+
const newParams = new URLSearchParams(search as any)
|
|
14
|
+
|
|
15
|
+
for (const [key, value] of newParams) {
|
|
16
|
+
params.set(key, value)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const queryString = params.toString()
|
|
20
|
+
return `${path}${queryString ? '?' + queryString : ''}${hash}`
|
|
21
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { normalizeRoutes, type RouteObject } from './routes'
|
|
3
|
+
|
|
4
|
+
const loadComponent: RouteObject['component'] = async () => ({
|
|
5
|
+
default: () => null,
|
|
6
|
+
})
|
|
7
|
+
|
|
8
|
+
describe('normalizeRoutes', () => {
|
|
9
|
+
test('matches routes without names', () => {
|
|
10
|
+
const [route] = normalizeRoutes([
|
|
11
|
+
{
|
|
12
|
+
pattern: '/fetch-loading/:id',
|
|
13
|
+
component: loadComponent,
|
|
14
|
+
},
|
|
15
|
+
])
|
|
16
|
+
|
|
17
|
+
expect(route.name).toBeUndefined()
|
|
18
|
+
expect(route.matches('/fetch-loading/abc-123')).toEqual({ id: 'abc-123' })
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
test('matches catch-all routes', () => {
|
|
22
|
+
for (const pattern of ['*', '/*']) {
|
|
23
|
+
const [route] = normalizeRoutes([
|
|
24
|
+
{
|
|
25
|
+
pattern,
|
|
26
|
+
component: loadComponent,
|
|
27
|
+
},
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
expect(route.matches('/')).toEqual({})
|
|
31
|
+
expect(route.matches('/anything')).toEqual({})
|
|
32
|
+
expect(route.matches('/nested/path')).toEqual({})
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test('matches regexp params with optional groups', () => {
|
|
37
|
+
const [route] = normalizeRoutes([
|
|
38
|
+
{
|
|
39
|
+
name: 'blogPost',
|
|
40
|
+
pattern: '/blog/:id(\\d+){-:title}?',
|
|
41
|
+
component: loadComponent,
|
|
42
|
+
},
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
expect(route.matches('/blog/123')).toEqual({ id: '123' })
|
|
46
|
+
expect(route.matches('/blog/123-hello%20world')).toEqual({
|
|
47
|
+
id: '123',
|
|
48
|
+
title: 'hello world',
|
|
49
|
+
})
|
|
50
|
+
expect(route.matches('/blog/not-a-number')).toBeNull()
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
test('matches named wildcards', () => {
|
|
54
|
+
const [route] = normalizeRoutes([
|
|
55
|
+
{
|
|
56
|
+
name: 'files',
|
|
57
|
+
pattern: '/files/*path',
|
|
58
|
+
component: loadComponent,
|
|
59
|
+
},
|
|
60
|
+
])
|
|
61
|
+
|
|
62
|
+
expect(route.matches('/files/docs/api')).toEqual({ path: 'docs/api' })
|
|
63
|
+
expect(route.matches('/files/docs%20and%20api/reference')).toEqual({
|
|
64
|
+
path: 'docs and api/reference',
|
|
65
|
+
})
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { match as pathMatch } from 'path-to-regexp'
|
|
2
|
+
import type { ComponentType } from 'react'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Route params captured from the current URL pathname.
|
|
6
|
+
*/
|
|
7
|
+
export type RouteParams = Record<string, string | undefined>
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A React component that receives URL params captured for its route.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* const UserPage: RouteComponent<{ id: string }> = ({ id }) => <div>{id}</div>
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export type RouteComponent<TParams extends RouteParams = RouteParams> = ComponentType<TParams>
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A dynamically imported route component module.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```tsx
|
|
24
|
+
* export default function UserPage({ id }: { id: string }) {
|
|
25
|
+
* return <div>{id}</div>
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export type RouteComponentModule<TParams extends RouteParams = RouteParams> = {
|
|
30
|
+
default: RouteComponent<TParams>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Loads a route component on demand.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```tsx
|
|
38
|
+
* const loadUserPage: RouteComponentLoader<{ id: string }> = () => import('./pages/UserPage')
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export type RouteComponentLoader<TParams extends RouteParams = RouteParams> = () => Promise<
|
|
42
|
+
RouteComponentModule<TParams>
|
|
43
|
+
>
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Object route definition consumed by [`Router`]{@link Router}.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* const route: RouteObject = {
|
|
51
|
+
* name: 'userProfile',
|
|
52
|
+
* pattern: '/users/:id',
|
|
53
|
+
* component: () => import('./pages/UserProfile'),
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export type RouteObject = {
|
|
58
|
+
/**
|
|
59
|
+
* Optional route name used by the CLI to generate a URL helper.
|
|
60
|
+
*
|
|
61
|
+
* Routes without a name still participate in runtime matching, but are skipped by the
|
|
62
|
+
* helper generator.
|
|
63
|
+
*/
|
|
64
|
+
name?: string
|
|
65
|
+
pattern: string | URLPattern
|
|
66
|
+
component: RouteComponentLoader<any>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type Routes = RouteObject[]
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Route definition consumed by [`Router`]{@link Router}.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```tsx
|
|
76
|
+
* const routes: readonly Route[] = [
|
|
77
|
+
* { name: 'home', pattern: '/', component: () => import('./pages/Home') },
|
|
78
|
+
* { pattern: '/users/:id', component: () => import('./pages/UserLayout') },
|
|
79
|
+
* ]
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export type Route = RouteObject
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Route definition normalized into a single object shape with a pathname matcher.
|
|
86
|
+
*/
|
|
87
|
+
export type NormalizedRoute = {
|
|
88
|
+
name?: string
|
|
89
|
+
pattern: string | URLPattern
|
|
90
|
+
component: RouteComponentLoader<any>
|
|
91
|
+
matches(pathname: string): RouteParams | null
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function toUrlPattern(pattern: string | URLPattern): URLPattern {
|
|
95
|
+
if (typeof pattern !== 'string') return pattern
|
|
96
|
+
return new URLPattern({ pathname: pattern })
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function decodeRouteParams(groups: Record<string, unknown>): RouteParams {
|
|
100
|
+
const params: RouteParams = {}
|
|
101
|
+
for (const [key, value] of Object.entries(groups)) {
|
|
102
|
+
if (value == null) params[key] = undefined
|
|
103
|
+
else params[key] = decodeURIComponent(String(value))
|
|
104
|
+
}
|
|
105
|
+
return params
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function stripLegacyParamPattern(pattern: string, startIndex: number): number {
|
|
109
|
+
let depth = 1
|
|
110
|
+
let endIndex = startIndex + 1
|
|
111
|
+
while (endIndex < pattern.length && depth > 0) {
|
|
112
|
+
const char = pattern[endIndex]
|
|
113
|
+
if (char === '\\') {
|
|
114
|
+
endIndex += 2
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
if (char === '(') depth++
|
|
118
|
+
else if (char === ')') depth--
|
|
119
|
+
endIndex++
|
|
120
|
+
}
|
|
121
|
+
return endIndex
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Converts legacy `path-to-regexp` syntax that is ignored by URL generation into syntax accepted
|
|
126
|
+
* by the current parser.
|
|
127
|
+
*
|
|
128
|
+
* @param pattern - The route pattern to normalize.
|
|
129
|
+
* @returns The pattern with custom regexp constraints stripped and optional group suffixes removed.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* normalizeLegacyPathToRegexpSyntax('/blog/:id(\\d+){-:title}?')
|
|
134
|
+
* // '/blog/:id{-:title}'
|
|
135
|
+
* ```
|
|
136
|
+
*
|
|
137
|
+
* @internal
|
|
138
|
+
*/
|
|
139
|
+
export function normalizeLegacyPathToRegexpSyntax(pattern: string): string {
|
|
140
|
+
let normalized = ''
|
|
141
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
142
|
+
const char = pattern[i]
|
|
143
|
+
if (char === '\\') {
|
|
144
|
+
normalized += char
|
|
145
|
+
if (i + 1 < pattern.length) normalized += pattern[++i]
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (char === ':' || char === '*') {
|
|
150
|
+
normalized += char
|
|
151
|
+
while (i + 1 < pattern.length && /[$_\p{ID_Continue}]/u.test(pattern[i + 1])) {
|
|
152
|
+
normalized += pattern[++i]
|
|
153
|
+
}
|
|
154
|
+
if (pattern[i + 1] === '(') {
|
|
155
|
+
i = stripLegacyParamPattern(pattern, i + 1) - 1
|
|
156
|
+
}
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (char === '}' && pattern[i + 1] === '?') {
|
|
161
|
+
normalized += char
|
|
162
|
+
i++
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
normalized += char
|
|
167
|
+
}
|
|
168
|
+
return normalized
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Normalizes routes into objects with a shared matcher implementation.
|
|
173
|
+
*
|
|
174
|
+
* @param routes - The route definitions to normalize.
|
|
175
|
+
* @returns Routes with stable `name`, `pattern`, `component`, and `matches` fields.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* ```tsx
|
|
179
|
+
* const normalized = normalizeRoutes(routes)
|
|
180
|
+
* const match = normalized[0]?.matches('/users/123')
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
export function normalizeRoutes(routes: readonly Route[]): NormalizedRoute[] {
|
|
184
|
+
return routes.map((route) => {
|
|
185
|
+
const { name, pattern, component } = route
|
|
186
|
+
|
|
187
|
+
if (typeof pattern !== 'string') {
|
|
188
|
+
const urlPattern = toUrlPattern(pattern)
|
|
189
|
+
return {
|
|
190
|
+
name,
|
|
191
|
+
pattern,
|
|
192
|
+
component,
|
|
193
|
+
matches(pathname: string) {
|
|
194
|
+
const match = urlPattern.exec({ pathname } as any)
|
|
195
|
+
if (!match) return null
|
|
196
|
+
return ((match as any).pathname?.groups ?? {}) as RouteParams
|
|
197
|
+
},
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (pattern === '*' || pattern === '/*') {
|
|
202
|
+
return {
|
|
203
|
+
name,
|
|
204
|
+
pattern,
|
|
205
|
+
component,
|
|
206
|
+
matches: (_pathname: string) => ({}),
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
let matcher: ReturnType<typeof pathMatch> | undefined
|
|
211
|
+
let urlPattern: URLPattern | undefined
|
|
212
|
+
try {
|
|
213
|
+
matcher = pathMatch(pattern, { decode: decodeURIComponent })
|
|
214
|
+
} catch {
|
|
215
|
+
try {
|
|
216
|
+
urlPattern = toUrlPattern(pattern)
|
|
217
|
+
} catch {
|
|
218
|
+
matcher = pathMatch(normalizeLegacyPathToRegexpSyntax(pattern), {
|
|
219
|
+
decode: decodeURIComponent,
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
name,
|
|
225
|
+
pattern,
|
|
226
|
+
component,
|
|
227
|
+
matches(pathname: string) {
|
|
228
|
+
if (urlPattern) {
|
|
229
|
+
const match = urlPattern.exec({ pathname } as any)
|
|
230
|
+
if (!match) return null
|
|
231
|
+
return decodeRouteParams((match as any).pathname?.groups ?? {})
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (!matcher) return null
|
|
235
|
+
const match = matcher(pathname)
|
|
236
|
+
if (!match) return null
|
|
237
|
+
const params: RouteParams = {}
|
|
238
|
+
for (const [key, value] of Object.entries(match.params as any)) {
|
|
239
|
+
if (value == null) params[key] = undefined
|
|
240
|
+
else if (Array.isArray(value)) params[key] = value.join('/')
|
|
241
|
+
else params[key] = String(value)
|
|
242
|
+
}
|
|
243
|
+
return params
|
|
244
|
+
},
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
}
|
package/src/lib/url.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function pushUrl(next: string, state?: unknown): void {
|
|
2
|
+
window.history.pushState(state, '', next)
|
|
3
|
+
window.dispatchEvent(new PopStateEvent('popstate'))
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function replaceUrl(next: string, state?: unknown): void {
|
|
7
|
+
window.history.replaceState(state, '', next)
|
|
8
|
+
window.dispatchEvent(new PopStateEvent('popstate'))
|
|
9
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"jsx": "react-jsx",
|
|
5
|
+
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
|
6
|
+
"types": ["react", "react-dom"]
|
|
7
|
+
},
|
|
8
|
+
"include": ["src/**/*", "examples/**/*.ts", "examples/**/*.tsx"],
|
|
9
|
+
"exclude": ["**/*.test.*", "cli/**/*", "examples/dist/**/*", "examples/server/**/*"]
|
|
10
|
+
}
|
package/tsdown.config.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { defineConfig } from 'tsdown'
|
|
2
|
+
|
|
3
|
+
// https://tsdown.dev/reference/api/Interface.UserConfig
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
entry: {
|
|
6
|
+
index: 'src/index.ts',
|
|
7
|
+
bin: 'cli/bin.ts',
|
|
8
|
+
},
|
|
9
|
+
format: 'esm',
|
|
10
|
+
platform: 'neutral',
|
|
11
|
+
deps: {
|
|
12
|
+
neverBundle: [/^(node|bun):/, 'react'],
|
|
13
|
+
},
|
|
14
|
+
exports: {
|
|
15
|
+
legacy: true,
|
|
16
|
+
bin: {
|
|
17
|
+
rerouter: './cli/bin.ts',
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
dts: true, // The client must use "moduleResolution": "bundler", "node16" or "nodenext". "node" will not resolve the types properly.
|
|
21
|
+
})
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2023 Mark Penner
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|