clear-react-router 2.2.9 → 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 |
@@ -706,20 +707,25 @@ await invalidate('/post/[id]/comment/[id]');
706
707
  ```
707
708
 
708
709
  #### Force revalidation
709
- By default only paths that already exist in the cache are revalidated.
710
- Pass `{ force: true }` to also revalidate the exact path(s) you passed, even if they were never cached:
710
+ By default the exact path(s) you pass are always revalidated, even if they were never cached
711
+ — this also makes `invalidate()` work on an error page with an empty cache.
712
+ Pass `{ force: false }` to go back to cache-only revalidation:
711
713
 
712
714
  ```tsx
713
- await invalidate('/about', { force: true });
714
- await invalidate(['/about', '/post/10'], { force: true });
715
+ await invalidate('/about', { force: false });
715
716
  ```
716
717
 
718
+ Explicit `{ force: true }` behaves the same as the default; it exists for readability
719
+ and for combining with other options (see below).
720
+
717
721
  #### Stale-only revalidation
718
722
  By default, `invalidate` deletes matching cache entries and refetches them.
719
723
  Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
720
724
  ```tsx
721
725
  await invalidate('/notes', { staleOnly: true });
722
726
  ```
727
+ Note: `staleOnly` disables the default force — uncached paths are left alone, so no new
728
+ network requests are started for routes you never visited.
723
729
 
724
730
  #### Including child routes
725
731
 
@@ -754,6 +760,20 @@ will revalidate the cached child routes:
754
760
  /post/23
755
761
  /post/42/comments
756
762
  ```
763
+ #### Status transitions
764
+
765
+ When the revalidated path is the currently active route, a successful revalidation also
766
+ resets its status to `active`, while a failed one sets it to `error` — so recovering from
767
+ an error page is just `await invalidate()`:
768
+
769
+ ```tsx
770
+ // On an errorElement: refetch, and show the page again on success
771
+ await invalidate();
772
+ ```
773
+
774
+ Revalidating any other route never touches the current page status — background refreshes
775
+ stay invisible.
776
+
757
777
  #### Returns
758
778
 
759
779
  An array of objects with the following structure:
@@ -764,8 +784,8 @@ Each object represents a revalidated route, where `path` is the route pathname,
764
784
 
765
785
  #### Notes
766
786
 
767
- * Without `force` option, **only routes that already have cached data** are revalidated.
768
- * With `force: true`, the exact pathnames you pass are always revalidated (and stored in the cache).
787
+ * Without `force: false`, the exact pathnames you pass are always revalidated (and stored in the cache), even if they were never cached. Pass `{ force: false }` to revalidate **only routes that already have cached data**.
788
+ * With `{ staleOnly: true }`, uncached paths are never fetched — the default force does not apply.
769
789
  * Cached data is cleared before the new loader starts.
770
790
  * When used as an event handler, wrap the call in an arrow function:
771
791
 
@@ -888,9 +908,36 @@ Details worth knowing:
888
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.
889
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.
890
910
 
891
- ### `useIsDataLoading()`
911
+ ### `useRouteStatus()`
892
912
 
893
- Returns a boolean indicating whether any route loader is currently fetching data. Useful for global loading indicators (progress bar, spinner in the layout, etc.).
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
+ ```
921
+
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')`.
894
941
 
895
942
  ### `useRouterContext()`
896
943
 
@@ -1017,5 +1064,15 @@ For older browsers, the router gracefully falls back to regular navigation witho
1017
1064
  - React 16.8+ (for React.lazy and Suspense)
1018
1065
  - Use `default` export for your lazy-loaded components
1019
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
+
1020
1077
  ## License
1021
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;
@@ -274,26 +274,31 @@ var createNavigate = (routerState, revalidateCache) => {
274
274
  gcTimeout
275
275
  });
276
276
  };
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) => {
287
+ commitNavigation(() => routeItemDataState.setState({
288
+ routeItem,
289
+ location,
290
+ status: "pending"
291
+ }));
292
+ };
293
+ const isOptimisticHit = (routeItem, path) => !!routeItem?.optimistic && loaderMap.has(path);
294
+ const needsLoading = (routeItem, path) => !!routeItem?.loader && !isCacheItemFresh(path);
277
295
  const prepareNavigation = (routeItem, location, hasError) => {
278
296
  updateScrollMap(routeItemDataState, scrollMapState);
279
297
  createGcTimeout();
280
298
  if (hasError) return;
281
299
  const path = getPath(location);
282
- if (routeItem?.optimistic && loaderMap.has(path)) {
283
- commitNavigation(() => routeItemDataState.setState({
284
- routeItem,
285
- location,
286
- status: "optimistic"
287
- }));
288
- const currentLoaderState = loaderMap.get(path)?.state;
289
- if (currentLoaderState) loaderState.setState(currentLoaderState);
290
- return;
291
- }
292
- if (routeItem?.loader && !isCacheItemFresh(path)) commitNavigation(() => routeItemDataState.setState({
293
- routeItem,
294
- location,
295
- status: "pending"
296
- }));
300
+ if (isOptimisticHit(routeItem, path)) return commitOptimisticState(routeItem, location, path);
301
+ if (needsLoading(routeItem, path)) return commitPendingState(routeItem, location);
297
302
  };
298
303
  const polling = (routeItem, nextLocation) => {
299
304
  if (!routeItem?.pollingInterval) return;
@@ -401,11 +406,17 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
401
406
  search
402
407
  }
403
408
  });
404
- if (result && path === routePathname) loaderState.setState({
405
- data: result.data,
406
- loaderError: result.error,
407
- beforeLoadError: null
408
- });
409
+ if (result && path === routePathname) {
410
+ loaderState.setState({
411
+ data: result.data,
412
+ loaderError: result.error,
413
+ beforeLoadError: null
414
+ });
415
+ routeItemDataState.setState((prevState) => ({
416
+ ...prevState,
417
+ status: result.error ? "error" : "active"
418
+ }));
419
+ }
409
420
  return {
410
421
  path: pathname,
411
422
  ...result
@@ -416,7 +427,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
416
427
  if (!routeItem) return [];
417
428
  const pathnameSet = /* @__PURE__ */ new Set();
418
429
  for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
419
- if (options?.force) pathnameSet.add(pathname);
430
+ if (options?.force === true || options?.force === void 0 && !options?.staleOnly) pathnameSet.add(pathname);
420
431
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
421
432
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
422
433
  const [parentPath] = pathname.split("?");
@@ -735,31 +746,6 @@ var useNavigation = () => {
735
746
  //#endregion
736
747
  //#region hooks/useApplyCustomAnimation.ts
737
748
  var useApplyCustomAnimation = (animationDuration) => {
738
- useEffect(() => {
739
- const style = document.createElement("style");
740
- style.id = "spinner-style";
741
- style.textContent = `
742
- @keyframes cr-spin {
743
- 0% { transform: rotate(0deg); }
744
- 100% { transform: rotate(360deg); }
745
- }
746
-
747
- .cr-spinner {
748
- position: fixed;
749
- top: 5px;
750
- left: 5px;
751
- z-index: 9999;
752
- width: 1rem;
753
- height: 1rem;
754
- border: 2px solid gray;
755
- border-bottom-color: transparent;
756
- border-radius: 50%;
757
- animation: cr-spin 1s linear infinite;
758
- }
759
- `;
760
- document.head.appendChild(style);
761
- return () => style.remove();
762
- }, []);
763
749
  useEffect(() => {
764
750
  if (!animationDuration) return;
765
751
  const style = document.createElement("style");
@@ -815,13 +801,6 @@ var useReload = () => {
815
801
  }, [invalidate]);
816
802
  };
817
803
  //#endregion
818
- //#region components/Spinner.tsx
819
- var Spinner = () => /* @__PURE__ */ jsx("span", {
820
- className: "cr-spinner",
821
- role: "status",
822
- "aria-label": "Loading"
823
- });
824
- //#endregion
825
804
  //#region utils/renderElement.tsx
826
805
  var renderElement = (Component) => {
827
806
  if (!Component) return null;
@@ -834,12 +813,11 @@ var EmptyBoundary = ({ children }) => children;
834
813
  var IS_MOBILE = isMobile();
835
814
  var MOBILE_CACHE_SIZE = 60;
836
815
  var DESKTOP_CACHE_SIZE = 150;
837
- 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 }) => {
838
817
  const { useRouteItemData } = router.hooks;
839
818
  const [{ routeItem, status, location }] = useRouteItemData();
840
819
  const isError = status === "error";
841
820
  const isLoading = status === "pending";
842
- const isOptimistic = status === "optimistic";
843
821
  useNavigation();
844
822
  useSetRouterConfig({
845
823
  routes,
@@ -863,9 +841,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
863
841
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
864
842
  if (!routeItem) return null;
865
843
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
866
- return /* @__PURE__ */ jsxs("div", {
844
+ return /* @__PURE__ */ jsx("div", {
867
845
  style: { viewTransitionName: "page" },
868
- 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)
869
847
  });
870
848
  };
871
849
  //#endregion
@@ -979,10 +957,7 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
979
957
  var useParams = router.hooks.useParams;
980
958
  //#endregion
981
959
  //#region hooks/useLocation.ts
982
- var useLocation = () => {
983
- const [routeItemData] = router.hooks.useRouteItemData();
984
- return routeItemData.location;
985
- };
960
+ var useLocation = () => router.hooks.useRouteItemDataSelector((state) => state.location);
986
961
  //#endregion
987
962
  //#region hooks/useLoaderState.ts
988
963
  var useLoaderState = router.hooks.useLoaderState;
@@ -1027,11 +1002,11 @@ var useBlocker = (blockerFn) => {
1027
1002
  //#region hooks/useAction.ts
1028
1003
  var useAction = router.hooks.useAction;
1029
1004
  //#endregion
1030
- //#region hooks/useIsDataLoading.ts
1031
- var useIsDataLoading = () => {
1005
+ //#region hooks/useRouteStatus.ts
1006
+ function useRouteStatus(predicate) {
1032
1007
  const { useRouteItemDataSelector } = router.hooks;
1033
- return useRouteItemDataSelector(({ status }) => status) === "pending";
1034
- };
1008
+ return useRouteItemDataSelector(({ status }) => predicate ? predicate(status) : status);
1009
+ }
1035
1010
  //#endregion
1036
1011
  //#region hooks/useRouterContext.ts
1037
1012
  var useRouterContext = () => {
@@ -1152,4 +1127,4 @@ var lazy = (importFn) => ({
1152
1127
  importFn
1153
1128
  });
1154
1129
  //#endregion
1155
- 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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.9",
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;