clear-react-router 2.4.8 → 2.5.0

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
@@ -33,7 +33,8 @@ It provides first-class support for:
33
33
  - **Programmatic Redirects** - Redirect from beforeLoad hook
34
34
  - **Cache invalidation** - Manual route invalidation
35
35
  - **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
36
- - **Prefetching** - Preload data on hover for instant navigation
36
+ - **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `enableCacheSnapshot` and `useCacheSnapshot()`
37
+ - **Prefetching** - Preload data on hover; prefetched entries stay fresh for 30 seconds before the first navigation
37
38
  - **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
38
39
  - **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
39
40
  - **Optimistic navigation** — Instantly renders stale cached data while fresh data is loaded in the background.
@@ -73,7 +74,7 @@ Netlify (`public/_redirects`):
73
74
  | `defaultLoaderFallback` | `ReactElement \| () => ReactElement` | `optional` | Default loading fallback for every route loader |
74
75
  | `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
75
76
  | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
76
- | `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
77
+ | `defaultStaleTime` | `number` | `0` | Default time in milliseconds before cached loader data is considered stale. When unset (or `0`), data is stale immediately and navigation revalidates it |
77
78
  | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
78
79
  | `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
79
80
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
@@ -81,6 +82,7 @@ Netlify (`public/_redirects`):
81
82
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
82
83
  | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
83
84
  | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
85
+ | `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
84
86
 
85
87
  > **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
86
88
 
@@ -104,7 +106,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
104
106
  | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
105
107
  | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
106
108
  | `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
107
- | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, cached data never expires |
109
+ | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
108
110
  | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
109
111
  | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
110
112
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
@@ -248,6 +250,8 @@ When using a custom element via `as`, these attributes arrive in `props` togethe
248
250
  | `'viewport'` | Prefetches when the link enters the viewport (using Intersection Observer) |
249
251
  | `'none'` | No prefetching |
250
252
 
253
+ > A prefetched entry is considered fresh for 30 seconds. The first navigation within that window reuses it without running the loader; after that, the route's normal `staleTime` applies (by default `0`, so the next revisit revalidates). A longer route `staleTime` is never shortened by prefetching.
254
+
251
255
  ### Custom elements via `as`
252
256
 
253
257
  When using `as` to render a custom component instead of the default `<a>`, your component **must spread all received props onto the underlying host element** — including `ref`. If any prop is dropped, the corresponding feature silently stops working (no error is thrown):
@@ -538,7 +542,7 @@ const routes = createRouter([
538
542
 
539
543
  Defines route-specific actions for handling data mutations such as creating, updating, or deleting resources.
540
544
 
541
- Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the current route is automatically invalidated, causing `loader` to run again in the background.
545
+ Actions are available through the `useSubmitAction` and `useAction` hooks. After a successful action, the route where the action was triggered is automatically invalidated, causing `loader` to run again in the background.
542
546
 
543
547
  ```tsx
