clear-react-router 2.0.7 → 2.0.9
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 +27 -10
- package/dist/cell.d.ts +6 -0
- package/dist/components/Link.d.ts +3 -1
- package/dist/index.js +113 -70
- package/dist/runtime/invalidate.d.ts +1 -1
- package/dist/runtime/navigate.d.ts +1 -1
- package/dist/runtime/prefetch.d.ts +2 -2
- package/dist/types.d.ts +10 -5
- package/dist/utils/commitState.d.ts +1 -1
- package/dist/utils/revalidateCache.d.ts +1 -1
- package/dist/utils/utils.d.ts +7 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
[](https://www.npmjs.com/package/clear-react-router)
|
|
2
|
-
|
|
3
1
|
# Clear Router
|
|
4
2
|
|
|
5
3
|
A lightweight, type-safe routing library for client side React applications with nested routes, data loading, navigation blocking, prefetching, and route actions.
|
|
@@ -54,7 +52,7 @@ It provides first-class support for:
|
|
|
54
52
|
| `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
|
|
55
53
|
| `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
|
|
56
54
|
| `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
|
|
57
|
-
| `defaultBeforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
|
|
55
|
+
| `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
|
|
58
56
|
| `defaultAfterLoad` | `({ params, context, setContext }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
|
|
59
57
|
| `defaultPreserveScroll` | `boolean \| undefined` | `true` | Default value for save and restore scroll position when navigating between pages |
|
|
60
58
|
| `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
|
|
@@ -71,7 +69,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
71
69
|
|----------|------|-------------|
|
|
72
70
|
| `path` | `string` | Route path, e.g., `/user/:userId` |
|
|
73
71
|
| `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
|
|
74
|
-
| `beforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
|
|
72
|
+
| `beforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
|
|
75
73
|
| `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
|
|
76
74
|
| `afterLoad` | `({ params, context, setContext }) => Promise<void>` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
|
|
77
75
|
| `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
|
|
@@ -85,14 +83,31 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
85
83
|
| `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
|
|
86
84
|
| `preserveScroll` | `boolean \| undefined` | Save and restore route scroll position when navigating between pages |
|
|
87
85
|
|
|
88
|
-
|
|
86
|
+
Before load arguments (see [`redirect`](#redirect) for details on programmatic redirects):
|
|
87
|
+
|
|
88
|
+
`beforeLoad` and `loader` both receive:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
{
|
|
92
|
+
params: Record<string, string>; // Route parameters
|
|
93
|
+
context: Record<string, unknown>; // Router context
|
|
94
|
+
setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
|
|
95
|
+
searchParams: Record<string, string>; // URL search parameters
|
|
96
|
+
location: Location; // Route location
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`beforeLoad` additionally receives:
|
|
101
|
+
```ts
|
|
102
|
+
{
|
|
103
|
+
redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`loader` additionally receives:
|
|
89
108
|
```ts
|
|
90
109
|
{
|
|
91
|
-
|
|
92
|
-
context: Record<string, unknown>; // Router context
|
|
93
|
-
setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
|
|
94
|
-
searchParams: Record<string, string>; // URL search parameters
|
|
95
|
-
signal: AbortSignal; // AbortController signal
|
|
110
|
+
signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
|
|
96
111
|
}
|
|
97
112
|
```
|
|
98
113
|
|
|
@@ -103,6 +118,8 @@ Component for client-side navigation with prefetch support, active state detecti
|
|
|
103
118
|
| Prop | Type | Default | Description |
|
|
104
119
|
|------|------|---------|-------------|
|
|
105
120
|
| `to` | `string` | required | Target path |
|
|
121
|
+
| `search` | `string \| undefined` | `undefined` | Query string appended to the target path |
|
|
122
|
+
| `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
|
|
106
123
|
| `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
|
|
107
124
|
| `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
|
|
108
125
|
| `prefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `Router` config | Override the global prefetch strategy |
|
package/dist/cell.d.ts
ADDED
|
@@ -6,6 +6,8 @@ type ElementState = {
|
|
|
6
6
|
};
|
|
7
7
|
type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
|
|
8
8
|
to: string;
|
|
9
|
+
search?: string;
|
|
10
|
+
state?: unknown;
|
|
9
11
|
children?: ReactNode;
|
|
10
12
|
as?: (props: ElementProps<T>, state: ElementState) => ReactElement;
|
|
11
13
|
prefetch?: RouterProps['defaultPrefetch'];
|
|
@@ -17,5 +19,5 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
|
|
|
17
19
|
style?: CSSProperties | ((arg: ElementState) => CSSProperties);
|
|
18
20
|
exact?: boolean;
|
|
19
21
|
};
|
|
20
|
-
export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
|
|
22
|
+
export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
|
|
21
23
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -30,16 +30,16 @@ var useGlobalState = ({ subscribe, getState, setState }) => {
|
|
|
30
30
|
};
|
|
31
31
|
//#endregion
|
|
32
32
|
//#region utils/commitState.ts
|
|
33
|
-
var createCommitState = ({ routeItemDataState,
|
|
33
|
+
var createCommitState = ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }) => (nextLocation, routeItem) => {
|
|
34
34
|
routeItemDataState.setState({
|
|
35
35
|
routeItem,
|
|
36
36
|
location: nextLocation
|
|
37
37
|
});
|
|
38
|
-
|
|
38
|
+
statusState.setState("active");
|
|
39
39
|
isOptimisticLoading.setState(false);
|
|
40
|
-
|
|
41
|
-
if (
|
|
42
|
-
history.pushState(null, "",
|
|
40
|
+
loaderState.setState(loaderStateRef.value);
|
|
41
|
+
if ((nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname) === window.location.pathname + window.location.search) return;
|
|
42
|
+
history.pushState(null, "", `${nextLocation.pathname}${nextLocation.search}`);
|
|
43
43
|
};
|
|
44
44
|
//#endregion
|
|
45
45
|
//#region constants.ts
|
|
@@ -108,7 +108,9 @@ var routerConfig = new RouterConfig();
|
|
|
108
108
|
var commitNavigation = (callback) => {
|
|
109
109
|
if (!routerConfig.isAnimated) return callback();
|
|
110
110
|
try {
|
|
111
|
-
document.startViewTransition(callback);
|
|
111
|
+
const transition = document.startViewTransition(callback);
|
|
112
|
+
transition.ready.catch(() => {});
|
|
113
|
+
transition.finished.catch(() => {});
|
|
112
114
|
} catch {
|
|
113
115
|
callback();
|
|
114
116
|
}
|
|
@@ -216,6 +218,17 @@ var isMobile = () => {
|
|
|
216
218
|
return hasCoarsePointer && isSmallScreen;
|
|
217
219
|
};
|
|
218
220
|
var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
221
|
+
var getPartialBeforeLoadArgs = (location) => {
|
|
222
|
+
const params = getParamsObject();
|
|
223
|
+
const { contextState } = router.state;
|
|
224
|
+
return {
|
|
225
|
+
params,
|
|
226
|
+
context: contextState.getState(),
|
|
227
|
+
setContext: contextState.setState,
|
|
228
|
+
searchParams: Object.fromEntries(new URLSearchParams(location.search).entries()),
|
|
229
|
+
location
|
|
230
|
+
};
|
|
231
|
+
};
|
|
219
232
|
var findRoute = (pathname, includeAll) => {
|
|
220
233
|
if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
|
|
221
234
|
return routerConfig.routes.find((el) => comparePaths(el, pathname));
|
|
@@ -226,7 +239,7 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
226
239
|
let navigationSeq = 0;
|
|
227
240
|
let interval = 0;
|
|
228
241
|
let abortController = null;
|
|
229
|
-
const { loaderState, scrollMapState,
|
|
242
|
+
const { loaderState, loaderStateRef, scrollMapState, statusState, contextState, loaderMap, routeItemDataState, isOptimisticLoading } = routerState;
|
|
230
243
|
const navigationExecutor = createCommitState(routerState);
|
|
231
244
|
const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
|
|
232
245
|
const createSignal = () => {
|
|
@@ -234,35 +247,34 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
234
247
|
abortController = new AbortController();
|
|
235
248
|
return abortController.signal;
|
|
236
249
|
};
|
|
237
|
-
const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search
|
|
250
|
+
const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
|
|
238
251
|
const getContext = () => ({
|
|
239
252
|
context: contextState.getState(),
|
|
240
253
|
setContext: contextState.setState
|
|
241
254
|
});
|
|
242
255
|
const routeResolve = (location) => {
|
|
243
|
-
|
|
256
|
+
loaderStateRef.set(emptyLoaderState);
|
|
244
257
|
const nextItem = findRoute(location.pathname, true);
|
|
245
258
|
return {
|
|
246
259
|
nextItem,
|
|
247
260
|
params: getParamsObject(nextItem, location.pathname)
|
|
248
261
|
};
|
|
249
262
|
};
|
|
250
|
-
const beforeLoad = async (routeItem,
|
|
263
|
+
const beforeLoad = async (routeItem, nextLocation) => {
|
|
251
264
|
const { defaultBeforeLoad } = routerConfig;
|
|
252
265
|
const runBeforeLoad = async (loaderFn) => {
|
|
253
266
|
const redirect = async (redirected) => await navigate(typeof redirected === "string" ? { pathname: redirected } : redirected);
|
|
254
267
|
try {
|
|
255
268
|
await loaderFn({
|
|
256
|
-
...getContext(),
|
|
257
269
|
redirect,
|
|
258
|
-
|
|
270
|
+
...getPartialBeforeLoadArgs(nextLocation)
|
|
259
271
|
});
|
|
260
|
-
|
|
272
|
+
loaderStateRef.set((prev) => ({
|
|
261
273
|
...prev,
|
|
262
274
|
beforeLoadError: null
|
|
263
275
|
}));
|
|
264
276
|
} catch (error) {
|
|
265
|
-
|
|
277
|
+
loaderStateRef.set((prev) => ({
|
|
266
278
|
...prev,
|
|
267
279
|
beforeLoadError: error
|
|
268
280
|
}));
|
|
@@ -290,19 +302,17 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
290
302
|
isOptimisticLoading.setState(true);
|
|
291
303
|
const currentLoaderState = loaderMap.get(path)?.state;
|
|
292
304
|
if (currentLoaderState) loaderState.setState(currentLoaderState);
|
|
293
|
-
} else
|
|
294
|
-
routeItem
|
|
295
|
-
|
|
296
|
-
}
|
|
297
|
-
else pendingState.setState(void 0);
|
|
305
|
+
} else {
|
|
306
|
+
const pendingShouldExist = routeItem?.loader && !isCacheItemFresh(path);
|
|
307
|
+
commitNavigation(() => statusState.setState(pendingShouldExist ? "pending" : "active"));
|
|
308
|
+
}
|
|
298
309
|
};
|
|
299
310
|
const polling = (routeItem, nextLocation) => {
|
|
300
311
|
if (!routeItem?.pollingInterval) return;
|
|
301
312
|
const signal = createSignal();
|
|
302
313
|
interval = window.setInterval(() => revalidateCache({
|
|
303
314
|
routeItem,
|
|
304
|
-
|
|
305
|
-
search: nextLocation.search,
|
|
315
|
+
location: nextLocation,
|
|
306
316
|
signal
|
|
307
317
|
}), routeItem.pollingInterval);
|
|
308
318
|
};
|
|
@@ -316,11 +326,10 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
316
326
|
const signal = createSignal();
|
|
317
327
|
const [result] = await Promise.all([revalidateCache({
|
|
318
328
|
routeItem,
|
|
319
|
-
|
|
320
|
-
search: nextLocation.search,
|
|
329
|
+
location: nextLocation,
|
|
321
330
|
signal
|
|
322
331
|
}), getLoaderDurationPromise(routeItem, nextLocation)]);
|
|
323
|
-
if (result)
|
|
332
|
+
if (result) loaderStateRef.set((prev) => ({
|
|
324
333
|
...prev,
|
|
325
334
|
...result
|
|
326
335
|
}));
|
|
@@ -338,11 +347,15 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
338
347
|
params
|
|
339
348
|
});
|
|
340
349
|
};
|
|
341
|
-
const navigate = async (
|
|
350
|
+
const navigate = async (rawLocation) => {
|
|
351
|
+
const nextLocation = {
|
|
352
|
+
...rawLocation,
|
|
353
|
+
search: rawLocation.search ?? ""
|
|
354
|
+
};
|
|
342
355
|
navigationSeq = navigationSeq + 1;
|
|
343
356
|
const seq = navigationSeq;
|
|
344
357
|
const { nextItem, params } = routeResolve(nextLocation);
|
|
345
|
-
await beforeLoad(nextItem,
|
|
358
|
+
await beforeLoad(nextItem, nextLocation);
|
|
346
359
|
if (seq !== navigationSeq) return;
|
|
347
360
|
prepareNavigation(nextItem, nextLocation);
|
|
348
361
|
await loader(nextItem, nextLocation, seq);
|
|
@@ -355,22 +368,20 @@ var createNavigate = (routerState, revalidateCache) => {
|
|
|
355
368
|
//#endregion
|
|
356
369
|
//#region runtime/invalidate.ts
|
|
357
370
|
var redirect = Promise.resolve;
|
|
358
|
-
var createInvalidate = ({ routeItemDataState, loaderState, loaderMap
|
|
371
|
+
var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
|
|
359
372
|
const invalidatePath = async (routeItem, pathname, options) => {
|
|
360
373
|
const routePathname = routeItemDataState.getState().location.pathname;
|
|
361
374
|
loaderMap.delete(pathname);
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
});
|
|
373
|
-
}
|
|
375
|
+
const [path, search = ""] = pathname.split("?");
|
|
376
|
+
const location = {
|
|
377
|
+
pathname: path,
|
|
378
|
+
search
|
|
379
|
+
};
|
|
380
|
+
if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
|
|
381
|
+
await routeItem.beforeLoad({
|
|
382
|
+
redirect,
|
|
383
|
+
...getPartialBeforeLoadArgs(location)
|
|
384
|
+
});
|
|
374
385
|
loaderState.setState((prev) => ({
|
|
375
386
|
...prev,
|
|
376
387
|
beforeLoadError: null
|
|
@@ -383,7 +394,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
383
394
|
}
|
|
384
395
|
const result = await revalidateCache({
|
|
385
396
|
routeItem,
|
|
386
|
-
|
|
397
|
+
location
|
|
387
398
|
});
|
|
388
399
|
if (result && pathname === routePathname) loaderState.setState({
|
|
389
400
|
data: result.data,
|
|
@@ -396,7 +407,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
396
407
|
};
|
|
397
408
|
};
|
|
398
409
|
const invalidateItem = async (pathname, options) => {
|
|
399
|
-
const routeItem = findRoute(pathname);
|
|
410
|
+
const routeItem = findRoute(pathname.split("?")[0]);
|
|
400
411
|
if (!routeItem) return [];
|
|
401
412
|
const pathnameSet = /* @__PURE__ */ new Set();
|
|
402
413
|
for (const [key] of loaderMap) if (comparePaths(routeItem, key)) pathnameSet.add(key);
|
|
@@ -414,13 +425,15 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
|
|
|
414
425
|
};
|
|
415
426
|
//#endregion
|
|
416
427
|
//#region runtime/prefetch.ts
|
|
417
|
-
var createPrefetch = (revalidateCache) => async (
|
|
418
|
-
const item = findRoute(pathname);
|
|
428
|
+
var createPrefetch = ({ routeItemDataState }, revalidateCache) => async (location) => {
|
|
429
|
+
const item = findRoute(location.pathname);
|
|
419
430
|
if (item) {
|
|
431
|
+
const currentLocation = routeItemDataState.getState().location;
|
|
432
|
+
if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
|
|
420
433
|
await item.preloadElement?.();
|
|
421
434
|
await revalidateCache({
|
|
422
435
|
routeItem: item,
|
|
423
|
-
|
|
436
|
+
location
|
|
424
437
|
});
|
|
425
438
|
}
|
|
426
439
|
};
|
|
@@ -458,9 +471,10 @@ var createRevalidateCache = (routerState) => {
|
|
|
458
471
|
}
|
|
459
472
|
return item;
|
|
460
473
|
};
|
|
461
|
-
const revalidateCache = async ({ routeItem,
|
|
474
|
+
const revalidateCache = async ({ routeItem, location, signal }, retried = 0) => {
|
|
462
475
|
if (!routeItem?.loader) return;
|
|
463
476
|
const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
|
|
477
|
+
const { pathname, search = "" } = location;
|
|
464
478
|
const path = `${pathname}${search}`;
|
|
465
479
|
if (loadingPromises.has(path)) {
|
|
466
480
|
moveItemToLastPosition(path);
|
|
@@ -490,7 +504,8 @@ var createRevalidateCache = (routerState) => {
|
|
|
490
504
|
context,
|
|
491
505
|
setContext,
|
|
492
506
|
searchParams,
|
|
493
|
-
signal: effectiveSignal
|
|
507
|
+
signal: effectiveSignal,
|
|
508
|
+
location
|
|
494
509
|
});
|
|
495
510
|
loaderMap.set(path, {
|
|
496
511
|
state: {
|
|
@@ -515,12 +530,15 @@ var createRevalidateCache = (routerState) => {
|
|
|
515
530
|
if (retry && retry.count > retried) {
|
|
516
531
|
loadingPromises.delete(path);
|
|
517
532
|
if (retry.delay) await sleep(retry.delay);
|
|
518
|
-
|
|
533
|
+
await revalidateCache({
|
|
519
534
|
routeItem,
|
|
520
|
-
|
|
521
|
-
search,
|
|
535
|
+
location,
|
|
522
536
|
signal
|
|
523
537
|
}, retried + 1);
|
|
538
|
+
return {
|
|
539
|
+
data: null,
|
|
540
|
+
error
|
|
541
|
+
};
|
|
524
542
|
} else return {
|
|
525
543
|
data: null,
|
|
526
544
|
error
|
|
@@ -535,6 +553,20 @@ var createRevalidateCache = (routerState) => {
|
|
|
535
553
|
return revalidateCache;
|
|
536
554
|
};
|
|
537
555
|
//#endregion
|
|
556
|
+
//#region cell.ts
|
|
557
|
+
var Cell = class {
|
|
558
|
+
constructor(_value) {
|
|
559
|
+
_defineProperty(this, "_value", void 0);
|
|
560
|
+
this._value = _value;
|
|
561
|
+
}
|
|
562
|
+
get value() {
|
|
563
|
+
return this._value;
|
|
564
|
+
}
|
|
565
|
+
set(action) {
|
|
566
|
+
this._value = typeof action === "function" ? action(this._value) : action;
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
//#endregion
|
|
538
570
|
//#region utils/createRouterInstance.ts
|
|
539
571
|
var createRouterInstance = () => {
|
|
540
572
|
const routerState = {
|
|
@@ -542,7 +574,7 @@ var createRouterInstance = () => {
|
|
|
542
574
|
routeItem: void 0,
|
|
543
575
|
location: {}
|
|
544
576
|
}),
|
|
545
|
-
|
|
577
|
+
statusState: create("idle"),
|
|
546
578
|
scrollMapState: create({}),
|
|
547
579
|
contextState: create({}),
|
|
548
580
|
blockedRouteState: create({
|
|
@@ -551,13 +583,14 @@ var createRouterInstance = () => {
|
|
|
551
583
|
}),
|
|
552
584
|
isOptimisticLoading: create(false),
|
|
553
585
|
loaderState: create(emptyLoaderState),
|
|
586
|
+
loaderStateRef: new Cell(emptyLoaderState),
|
|
554
587
|
loaderMap: /* @__PURE__ */ new Map(),
|
|
555
588
|
loadingPromises: /* @__PURE__ */ new Map()
|
|
556
589
|
};
|
|
557
590
|
const revalidateCache = createRevalidateCache(routerState);
|
|
558
591
|
const invalidate = createInvalidate(routerState, revalidateCache);
|
|
559
592
|
const navigate = createNavigate(routerState, revalidateCache);
|
|
560
|
-
const prefetch = createPrefetch(revalidateCache);
|
|
593
|
+
const prefetch = createPrefetch(routerState, revalidateCache);
|
|
561
594
|
const useGetAction = (actionKey) => {
|
|
562
595
|
const { routeItem } = routerState.routeItemDataState.getState();
|
|
563
596
|
const context = routerState.contextState.getState();
|
|
@@ -588,7 +621,7 @@ var createRouterInstance = () => {
|
|
|
588
621
|
useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
|
|
589
622
|
useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
|
|
590
623
|
useScrollMap: () => useGlobalState(routerState.scrollMapState),
|
|
591
|
-
|
|
624
|
+
useStatus: () => useGlobalState(routerState.statusState),
|
|
592
625
|
useContextState: () => useGlobalState(routerState.contextState),
|
|
593
626
|
useOptimisticLoading: () => useGlobalState(routerState.isOptimisticLoading),
|
|
594
627
|
useLoaderState: () => useGlobalState(routerState.loaderState)[0],
|
|
@@ -748,12 +781,12 @@ var IS_MOBILE = isMobile();
|
|
|
748
781
|
var MOBILE_CACHE_SIZE = 60;
|
|
749
782
|
var DESKTOP_CACHE_SIZE = 150;
|
|
750
783
|
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, defaultPreserveScroll = true, defaultMinLoaderDuration = 0, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, errorBoundary: ErrorBoundary = EmptyBoundary }) => {
|
|
751
|
-
const { useRouteItemData,
|
|
784
|
+
const { useRouteItemData, useStatus, useOptimisticLoading } = router.hooks;
|
|
752
785
|
const [routeItemData] = useRouteItemData();
|
|
753
|
-
const [
|
|
786
|
+
const [status] = useStatus();
|
|
754
787
|
const [isOptimisticLoading] = useOptimisticLoading();
|
|
755
788
|
const loaderState = useLoaderState();
|
|
756
|
-
const isLoading =
|
|
789
|
+
const isLoading = status === "pending";
|
|
757
790
|
useNavigation();
|
|
758
791
|
useSetRouterConfig({
|
|
759
792
|
routes,
|
|
@@ -773,7 +806,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
773
806
|
usePreserveScroll(routeItemData);
|
|
774
807
|
const { routeItem, location } = routeItemData;
|
|
775
808
|
const showErrorElement = !isLoading && Boolean(loaderState.loaderError || loaderState.beforeLoadError);
|
|
776
|
-
if (!showErrorElement && isLoading) return renderElement(
|
|
809
|
+
if (!showErrorElement && isLoading) return renderElement(routeItemData?.routeItem?.loaderFallback || defaultLoaderFallback);
|
|
777
810
|
if (!routeItem) return null;
|
|
778
811
|
if (showErrorElement) return renderElement(routeItem.errorElement || defaultErrorElement);
|
|
779
812
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
|
|
@@ -784,9 +817,10 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
784
817
|
//#endregion
|
|
785
818
|
//#region hooks/useIsRoutePending.ts
|
|
786
819
|
var useIsRoutePending = (routePath) => {
|
|
787
|
-
const {
|
|
788
|
-
const [
|
|
789
|
-
|
|
820
|
+
const { useStatus, useRouteItemData } = router.hooks;
|
|
821
|
+
const [routeItemData] = useRouteItemData();
|
|
822
|
+
const [status] = useStatus();
|
|
823
|
+
return status === "pending" && routeItemData?.location.pathname === routePath;
|
|
790
824
|
};
|
|
791
825
|
//#endregion
|
|
792
826
|
//#region hooks/useNavigate.ts
|
|
@@ -800,7 +834,7 @@ var useLocation = () => {
|
|
|
800
834
|
//#endregion
|
|
801
835
|
//#region components/Link.tsx
|
|
802
836
|
var defaultAs = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...props });
|
|
803
|
-
var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
|
|
837
|
+
var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
|
|
804
838
|
const isPending = useIsRoutePending(to);
|
|
805
839
|
const { pathname } = useLocation();
|
|
806
840
|
const navigate = useNavigate();
|
|
@@ -809,14 +843,23 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
809
843
|
const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
|
|
810
844
|
const prefetch = linkPrefetch || configPrefetch;
|
|
811
845
|
const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
|
|
846
|
+
const location = useMemo(() => ({
|
|
847
|
+
pathname: to,
|
|
848
|
+
search,
|
|
849
|
+
state
|
|
850
|
+
}), [
|
|
851
|
+
search,
|
|
852
|
+
state,
|
|
853
|
+
to
|
|
854
|
+
]);
|
|
812
855
|
const onMouseEnter = useCallback(() => {
|
|
813
856
|
if (prefetch !== "hover" || !prefetchDelay) return;
|
|
814
857
|
if (timeout.current) clearTimeout(timeout.current);
|
|
815
|
-
timeout.current = window.setTimeout(() => router.runtime.prefetch(
|
|
858
|
+
timeout.current = window.setTimeout(() => router.runtime.prefetch(location), prefetchDelay);
|
|
816
859
|
}, [
|
|
817
860
|
prefetch,
|
|
818
861
|
prefetchDelay,
|
|
819
|
-
|
|
862
|
+
location
|
|
820
863
|
]);
|
|
821
864
|
const onMouseLeave = useCallback(() => {
|
|
822
865
|
if (prefetch !== "hover" || !prefetchDelay) return;
|
|
@@ -828,21 +871,21 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
828
871
|
useEffect(() => {
|
|
829
872
|
if (prefetch !== "render") return;
|
|
830
873
|
(async () => {
|
|
831
|
-
await router.runtime.prefetch(
|
|
874
|
+
await router.runtime.prefetch(location);
|
|
832
875
|
})();
|
|
833
|
-
}, [prefetch,
|
|
876
|
+
}, [prefetch, location]);
|
|
834
877
|
useEffect(() => {
|
|
835
878
|
if (prefetch !== "viewport") return;
|
|
836
879
|
const element = elementRef.current;
|
|
837
880
|
if (!element) return;
|
|
838
881
|
const observer = new IntersectionObserver(async ([entry]) => {
|
|
839
882
|
if (!entry.isIntersecting) return;
|
|
840
|
-
await router.runtime.prefetch(
|
|
883
|
+
await router.runtime.prefetch(location);
|
|
841
884
|
observer.disconnect();
|
|
842
885
|
});
|
|
843
886
|
observer.observe(element);
|
|
844
887
|
return () => observer.disconnect();
|
|
845
|
-
}, [prefetch,
|
|
888
|
+
}, [prefetch, location]);
|
|
846
889
|
useEffect(() => () => {
|
|
847
890
|
if (timeout.current) clearTimeout(timeout.current);
|
|
848
891
|
}, []);
|
|
@@ -864,7 +907,7 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
|
|
|
864
907
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
865
908
|
event.preventDefault();
|
|
866
909
|
await beforeNavigate?.();
|
|
867
|
-
await navigate(
|
|
910
|
+
await navigate(location);
|
|
868
911
|
};
|
|
869
912
|
return as({
|
|
870
913
|
ref: elementRef,
|
|
@@ -972,9 +1015,9 @@ var useAction = router.hooks.useAction;
|
|
|
972
1015
|
//#endregion
|
|
973
1016
|
//#region hooks/useIsDataLoading.ts
|
|
974
1017
|
var useIsDataLoading = () => {
|
|
975
|
-
const {
|
|
976
|
-
const [
|
|
977
|
-
return
|
|
1018
|
+
const { useStatus } = router.hooks;
|
|
1019
|
+
const [status] = useStatus();
|
|
1020
|
+
return status === "pending";
|
|
978
1021
|
};
|
|
979
1022
|
//#endregion
|
|
980
1023
|
//#region hooks/useRouterContext.ts
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
|
|
2
|
-
export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap
|
|
2
|
+
export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Location, RevalidateCache, RouterState } from '../types';
|
|
2
|
-
export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (
|
|
2
|
+
export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (rawLocation: Location) => Promise<void>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { RevalidateCache } from '../types';
|
|
2
|
-
export declare const createPrefetch: (revalidateCache: RevalidateCache) => (
|
|
1
|
+
import { RevalidateCache, RouterState } from '../types';
|
|
2
|
+
export declare const createPrefetch: ({ routeItemDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ComponentType, type CSSProperties, Dispatch, MouseEvent, ReactElement, ReactNode, Ref, SetStateAction } from 'react';
|
|
2
2
|
import { Store, useGlobalState } from './create';
|
|
3
|
+
import { Cell } from './cell';
|
|
3
4
|
export declare const LAZY_MARKER: unique symbol;
|
|
4
5
|
export type LazyComponent = {
|
|
5
6
|
readonly [LAZY_MARKER]: true;
|
|
@@ -13,6 +14,8 @@ export type BeforeLoad = (arg: {
|
|
|
13
14
|
redirect: (arg: Location | string) => Promise<void>;
|
|
14
15
|
params: Record<string, string>;
|
|
15
16
|
setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
|
|
17
|
+
searchParams: Record<string, string>;
|
|
18
|
+
location: Location;
|
|
16
19
|
}) => Promise<unknown> | undefined | void;
|
|
17
20
|
export type ClientRouteItem = {
|
|
18
21
|
path: string;
|
|
@@ -23,6 +26,7 @@ export type ClientRouteItem = {
|
|
|
23
26
|
setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
|
|
24
27
|
searchParams: Record<string, string>;
|
|
25
28
|
signal: AbortSignal;
|
|
29
|
+
location: Location;
|
|
26
30
|
}): Promise<unknown>;
|
|
27
31
|
loaderFallback?: RenderElement;
|
|
28
32
|
errorElement?: RenderElement;
|
|
@@ -62,9 +66,8 @@ export type Location = {
|
|
|
62
66
|
};
|
|
63
67
|
export type BlockerState = 'blocked' | 'unblocked' | 'charged';
|
|
64
68
|
export type RevalidateCacheArgs = {
|
|
65
|
-
|
|
69
|
+
location: Location;
|
|
66
70
|
routeItem?: RouteItem;
|
|
67
|
-
search?: string;
|
|
68
71
|
signal?: AbortSignal;
|
|
69
72
|
};
|
|
70
73
|
export type LoaderState<T = unknown> = {
|
|
@@ -114,9 +117,10 @@ export type LoadingPromise = Promise<{
|
|
|
114
117
|
data: null;
|
|
115
118
|
error: unknown;
|
|
116
119
|
} | undefined>;
|
|
120
|
+
export type Status = 'idle' | 'pending' | 'active';
|
|
117
121
|
export type RouterState = {
|
|
118
122
|
routeItemDataState: Store<RouteItemData>;
|
|
119
|
-
|
|
123
|
+
statusState: Store<Status>;
|
|
120
124
|
scrollMapState: Store<Record<string, number>>;
|
|
121
125
|
contextState: Store<Record<string, unknown>>;
|
|
122
126
|
blockedRouteState: Store<{
|
|
@@ -125,6 +129,7 @@ export type RouterState = {
|
|
|
125
129
|
}>;
|
|
126
130
|
isOptimisticLoading: Store<boolean>;
|
|
127
131
|
loaderState: Store<LoaderState>;
|
|
132
|
+
loaderStateRef: Cell<LoaderState>;
|
|
128
133
|
loaderMap: Map<string, LoaderStateItem>;
|
|
129
134
|
loadingPromises: Map<string, LoadingPromise>;
|
|
130
135
|
};
|
|
@@ -133,7 +138,7 @@ export type RouterType = {
|
|
|
133
138
|
runtime: {
|
|
134
139
|
navigate(arg: Location): Promise<void>;
|
|
135
140
|
invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
|
|
136
|
-
prefetch(
|
|
141
|
+
prefetch(location: Location): Promise<void>;
|
|
137
142
|
};
|
|
138
143
|
hooks: {
|
|
139
144
|
useBlockedRoute: () => ReturnType<typeof useGlobalState<{
|
|
@@ -142,7 +147,7 @@ export type RouterType = {
|
|
|
142
147
|
}>>;
|
|
143
148
|
useRouteItemData: () => ReturnType<typeof useGlobalState<RouteItemData>>;
|
|
144
149
|
useScrollMap: () => ReturnType<typeof useGlobalState<Record<string, number>>>;
|
|
145
|
-
|
|
150
|
+
useStatus: () => ReturnType<typeof useGlobalState<Status>>;
|
|
146
151
|
useContextState: () => ReturnType<typeof useGlobalState<Record<string, unknown>>>;
|
|
147
152
|
useOptimisticLoading: () => ReturnType<typeof useGlobalState<boolean>>;
|
|
148
153
|
useLoaderState: <T>() => LoaderState<T>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { Location, RouteItem, RouterState } from '../types';
|
|
2
|
-
export declare const createCommitState: ({ routeItemDataState,
|
|
2
|
+
export declare const createCommitState: ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }: RouterState) => (nextLocation: Location, routeItem: RouteItem | undefined) => void;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
|
|
2
|
-
export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem,
|
|
2
|
+
export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
|
package/dist/utils/utils.d.ts
CHANGED
|
@@ -5,3 +5,10 @@ export declare const parseWindowLocation: (location: typeof window.location) =>
|
|
|
5
5
|
export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
|
|
6
6
|
export declare const isMobile: () => boolean;
|
|
7
7
|
export declare const sleep: (ms: number) => Promise<unknown>;
|
|
8
|
+
export declare const getPartialBeforeLoadArgs: (location: Location) => {
|
|
9
|
+
params: Record<string, string>;
|
|
10
|
+
context: Record<string, unknown>;
|
|
11
|
+
setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
|
|
12
|
+
searchParams: Record<string, string>;
|
|
13
|
+
location: Location;
|
|
14
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clear-react-router",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.9",
|
|
4
4
|
"description": "A lightweight, type-safe routing library for React applications",
|
|
5
5
|
"author": "Andrew Bubnov",
|
|
6
6
|
"scripts": {
|
|
@@ -16,12 +16,14 @@
|
|
|
16
16
|
"data-loading",
|
|
17
17
|
"navigation-blocker",
|
|
18
18
|
"scroll-restoration",
|
|
19
|
-
"breadcrumbs",
|
|
20
19
|
"search-params",
|
|
21
20
|
"lazy-loading",
|
|
22
21
|
"prefetching",
|
|
23
22
|
"view-transitions",
|
|
24
|
-
"animations"
|
|
23
|
+
"animations",
|
|
24
|
+
"retry",
|
|
25
|
+
"polling",
|
|
26
|
+
"cache-invalidation"
|
|
25
27
|
],
|
|
26
28
|
"repository": {
|
|
27
29
|
"type": "git",
|