clear-react-router 2.5.1 → 2.5.3

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 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
  |------|------|---------|-------------|
@@ -947,15 +994,21 @@ await invalidate(['/posts', '/profile', '/settings']);
947
994
 
948
995
  #### Dynamic routes
949
996
 
950
- When a dynamic route pattern is provided, every cached route that matches the pattern will be revalidated.
997
+ Pass a concrete dynamic pathname to revalidate only that cached route:
998
+
999
+ ```tsx
1000
+ await invalidate('/post/17');
1001
+ ```
951
1002
 
952
- For example:
1003
+ Only `/post/17` is refetched; cached `/post/1` and `/post/42` are left untouched.
1004
+
1005
+ Pass a dynamic route pattern to revalidate every cached route that matches it:
953
1006
 
954
1007
  ```tsx
955
- await invalidate('/post/[id]');
1008
+ await invalidate('/post/[id]'); // or await invalidate('/post/:id')
956
1009
  ```
957
1010
 
958
- will revalidate all cached routes such as:
1011
+ This revalidates all cached routes such as:
959
1012
 
960
1013
  ```text
961
1014
  /post/1
@@ -963,14 +1016,17 @@ will revalidate all cached routes such as:
963
1016
  /post/42
964
1017
  ```
965
1018
 
1019
+ Pattern-based invalidation is cache-only: it never sends `:param`/`[param]` to a loader.
1020
+ If no cached route matches, nothing is fetched.
1021
+
966
1022
  This also works for nested dynamic routes:
967
1023
 
968
1024
  ```tsx
969
- await invalidate('/post/[id]/comment/[id]');
1025
+ await invalidate('/post/[id]/comment/:commentId');
970
1026
  ```
971
1027
 
972
1028
  #### Force revalidation
973
- By default the exact path(s) you pass are always revalidated, even if they were never cached
1029
+ By default concrete pathnames are always revalidated, even if they were never cached
974
1030
  — this also makes `invalidate()` work on an error page with an empty cache.
975
1031
  Pass `{ force: false }` to go back to cache-only revalidation:
976
1032
 
@@ -978,8 +1034,8 @@ Pass `{ force: false }` to go back to cache-only revalidation:
978
1034
  await invalidate('/about', { force: false });
979
1035
  ```
980
1036
 
981
- Explicit `{ force: true }` behaves the same as the default; it exists for readability
982
- and for combining with other options (see below).
1037
+ Explicit `{ force: true }` behaves the same as the default for concrete paths. Pattern
1038
+ targets stay cache-only regardless of `force`.
983
1039
 
984
1040
  #### Stale-only revalidation
985
1041
  By default, `invalidate` deletes matching cache entries and refetches them.
@@ -1025,17 +1081,18 @@ will revalidate the cached child routes:
1025
1081
  ```
1026
1082
  #### Status transitions
1027
1083
 
1028
- When the revalidated path is the currently active route, a successful revalidation also
1029
- resets its status to `active`, while a failed one sets it to `error` — so recovering from
1030
- 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()`:
1031
1087
 
1032
1088
  ```tsx
1033
1089
  // On an errorElement: refetch, and show the page again on success
1034
1090
  await invalidate();