544
548
  actions?: ({ params, context, searchParams, setContext, location }) => ({
@@ -642,7 +646,7 @@ const handleClick = async () => await save({ data: 'Hello world!' });
642
646
  <button onClick={handleClick}>Save</button>
643
647
  ```
644
648
 
645
- `useAction` automatically invalidates the current route after a successful action, causing `loader` to run again in the background.
649
+ `useAction` automatically invalidates the route where the action was triggered after a successful action, causing `loader` to run again in the background. This remains the same route even if the user navigates away while the action is in flight.
646
650
 
647
651
  This hook is useful when the mutation is triggered programmatically, such as from dialogs, context menus, drag-and-drop interactions, keyboard shortcuts, or custom UI components.
648
652
 
@@ -823,7 +827,7 @@ beforeLoad: async ({ location, redirect }) => {
823
827
 
824
828
  ### `useLoaderState<T>()`
825
829
 
826
- Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is automatically cached and reused when navigating back to the same route.
830
+ Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is cached, but whether a revisit reuses it depends on `staleTime`: by default cached data is stale immediately and the loader runs again.
827
831
 
828
832
  **Returns:**
829
833
 
@@ -840,8 +844,7 @@ const UserProfile = () => {
840
844
 
841
845
  ### Caching behavior:
842
846
 
843
- - The loader result is cached and reused when navigating back to the same route (e.g., from /user/123 back to /user/456 it will be a new request because different params, but from /user/456 to /user/456 — cache hit).
844
- - Use `staleTime` in route config to control how long cache is considered fresh:
847
+ - The loader result is cached. Without `staleTime` (and without `defaultStaleTime`), the entry is stale immediately, so navigating back to the same route runs the loader again. Set `staleTime` to reuse data within a time window:
845
848
 
846
849
  ```tsx
847
850
  {
@@ -851,6 +854,8 @@ const UserProfile = () => {
851
854
  }
852
855
  ```
853
856
 
857
+ - Use `staleTime: Infinity` when data should stay fresh until it is explicitly invalidated, garbage-collected or evicted.
858
+
854
859
  - The cache is bounded by `maxCacheSize` — once the limit is reached, the least recently used entry is evicted to make room for a new one, regardless of whether it's still fresh. This caps memory usage for apps with many high-cardinality dynamic routes (e.g. `/product/:id` across a large catalog). It defaults to a device-aware value (lower on mobile) and can be overridden on the `Router`:
855
860
 
856
861
  ```tsx
@@ -858,6 +863,55 @@ const UserProfile = () => {
858
863
  ```
859
864
 
860
865
 
866
+ ### `useCacheSnapshot()`
867
+
868
+ Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
869
+ monitoring. Requires `<Router enableCacheSnapshot>`; while the flag is off the snapshot is empty and nothing is built.
870
+
871
+ ```tsx
872
+ import { useCacheSnapshot } from 'clear-react-router';
873
+
874
+ const CachePanel = () => {
875
+ const entries = useCacheSnapshot();
876
+
877
+ return (
878
+ <ul>
879
+ {entries.map(entry => (
880
+ <li key={entry.path}>
881
+ {entry.path} — {entry.reason ?? 'unknown'} — {entry.isLoading ? 'loading' : 'cached'}
882
+ </li>
883
+ ))}
884
+ </ul>
885
+ );
886
+ };
887
+
888
+ <Router routes={routes} enableCacheSnapshot />
889
+ ```
890
+
891
+ ```ts
892
+ type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
893
+
894
+ type CacheSnapshotEntry = {
895
+ path: string; // pathname + search
896
+ data: unknown; // loader result; undefined while the first load is in flight
897
+ timestamp: number; // when the entry was written (ms since epoch)
898
+ staleTime: number | undefined; // effective staleTime: route value, default, or 0 when neither is set
899
+ reason?: CacheReason; // what wrote the entry last
900
+ gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
901
+ gcDuration: number | undefined; // the route's gcTime, for progress display
902
+ isLoading: boolean; // a loader for this path is currently running
903
+ };
904
+
905
+ type CacheSnapshot = CacheSnapshotEntry[];
906
+ ```
907
+
908
+ Notes:
909
+
910
+ - The snapshot is a projection, not a second cache — changing it does nothing.
911
+ - Entries appear for in-flight first loads too (`data: undefined`, `isLoading: true`), so a devtool never misses a request.
912
+ - Mounting the hook refreshes the snapshot, so a panel opened after navigation still sees existing entries.
913
+ - `enableCacheSnapshot` is process-wide (the router is a singleton): if several `<Router>`s render with different values, the last rendered one wins. Enable it only when a consumer is actually mounted.
914
+
861
915
  ### `useInvalidate()`
862
916
 
863
917
  Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route `loader` again.
@@ -1276,8 +1330,9 @@ Try it live — no setup: **[clear-router playground](https://clear-react-router
1276
1330
 
1277
1331
  Scroll restoration (window + named containers), retry with attempt counts, live polling,
1278
1332
  actions with invalidation, navigation blocking, hover prefetch, optimistic navigation,
1279
- LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, search params,
1280
- and a context-based auth guard — all running against a fake in-browser server.
1333
+ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, a live cache visualizer
1334
+ (toggle it in settings), search params, and a context-based auth guard — all running against a fake
1335
+ in-browser server.
1281
1336
  Open devtools and click around.
1282
1337
 
1283
1338
  ## License
@@ -1,3 +1,3 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { RouterProps } from '../types';
3
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
3
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
@@ -13,6 +13,7 @@ declare class RouterConfig {
13
13
  defaultStaleTime?: RouterProps['defaultStaleTime'];
14
14
  defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
15
15
  defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
16
+ enableCacheSnapshot: boolean;
16
17
  configure(config: Partial<RouterConfig>): void;
17
18
  }
18
19
  export declare const routerConfig: RouterConfig;
@@ -0,0 +1,2 @@
1
+ import type { CacheSnapshot } from '../types';
2
+ export declare const useCacheSnapshot: () => CacheSnapshot;
package/dist/index.d.ts CHANGED
@@ -12,7 +12,8 @@ export { useRouterContext } from './hooks/useRouterContext';
12
12
  export { useSearchParams } from './hooks/useSearchParams';
13
13
  export { useSubmitAction } from './hooks/useSubmitAction';
14
14
  export { useRestoreScroll } from './hooks/useRestoreScroll';
15
+ export { useCacheSnapshot } from './hooks/useCacheSnapshot';
15
16
  export { createRouter } from './creators/createRouter';
16
17
  export { lazy } from './utils/lazy';
17
- export type { RouteItem, ClientRouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, } from './types';
18
+ export type { RouteItem, ClientRouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, CacheSnapshot, CacheSnapshotEntry, CacheReason, } from './types';
18
19
  export type { ElementProps, LinkProps } from './components/Link';
package/dist/index.js CHANGED
@@ -100,6 +100,7 @@ var RouterConfig = class {
100
100
  _defineProperty(this, "defaultStaleTime", void 0);
101
101
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
102
102
  _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
103
+ _defineProperty(this, "enableCacheSnapshot", false);
103
104
  }
104
105
  configure(config) {
105
106
  Object.assign(this, config);
@@ -123,8 +124,8 @@ var commitNavigation = (callback, isCommited) => {
123
124
  var createIsCacheItemFresh = (loaderMap) => (path) => {
124
125
  const item = loaderMap.get(path);
125
126
  if (item === void 0) return false;
126
- const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime;
127
- if (resolvedStaleTime === void 0) return true;
127
+ const resolvedStaleTime = item.staleTime ?? routerConfig.defaultStaleTime ?? 0;
128
+ if (resolvedStaleTime <= 0) return false;
128
129
  return Date.now() - item.timestamp <= resolvedStaleTime;
129
130
  };
130
131
  //#endregion
@@ -207,7 +208,7 @@ var findRoute = (pathname, includeAll) => {
207
208
  };
208
209
  //#endregion
209
210
  //#region runtime/navigate.ts
210
- var createNavigate = (routerState, revalidateCache) => {
211
+ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
211
212
  let navigationSeq = 0;
212
213
  let interval = 0;
213
214
  let abortController = null;
@@ -273,11 +274,18 @@ var createNavigate = (routerState, revalidateCache) => {
273
274
  const currentLoaderEntry = loaderMap.get(path);
274
275
  if (!currentLoaderEntry) return;
275
276
  if (currentLoaderEntry.gcTimeout) window.clearTimeout(currentLoaderEntry?.gcTimeout);
276
- const gcTimeout = window.setTimeout(() => loaderMap.delete(path), routeItem.gcTime);
277
+ const gcExpiresAt = Date.now() + routeItem.gcTime;
278
+ const gcTimeout = window.setTimeout(() => {
279
+ loaderMap.delete(path);
280
+ syncCacheSnapshot();
281
+ }, routeItem.gcTime);
277
282
  loaderMap.set(path, {
278
283
  ...currentLoaderEntry,
279
- gcTimeout
284
+ gcTimeout,
285
+ gcExpiresAt,
286
+ gcDuration: routeItem.gcTime
280
287
  });
288
+ syncCacheSnapshot();
281
289
  };
282
290
  const commitOptimisticState = (routeItem, location, path) => {
283
291
  const currentLoaderState = loaderMap.get(path)?.state;
@@ -317,7 +325,8 @@ var createNavigate = (routerState, revalidateCache) => {
317
325
  routeItem,
318
326
  location: nextLocation,
319
327
  signal,
320
- force: true
328
+ force: true,
329
+ reason: "polling"
321
330
  });
322
331
  if (!result || signal.aborted) return;
323
332
  const { location: currentLocation } = routeDataState.getState();
@@ -342,7 +351,8 @@ var createNavigate = (routerState, revalidateCache) => {
342
351
  const [result] = await Promise.all([revalidateCache({
343
352
  routeItem,
344
353
  location: nextLocation,
345
- signal
354
+ signal,
355
+ reason: "navigation"
346
356
  }), getLoaderDurationPromise(routeItem, nextLocation)]);
347
357
  if (seq !== navigationSeq) return;
348
358
  polling(routeItem, nextLocation);
@@ -360,12 +370,13 @@ var createNavigate = (routerState, revalidateCache) => {
360
370
  if (defaultAfterLoad) await defaultAfterLoad(args);
361
371
  };
362
372
  const checkBlocked = (nextLocation) => {
363
- if (blockerState.getState() === "charged") {
373
+ const currentState = blockerState.getState();
374
+ if (currentState === "charged") {
364
375
  blockerState.setState("blocked");
365
376
  blockedTargetState.setState(nextLocation);
366
377
  return true;
367
378
  }
368
- return false;
379
+ return currentState === "blocked";
369
380
  };
370
381
  const clearCurrentGcTimeout = (routeItem, location) => {
371
382
  const path = `${location.pathname}${location.search}`;
@@ -375,7 +386,9 @@ var createNavigate = (routerState, revalidateCache) => {
375
386
  window.clearTimeout(currentLoaderEntry.gcTimeout);
376
387
  loaderMap.set(path, {
377
388
  ...currentLoaderEntry,
378
- gcTimeout: void 0
389
+ gcTimeout: void 0,
390
+ gcExpiresAt: void 0,
391
+ gcDuration: void 0
379
392
  });
380
393
  };
381
394
  const navigate = async (rawLocation) => {
@@ -415,17 +428,23 @@ var createNavigate = (routerState, revalidateCache) => {
415
428
  //#endregion
416
429
  //#region runtime/invalidate.ts
417
430
  var separatePathname = (text) => text.split("?")[0];
418
- var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache) => {
431
+ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
419
432
  const invalidatePath = async (routeItem, pathname, options) => {
420
433
  const routePathname = routeDataState.getState().location.pathname;
421
- if (!options?.staleOnly) loaderMap.delete(pathname);
434
+ if (!options?.staleOnly) {
435
+ loaderMap.delete(pathname);
436
+ syncCacheSnapshot();
437
+ await loadingPromises.get(pathname);
438
+ }
422
439
  const [path, search = ""] = pathname.split("?");
423
440
  const result = await revalidateCache({
424
441
  routeItem,
425
442
  location: {
426
443
  pathname: path,
427
444
  search
428
- }
445
+ },
446
+ reason: "invalidate",
447
+ force: !options?.staleOnly
429
448
  });
430
449
  if (result && path === routePathname) routeDataState.setState((prevState) => ({
431
450
  ...prevState,
@@ -478,7 +497,8 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
478
497
  await item.preloadElement?.();
479
498
  await revalidateCache({
480
499
  routeItem: item,
481
- location
500
+ location,
501
+ reason: "prefetch"
482
502
  });
483
503
  };
484
504
  const drain = () => {
@@ -502,6 +522,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
502
522
  };
503
523
  //#endregion
504
524
  //#region runtime/revalidateCache.ts
525
+ var PRELOAD_STALE_TIME = 3e4;
505
526
  var isObjectRetry = (arg) => typeof arg === "object";
506
527
  var createRetry = (arg) => {
507
528
  if (arg === void 0) return null;
@@ -519,23 +540,27 @@ var getRetry = (routeItem) => {
519
540
  delay: routeRetry ? routeRetry.delay : globalRetry?.delay || 0
520
541
  };
521
542
  };
522
- var createRevalidateCache = (routerState) => {
543
+ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
523
544
  const { loaderMap, loadingPromises, contextState } = routerState;
524
545
  const flightOwners = /* @__PURE__ */ new Map();
525
546
  const evict = () => {
526
547
  if (loaderMap.size <= routerConfig.maxCacheSize) return;
527
548
  const oldestKey = loaderMap.keys().next().value;
528
- if (oldestKey) loaderMap.delete(oldestKey);
549
+ if (oldestKey) {
550
+ loaderMap.delete(oldestKey);
551
+ syncCacheSnapshot();
552
+ }
529
553
  };
530
554
  const moveItemToLastPosition = (path) => {
531
555
  const item = loaderMap.get(path);
532
556
  if (item) {
533
557
  loaderMap.delete(path);
534
558
  loaderMap.set(path, item);
559
+ syncCacheSnapshot();
535
560
  }
536
561
  return item;
537
562
  };
538
- const revalidateCache = async ({ routeItem, location, signal, force }, retried = 0) => {
563
+ const revalidateCache = async ({ routeItem, location, signal, force, reason }, retried = 0) => {
539
564
  if (!routeItem?.loader) return;
540
565
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
541
566
  const { pathname, search = "" } = location;
@@ -546,13 +571,19 @@ var createRevalidateCache = (routerState) => {
546
571
  owner.abort();
547
572
  loadingPromises.delete(path);
548
573
  flightOwners.delete(path);
574
+ syncCacheSnapshot();
549
575
  } else {
550
576
  moveItemToLastPosition(path);
551
577
  return loadingPromises.get(path);
552
578
  }
553
579
  }
554
580
  if (!force && isCacheItemFresh(path)) {
555
- const item = moveItemToLastPosition(path);
581
+ const item = loaderMap.get(path);
582
+ if (reason === "navigation" && item?.reason === "prefetch") {
583
+ item.reason = "navigation";
584
+ item.staleTime = routeItem.staleTime;
585
+ }
586
+ moveItemToLastPosition(path);
556
587
  if (!item?.state) return void 0;
557
588
  return item.state.loaderError ? {
558
589
  data: null,
@@ -575,6 +606,7 @@ var createRevalidateCache = (routerState) => {
575
606
  signal: effectiveSignal,
576
607
  attempt: retried + 1
577
608
  });
609
+ const resolvedStaleTime = routeItem.staleTime ?? routerConfig.defaultStaleTime ?? 0;
578
610
  loaderMap.set(path, {
579
611
  state: {
580
612
  data: result,
@@ -582,9 +614,11 @@ var createRevalidateCache = (routerState) => {
582
614
  loaderError: null
583
615
  },
584
616
  timestamp: Date.now(),
585
- staleTime: routeItem.staleTime
617
+ staleTime: reason === "prefetch" ? Math.max(resolvedStaleTime, PRELOAD_STALE_TIME) : routeItem.staleTime,
618
+ reason
586
619
  });
587
620
  evict();
621
+ syncCacheSnapshot();
588
622
  return {
589
623
  data: result,
590
624
  error: null
@@ -605,7 +639,8 @@ var createRevalidateCache = (routerState) => {
605
639
  routeItem,
606
640
  location,
607
641
  signal,
608
- force
642
+ force,
643
+ reason
609
644
  }, retried + 1);
610
645
  } else return {
611
646
  data: null,
@@ -615,17 +650,50 @@ var createRevalidateCache = (routerState) => {
615
650
  if (isOwner()) {
616
651
  loadingPromises.delete(path);
617
652
  flightOwners.delete(path);
653
+ syncCacheSnapshot();
618
654
  }
619
655
  }
620
656
  })();
621
657
  loadingPromises.set(path, promise);
658
+ syncCacheSnapshot();
622
659
  return promise;
623
660
  };
624
661
  return revalidateCache;
625
662
  };
626
663
  //#endregion
664
+ //#region runtime/syncCacheSnapshot.ts
665
+ var createCacheSnapshot = (loaderMap, loadingPromises) => {
666
+ const entries = [];
667
+ for (const [path, item] of loaderMap) entries.push({
668
+ path,
669
+ data: item.state?.data,
670
+ timestamp: item.timestamp,
671
+ staleTime: item.staleTime ?? routerConfig.defaultStaleTime ?? 0,
672
+ reason: item.reason,
673
+ gcExpiresAt: item.gcExpiresAt,
674
+ gcDuration: item.gcDuration,
675
+ isLoading: loadingPromises.has(path)
676
+ });
677
+ for (const path of loadingPromises.keys()) {
678
+ if (loaderMap.has(path)) continue;
679
+ entries.push({
680
+ path,
681
+ data: void 0,
682
+ timestamp: Date.now(),
683
+ staleTime: routerConfig.defaultStaleTime ?? 0,
684
+ gcExpiresAt: void 0,
685
+ gcDuration: void 0,
686
+ isLoading: true
687
+ });
688
+ }
689
+ return entries;
690
+ };
691
+ //#endregion
627
692
  //#region creators/createRouterInstance.ts
628
693
  var createRouterInstance = (synchronizer) => {
694
+ const loaderMap = /* @__PURE__ */ new Map();
695
+ const loadingPromises = /* @__PURE__ */ new Map();
696
+ const cacheSnapshotState = create([]);
629
697
  const routerState = {
630
698
  routeDataState: create({
631
699
  routeItem: void 0,
@@ -637,12 +705,16 @@ var createRouterInstance = (synchronizer) => {
637
705
  contextState: create({}),
638
706
  blockerState: create("unblocked"),
639
707
  blockedTargetState: create(null),
640
- loaderMap: /* @__PURE__ */ new Map(),
641
- loadingPromises: /* @__PURE__ */ new Map()
708
+ cacheSnapshotState,
709
+ loaderMap,
710
+ loadingPromises
711
+ };
712
+ const syncCacheSnapshot = () => {
713
+ if (routerConfig.enableCacheSnapshot) cacheSnapshotState.setState(createCacheSnapshot(loaderMap, loadingPromises));
642
714
  };
643
- const revalidateCache = createRevalidateCache(routerState);
644
- const navigate = createNavigate(routerState, revalidateCache);
645
- const invalidate = createInvalidate(routerState, revalidateCache);
715
+ const revalidateCache = createRevalidateCache(routerState, syncCacheSnapshot);
716
+ const navigate = createNavigate(routerState, revalidateCache, syncCacheSnapshot);
717
+ const invalidate = createInvalidate(routerState, revalidateCache, syncCacheSnapshot);
646
718
  const prefetch = createPrefetch(routerState, revalidateCache);
647
719
  const getCurrentAction = (actionKey) => {
648
720
  const { routeItem, location } = routerState.routeDataState.getState();
@@ -666,7 +738,8 @@ var createRouterInstance = (synchronizer) => {
666
738
  runtime: {
667
739
  navigate,
668
740
  invalidate,
669
- prefetch
741
+ prefetch,
742
+ syncCacheSnapshot
670
743
  },
671
744
  hooks: {
672
745
  useBlockerState: () => useGlobalState(routerState.blockerState, synchronizer),
@@ -716,8 +789,11 @@ var createRouterInstance = (synchronizer) => {
716
789
  useAction: (action, options = {}) => {
717
790
  return async (input) => {
718
791
  try {
719
- const data = await getCurrentAction(action)(input);
720
- await invalidate();
792
+ const currentAction = getCurrentAction(action);
793
+ const { location } = routerState.routeDataState.getState();
794
+ const path = `${location.pathname}${location.search ?? ""}`;
795
+ const data = await currentAction(input);
796
+ await invalidate(path);
721
797
  options.onSuccess?.(data);
722
798
  return {
723
799
  data,
@@ -762,6 +838,7 @@ var createRouterInstance = (synchronizer) => {
762
838
  const state = routerState.routeDataState;
763
839
  return synchronizer(state.subscribe, () => callback(state.getState()));
764
840
  },
841
+ useCacheSnapshot: () => useGlobalState(routerState.cacheSnapshotState, synchronizer)[0],
765
842
  useSetLocation: () => (location) => routerState.routeDataState.setState((prevState) => ({
766
843
  ...prevState,
767
844
  location
@@ -778,6 +855,7 @@ var useNavigation = () => {
778
855
  const { navigate } = router.runtime;
779
856
  const { useRouteDataSelector, useBlockerState } = router.hooks;
780
857
  const location = useRouteDataSelector((state) => state.location);
858
+ const skipForwardPop = useRef(false);
781
859
  const [blockerState] = useBlockerState();
782
860
  useEffect(() => {
783
861
  const handler = async (event) => {
@@ -786,7 +864,19 @@ var useNavigation = () => {
786
864
  pathname: location.pathname,
787
865
  search: location.search
788
866
  };
789
- if (blockerState === "charged") history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
867
+ if (skipForwardPop.current) {
868
+ skipForwardPop.current = false;
869
+ if (newLocation.pathname === location.pathname && (newLocation.search ?? "") === (location.search ?? "")) return;
870
+ }
871
+ if (blockerState === "charged" || blockerState === "blocked") {
872
+ skipForwardPop.current = true;
873
+ if (blockerState === "charged") await navigate({
874
+ ...newLocation,
875
+ prevLocation
876
+ });
877
+ history.forward();
878
+ return;
879
+ }
790
880
  await navigate({
791
881
  ...newLocation,
792
882
  prevLocation
@@ -875,7 +965,7 @@ var EmptyBoundary = ({ children }) => children;
875
965
  var IS_MOBILE = isMobile();
876
966
  var MOBILE_CACHE_SIZE = 60;
877
967
  var DESKTOP_CACHE_SIZE = 150;
878
- 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 }) => {
968
+ 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 }) => {
879
969
  const { useRouteDataSelector } = router.hooks;
880
970
  const routeItem = useRouteDataSelector((state) => state.routeItem);
881
971
  const location = useRouteDataSelector((state) => state.location);
@@ -896,7 +986,8 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
896
986
  maxCacheSize,
897
987
  revalidateOnFocus,
898
988
  revalidateOnReconnect,
899
- defaultScrollRestorationBehavior
989
+ defaultScrollRestorationBehavior,
990
+ enableCacheSnapshot
900
991
  });
901
992
  useApplyCustomAnimation(animationDuration);
902
993
  useSetInitialContext(initialContext);
@@ -922,15 +1013,15 @@ var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
922
1013
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
923
1014
  var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
924
1015
  const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
1016
+ const searchString = typeof search === "object" ? formatSearchObject(search) : search;
925
1017
  const { useRouteDataSelector } = router.hooks;
926
- const isPending = useRouteDataSelector(({ location: { pathname: currentPathname }, status }) => currentPathname === pathname && status === "pending");
1018
+ const isPending = useRouteDataSelector(({ location: { pathname: currentPathname, search: currentSearch = "" }, status }) => currentPathname === pathname && currentSearch === searchString && status === "pending");
927
1019
  const navigate = useNavigate();
928
1020
  const isActive = useRouteDataSelector(({ location: { pathname: currentPathname } }) => comparator(pathname, currentPathname, exact));
929
1021
  const timeout = useRef(0);
930
1022
  const elementRef = useRef(null);
931
1023
  const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
932
1024
  const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
933
- const searchString = typeof search === "object" ? formatSearchObject(search) : search;
934
1025
  const location = useMemo(() => ({
935
1026
  pathname,
936
1027
  search: searchString,
@@ -1086,11 +1177,15 @@ var useBlocker = (blockerFn) => {
1086
1177
  return {
1087
1178
  state: blockerState,
1088
1179
  process: useCallback(async () => {
1089
- if (nextLocation) await navigate(nextLocation);
1180
+ if (!nextLocation) return;
1181
+ const target = nextLocation;
1182
+ setBlockerState("unblocked");
1183
+ await navigate(target);
1090
1184
  setNextLocation(null);
1091
1185
  }, [
1092
1186
  navigate,
1093
1187
  nextLocation,
1188
+ setBlockerState,
1094
1189
  setNextLocation
1095
1190
  ]),
1096
1191
  reset: useCallback(() => {
@@ -1189,6 +1284,13 @@ var useSubmitAction = (action, options) => {
1189
1284
  };
1190
1285
  };
1191
1286
  //#endregion
1287
+ //#region hooks/useCacheSnapshot.ts
1288
+ var useCacheSnapshot = () => {
1289
+ const snapshot = router.hooks.useCacheSnapshot();
1290
+ useEffect(() => router.runtime.syncCacheSnapshot(), []);
1291
+ return snapshot;
1292
+ };
1293
+ //#endregion
1192
1294
  //#region utils/createLazyComponent.tsx
1193
1295
  var createLazyComponent = (importFn, fallback) => {
1194
1296
  const load = () => importFn().then((module) => ({ default: module.default || module }));
@@ -1230,4 +1332,4 @@ var lazy = (importFn) => ({
1230
1332
  importFn
1231
1333
  });
1232
1334
  //#endregion
1233
- export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
1335
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useCacheSnapshot, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeDataState, loaderMap, loadingPromises }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (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) => (rawLocation: Location) => Promise<void>;
2
+ export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (rawLocation: Location) => Promise<void>;
@@ -1,2 +1,2 @@
1
1
  import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
2
- export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal, force }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
2
+ export declare const createRevalidateCache: (routerState: RouterState, syncCacheSnapshot: () => void) => ({ routeItem, location, signal, force, reason }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
@@ -0,0 +1,2 @@
1
+ import { CacheSnapshot, LoaderStateItem, LoadingPromise } from '../types';
2
+ export declare const createCacheSnapshot: (loaderMap: Map<string, LoaderStateItem>, loadingPromises: Map<string, LoadingPromise>) => CacheSnapshot;
package/dist/types.d.ts CHANGED
@@ -63,11 +63,13 @@ export type Location = {
63
63
  prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
64
64
  };
65
65
  export type BlockerState = 'blocked' | 'unblocked' | 'charged';
66
+ export type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
66
67
  export type RevalidateCacheArgs = {
67
68
  location: Location;
68
69
  routeItem?: RouteItem;
69
70
  signal?: AbortSignal;
70
71
  force?: boolean;
72
+ reason?: CacheReason;
71
73
  };
72
74
  export type LoaderState<T = unknown> = {
73
75
  data: T;
@@ -105,13 +107,29 @@ export type RouterProps = {
105
107
  revalidateOnFocus?: boolean;
106
108
  revalidateOnReconnect?: boolean;
107
109
  context?: Record<string, unknown>;
110
+ /** Enables cache snapshot tracking for devtools. `useCacheSnapshot` returns an empty list without it. */
111
+ enableCacheSnapshot?: boolean;
108
112
  };
109
113
  export type LoaderStateItem = {
110
114
  state: LoaderState;
111
115
  timestamp: number;
112
116
  staleTime: number | undefined;
117
+ reason?: CacheReason;
113
118
  gcTimeout?: number;
119
+ gcExpiresAt?: number;
120
+ gcDuration?: number;
114
121
  };
122
+ export type CacheSnapshotEntry = {
123
+ path: string;
124
+ data: unknown;
125
+ timestamp: number;
126
+ staleTime: number | undefined;
127
+ reason?: CacheReason;
128
+ gcExpiresAt: number | undefined;
129
+ gcDuration: number | undefined;
130
+ isLoading: boolean;
131
+ };
132
+ export type CacheSnapshot = CacheSnapshotEntry[];
115
133
  export type LoadingPromise = Promise<{
116
134
  data: unknown;
117
135
  error: null;
@@ -126,6 +144,7 @@ export type RouterState = {
126
144
  contextState: Store<Record<string, unknown>>;
127
145
  blockerState: Store<BlockerState>;
128
146
  blockedTargetState: Store<Location | null>;
147
+ cacheSnapshotState: Store<CacheSnapshot>;
129
148
  loaderMap: Map<string, LoaderStateItem>;
130
149
  loadingPromises: Map<string, LoadingPromise>;
131
150
  };
@@ -134,6 +153,7 @@ export type RouterType = {
134
153
  navigate(arg: Location): Promise<void>;
135
154
  invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
136
155
  prefetch(location: Location, signal?: AbortSignal): Promise<void>;
156
+ syncCacheSnapshot(): void;
137
157
  };
138
158
  hooks: {
139
159
  useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
@@ -151,6 +171,7 @@ export type RouterType = {
151
171
  }>;
152
172
  useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
153
173
  useRouteDataSelector<T>(callback: (arg: RouteData) => T): T;
174
+ useCacheSnapshot(): CacheSnapshot;
154
175
  useSetLocation(): (location: Location) => void;
155
176
  };
156
177
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.8",
3
+ "version": "2.5.0",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {