clear-react-router 2.3.0 → 2.3.1

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 |
@@ -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,42 +274,32 @@ 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({
294
- routeItem,
295
- location,
296
- status: "optimistic"
297
- }));
298
- const currentLoaderState = loaderMap.get(path)?.state;
299
- 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
- }
277
+ const commitOptimisticState = (routeItem, location, path) => {
278
+ commitNavigation(() => routeItemDataState.setState({
279
+ routeItem,
280
+ location,
281
+ status: "optimistic"
282
+ }));
283
+ const currentLoaderState = loaderMap.get(path)?.state;
284
+ if (currentLoaderState) loaderState.setState(currentLoaderState);
285
+ };
286
+ const commitPendingState = (routeItem, location) => {
310
287
  commitNavigation(() => routeItemDataState.setState({
311
288
  routeItem,
312
289
  location,
313
- status: "active"
290
+ status: "pending"
314
291
  }));
315
292
  };
293
+ const isOptimisticHit = (routeItem, path) => !!routeItem?.optimistic && loaderMap.has(path);
294
+ const needsLoading = (routeItem, path) => !!routeItem?.loader && !isCacheItemFresh(path);
295
+ const prepareNavigation = (routeItem, location, hasError) => {
296
+ updateScrollMap(routeItemDataState, scrollMapState);
297
+ createGcTimeout();
298
+ if (hasError) return;
299
+ const path = getPath(location);
300
+ if (isOptimisticHit(routeItem, path)) return commitOptimisticState(routeItem, location, path);
301
+ if (needsLoading(routeItem, path)) return commitPendingState(routeItem, location);
302
+ };
316
303
  const polling = (routeItem, nextLocation) => {
317
304
  if (!routeItem?.pollingInterval) return;
318
305
  pollingController?.abort();
@@ -396,6 +383,7 @@ var createNavigate = (routerState, revalidateCache) => {
396
383
  };
397
384
  commitNavigation(() => commitState({
398
385
  location: nextLocation,
386
+ routeItem: nextItem,
399
387
  loaderStateValue
400
388
  }));
401
389
  clearCurrentGcTimeout(nextItem, nextLocation);
@@ -758,31 +746,6 @@ var useNavigation = () => {
758
746
  //#endregion
759
747
  //#region hooks/useApplyCustomAnimation.ts
760
748
  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
749
  useEffect(() => {
787
750
  if (!animationDuration) return;
788
751
  const style = document.createElement("style");
@@ -838,13 +801,6 @@ var useReload = () => {
838
801
  }, [invalidate]);
839
802
  };
840
803
  //#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
804
  //#region utils/renderElement.tsx
849
805
  var renderElement = (Component) => {
850
806
  if (!Component) return null;
@@ -857,12 +813,11 @@ var EmptyBoundary = ({ children }) => children;
857
813
  var IS_MOBILE = isMobile();
858
814
  var MOBILE_CACHE_SIZE = 60;
859
815
  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 }) => {
816
+ 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
817
  const { useRouteItemData } = router.hooks;
862
818
  const [{ routeItem, status, location }] = useRouteItemData();
863
819
  const isError = status === "error";
864
820
  const isLoading = status === "pending";
865
- const isOptimistic = status === "optimistic";
866
821
  useNavigation();
867
822
  useSetRouterConfig({
868
823
  routes,
@@ -886,9 +841,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
886
841
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
887
842
  if (!routeItem) return null;
888
843
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
889
- return /* @__PURE__ */ jsxs("div", {
844
+ return /* @__PURE__ */ jsx("div", {
890
845
  style: { viewTransitionName: "page" },
891
- children: [/* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname), optimisticSpinner && isOptimistic && /* @__PURE__ */ jsx(Spinner, {})]
846
+ children: /* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname)
892
847
  });
893
848
  };
894
849
  //#endregion
@@ -1047,11 +1002,11 @@ var useBlocker = (blockerFn) => {
1047
1002
  //#region hooks/useAction.ts
1048
1003
  var useAction = router.hooks.useAction;
1049
1004
  //#endregion
1050
- //#region hooks/useIsDataLoading.ts
1051
- var useIsDataLoading = () => {
1005
+ //#region hooks/useRouteStatus.ts
1006
+ function useRouteStatus(predicate) {
1052
1007
  const { useRouteItemDataSelector } = router.hooks;
1053
- return useRouteItemDataSelector(({ status }) => status) === "pending";
1054
- };
1008
+ return useRouteItemDataSelector(({ status }) => predicate ? predicate(status) : status);
1009
+ }
1055
1010
  //#endregion
1056
1011
  //#region hooks/useRouterContext.ts
1057
1012
  var useRouterContext = () => {
@@ -1172,4 +1127,4 @@ var lazy = (importFn) => ({
1172
1127
  importFn
1173
1128
  });
1174
1129
  //#endregion
1175
- export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouterContext, useSearchParams, useSubmitAction };
1130
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
package/dist/types.d.ts CHANGED
@@ -70,10 +70,11 @@ export type LoaderState<T = unknown> = {
70
70
  loaderError: Error | null;
71
71
  beforeLoadError: Error | null;
72
72
  };
73
+ export type Status = 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
73
74
  export type RouteItemData = {
74
75
  location: Location;
75
76
  routeItem: RouteItem | undefined;
76
- status: 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
77
+ status: Status;
77
78
  };
78
79
  type ObjectRetry = {
79
80
  count: number;
@@ -84,7 +85,6 @@ export type RouterProps = {
84
85
  routes: RouteItem[];
85
86
  isAnimated?: boolean;
86
87
  animationDuration?: number;
87
- optimisticSpinner?: boolean;
88
88
  defaultRetry?: Retry;
89
89
  defaultStaleTime?: number;
90
90
  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.1",
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;