1035
1091
  ```
1036
1092
 
1037
- Revalidating any other route never touches the current page status — background refreshes
1038
- 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.
1039
1096
 
1040
1097
  #### Returns
1041
1098
 
@@ -1047,7 +1104,7 @@ Each object represents a revalidated route, where `path` is the route pathname,
1047
1104
 
1048
1105
  #### Notes
1049
1106
 
1050
- * Without `force: false`, the exact pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
1107
+ * Without `force: false`, concrete pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Dynamic patterns only revalidate cached matches and never fetch the pattern itself. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
1051
1108
  * With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
1052
1109
  * Cached data is cleared before the new loader starts.
1053
1110
  * When used as an event handler, wrap the call in an arrow function:
@@ -1256,6 +1313,32 @@ function ProductFilter() {
1256
1313
 
1257
1314
  > **Note:** `getSearchParams` returns `string` for single values, `string[]` for multiple values, and `''` if the key is not found.
1258
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
+
1259
1342
  ## Lazy Loading
1260
1343
 
1261
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
@@ -143,12 +143,19 @@ var parseWindowLocation = (location) => ({
143
143
  search: location.search,
144
144
  state: history.state ?? void 0
145
145
  });
146
+ var isParamSegment = (segment) => segment.startsWith(":") || /^\[[^\]]+]$/.test(segment);
147
+ var matchPathPattern = (pattern, pathname) => {
148
+ const patternSegments = pattern.split("/").filter(Boolean);
149
+ const pathSegments = pathname.split("/").filter(Boolean);
150
+ return patternSegments.length === pathSegments.length ? patternSegments.every((segment, index) => isParamSegment(segment) || segment === pathSegments[index]) : false;
151
+ };
146
152
  var comparePaths = (route, pathname) => {
147
153
  const pattern = route.pattern.split("/").filter(Boolean);
148
154
  const current = pathname.split("/").filter(Boolean);
149
155
  return pattern.length === current.length ? pattern.every((segment, index) => segment.startsWith(":") || segment === current[index]) : false;
150
156
  };
151
157
  var isMobile = () => {
158
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
152
159
  const hasCoarsePointer = window.matchMedia("(pointer: coarse)").matches;
153
160
  const isSmallScreen = window.matchMedia("(max-width: 768px)").matches;
154
161
  return hasCoarsePointer && isSmallScreen;
@@ -427,10 +434,13 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
427
434
  };
428
435
  //#endregion
429
436
  //#region runtime/invalidate.ts
430
- var separatePathname = (text) => text.split("?")[0];
437
+ var separatePathname = (text) => text.split("?")[0].replace(/\/+$/, "") || "/";
438
+ var normalizePath = (text) => {
439
+ const [pathname, search = ""] = text.split("?");
440
+ return `${separatePathname(pathname)}${search ? `?${search}` : ""}`;
441
+ };
431
442
  var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
432
443
  const invalidatePath = async (routeItem, pathname, options) => {
433
- const routePathname = routeDataState.getState().location.pathname;
434
444
  if (!options?.staleOnly) {
435
445
  loaderMap.delete(pathname);
436
446
  syncCacheSnapshot();
@@ -446,7 +456,8 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
446
456
  reason: "invalidate",
447
457
  force: !options?.staleOnly
448
458
  });
449
- if (result && path === routePathname) routeDataState.setState((prevState) => ({
459
+ const activeLocation = routeDataState.getState().location;
460
+ if (result && normalizePath(pathname) === normalizePath(`${activeLocation.pathname}${activeLocation.search}`)) routeDataState.setState((prevState) => ({
450
461
  ...prevState,
451
462
  loaderState: {
452
463
  data: result.data,
@@ -463,11 +474,15 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
463
474
  const invalidateItem = async (pathname, options) => {
464
475
  const routeItem = findRoute(separatePathname(pathname));
465
476
  if (!routeItem) return [];
477
+ const targetPathname = separatePathname(pathname);
478
+ const isPattern = targetPathname.split("/").filter(Boolean).some(isParamSegment);
466
479
  const pathnameSet = /* @__PURE__ */ new Set();
467
- for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
468
- const hasUnresolvedParams = separatePathname(pathname).split("/").some((segment) => segment.startsWith(":"));
480
+ for (const [key] of loaderMap) {
481
+ const keyPathname = separatePathname(key);
482
+ if (isPattern ? matchPathPattern(targetPathname, keyPathname) : keyPathname === targetPathname) pathnameSet.add(key);
483
+ }
469
484
  const implicitForce = options?.force === void 0 && !options?.staleOnly;
470
- if (options?.force === true || implicitForce && !hasUnresolvedParams) pathnameSet.add(pathname);
485
+ if (!isPattern && (options?.force === true || implicitForce)) pathnameSet.add(pathname);
471
486
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
472
487
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
473
488
  const [parentPath] = pathname.split("?");
@@ -486,7 +501,6 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
486
501
  var MOBILE_PREFETCH_CONCURRENCY = 2;
487
502
  var DESKTOP_PREFETCH_CONCURRENCY = 4;
488
503
  var createPrefetch = ({ routeDataState }, revalidateCache) => {
489
- const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
490
504
  const queue = [];
491
505
  let active = 0;
492
506
  const run = async (location) => {
@@ -502,6 +516,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
502
516
  });
503
517
  };
504
518
  const drain = () => {
519
+ const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
505
520
  while (active < maxConcurrent && queue.length) {
506
521
  active++;
507
522
  queue.shift()();
@@ -966,10 +981,12 @@ var renderElement = (Component) => {
966
981
  //#endregion
967
982
  //#region components/Router.tsx
968
983
  var EmptyBoundary = ({ children }) => children;
969
- var IS_MOBILE = isMobile();
970
984
  var MOBILE_CACHE_SIZE = 60;
971
985
  var DESKTOP_CACHE_SIZE = 150;
972
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
986
+ 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 }) => {
987
+ const isMobileDevice = isMobile();
988
+ const resolvedMaxCacheSize = maxCacheSize ?? (isMobileDevice ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE);
989
+ const resolvedDefaultPrefetch = defaultPrefetch ?? (isMobileDevice ? "viewport" : "hover");
973
990
  const { useRouteDataSelector } = router.hooks;
974
991
  const routeItem = useRouteDataSelector((state) => state.routeItem);
975
992
  const location = useRouteDataSelector((state) => state.location);
@@ -980,14 +997,14 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
980
997
  useSetRouterConfig({
981
998
  routes,
982
999
  isAnimated,
983
- defaultPrefetch,
1000
+ defaultPrefetch: resolvedDefaultPrefetch,
984
1001
  defaultHoverPrefetchDelay,
985
1002
  defaultBeforeLoad,
986
1003
  defaultAfterLoad,
987
1004
  defaultRetry,
988
1005
  defaultStaleTime,
989
1006
  defaultMinLoaderDuration,
990
- maxCacheSize,
1007
+ maxCacheSize: resolvedMaxCacheSize,
991
1008
  revalidateOnFocus,
992
1009
  revalidateOnReconnect,
993
1010
  defaultScrollRestorationBehavior,
@@ -2,6 +2,8 @@ import { Store } from '../create';
2
2
  import { Location, RouteItem, RouteData, RouterState, ScrollMap, SearchObject } from '../types';
3
3
  export declare const getParams: (location: Location, routeItem?: RouteItem) => Record<string, string>;
4
4
  export declare const parseWindowLocation: (location: typeof window.location) => Location;
5
+ export declare const isParamSegment: (segment: string) => boolean;
6
+ export declare const matchPathPattern: (pattern: string, pathname: string) => boolean;
5
7
  export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
6
8
  export declare const isMobile: () => boolean;
7
9
  export declare const sleep: (ms: number) => Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.5.1",
3
+ "version": "2.5.3",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {