clear-react-router 2.3.0 → 2.3.2

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
@@ -19,6 +19,8 @@ It provides first-class support for:
19
19
  * Simple, provider-free architecture
20
20
  * Small, explicit API
21
21
 
22
+ > 👉 TL;DR? **[Try the live playground](https://clear-react-router.vercel.app/playground)** — no setup, click around.
23
+
22
24
 
23
25
  ## Features
24
26
 
@@ -47,7 +49,6 @@ It provides first-class support for:
47
49
  | `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
48
50
  | `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
49
51
  | `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
50
- | `optimisticSpinner` | `boolean \| undefined` | `true` | Show a small spinner in the corner while optimistic route data revalidates in the background |
51
52
  | `context` | `object` | `{}` | Initial context (user, theme, etc.) |
52
53
  | `errorBoundary` | `ComponentType<{ children: ReactNode }>` | `undefined` | Custom error boundary component for catching render errors in route components |
53
54
  | `defaultMinLoaderDuration` | `number \| undefined` | `0` | Default minimum time the loader fallback stays visible, to avoid flickering |
@@ -85,7 +86,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
85
86
  | `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 |
86
87
  | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
87
88
  | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
88
- | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
89
+ | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
89
90
  | `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
90
91
  | `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
91
92
 
@@ -907,9 +908,36 @@ Details worth knowing:
907
908
  * An optional behavior argument on the hook overrides the scroll behavior for these calls (`useRestoreScroll('smooth')`); by default the route's `scrollRestorationBehavior`, then the router's `defaultScrollRestorationBehavior`, applies.
908
909
  * For element-level restoration (`scrollRestoration: ['panel']`), container `id`s must be unique and stable across visits — a typo or a remounted `id` logs a warning and skips that container.
909
910
 
910
- ### `useIsDataLoading()`
911
+ ### `useRouteStatus()`
912
+
913
+ Returns the current route status (`'idle' | 'pending' | 'active' | 'optimistic' | 'error'`), or — when called with a predicate — whether it matches. Useful for global loading indicators (progress bar, spinner in the layout, etc.) and for reacting to specific states.
914
+
915
+ ```tsx
916
+ import { useRouteStatus } from 'clear-react-router';
917
+
918
+ const isLoading = useRouteStatus(status => status === 'pending' || status === 'optimistic');
919
+ const isOptimistic = useRouteStatus(status => status === 'optimistic');
920
+ ```
911
921
 
912
- Returns a boolean indicating whether any route loader is currently fetching data. Useful for global loading indicators (progress bar, spinner in the layout, etc.).
922
+ To render your own loading indicator (for example next to a link while its target revalidates), combine it with the link state:
923
+
924
+ ```tsx
925
+ import { Link, useRouteStatus } from 'clear-react-router';
926
+
927
+ const NavLink = ({ to, children }: { to: string; children: ReactNode }) => {
928
+ const isLoading = useRouteStatus(status => status === 'pending' || status === 'optimistic');
929
+ return (
930
+ <Link to={to} className={({ isPending }) => (isPending ? 'link-pending' : '')}>
931
+ {children}
932
+ {isLoading && <span aria-hidden="true"> •••</span>}
933
+ </Link>
934
+ );
935
+ };
936
+ ```
937
+
938
+ For per-link pending styling without custom components, `pendingClassName` and the `className`/`style` functions (which receive `{ isActive, isPending }`) cover most cases with no extra code.
939
+
940
+ > **Migration note:** `useIsDataLoading()` is removed — it is exactly `useRouteStatus(status => status === 'pending' || status === 'optimistic')`.
913
941
 
914
942
  ### `useRouterContext()`
915
943
 
@@ -1036,5 +1064,15 @@ For older browsers, the router gracefully falls back to regular navigation witho
1036
1064
  - React 16.8+ (for React.lazy and Suspense)
1037
1065
  - Use `default` export for your lazy-loaded components
1038
1066
 
1067
+ ## Playground
1068
+
1069
+ Try it live — no setup: **[clear-router playground](https://clear-react-router.vercel.app/playground)**.
1070
+
1071
+ Scroll restoration (window + named containers), retry with attempt counts, live polling,
1072
+ actions with invalidation, navigation blocking, hover prefetch, optimistic navigation,
1073
+ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, search params,
1074
+ and a context-based auth guard — all running against a fake in-browser server.
1075
+ Open devtools and click around.
1076
+
1039
1077
  ## License
1040
1078
  MIT
@@ -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, revalidateOnFocus, revalidateOnReconnect, 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, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,3 @@
1
+ import type { Status } from '../types';
2
+ export declare function useRouteStatus(): Status;
3
+ export declare function useRouteStatus(predicate: (status: Status) => boolean): boolean;
package/dist/index.d.ts CHANGED
@@ -7,12 +7,12 @@ export { useLoaderState } from './hooks/useLoaderState';
7
7
  export { useInvalidate } from './hooks/useInvalidate';
8
8
  export { useBlocker } from './hooks/useBlocker';
9
9
  export { useAction } from './hooks/useAction';
10
- export { useIsDataLoading } from './hooks/useIsDataLoading';
10
+ export { useRouteStatus } from './hooks/useRouteStatus';
11
11
  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
15
  export { createRouter } from './creators/createRouter';
16
16
  export { lazy } from './utils/lazy';
17
- export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation } from './types';
17
+ export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation, Status } from './types';
18
18
  export type { ElementProps } from './components/Link';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
- import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { jsx } from "react/jsx-runtime";
3
3
  //#region create.ts
4
4
  var create = (initialState) => {
5
5
  let state = initialState;
@@ -28,15 +28,12 @@ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
28
28
  };
29
29
  //#endregion
30
30
  //#region utils/commitState.ts
31
- var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ loaderStateValue, location }) => {
31
+ var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
32
32
  const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
33
- routeItemDataState.setState((prevState) => {
34
- if (prevState.status === "active") return prevState;
35
- return {
36
- ...prevState,
37
- location,
38
- status: isError ? "error" : "active"
39
- };
33
+ routeItemDataState.setState({
34
+ routeItem,
35
+ location,
36
+ status: isError ? "error" : "active"
40
37
  });
41
38
  loaderState.setState(loaderStateValue);
42
39
  if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
@@ -277,52 +274,55 @@ var createNavigate = (routerState, revalidateCache) => {
277
274
  gcTimeout
278
275
  });
279
276
  };
280
- const prepareNavigation = (routeItem, location, hasError) => {
281
- updateScrollMap(routeItemDataState, scrollMapState);
282
- createGcTimeout();
283
- if (hasError) {
284
- commitNavigation(() => routeItemDataState.setState({
285
- routeItem,
286
- location,
287
- status: "error"
288
- }));
289
- return;
290
- }
291
- const path = getPath(location);
292
- if (routeItem?.optimistic && loaderMap.has(path)) {
293
- commitNavigation(() => routeItemDataState.setState({
277
+ const commitOptimisticState = (routeItem, location, path) => {
278
+ const currentLoaderState = loaderMap.get(path)?.state;
279
+ commitNavigation(() => {
280
+ routeItemDataState.setState({
294
281
  routeItem,
295
282
  location,
296
283
  status: "optimistic"
297
- }));
298
- const currentLoaderState = loaderMap.get(path)?.state;
284
+ });
299
285
  if (currentLoaderState) loaderState.setState(currentLoaderState);
300
- return;
301
- }
302
- if (routeItem?.loader && !isCacheItemFresh(path)) {
303
- commitNavigation(() => routeItemDataState.setState({
304
- routeItem,
305
- location,
306
- status: "pending"
307
- }));
308
- return;
309
- }
286
+ });
287
+ };
288
+ const commitPendingState = (routeItem, location) => {
310
289
  commitNavigation(() => routeItemDataState.setState({
311
290
  routeItem,
312
291
  location,
313
- status: "active"
292
+ status: "pending"
314
293
  }));
315
294
  };
295
+ const isOptimisticHit = (routeItem, path) => !!routeItem?.optimistic && loaderMap.has(path);
296
+ const needsLoading = (routeItem, path) => !!routeItem?.loader && !isCacheItemFresh(path);
297
+ const prepareNavigation = (routeItem, location, hasError) => {
298
+ updateScrollMap(routeItemDataState, scrollMapState);
299
+ createGcTimeout();
300
+ if (hasError) return;
301
+ const path = getPath(location);
302
+ if (isOptimisticHit(routeItem, path)) return commitOptimisticState(routeItem, location, path);
303
+ if (needsLoading(routeItem, path)) return commitPendingState(routeItem, location);
304
+ };
316
305
  const polling = (routeItem, nextLocation) => {
317
306
  if (!routeItem?.pollingInterval) return;
318
307
  pollingController?.abort();
319
308
  pollingController = new AbortController();
320
309
  const signal = pollingController.signal;
321
- interval = window.setInterval(() => revalidateCache({
322
- routeItem,
323
- location: nextLocation,
324
- signal
325
- }), routeItem.pollingInterval);
310
+ interval = window.setInterval(async () => {
311
+ const result = await revalidateCache({
312
+ routeItem,
313
+ location: nextLocation,
314
+ signal,
315
+ force: true
316
+ });
317
+ if (!result || signal.aborted) return;
318
+ const { location: currentLocation } = routeItemDataState.getState();
319
+ if (`${currentLocation.pathname}${currentLocation.search ?? ""}` !== getPath(nextLocation)) return;
320
+ loaderState.setState({
321
+ data: result.data,
322
+ loaderError: result.error,
323
+ beforeLoadError: null
324
+ });
325
+ }, routeItem.pollingInterval);
326
326
  };
327
327
  const getLoaderDurationPromise = (routeItem, nextLocation) => {
328
328
  const minLoaderDuration = routeItem?.minLoaderDuration ?? routerConfig.defaultMinLoaderDuration ?? 0;
@@ -396,6 +396,7 @@ var createNavigate = (routerState, revalidateCache) => {
396
396
  };
397
397
  commitNavigation(() => commitState({
398
398
  location: nextLocation,
399
+ routeItem: nextItem,
399
400
  loaderStateValue
400
401
  }));
401
402
  clearCurrentGcTimeout(nextItem, nextLocation);
@@ -502,7 +503,7 @@ var createRevalidateCache = (routerState) => {
502
503
  }
503
504
  return item;
504
505
  };
505
- const revalidateCache = async ({ routeItem, location, signal }, retried = 0) => {
506
+ const revalidateCache = async ({ routeItem, location, signal, force }, retried = 0) => {
506
507
  if (!routeItem?.loader) return;
507
508
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
508
509
  const { pathname, search = "" } = location;
@@ -518,7 +519,7 @@ var createRevalidateCache = (routerState) => {
518
519
  return loadingPromises.get(path);
519
520
  }
520
521
  }
521
- if (isCacheItemFresh(path)) {
522
+ if (!force && isCacheItemFresh(path)) {
522
523
  const item = moveItemToLastPosition(path);
523
524
  if (!item?.state) return void 0;
524
525
  return item.state.loaderError ? {
@@ -570,7 +571,8 @@ var createRevalidateCache = (routerState) => {
570
571
  return revalidateCache({
571
572
  routeItem,
572
573
  location,
573
- signal
574
+ signal,
575
+ force
574
576
  }, retried + 1);
575
577
  } else return {
576
578
  data: null,
@@ -758,31 +760,6 @@ var useNavigation = () => {
758
760
  //#endregion
759
761
  //#region hooks/useApplyCustomAnimation.ts
760
762
  var useApplyCustomAnimation = (animationDuration) => {
761
- useEffect(() => {
762
- const style = document.createElement("style");
763
- style.id = "spinner-style";
764
- style.textContent = `
765
- @keyframes cr-spin {
766
- 0% { transform: rotate(0deg); }
767
- 100% { transform: rotate(360deg); }
768
- }
769
-
770
- .cr-spinner {
771
- position: fixed;
772
- top: 5px;
773
- left: 5px;
774
- z-index: 9999;
775
- width: 1rem;
776
- height: 1rem;
777
- border: 2px solid gray;
778
- border-bottom-color: transparent;
779
- border-radius: 50%;
780
- animation: cr-spin 1s linear infinite;
781
- }
782
- `;
783
- document.head.appendChild(style);
784
- return () => style.remove();
785
- }, []);
786
763
  useEffect(() => {
787
764
  if (!animationDuration) return;
788
765
  const style = document.createElement("style");
@@ -838,13 +815,6 @@ var useReload = () => {
838
815
  }, [invalidate]);
839
816
  };
840
817
  //#endregion
841
- //#region components/Spinner.tsx
842
- var Spinner = () => /* @__PURE__ */ jsx("span", {
843
- className: "cr-spinner",
844
- role: "status",
845
- "aria-label": "Loading"
846
- });
847
- //#endregion
848
818
  //#region utils/renderElement.tsx
849
819
  var renderElement = (Component) => {
850
820
  if (!Component) return null;
@@ -857,12 +827,11 @@ var EmptyBoundary = ({ children }) => children;
857
827
  var IS_MOBILE = isMobile();
858
828
  var MOBILE_CACHE_SIZE = 60;
859
829
  var DESKTOP_CACHE_SIZE = 150;
860
- 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 }) => {
830
+ 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 }) => {
861
831
  const { useRouteItemData } = router.hooks;
862
832
  const [{ routeItem, status, location }] = useRouteItemData();
863
833
  const isError = status === "error";
864
834
  const isLoading = status === "pending";
865
- const isOptimistic = status === "optimistic";
866
835
  useNavigation();
867
836
  useSetRouterConfig({
868
837
  routes,
@@ -886,9 +855,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
886
855
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
887
856
  if (!routeItem) return null;
888
857
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
889
- return /* @__PURE__ */ jsxs("div", {
858
+ return /* @__PURE__ */ jsx("div", {
890
859
  style: { viewTransitionName: "page" },
891
- children: [/* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname), optimisticSpinner && isOptimistic && /* @__PURE__ */ jsx(Spinner, {})]
860
+ children: /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname)
892
861
  });
893
862
  };
894
863
  //#endregion
@@ -1047,11 +1016,11 @@ var useBlocker = (blockerFn) => {
1047
1016
  //#region hooks/useAction.ts
1048
1017
  var useAction = router.hooks.useAction;
1049
1018
  //#endregion
1050
- //#region hooks/useIsDataLoading.ts
1051
- var useIsDataLoading = () => {
1019
+ //#region hooks/useRouteStatus.ts
1020
+ function useRouteStatus(predicate) {
1052
1021
  const { useRouteItemDataSelector } = router.hooks;
1053
- return useRouteItemDataSelector(({ status }) => status) === "pending";
1054
- };
1022
+ return useRouteItemDataSelector(({ status }) => predicate ? predicate(status) : status);
1023
+ }
1055
1024
  //#endregion
1056
1025
  //#region hooks/useRouterContext.ts
1057
1026
  var useRouterContext = () => {
@@ -1172,4 +1141,4 @@ var lazy = (importFn) => ({
1172
1141
  importFn
1173
1142
  });
1174
1143
  //#endregion
1175
- export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouterContext, useSearchParams, useSubmitAction };
1144
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
@@ -1,2 +1,2 @@
1
1
  import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
2
- export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
2
+ export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal, force }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
package/dist/types.d.ts CHANGED
@@ -64,16 +64,18 @@ export type RevalidateCacheArgs = {
64
64
  location: Location;
65
65
  routeItem?: RouteItem;
66
66
  signal?: AbortSignal;
67
+ force?: boolean;
67
68
  };
68
69
  export type LoaderState<T = unknown> = {
69
70
  data: T;
70
71
  loaderError: Error | null;
71
72
  beforeLoadError: Error | null;
72
73
  };
74
+ export type Status = 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
73
75
  export type RouteItemData = {
74
76
  location: Location;
75
77
  routeItem: RouteItem | undefined;
76
- status: 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
78
+ status: Status;
77
79
  };
78
80
  type ObjectRetry = {
79
81
  count: number;
@@ -84,7 +86,6 @@ export type RouterProps = {
84
86
  routes: RouteItem[];
85
87
  isAnimated?: boolean;
86
88
  animationDuration?: number;
87
- optimisticSpinner?: boolean;
88
89
  defaultRetry?: Retry;
89
90
  defaultStaleTime?: number;
90
91
  defaultLoaderFallback?: RenderElement;
@@ -1,7 +1,8 @@
1
- import { LoaderState, Location, RouterState } from '../types';
1
+ import { LoaderState, Location, RouteItem, RouterState } from '../types';
2
2
  type CommitState = {
3
3
  location: Location;
4
4
  loaderStateValue: LoaderState;
5
+ routeItem?: RouteItem;
5
6
  };
6
- export declare const createCommitState: ({ loaderState, routeItemDataState, blockerState }: RouterState) => ({ loaderStateValue, location }: CommitState) => void;
7
+ export declare const createCommitState: ({ loaderState, routeItemDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
7
8
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.3.0",
3
+ "version": "2.3.2",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
@@ -1 +0,0 @@
1
- export declare const Spinner: () => import("react/jsx-runtime").JSX.Element;
@@ -1 +0,0 @@
1
- export declare const useIsDataLoading: () => boolean;