clear-react-router 2.1.6 → 2.1.8

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,7 +58,8 @@ It provides first-class support for:
58
58
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
59
59
  | `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
60
60
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
61
-
61
+ | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
62
+ | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
62
63
 
63
64
  > **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.
64
65
 
@@ -497,14 +498,10 @@ Return value:
497
498
  | Argument | Type | Description |
498
499
  |----------|------|-------------|
499
500
  | `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
500
- | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails and `withBeforeLoad` value to set route's `beforeLoad` to run. |
501
+ | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
501
502
 
502
503
  ```ts
503
- type Options = Partial<{
504
- onSuccess: (args: unknown) => void;
505
- onError: (args: unknown) => void;
506
- withBeforeLoad?: boolean;
507
- }> | undefined;
504
+ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void }> | undefined;
508
505
  ```
509
506
 
510
507
  ```tsx
@@ -619,7 +616,7 @@ const UserProfile = () => {
619
616
 
620
617
  ### `useInvalidate()`
621
618
 
622
- Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route loader again.
619
+ Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route `loader` again.
623
620
 
624
621
  #### Current route
625
622
 
@@ -680,6 +677,13 @@ await invalidate('/about', { force: true });
680
677
  await invalidate(['/about', '/post/10'], { force: true });
681
678
  ```
682
679
 
680
+ #### Stale-only revalidation
681
+ By default, `invalidate` deletes matching cache entries and refetches them.
682
+ Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
683
+ ```tsx
684
+ await invalidate('/notes', { staleOnly: true });
685
+ ```
686
+
683
687
  #### Including child routes
684
688
 
685
689
  To revalidate routes together with their cached child routes, pass the `withChildren` option:
@@ -713,15 +717,6 @@ will revalidate the cached child routes:
713
717
  /post/23
714
718
  /post/42/comments
715
719
  ```
716
- #### Including `beforeLoad`
717
-
718
- To include the `beforeLoad` function in the revalidation process, pass the `withBeforeLoad` option:
719
-
720
- ```tsx
721
- await invalidate('/posts', { withBeforeLoad: true });
722
- await invalidate(['/posts', '/users'], { withBeforeLoad: true });
723
- ```
724
-
725
720
  #### Returns
726
721
 
727
722
  An array of objects with the following structure:
@@ -1,2 +1,2 @@
1
1
  import { RouterProps } from '../types';
2
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, optimisticSpinner, defaultMinLoaderDuration, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
2
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, optimisticSpinner, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
@@ -4,6 +4,8 @@ declare class RouterConfig {
4
4
  maxCacheSize: number;
5
5
  defaultPrefetch: RouterProps['defaultPrefetch'];
6
6
  isAnimated: RouterProps['isAnimated'];
7
+ revalidateOnFocus: boolean;
8
+ revalidateOnReconnect: boolean;
7
9
  defaultHoverPrefetchDelay: number;
8
10
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
9
11
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
@@ -0,0 +1 @@
1
+ export declare const useReload: () => void;
package/dist/index.js CHANGED
@@ -30,13 +30,13 @@ var useGlobalState = ({ subscribe, getState, setState }) => {
30
30
  };
31
31
  //#endregion
32
32
  //#region utils/commitState.ts
33
- var createCommitState = ({ statusState, loaderStateRef, loaderState, routeItemDataState }) => (nextLocation, routeItem) => {
34
- if (!routeItem?.loader) routeItemDataState.setState({
33
+ var createCommitState = ({ loaderStateRef, loaderState, routeItemDataState }) => (nextLocation, routeItem) => {
34
+ const isError = loaderStateRef.value.loaderError || loaderStateRef.value.beforeLoadError;
35
+ routeItemDataState.setState({
35
36
  routeItem,
36
- location: nextLocation
37
+ location: nextLocation,
38
+ status: isError ? "error" : "active"
37
39
  });
38
- const isError = loaderStateRef.value.loaderError || loaderStateRef.value.beforeLoadError;
39
- statusState.setState(isError ? "error" : "active");
40
40
  loaderState.setState(loaderStateRef.value);
41
41
  if ((nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname) === window.location.pathname + window.location.search) return;
42
42
  history.pushState(null, "", `${nextLocation.pathname}${nextLocation.search}`);
@@ -92,6 +92,8 @@ var RouterConfig = class {
92
92
  _defineProperty(this, "maxCacheSize", 0);
93
93
  _defineProperty(this, "defaultPrefetch", "hover");
94
94
  _defineProperty(this, "isAnimated", false);
95
+ _defineProperty(this, "revalidateOnFocus", false);
96
+ _defineProperty(this, "revalidateOnReconnect", false);
95
97
  _defineProperty(this, "defaultHoverPrefetchDelay", 150);
96
98
  _defineProperty(this, "defaultBeforeLoad", void 0);
97
99
  _defineProperty(this, "defaultAfterLoad", void 0);
@@ -217,7 +219,7 @@ var createNavigate = (routerState, revalidateCache) => {
217
219
  let navigationSeq = 0;
218
220
  let interval = 0;
219
221
  let abortController = null;
220
- const { loaderState, loaderStateRef, statusState, contextState, loaderMap, routeItemDataState, scrollMapState } = routerState;
222
+ const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState } = routerState;
221
223
  const commitState = createCommitState(routerState);
222
224
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
223
225
  const createSignal = () => {
@@ -263,18 +265,22 @@ var createNavigate = (routerState, revalidateCache) => {
263
265
  };
264
266
  const prepareNavigation = (routeItem, location) => {
265
267
  updateScrollMap(routeItemDataState, scrollMapState);
266
- if (routeItem?.loader) routeItemDataState.setState({
267
- routeItem,
268
- location
269
- });
270
268
  const path = getPath(location);
271
269
  if (routeItem?.optimistic && loaderMap.has(path)) {
272
- statusState.setState("optimistic");
270
+ commitNavigation(() => routeItemDataState.setState({
271
+ routeItem,
272
+ location,
273
+ status: "optimistic"
274
+ }));
273
275
  const currentLoaderState = loaderMap.get(path)?.state;
274
276
  if (currentLoaderState) loaderState.setState(currentLoaderState);
275
277
  return;
276
278
  }
277
- if (routeItem?.loader && !isCacheItemFresh(path)) statusState.setState("pending");
279
+ if (routeItem?.loader && !isCacheItemFresh(path)) commitNavigation(() => routeItemDataState.setState({
280
+ routeItem,
281
+ location,
282
+ status: "pending"
283
+ }));
278
284
  };
279
285
  const polling = (routeItem, nextLocation) => {
280
286
  if (!routeItem?.pollingInterval) return;
@@ -337,36 +343,20 @@ var createNavigate = (routerState, revalidateCache) => {
337
343
  };
338
344
  //#endregion
339
345
  //#region runtime/invalidate.ts
340
- var redirect = Promise.resolve;
341
- var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextState }, revalidateCache) => {
346
+ var separatePathname = (text) => text.split("?")[0];
347
+ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
342
348
  const invalidatePath = async (routeItem, pathname, options) => {
343
349
  const routePathname = routeItemDataState.getState().location.pathname;
344
- loaderMap.delete(pathname);
350
+ if (!options?.staleOnly) loaderMap.delete(pathname);
345
351
  const [path, search = ""] = pathname.split("?");
346
- const location = {
347
- pathname: path,
348
- search
349
- };
350
- if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
351
- await routeItem.beforeLoad({
352
- redirect,
353
- ...getPartialLoaderArgs(contextState, location, routeItem)
354
- });
355
- loaderState.setState((prev) => ({
356
- ...prev,
357
- beforeLoadError: null
358
- }));
359
- } catch (error) {
360
- loaderState.setState((prev) => ({
361
- ...prev,
362
- beforeLoadError: error
363
- }));
364
- }
365
352
  const result = await revalidateCache({
366
353
  routeItem,
367
- location
354
+ location: {
355
+ pathname: path,
356
+ search
357
+ }
368
358
  });
369
- if (result && pathname === routePathname) loaderState.setState({
359
+ if (result && path === routePathname) loaderState.setState({
370
360
  data: result.data,
371
361
  loaderError: result.error,
372
362
  beforeLoadError: null
@@ -377,18 +367,20 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
377
367
  };
378
368
  };
379
369
  const invalidateItem = async (pathname, options) => {
380
- const routeItem = findRoute(pathname.split("?")[0]);
370
+ const routeItem = findRoute(separatePathname(pathname));
381
371
  if (!routeItem) return [];
382
372
  const pathnameSet = /* @__PURE__ */ new Set();
383
- for (const [key] of loaderMap) if (comparePaths(routeItem, key)) pathnameSet.add(key);
373
+ for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
384
374
  if (options?.force) pathnameSet.add(pathname);
385
375
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
386
376
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
387
- const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${pathname}${child.path}`, options)));
377
+ const [parentPath] = pathname.split("?");
378
+ const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${parentPath}${child.path}`, options)));
388
379
  return [...currentResults, ...childResults.flat()];
389
380
  };
390
381
  return async (pathList, options) => {
391
- const routePathname = routeItemDataState.getState().location.pathname;
382
+ const { pathname, search } = routeItemDataState.getState().location;
383
+ const routePathname = `${pathname}${search}`;
392
384
  const pathnameList = Array.isArray(pathList) ? pathList : pathList ? [pathList] : [routePathname];
393
385
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
394
386
  };
@@ -534,9 +526,9 @@ var createRouterInstance = () => {
534
526
  const routerState = {
535
527
  routeItemDataState: create({
536
528
  routeItem: void 0,
537
- location: {}
529
+ location: {},
530
+ status: "idle"
538
531
  }),
539
- statusState: create("idle"),
540
532
  scrollMapState: create({}),
541
533
  contextState: create({}),
542
534
  blockedRouteState: create({
@@ -549,8 +541,8 @@ var createRouterInstance = () => {
549
541
  loadingPromises: /* @__PURE__ */ new Map()
550
542
  };
551
543
  const revalidateCache = createRevalidateCache(routerState);
552
- const invalidate = createInvalidate(routerState, revalidateCache);
553
544
  const navigate = createNavigate(routerState, revalidateCache);
545
+ const invalidate = createInvalidate(routerState, revalidateCache);
554
546
  const prefetch = createPrefetch(routerState, revalidateCache);
555
547
  const getCurrentAction = (actionKey) => {
556
548
  const { routeItem, location } = routerState.routeItemDataState.getState();
@@ -581,7 +573,6 @@ var createRouterInstance = () => {
581
573
  useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
582
574
  useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
583
575
  useScrollMap: () => useGlobalState(routerState.scrollMapState),
584
- useStatus: () => useGlobalState(routerState.statusState),
585
576
  useContextState: () => useGlobalState(routerState.contextState),
586
577
  useLoaderState: () => useGlobalState(routerState.loaderState)[0],
587
578
  useParams: () => {
@@ -611,7 +602,7 @@ var createRouterInstance = () => {
611
602
  return async (formData) => {
612
603
  try {
613
604
  const data = await currentAction(formData);
614
- await invalidate("", { withBeforeLoad: options.withBeforeLoad });
605
+ await invalidate();
615
606
  options.onSuccess?.(data);
616
607
  return {
617
608
  data,
@@ -724,6 +715,25 @@ var useSetInitialContext = (initialContext) => {
724
715
  }, [initialContext, setContext]);
725
716
  };
726
717
  //#endregion
718
+ //#region hooks/useReload.ts
719
+ var useReload = () => {
720
+ const { invalidate } = router.runtime;
721
+ useEffect(() => {
722
+ if (!routerConfig.revalidateOnFocus) return;
723
+ const handler = () => {
724
+ if (document.visibilityState === "visible") invalidate("", { staleOnly: true });
725
+ };
726
+ document.addEventListener("visibilitychange", handler);
727
+ return () => document.removeEventListener("visibilitychange", handler);
728
+ }, [invalidate]);
729
+ useEffect(() => {
730
+ if (!routerConfig.revalidateOnReconnect) return;
731
+ const handler = () => invalidate("", { staleOnly: true });
732
+ window.addEventListener("online", handler);
733
+ return () => window.removeEventListener("online", handler);
734
+ }, [invalidate]);
735
+ };
736
+ //#endregion
727
737
  //#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
728
738
  /**
729
739
  * @license React
@@ -774,10 +784,9 @@ var EmptyBoundary = ({ children }) => children;
774
784
  var IS_MOBILE = isMobile();
775
785
  var MOBILE_CACHE_SIZE = 60;
776
786
  var DESKTOP_CACHE_SIZE = 150;
777
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, defaultMinLoaderDuration = 0, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary }) => {
778
- const { useRouteItemData, useStatus } = router.hooks;
779
- const [routeItemData] = useRouteItemData();
780
- const [status] = useStatus();
787
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, 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 }) => {
788
+ const { useRouteItemData } = router.hooks;
789
+ const [{ routeItem, status, location }] = useRouteItemData();
781
790
  const isError = status === "error";
782
791
  const isLoading = status === "pending";
783
792
  const isOptimistic = status === "optimistic";
@@ -792,13 +801,15 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
792
801
  defaultRetry,
793
802
  defaultStaleTime,
794
803
  defaultMinLoaderDuration,
795
- maxCacheSize
804
+ maxCacheSize,
805
+ revalidateOnFocus,
806
+ revalidateOnReconnect
796
807
  });
797
808
  useApplyCustomAnimation(animationDuration);
798
809
  useSetInitialContext(initialContext);
799
810
  usePreserveScroll(defaultScrollRestorationBehavior);
800
- const { routeItem, location } = routeItemData;
801
- if (isLoading && !isError) return renderElement(routeItemData?.routeItem?.loaderFallback || defaultLoaderFallback);
811
+ useReload();
812
+ if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
802
813
  if (!routeItem) return null;
803
814
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
804
815
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
@@ -809,10 +820,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
809
820
  //#endregion
810
821
  //#region hooks/useIsRoutePending.ts
811
822
  var useIsRoutePending = (routePath) => {
812
- const { useStatus, useRouteItemData } = router.hooks;
823
+ const { useRouteItemData } = router.hooks;
813
824
  const [routeItemData] = useRouteItemData();
814
- const [status] = useStatus();
815
- return status === "pending" && routeItemData?.location.pathname === routePath;
825
+ return routeItemData.status === "pending" && routeItemData?.location.pathname === routePath;
816
826
  };
817
827
  //#endregion
818
828
  //#region hooks/useNavigate.ts
@@ -974,9 +984,9 @@ var useAction = router.hooks.useAction;
974
984
  //#endregion
975
985
  //#region hooks/useIsDataLoading.ts
976
986
  var useIsDataLoading = () => {
977
- const { useStatus } = router.hooks;
978
- const [status] = useStatus();
979
- return status === "pending";
987
+ const { useRouteItemData } = router.hooks;
988
+ const [routeData] = useRouteItemData();
989
+ return routeData.status === "pending";
980
990
  };
981
991
  //#endregion
982
992
  //#region hooks/useRouterContext.ts
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap, contextState }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
package/dist/types.d.ts CHANGED
@@ -72,6 +72,7 @@ export type LoaderState<T = unknown> = {
72
72
  export type RouteItemData = {
73
73
  location: Location;
74
74
  routeItem: RouteItem | undefined;
75
+ status: 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
75
76
  };
76
77
  type ObjectRetry = {
77
78
  count: number;
@@ -97,6 +98,8 @@ export type RouterProps = {
97
98
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
98
99
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
99
100
  defaultScrollRestorationBehavior?: ScrollRestorationBehavior;
101
+ revalidateOnFocus?: boolean;
102
+ revalidateOnReconnect?: boolean;
100
103
  context?: Record<string, unknown>;
101
104
  };
102
105
  export type LoaderStateItem = {
@@ -111,11 +114,9 @@ export type LoadingPromise = Promise<{
111
114
  data: null;
112
115
  error: unknown;
113
116
  } | undefined>;
114
- export type Status = 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
115
117
  export type ScrollMap = Record<string, [string, number][]>;
116
118
  export type RouterState = {
117
119
  routeItemDataState: Store<RouteItemData>;
118
- statusState: Store<Status>;
119
120
  scrollMapState: Store<ScrollMap>;
120
121
  contextState: Store<Record<string, unknown>>;
121
122
  blockedRouteState: Store<{
@@ -141,7 +142,6 @@ export type RouterType = {
141
142
  }>>;
142
143
  useRouteItemData(): ReturnType<typeof useGlobalState<RouteItemData>>;
143
144
  useScrollMap(): ReturnType<typeof useGlobalState<ScrollMap>>;
144
- useStatus(): ReturnType<typeof useGlobalState<Status>>;
145
145
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
146
146
  useLoaderState<T>(): LoaderState<T>;
147
147
  useParams<T>(): T;
@@ -155,14 +155,13 @@ export type RouterType = {
155
155
  };
156
156
  export type InvalidateOptions = {
157
157
  withChildren?: boolean;
158
- withBeforeLoad?: boolean;
159
158
  force?: boolean;
159
+ staleOnly?: boolean;
160
160
  };
161
161
  export type RevalidateCache = (args: RevalidateCacheArgs) => LoadingPromise;
162
162
  export type Options = Partial<{
163
163
  onSuccess: (args: unknown) => void;
164
164
  onError: (args: unknown) => void;
165
- withBeforeLoad?: boolean;
166
165
  }> | undefined;
167
166
  export type InvalidateResult = {
168
167
  path: string;
@@ -1,2 +1,2 @@
1
1
  import { Location, RouteItem, RouterState } from '../types';
2
- export declare const createCommitState: ({ statusState, loaderStateRef, loaderState, routeItemDataState }: RouterState) => (nextLocation: Location, routeItem?: RouteItem) => void;
2
+ export declare const createCommitState: ({ loaderStateRef, loaderState, routeItemDataState }: RouterState) => (nextLocation: Location, routeItem?: RouteItem) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.1.6",
3
+ "version": "2.1.8",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {