clear-react-router 2.5.2 → 2.5.4
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 +81 -7
- package/dist/index.js +33 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -58,6 +58,8 @@ Netlify (`public/_redirects`):
|
|
|
58
58
|
/* /index.html 200
|
|
59
59
|
```
|
|
60
60
|
|
|
61
|
+
The host rewrite only serves the app shell. To render your own UI for unknown client-side URLs, add a router-level catch-all — see [Catch-all / 404](#catch-all--404).
|
|
62
|
+
|
|
61
63
|
## API
|
|
62
64
|
|
|
63
65
|
### `Router`
|
|
@@ -94,7 +96,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
|
|
|
94
96
|
|
|
95
97
|
| Property | Type | Description |
|
|
96
98
|
|----------|------|-------------|
|
|
97
|
-
| `path` | `string` | Route path, e.g., `/user/:userId
|
|
99
|
+
| `path` | `string` | Route path, e.g., `/user/:userId`. A child path is appended to the parent pattern — see [Nested routes](#nested-routes) |
|
|
98
100
|
| `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
|
|
99
101
|
| `layout` | Component that accepts `children` | Wraps this route's element and is inherited by every descendant route. A descendant's own `layout` nests *inside* the inherited ones (see [Layouts](#layouts)) |
|
|
100
102
|
| `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 |
|
|
@@ -134,6 +136,8 @@ see [`Location`](#uselocation) and [`Where you came from`](#where-you-came-from)
|
|
|
134
136
|
```
|
|
135
137
|
see [`redirect`](#redirect) for details on programmatic redirects
|
|
136
138
|
|
|
139
|
+
> `beforeLoad` runs only for the route that matched the URL (plus the global `Router.defaultBeforeLoad`). It is **not inherited** from parent routes — put an auth guard on the leaf route or use `defaultBeforeLoad` for app-wide checks.
|
|
140
|
+
|
|
137
141
|
`loader` additionally receives:
|
|
138
142
|
```ts
|
|
139
143
|
{
|
|
@@ -144,6 +148,49 @@ see [`redirect`](#redirect) for details on programmatic redirects
|
|
|
144
148
|
> **Note:** `gcTime` is independent from `staleTime` — `staleTime` controls when cached data is considered outdated (and needs a refetch), while `gcTime` controls how long the cache entry stays in memory at all once you leave that route. Data can be fresh and still get garbage-collected, or stale and still linger in memory, depending on which you set. The timer starts only when you navigate away from the route and is cancelled if you come back before it fires — it isn't affected by prefetching. This is mainly useful for routes with heavy or fast-changing data (large tables, dashboards with charts) that you don't want lingering in memory indefinitely, even when `maxCacheSize` hasn't been reached yet.
|
|
145
149
|
If a route is both `optimistic` and has `gcTime` set, keep in mind the cached snapshot can disappear while you're relying on it for an instant render — combine the two deliberately, not by default.
|
|
146
150
|
|
|
151
|
+
### Nested routes
|
|
152
|
+
|
|
153
|
+
A child `path` is **appended to the parent pattern**. Write only the new segment(s), not a full absolute path:
|
|
154
|
+
|
|
155
|
+
```tsx
|
|
156
|
+
const routes = createRouter([
|
|
157
|
+
{
|
|
158
|
+
path: '/projects',
|
|
159
|
+
element: <Projects />,
|
|
160
|
+
children: [
|
|
161
|
+
{ path: ':projectId', element: <Project /> }, // -> /projects/:projectId
|
|
162
|
+
{ path: 'new', element: <NewProject /> }, // -> /projects/new
|
|
163
|
+
],
|
|
164
|
+
},
|
|
165
|
+
]);
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
A leading `/` is tolerated — `settings` and `/settings` produce the same pattern — but it does **not** make the path absolute. Repeating the parent prefix creates a wrong pattern:
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
// ❌ becomes /projects/projects/p-2 — no URL matches it
|
|
172
|
+
{ path: '/projects', children: [{ path: '/projects/p-2', element: <Project /> }] }
|
|
173
|
+
|
|
174
|
+
// ✅ /projects/p-2
|
|
175
|
+
{ path: '/projects', children: [{ path: ':projectId', element: <Project /> }] }
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
In development, `createRouter` warns when a child path repeats the parent prefix, and the router warns when a navigation matches no route. To render a UI for unknown URLs, add a catch-all route.
|
|
179
|
+
|
|
180
|
+
### Catch-all / 404
|
|
181
|
+
|
|
182
|
+
Add one route with `path: '*'` as the **last** entry. It matches any depth:
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
const routes = createRouter([
|
|
186
|
+
{ path: '/', element: <Home /> },
|
|
187
|
+
// ...other routes
|
|
188
|
+
{ path: '*', element: <NotFound /> },
|
|
189
|
+
]);
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
`/:notFound` matches exactly one segment; `path: '*'` is the single catch-all for all unknown URLs. Keep it last so it doesn't shadow real routes.
|
|
193
|
+
|
|
147
194
|
### Layouts
|
|
148
195
|
|
|
149
196
|
A route can declare a `layout`: a component that wraps the route's element and is **inherited by every descendant route**. Layouts **stack**: a descendant's own `layout` nests *inside* the inherited ones, outermost first. Use it for chrome and state that must survive navigation within a subtree — an app shell, a section navbar, tabs, a scroll container, a wizard.
|
|
@@ -200,7 +247,7 @@ Component for client-side navigation with prefetch support, active state detecti
|
|
|
200
247
|
|
|
201
248
|
Rule of thumb: `to` for plain URLs, `path` + `params` when you want the pattern checked and segments URL-encoded.
|
|
202
249
|
|
|
203
|
-
Active matching: `'/'` matches only exactly `'/'`; any other target is active on exact match or — with the default `exact={false}` — on nested URLs too (`/settings` is active at `/settings/profile`).
|
|
250
|
+
Active matching: `'/'` matches only exactly `'/'`; any other target is active on exact match or — with the default `exact={false}` — on nested URLs too (`/settings` is active at `/settings/profile`). Pass `exact` on contextual links (for example a back-link to `/settings`) when a child URL should not keep the link active.
|
|
204
251
|
|
|
205
252
|
| Prop | Type | Default | Description |
|
|
206
253
|
|------|------|---------|-------------|
|
|
@@ -1034,17 +1081,18 @@ will revalidate the cached child routes:
|
|
|
1034
1081
|
```
|
|
1035
1082
|
#### Status transitions
|
|
1036
1083
|
|
|
1037
|
-
When the revalidated path
|
|
1038
|
-
resets its status to `active`, while a failed one sets it to `error` — so
|
|
1039
|
-
an error page is just `await invalidate()`:
|
|
1084
|
+
When the revalidated path matches the currently active `pathname + search`, a successful
|
|
1085
|
+
revalidation also resets its status to `active`, while a failed one sets it to `error` — so
|
|
1086
|
+
recovering from an error page is just `await invalidate()`:
|
|
1040
1087
|
|
|
1041
1088
|
```tsx
|
|
1042
1089
|
// On an errorElement: refetch, and show the page again on success
|
|
1043
1090
|
await invalidate();
|
|
1044
1091
|
```
|
|
1045
1092
|
|
|
1046
|
-
Revalidating any other route never touches the current page status —
|
|
1047
|
-
stay invisible.
|
|
1093
|
+
Revalidating any other route or search variant never touches the current page status —
|
|
1094
|
+
background refreshes stay invisible. Note that invalidating a pathname revalidates every
|
|
1095
|
+
cached search variant of that pathname.
|
|
1048
1096
|
|
|
1049
1097
|
#### Returns
|
|
1050
1098
|
|
|
@@ -1265,6 +1313,32 @@ function ProductFilter() {
|
|
|
1265
1313
|
|
|
1266
1314
|
> **Note:** `getSearchParams` returns `string` for single values, `string[]` for multiple values, and `''` if the key is not found.
|
|
1267
1315
|
|
|
1316
|
+
> **Note:** `setSearchParams` replaces the current history entry in place and does **not** run the route `loader` again. If the loader depends on query params, opt in explicitly:
|
|
1317
|
+
|
|
1318
|
+
```tsx
|
|
1319
|
+
function ProductFilter() {
|
|
1320
|
+
const { searchParams, setSearchParams } = useSearchParams();
|
|
1321
|
+
const { pathname } = useLocation();
|
|
1322
|
+
const navigate = useNavigate();
|
|
1323
|
+
const invalidate = useInvalidate();
|
|
1324
|
+
|
|
1325
|
+
// Full navigation: runs beforeLoad / loader / afterLoad and pushes a history entry
|
|
1326
|
+
const applyFilter = () => {
|
|
1327
|
+
const next = new URLSearchParams(searchParams);
|
|
1328
|
+
next.set('brand', 'nike');
|
|
1329
|
+
navigate({ pathname, search: `?${next.toString()}` });
|
|
1330
|
+
};
|
|
1331
|
+
|
|
1332
|
+
// Explicit revalidation: keeps the history entry, reruns the loader, skips beforeLoad / afterLoad
|
|
1333
|
+
const revalidateFilter = async () => {
|
|
1334
|
+
setSearchParams('brand', 'nike');
|
|
1335
|
+
await invalidate();
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
```
|
|
1339
|
+
|
|
1340
|
+
`invalidate()` revalidates every cached search variant of the pathname; only the variant matching the active `pathname + search` updates the current loader state.
|
|
1341
|
+
|
|
1268
1342
|
## Lazy Loading
|
|
1269
1343
|
|
|
1270
1344
|
Clear Router supports code-splitting out of the box. Simply wrap dynamic import into a library's `lazy` function:
|
package/dist/index.js
CHANGED
|
@@ -155,6 +155,7 @@ var comparePaths = (route, pathname) => {
|
|
|
155
155
|
return pattern.length === current.length ? pattern.every((segment, index) => segment.startsWith(":") || segment === current[index]) : false;
|
|
156
156
|
};
|
|
157
157
|
var isMobile = () => {
|
|
158
|
+
if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
|
|
158
159
|
const hasCoarsePointer = window.matchMedia("(pointer: coarse)").matches;
|
|
159
160
|
const isSmallScreen = window.matchMedia("(max-width: 768px)").matches;
|
|
160
161
|
return hasCoarsePointer && isSmallScreen;
|
|
@@ -372,8 +373,16 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
|
|
|
372
373
|
params,
|
|
373
374
|
searchParams
|
|
374
375
|
};
|
|
375
|
-
if (routeItem?.afterLoad)
|
|
376
|
-
|
|
376
|
+
if (routeItem?.afterLoad) try {
|
|
377
|
+
await routeItem.afterLoad(args);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
console.error("[clear-router] Route afterLoad failed:", error);
|
|
380
|
+
}
|
|
381
|
+
if (defaultAfterLoad) try {
|
|
382
|
+
await defaultAfterLoad(args);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
console.error("[clear-router] Default afterLoad failed:", error);
|
|
385
|
+
}
|
|
377
386
|
};
|
|
378
387
|
const checkBlocked = (nextLocation) => {
|
|
379
388
|
const currentState = blockerState.getState();
|
|
@@ -434,9 +443,12 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
|
|
|
434
443
|
//#endregion
|
|
435
444
|
//#region runtime/invalidate.ts
|
|
436
445
|
var separatePathname = (text) => text.split("?")[0].replace(/\/+$/, "") || "/";
|
|
446
|
+
var normalizePath = (text) => {
|
|
447
|
+
const [pathname, search = ""] = text.split("?");
|
|
448
|
+
return `${separatePathname(pathname)}${search ? `?${search}` : ""}`;
|
|
449
|
+
};
|
|
437
450
|
var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
|
|
438
451
|
const invalidatePath = async (routeItem, pathname, options) => {
|
|
439
|
-
const routePathname = routeDataState.getState().location.pathname;
|
|
440
452
|
if (!options?.staleOnly) {
|
|
441
453
|
loaderMap.delete(pathname);
|
|
442
454
|
syncCacheSnapshot();
|
|
@@ -452,7 +464,8 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
|
|
|
452
464
|
reason: "invalidate",
|
|
453
465
|
force: !options?.staleOnly
|
|
454
466
|
});
|
|
455
|
-
|
|
467
|
+
const activeLocation = routeDataState.getState().location;
|
|
468
|
+
if (result && normalizePath(pathname) === normalizePath(`${activeLocation.pathname}${activeLocation.search}`)) routeDataState.setState((prevState) => ({
|
|
456
469
|
...prevState,
|
|
457
470
|
loaderState: {
|
|
458
471
|
data: result.data,
|
|
@@ -496,7 +509,6 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
|
|
|
496
509
|
var MOBILE_PREFETCH_CONCURRENCY = 2;
|
|
497
510
|
var DESKTOP_PREFETCH_CONCURRENCY = 4;
|
|
498
511
|
var createPrefetch = ({ routeDataState }, revalidateCache) => {
|
|
499
|
-
const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
|
|
500
512
|
const queue = [];
|
|
501
513
|
let active = 0;
|
|
502
514
|
const run = async (location) => {
|
|
@@ -512,6 +524,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
|
|
|
512
524
|
});
|
|
513
525
|
};
|
|
514
526
|
const drain = () => {
|
|
527
|
+
const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
|
|
515
528
|
while (active < maxConcurrent && queue.length) {
|
|
516
529
|
active++;
|
|
517
530
|
queue.shift()();
|
|
@@ -579,8 +592,9 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
579
592
|
const path = `${pathname}${search}`;
|
|
580
593
|
if (loadingPromises.has(path)) {
|
|
581
594
|
const owner = flightOwners.get(path);
|
|
582
|
-
|
|
583
|
-
|
|
595
|
+
const ownerWasAborted = owner instanceof AbortController ? owner.signal.aborted : owner?.aborted;
|
|
596
|
+
if (signal && owner instanceof AbortController || ownerWasAborted) {
|
|
597
|
+
if (owner instanceof AbortController) owner.abort();
|
|
584
598
|
loadingPromises.delete(path);
|
|
585
599
|
flightOwners.delete(path);
|
|
586
600
|
syncCacheSnapshot();
|
|
@@ -618,6 +632,10 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
618
632
|
signal: effectiveSignal,
|
|
619
633
|
attempt: retried + 1
|
|
620
634
|
});
|
|
635
|
+
if (!isOwner() || effectiveSignal.aborted) return {
|
|
636
|
+
data: null,
|
|
637
|
+
error: null
|
|
638
|
+
};
|
|
621
639
|
const resolvedStaleTime = routeItem.staleTime ?? routerConfig.defaultStaleTime ?? 0;
|
|
622
640
|
loaderMap.set(path, {
|
|
623
641
|
state: {
|
|
@@ -636,7 +654,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
|
|
|
636
654
|
error: null
|
|
637
655
|
};
|
|
638
656
|
} catch (error) {
|
|
639
|
-
if (effectiveSignal.aborted) return {
|
|
657
|
+
if (effectiveSignal.aborted || !isOwner()) return {
|
|
640
658
|
data: null,
|
|
641
659
|
error: null
|
|
642
660
|
};
|
|
@@ -976,28 +994,29 @@ var renderElement = (Component) => {
|
|
|
976
994
|
//#endregion
|
|
977
995
|
//#region components/Router.tsx
|
|
978
996
|
var EmptyBoundary = ({ children }) => children;
|
|
979
|
-
var IS_MOBILE = isMobile();
|
|
980
997
|
var MOBILE_CACHE_SIZE = 60;
|
|
981
998
|
var DESKTOP_CACHE_SIZE = 150;
|
|
982
|
-
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize
|
|
999
|
+
var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
|
|
1000
|
+
const isMobileDevice = isMobile();
|
|
1001
|
+
const resolvedMaxCacheSize = maxCacheSize ?? (isMobileDevice ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE);
|
|
1002
|
+
const resolvedDefaultPrefetch = defaultPrefetch ?? (isMobileDevice ? "viewport" : "hover");
|
|
983
1003
|
const { useRouteDataSelector } = router.hooks;
|
|
984
1004
|
const routeItem = useRouteDataSelector((state) => state.routeItem);
|
|
985
1005
|
const location = useRouteDataSelector((state) => state.location);
|
|
986
1006
|
const status = useRouteDataSelector((state) => state.status);
|
|
987
1007
|
const isError = status === "error";
|
|
988
1008
|
const isLoading = status === "pending";
|
|
989
|
-
useNavigation();
|
|
990
1009
|
useSetRouterConfig({
|
|
991
1010
|
routes,
|
|
992
1011
|
isAnimated,
|
|
993
|
-
defaultPrefetch,
|
|
1012
|
+
defaultPrefetch: resolvedDefaultPrefetch,
|
|
994
1013
|
defaultHoverPrefetchDelay,
|
|
995
1014
|
defaultBeforeLoad,
|
|
996
1015
|
defaultAfterLoad,
|
|
997
1016
|
defaultRetry,
|
|
998
1017
|
defaultStaleTime,
|
|
999
1018
|
defaultMinLoaderDuration,
|
|
1000
|
-
maxCacheSize,
|
|
1019
|
+
maxCacheSize: resolvedMaxCacheSize,
|
|
1001
1020
|
revalidateOnFocus,
|
|
1002
1021
|
revalidateOnReconnect,
|
|
1003
1022
|
defaultScrollRestorationBehavior,
|
|
@@ -1007,6 +1026,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
|
|
|
1007
1026
|
useSetInitialContext(initialContext);
|
|
1008
1027
|
useRestoreRouteScroll(defaultScrollRestorationBehavior);
|
|
1009
1028
|
useReload();
|
|
1029
|
+
useNavigation();
|
|
1010
1030
|
const loadingContent = isLoading && !isError;
|
|
1011
1031
|
if (!routeItem) return renderElement(loadingContent ? defaultLoaderFallback : void 0);
|
|
1012
1032
|
const content = loadingContent ? renderElement(routeItem.loaderFallback || defaultLoaderFallback) : isError ? renderElement(routeItem.errorElement || defaultErrorElement) : /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname);
|