clear-react-router 2.5.2 → 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.
Files changed (3) hide show
  1. package/README.md +81 -7
  2. package/dist/index.js +14 -7
  3. 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 is the currently active route, a successful revalidation also
1038
- resets its status to `active`, while a failed one sets it to `error` — so recovering from
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 — background refreshes
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;
@@ -434,9 +435,12 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
434
435
  //#endregion
435
436
  //#region runtime/invalidate.ts
436
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
+ };
437
442
  var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
438
443
  const invalidatePath = async (routeItem, pathname, options) => {
439
- const routePathname = routeDataState.getState().location.pathname;
440
444
  if (!options?.staleOnly) {
441
445
  loaderMap.delete(pathname);
442
446
  syncCacheSnapshot();
@@ -452,7 +456,8 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
452
456
  reason: "invalidate",
453
457
  force: !options?.staleOnly
454
458
  });
455
- 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) => ({
456
461
  ...prevState,
457
462
  loaderState: {
458
463
  data: result.data,
@@ -496,7 +501,6 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
496
501
  var MOBILE_PREFETCH_CONCURRENCY = 2;
497
502
  var DESKTOP_PREFETCH_CONCURRENCY = 4;
498
503
  var createPrefetch = ({ routeDataState }, revalidateCache) => {
499
- const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
500
504
  const queue = [];
501
505
  let active = 0;
502
506
  const run = async (location) => {
@@ -512,6 +516,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
512
516
  });
513
517
  };
514
518
  const drain = () => {
519
+ const maxConcurrent = isMobile() ? MOBILE_PREFETCH_CONCURRENCY : DESKTOP_PREFETCH_CONCURRENCY;
515
520
  while (active < maxConcurrent && queue.length) {
516
521
  active++;
517
522
  queue.shift()();
@@ -976,10 +981,12 @@ var renderElement = (Component) => {
976
981
  //#endregion
977
982
  //#region components/Router.tsx
978
983
  var EmptyBoundary = ({ children }) => children;
979
- var IS_MOBILE = isMobile();
980
984
  var MOBILE_CACHE_SIZE = 60;
981
985
  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 = 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");
983
990
  const { useRouteDataSelector } = router.hooks;
984
991
  const routeItem = useRouteDataSelector((state) => state.routeItem);
985
992
  const location = useRouteDataSelector((state) => state.location);
@@ -990,14 +997,14 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
990
997
  useSetRouterConfig({
991
998
  routes,
992
999
  isAnimated,
993
- defaultPrefetch,
1000
+ defaultPrefetch: resolvedDefaultPrefetch,
994
1001
  defaultHoverPrefetchDelay,
995
1002
  defaultBeforeLoad,
996
1003
  defaultAfterLoad,
997
1004
  defaultRetry,
998
1005
  defaultStaleTime,
999
1006
  defaultMinLoaderDuration,
1000
- maxCacheSize,
1007
+ maxCacheSize: resolvedMaxCacheSize,
1001
1008
  revalidateOnFocus,
1002
1009
  revalidateOnReconnect,
1003
1010
  defaultScrollRestorationBehavior,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.5.2",
3
+ "version": "2.5.3",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {