@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
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { ClassValue } from "@mpen/classcat";
|
|
2
|
+
import * as _$react from "react";
|
|
3
|
+
import { ComponentType, ReactNode } from "react";
|
|
4
|
+
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
5
|
+
import { OverrideProps } from "@mpen/ts-types/react";
|
|
6
|
+
import { Override } from "@mpen/ts-types";
|
|
7
|
+
|
|
8
|
+
//#region src/components/Link.d.ts
|
|
9
|
+
/**
|
|
10
|
+
* Values accepted by [`Link`]{@link Link} for building query strings.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* <Link to="/matches" search={{ page: 2, sort: 'desc' }}>
|
|
15
|
+
* Matches
|
|
16
|
+
* </Link>
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
type SearchParamsInit = string | string[][] | Record<string, string | number | boolean | undefined | null> | URLSearchParams;
|
|
20
|
+
/**
|
|
21
|
+
* Props for [`Link`]{@link Link}.
|
|
22
|
+
*/
|
|
23
|
+
type LinkProps = OverrideProps<'a', {
|
|
24
|
+
/**
|
|
25
|
+
* Classes to apply to the rendered anchor.
|
|
26
|
+
*/
|
|
27
|
+
className?: ClassValue;
|
|
28
|
+
/**
|
|
29
|
+
* Destination URL passed to the rendered anchor's `href` attribute.
|
|
30
|
+
*/
|
|
31
|
+
to: string;
|
|
32
|
+
/**
|
|
33
|
+
* Query parameters to merge into [`LinkProps.to`]{@link LinkProps#to}.
|
|
34
|
+
*/
|
|
35
|
+
search?: SearchParamsInit;
|
|
36
|
+
/**
|
|
37
|
+
* Whether navigation should replace the current history entry instead of pushing a new one.
|
|
38
|
+
*/
|
|
39
|
+
replace?: boolean;
|
|
40
|
+
href: never;
|
|
41
|
+
onClick: never;
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* Renders an anchor that navigates with rerouter history updates on ordinary clicks.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```tsx
|
|
48
|
+
* <Link to="/matches/42" search={{ tab: 'details' }}>
|
|
49
|
+
* View match
|
|
50
|
+
* </Link>
|
|
51
|
+
* ```
|
|
52
|
+
*
|
|
53
|
+
* @param props - Anchor props plus rerouter navigation options.
|
|
54
|
+
* @returns An anchor element that pushes or replaces the browser URL.
|
|
55
|
+
*/
|
|
56
|
+
declare function Link({
|
|
57
|
+
to,
|
|
58
|
+
search,
|
|
59
|
+
children,
|
|
60
|
+
className,
|
|
61
|
+
replace,
|
|
62
|
+
...rest
|
|
63
|
+
}: LinkProps): _$react_jsx_runtime0.JSX.Element;
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/components/NavLink.d.ts
|
|
66
|
+
type NavLinkMatch = 'exact' | 'prefix';
|
|
67
|
+
/**
|
|
68
|
+
* Props for [`NavLink`]{@link NavLink}.
|
|
69
|
+
*/
|
|
70
|
+
type NavLinkProps = Override<LinkProps, {
|
|
71
|
+
/**
|
|
72
|
+
* Classes to apply when the link target matches the current path.
|
|
73
|
+
*/
|
|
74
|
+
activeClass?: ClassValue;
|
|
75
|
+
/**
|
|
76
|
+
* Classes to apply when the link target does not match the current path.
|
|
77
|
+
*/
|
|
78
|
+
inactiveClass?: ClassValue;
|
|
79
|
+
/**
|
|
80
|
+
* How to compare the link target to the current path.
|
|
81
|
+
*
|
|
82
|
+
* @defaultValue `'exact'`
|
|
83
|
+
*/
|
|
84
|
+
match?: NavLinkMatch;
|
|
85
|
+
}>;
|
|
86
|
+
/**
|
|
87
|
+
* Renders a [`Link`]{@link Link} with classes selected from the current route.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```tsx
|
|
91
|
+
* <NavLink
|
|
92
|
+
* activeClass={['pill', 'active']}
|
|
93
|
+
* inactiveClass={['pill', { muted: true }]}
|
|
94
|
+
* to="/settings"
|
|
95
|
+
* >
|
|
96
|
+
* Settings
|
|
97
|
+
* </NavLink>
|
|
98
|
+
* ```
|
|
99
|
+
*
|
|
100
|
+
* @param props - Link props plus active and inactive class values.
|
|
101
|
+
* @returns An anchor element that navigates through rerouter.
|
|
102
|
+
*/
|
|
103
|
+
declare function NavLink({
|
|
104
|
+
activeClass,
|
|
105
|
+
className,
|
|
106
|
+
inactiveClass,
|
|
107
|
+
match,
|
|
108
|
+
to,
|
|
109
|
+
...props
|
|
110
|
+
}: NavLinkProps): _$react_jsx_runtime0.JSX.Element;
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region src/lib/routes.d.ts
|
|
113
|
+
/**
|
|
114
|
+
* Route params captured from the current URL pathname.
|
|
115
|
+
*/
|
|
116
|
+
type RouteParams = Record<string, string | undefined>;
|
|
117
|
+
/**
|
|
118
|
+
* A React component that receives URL params captured for its route.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```tsx
|
|
122
|
+
* const UserPage: RouteComponent<{ id: string }> = ({ id }) => <div>{id}</div>
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
type RouteComponent<TParams extends RouteParams = RouteParams> = ComponentType<TParams>;
|
|
126
|
+
/**
|
|
127
|
+
* A dynamically imported route component module.
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```tsx
|
|
131
|
+
* export default function UserPage({ id }: { id: string }) {
|
|
132
|
+
* return <div>{id}</div>
|
|
133
|
+
* }
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
type RouteComponentModule<TParams extends RouteParams = RouteParams> = {
|
|
137
|
+
default: RouteComponent<TParams>;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Loads a route component on demand.
|
|
141
|
+
*
|
|
142
|
+
* @example
|
|
143
|
+
* ```tsx
|
|
144
|
+
* const loadUserPage: RouteComponentLoader<{ id: string }> = () => import('./pages/UserPage')
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
type RouteComponentLoader<TParams extends RouteParams = RouteParams> = () => Promise<RouteComponentModule<TParams>>;
|
|
148
|
+
/**
|
|
149
|
+
* Object route definition consumed by [`Router`]{@link Router}.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* ```tsx
|
|
153
|
+
* const route: RouteObject = {
|
|
154
|
+
* name: 'userProfile',
|
|
155
|
+
* pattern: '/users/:id',
|
|
156
|
+
* component: () => import('./pages/UserProfile'),
|
|
157
|
+
* }
|
|
158
|
+
* ```
|
|
159
|
+
*/
|
|
160
|
+
type RouteObject = {
|
|
161
|
+
/**
|
|
162
|
+
* Optional route name used by the CLI to generate a URL helper.
|
|
163
|
+
*
|
|
164
|
+
* Routes without a name still participate in runtime matching, but are skipped by the
|
|
165
|
+
* helper generator.
|
|
166
|
+
*/
|
|
167
|
+
name?: string;
|
|
168
|
+
pattern: string | URLPattern;
|
|
169
|
+
component: RouteComponentLoader<any>;
|
|
170
|
+
};
|
|
171
|
+
type Routes = RouteObject[];
|
|
172
|
+
/**
|
|
173
|
+
* Route definition consumed by [`Router`]{@link Router}.
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```tsx
|
|
177
|
+
* const routes: readonly Route[] = [
|
|
178
|
+
* { name: 'home', pattern: '/', component: () => import('./pages/Home') },
|
|
179
|
+
* { pattern: '/users/:id', component: () => import('./pages/UserLayout') },
|
|
180
|
+
* ]
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
type Route = RouteObject;
|
|
184
|
+
/**
|
|
185
|
+
* Route definition normalized into a single object shape with a pathname matcher.
|
|
186
|
+
*/
|
|
187
|
+
type NormalizedRoute = {
|
|
188
|
+
name?: string;
|
|
189
|
+
pattern: string | URLPattern;
|
|
190
|
+
component: RouteComponentLoader<any>;
|
|
191
|
+
matches(pathname: string): RouteParams | null;
|
|
192
|
+
};
|
|
193
|
+
/**
|
|
194
|
+
* Converts legacy `path-to-regexp` syntax that is ignored by URL generation into syntax accepted
|
|
195
|
+
* by the current parser.
|
|
196
|
+
*
|
|
197
|
+
* @param pattern - The route pattern to normalize.
|
|
198
|
+
* @returns The pattern with custom regexp constraints stripped and optional group suffixes removed.
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* ```ts
|
|
202
|
+
* normalizeLegacyPathToRegexpSyntax('/blog/:id(\\d+){-:title}?')
|
|
203
|
+
* // '/blog/:id{-:title}'
|
|
204
|
+
* ```
|
|
205
|
+
*
|
|
206
|
+
* @internal
|
|
207
|
+
*/
|
|
208
|
+
declare function normalizeLegacyPathToRegexpSyntax(pattern: string): string;
|
|
209
|
+
/**
|
|
210
|
+
* Normalizes routes into objects with a shared matcher implementation.
|
|
211
|
+
*
|
|
212
|
+
* @param routes - The route definitions to normalize.
|
|
213
|
+
* @returns Routes with stable `name`, `pattern`, `component`, and `matches` fields.
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```tsx
|
|
217
|
+
* const normalized = normalizeRoutes(routes)
|
|
218
|
+
* const match = normalized[0]?.matches('/users/123')
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
declare function normalizeRoutes(routes: readonly Route[]): NormalizedRoute[];
|
|
222
|
+
//#endregion
|
|
223
|
+
//#region src/components/Router.d.ts
|
|
224
|
+
/**
|
|
225
|
+
* Props for [`Router`]{@link Router}.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```tsx
|
|
229
|
+
* <Router routes={routes} loading={<div>Loading...</div>} />
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
interface RouterProps {
|
|
233
|
+
/**
|
|
234
|
+
* Route definitions to match against the current URL pathname.
|
|
235
|
+
*/
|
|
236
|
+
routes: readonly Route[];
|
|
237
|
+
/**
|
|
238
|
+
* Optional fallback rendered while a matched route component module is loading.
|
|
239
|
+
*/
|
|
240
|
+
loading?: ReactNode;
|
|
241
|
+
/**
|
|
242
|
+
* Delay before rendering [`RouterProps.loading`]{@link RouterProps#loading} for a suspended
|
|
243
|
+
* route, in milliseconds.
|
|
244
|
+
*
|
|
245
|
+
* @defaultValue `400`
|
|
246
|
+
*/
|
|
247
|
+
loadingDelayMs?: number;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Renders the first route that matches the current URL pathname.
|
|
251
|
+
*
|
|
252
|
+
* @param props - The router props.
|
|
253
|
+
* @returns The matched lazy route component, the loading fallback, or `null`.
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```tsx
|
|
257
|
+
* import routes from './routes'
|
|
258
|
+
*
|
|
259
|
+
* function App() {
|
|
260
|
+
* return <Router routes={routes} loading={<div>Loading...</div>} loadingDelayMs={400} />
|
|
261
|
+
* }
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
declare function Router({
|
|
265
|
+
routes,
|
|
266
|
+
loading,
|
|
267
|
+
loadingDelayMs
|
|
268
|
+
}: RouterProps): string | number | bigint | boolean | _$react_jsx_runtime0.JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | _$react.ReactPortal | _$react.ReactElement<unknown, string | _$react.JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null;
|
|
269
|
+
//#endregion
|
|
270
|
+
//#region src/lib/url.d.ts
|
|
271
|
+
declare function pushUrl(next: string, state?: unknown): void;
|
|
272
|
+
declare function replaceUrl(next: string, state?: unknown): void;
|
|
273
|
+
//#endregion
|
|
274
|
+
//#region src/hooks/useUrl.d.ts
|
|
275
|
+
declare function useUrlPath(): string;
|
|
276
|
+
declare function useUrlSearchParams(): URLSearchParams;
|
|
277
|
+
//#endregion
|
|
278
|
+
export { Link, LinkProps, NavLink, NavLinkMatch, NavLinkProps, NormalizedRoute, Route, RouteComponent, RouteComponentLoader, RouteComponentModule, RouteObject, RouteParams, Router, RouterProps, Routes, SearchParamsInit, normalizeLegacyPathToRegexpSyntax, normalizeRoutes, pushUrl, replaceUrl, useUrlPath, useUrlSearchParams };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { n as normalizeRoutes, t as normalizeLegacyPathToRegexpSyntax } from "./routes-PW-bNm8e.js";
|
|
2
|
+
import { cc } from "@mpen/classcat";
|
|
3
|
+
import { Suspense, startTransition, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { jsx } from "react/jsx-runtime";
|
|
5
|
+
//#region src/lib/url.ts
|
|
6
|
+
function pushUrl(next, state) {
|
|
7
|
+
window.history.pushState(state, "", next);
|
|
8
|
+
window.dispatchEvent(new PopStateEvent("popstate"));
|
|
9
|
+
}
|
|
10
|
+
function replaceUrl(next, state) {
|
|
11
|
+
window.history.replaceState(state, "", next);
|
|
12
|
+
window.dispatchEvent(new PopStateEvent("popstate"));
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/lib/mergeSearch.ts
|
|
16
|
+
function mergeSearch(to, search) {
|
|
17
|
+
const hashIndex = to.indexOf("#");
|
|
18
|
+
const hash = hashIndex !== -1 ? to.slice(hashIndex) : "";
|
|
19
|
+
const pathAndQuery = hashIndex !== -1 ? to.slice(0, hashIndex) : to;
|
|
20
|
+
const queryIndex = pathAndQuery.indexOf("?");
|
|
21
|
+
const path = queryIndex !== -1 ? pathAndQuery.slice(0, queryIndex) : pathAndQuery;
|
|
22
|
+
const existingQuery = queryIndex !== -1 ? pathAndQuery.slice(queryIndex + 1) : "";
|
|
23
|
+
const params = new URLSearchParams(existingQuery);
|
|
24
|
+
const newParams = new URLSearchParams(search);
|
|
25
|
+
for (const [key, value] of newParams) params.set(key, value);
|
|
26
|
+
const queryString = params.toString();
|
|
27
|
+
return `${path}${queryString ? "?" + queryString : ""}${hash}`;
|
|
28
|
+
}
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/components/Link.tsx
|
|
31
|
+
/**
|
|
32
|
+
* Renders an anchor that navigates with rerouter history updates on ordinary clicks.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```tsx
|
|
36
|
+
* <Link to="/matches/42" search={{ tab: 'details' }}>
|
|
37
|
+
* View match
|
|
38
|
+
* </Link>
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @param props - Anchor props plus rerouter navigation options.
|
|
42
|
+
* @returns An anchor element that pushes or replaces the browser URL.
|
|
43
|
+
*/
|
|
44
|
+
function Link({ to, search, children, className, replace, ...rest }) {
|
|
45
|
+
const href = search ? mergeSearch(to, search) : to;
|
|
46
|
+
const linkClassName = cc(className);
|
|
47
|
+
const onClick = (ev) => {
|
|
48
|
+
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
49
|
+
if (ev.button !== 0) return;
|
|
50
|
+
ev.preventDefault();
|
|
51
|
+
startTransition(() => {
|
|
52
|
+
if (replace) replaceUrl(href);
|
|
53
|
+
else pushUrl(href);
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
return /* @__PURE__ */ jsx("a", {
|
|
57
|
+
...rest,
|
|
58
|
+
className: linkClassName || void 0,
|
|
59
|
+
href,
|
|
60
|
+
onClick,
|
|
61
|
+
children
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/hooks/useUrl.ts
|
|
66
|
+
const getPathname = () => window.location.pathname;
|
|
67
|
+
const getSearch = () => window.location.search;
|
|
68
|
+
function subscribe(cb) {
|
|
69
|
+
const handler = () => cb();
|
|
70
|
+
window.addEventListener("popstate", handler);
|
|
71
|
+
return () => {
|
|
72
|
+
window.removeEventListener("popstate", handler);
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function useUrlPath() {
|
|
76
|
+
return useSyncExternalStore(subscribe, getPathname, getPathname);
|
|
77
|
+
}
|
|
78
|
+
function useUrlSearchParams() {
|
|
79
|
+
const search = useSyncExternalStore(subscribe, getSearch, getSearch);
|
|
80
|
+
return useMemo(() => new URLSearchParams(search), [search]);
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/components/NavLink.tsx
|
|
84
|
+
function isActivePath(pathname, targetPathname, match) {
|
|
85
|
+
if (pathname === targetPathname) return true;
|
|
86
|
+
if (match === "exact") return false;
|
|
87
|
+
if (targetPathname === "/") return false;
|
|
88
|
+
return pathname.startsWith(`${targetPathname}/`);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Renders a [`Link`]{@link Link} with classes selected from the current route.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* ```tsx
|
|
95
|
+
* <NavLink
|
|
96
|
+
* activeClass={['pill', 'active']}
|
|
97
|
+
* inactiveClass={['pill', { muted: true }]}
|
|
98
|
+
* to="/settings"
|
|
99
|
+
* >
|
|
100
|
+
* Settings
|
|
101
|
+
* </NavLink>
|
|
102
|
+
* ```
|
|
103
|
+
*
|
|
104
|
+
* @param props - Link props plus active and inactive class values.
|
|
105
|
+
* @returns An anchor element that navigates through rerouter.
|
|
106
|
+
*/
|
|
107
|
+
function NavLink({ activeClass, className, inactiveClass, match = "exact", to, ...props }) {
|
|
108
|
+
const linkClassName = cc(className, isActivePath(useUrlPath(), new URL(to, window.location.href).pathname, match) ? activeClass : inactiveClass);
|
|
109
|
+
return /* @__PURE__ */ jsx(Link, {
|
|
110
|
+
...props,
|
|
111
|
+
className: linkClassName || void 0,
|
|
112
|
+
to
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/components/Router.tsx
|
|
117
|
+
const DEFAULT_LOADING_DELAY_MS = 400;
|
|
118
|
+
const loadedRouteComponents = /* @__PURE__ */ new WeakMap();
|
|
119
|
+
const loadingRouteComponents = /* @__PURE__ */ new WeakMap();
|
|
120
|
+
function loadRouteComponent(component) {
|
|
121
|
+
const loaded = loadedRouteComponents.get(component);
|
|
122
|
+
if (loaded) return Promise.resolve(loaded);
|
|
123
|
+
let loading = loadingRouteComponents.get(component);
|
|
124
|
+
if (!loading) {
|
|
125
|
+
loading = component().then((module) => {
|
|
126
|
+
loadedRouteComponents.set(component, module.default);
|
|
127
|
+
loadingRouteComponents.delete(component);
|
|
128
|
+
return module.default;
|
|
129
|
+
});
|
|
130
|
+
loadingRouteComponents.set(component, loading);
|
|
131
|
+
}
|
|
132
|
+
return loading;
|
|
133
|
+
}
|
|
134
|
+
function findRouteMatch(routes, pathname) {
|
|
135
|
+
for (const route of routes) {
|
|
136
|
+
const params = route.matches(pathname);
|
|
137
|
+
if (!params) continue;
|
|
138
|
+
return {
|
|
139
|
+
route,
|
|
140
|
+
params,
|
|
141
|
+
pathname
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
function getLoadedRoute(match) {
|
|
147
|
+
if (!match) return null;
|
|
148
|
+
const Component = loadedRouteComponents.get(match.route.component);
|
|
149
|
+
if (!Component) return null;
|
|
150
|
+
return {
|
|
151
|
+
...match,
|
|
152
|
+
Component
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function scheduleTransition(cb) {
|
|
156
|
+
queueMicrotask(() => {
|
|
157
|
+
startTransition(cb);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
function useRenderedRoute(match, loadingDelayMs) {
|
|
161
|
+
const [renderedRoute, setRenderedRoute] = useState(() => getLoadedRoute(match));
|
|
162
|
+
const [showLoading, setShowLoading] = useState(false);
|
|
163
|
+
const [loadError, setLoadError] = useState(null);
|
|
164
|
+
useEffect(() => {
|
|
165
|
+
if (!match) {
|
|
166
|
+
scheduleTransition(() => {
|
|
167
|
+
setRenderedRoute(null);
|
|
168
|
+
setShowLoading(false);
|
|
169
|
+
setLoadError(null);
|
|
170
|
+
});
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const loaded = getLoadedRoute(match);
|
|
174
|
+
if (loaded) {
|
|
175
|
+
scheduleTransition(() => {
|
|
176
|
+
setRenderedRoute(loaded);
|
|
177
|
+
setShowLoading(false);
|
|
178
|
+
setLoadError(null);
|
|
179
|
+
});
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
let active = true;
|
|
183
|
+
let timeout;
|
|
184
|
+
scheduleTransition(() => {
|
|
185
|
+
setShowLoading(false);
|
|
186
|
+
});
|
|
187
|
+
if (loadingDelayMs <= 0) timeout = setTimeout(() => {
|
|
188
|
+
if (active) setShowLoading(true);
|
|
189
|
+
}, 0);
|
|
190
|
+
else timeout = setTimeout(() => {
|
|
191
|
+
if (active) setShowLoading(true);
|
|
192
|
+
}, loadingDelayMs);
|
|
193
|
+
loadRouteComponent(match.route.component).then((Component) => {
|
|
194
|
+
if (!active) return;
|
|
195
|
+
if (timeout) clearTimeout(timeout);
|
|
196
|
+
startTransition(() => {
|
|
197
|
+
setRenderedRoute({
|
|
198
|
+
...match,
|
|
199
|
+
Component
|
|
200
|
+
});
|
|
201
|
+
setShowLoading(false);
|
|
202
|
+
setLoadError(null);
|
|
203
|
+
});
|
|
204
|
+
}).catch((error) => {
|
|
205
|
+
if (!active) return;
|
|
206
|
+
setLoadError(error);
|
|
207
|
+
});
|
|
208
|
+
return () => {
|
|
209
|
+
active = false;
|
|
210
|
+
if (timeout) clearTimeout(timeout);
|
|
211
|
+
};
|
|
212
|
+
}, [loadingDelayMs, match]);
|
|
213
|
+
if (loadError) throw loadError;
|
|
214
|
+
return {
|
|
215
|
+
renderedRoute,
|
|
216
|
+
showLoading
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Renders the first route that matches the current URL pathname.
|
|
221
|
+
*
|
|
222
|
+
* @param props - The router props.
|
|
223
|
+
* @returns The matched lazy route component, the loading fallback, or `null`.
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```tsx
|
|
227
|
+
* import routes from './routes'
|
|
228
|
+
*
|
|
229
|
+
* function App() {
|
|
230
|
+
* return <Router routes={routes} loading={<div>Loading...</div>} loadingDelayMs={400} />
|
|
231
|
+
* }
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
function Router({ routes, loading = null, loadingDelayMs = DEFAULT_LOADING_DELAY_MS }) {
|
|
235
|
+
const pathname = useUrlPath();
|
|
236
|
+
const normalizedRoutes = useMemo(() => normalizeRoutes(routes), [routes]);
|
|
237
|
+
const { renderedRoute, showLoading } = useRenderedRoute(useMemo(() => findRouteMatch(normalizedRoutes, pathname), [normalizedRoutes, pathname]), loadingDelayMs);
|
|
238
|
+
if (showLoading) return loading;
|
|
239
|
+
if (!renderedRoute) return null;
|
|
240
|
+
const { Component, params } = renderedRoute;
|
|
241
|
+
return /* @__PURE__ */ jsx(Suspense, {
|
|
242
|
+
fallback: loading,
|
|
243
|
+
children: /* @__PURE__ */ jsx(Component, { ...params })
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
//#endregion
|
|
247
|
+
export { Link, NavLink, Router, normalizeLegacyPathToRegexpSyntax, normalizeRoutes, pushUrl, replaceUrl, useUrlPath, useUrlSearchParams };
|