clear-react-router 2.3.2 → 2.4.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
@@ -82,7 +82,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
82
82
  | `loaderFallback` | `ReactElement \| () => ReactElement` | Loading fallback for the route's `loader`. Overrides the global `Router.defaultLoaderFallback` |
83
83
  | `retry` | `number \| { count: number; delay: number }` | Overrides the global cache revalidation retry policy for this route |
84
84
  | `optimistic` | `boolean \| undefined` | Instant navigation using stale data while fresh data is loaded in the background |
85
- | `errorElement` | `ReactElement \| () => ReactElement` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
85
+ | `errorElement` | `ReactElement \| () => ReactElement \| LazyComponent` | Error fallback for the route. Overrides the global `Router.defaultErrorElement` |
86
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 |
87
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 |
88
88
  | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
@@ -115,6 +115,7 @@ see [`redirect`](#redirect) for details on programmatic redirects
115
115
  ```ts
116
116
  {
117
117
  signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
118
+ attempt: number; // 1-based attempt counter within this fetch: 1 on first try, 2+ on retries
118
119
  }
119
120
  ```
120
121
  > **Note:** `gcTime` is independent from `staleTime` — `staleTime` controls when cached data is considered outdated (and needs a refetch), while `gcTime` controls how long the cache entry stays in memory at all once you leave that route. Data can be fresh and still get garbage-collected, or stale and still linger in memory, depending on which you set. The timer starts only when you navigate away from the route and is cancelled if you come back before it fires — it isn't affected by prefetching. This is mainly useful for routes with heavy or fast-changing data (large tables, dashboards with charts) that you don't want lingering in memory indefinitely, even when `maxCacheSize` hasn't been reached yet.
@@ -1 +1,2 @@
1
- export declare const useLoaderState: <T>() => import("../types").LoaderState<T>;
1
+ import type { LoaderState } from '../types';
2
+ export declare const useLoaderState: <T = unknown>() => LoaderState<T>;
@@ -0,0 +1,2 @@
1
+ import { ScrollRestorationBehavior } from '../types';
2
+ export declare const useRestoreRouteScroll: (behavior?: ScrollRestorationBehavior) => void;
package/dist/index.js CHANGED
@@ -28,14 +28,14 @@ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
28
28
  };
29
29
  //#endregion
30
30
  //#region utils/commitState.ts
31
- var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
31
+ var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
32
32
  const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
33
- routeItemDataState.setState({
33
+ routeDataState.setState({
34
34
  routeItem,
35
35
  location,
36
- status: isError ? "error" : "active"
36
+ status: isError ? "error" : "active",
37
+ loaderState: loaderStateValue
37
38
  });
38
- loaderState.setState(loaderStateValue);
39
39
  if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
40
40
  if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
41
41
  history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
@@ -163,8 +163,8 @@ var getPartialLoaderArgs = (contextState, location, routeItem) => {
163
163
  };
164
164
  };
165
165
  var isVerticalScroll = (el) => !!el && el.scrollHeight > el.clientHeight;
166
- var updateScrollMap = (routeItemDataState, scrollMapState) => {
167
- const { routeItem, location: { pathname } } = routeItemDataState.getState();
166
+ var updateScrollMap = (routeDataState, scrollMapState) => {
167
+ const { routeItem, location: { pathname } } = routeDataState.getState();
168
168
  scrollMapState.setState((prevState) => {
169
169
  if (Array.isArray(routeItem?.scrollRestoration)) return {
170
170
  ...prevState,
@@ -213,7 +213,7 @@ var createNavigate = (routerState, revalidateCache) => {
213
213
  pollingController?.abort();
214
214
  pollingController = null;
215
215
  };
216
- const { loaderState, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
216
+ const { contextState, loaderMap, routeDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
217
217
  const commitState = createCommitState(routerState);
218
218
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
219
219
  const createSignal = () => {
@@ -233,7 +233,7 @@ var createNavigate = (routerState, revalidateCache) => {
233
233
  const { defaultBeforeLoad } = routerConfig;
234
234
  const runBeforeLoad = async (loaderFn) => {
235
235
  const redirect = async (redirected) => {
236
- const { location } = routeItemDataState.getState();
236
+ const { location } = routeDataState.getState();
237
237
  const prevLocation = {
238
238
  pathname: location.pathname,
239
239
  search: location.search
@@ -262,7 +262,7 @@ var createNavigate = (routerState, revalidateCache) => {
262
262
  return error;
263
263
  };
264
264
  const createGcTimeout = () => {
265
- const { routeItem, location } = routeItemDataState.getState();
265
+ const { routeItem, location } = routeDataState.getState();
266
266
  if (!routeItem?.gcTime) return;
267
267
  const path = `${location.pathname}${location.search}`;
268
268
  const currentLoaderEntry = loaderMap.get(path);
@@ -277,25 +277,25 @@ var createNavigate = (routerState, revalidateCache) => {
277
277
  const commitOptimisticState = (routeItem, location, path) => {
278
278
  const currentLoaderState = loaderMap.get(path)?.state;
279
279
  commitNavigation(() => {
280
- routeItemDataState.setState({
280
+ routeDataState.setState((prevState) => ({
281
+ ...prevState,
281
282
  routeItem,
282
283
  location,
283
- status: "optimistic"
284
- });
285
- if (currentLoaderState) loaderState.setState(currentLoaderState);
284
+ status: "optimistic",
285
+ ...currentLoaderState && { loaderState: currentLoaderState }
286
+ }));
286
287
  });
287
288
  };
288
- const commitPendingState = (routeItem, location) => {
289
- commitNavigation(() => routeItemDataState.setState({
290
- routeItem,
291
- location,
292
- status: "pending"
293
- }));
294
- };
289
+ const commitPendingState = (routeItem, location) => commitNavigation(() => routeDataState.setState((prevState) => ({
290
+ ...prevState,
291
+ routeItem,
292
+ location,
293
+ status: "pending"
294
+ })));
295
295
  const isOptimisticHit = (routeItem, path) => !!routeItem?.optimistic && loaderMap.has(path);
296
296
  const needsLoading = (routeItem, path) => !!routeItem?.loader && !isCacheItemFresh(path);
297
297
  const prepareNavigation = (routeItem, location, hasError) => {
298
- updateScrollMap(routeItemDataState, scrollMapState);
298
+ updateScrollMap(routeDataState, scrollMapState);
299
299
  createGcTimeout();
300
300
  if (hasError) return;
301
301
  const path = getPath(location);
@@ -315,13 +315,16 @@ var createNavigate = (routerState, revalidateCache) => {
315
315
  force: true
316
316
  });
317
317
  if (!result || signal.aborted) return;
318
- const { location: currentLocation } = routeItemDataState.getState();
318
+ const { location: currentLocation } = routeDataState.getState();
319
319
  if (`${currentLocation.pathname}${currentLocation.search ?? ""}` !== getPath(nextLocation)) return;
320
- loaderState.setState({
321
- data: result.data,
322
- loaderError: result.error,
323
- beforeLoadError: null
324
- });
320
+ routeDataState.setState((prevState) => ({
321
+ ...prevState,
322
+ loaderState: {
323
+ data: result.data,
324
+ loaderError: result.error,
325
+ beforeLoadError: null
326
+ }
327
+ }));
325
328
  }, routeItem.pollingInterval);
326
329
  };
327
330
  const getLoaderDurationPromise = (routeItem, nextLocation) => {
@@ -407,9 +410,9 @@ var createNavigate = (routerState, revalidateCache) => {
407
410
  //#endregion
408
411
  //#region runtime/invalidate.ts
409
412
  var separatePathname = (text) => text.split("?")[0];
410
- var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
413
+ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache) => {
411
414
  const invalidatePath = async (routeItem, pathname, options) => {
412
- const routePathname = routeItemDataState.getState().location.pathname;
415
+ const routePathname = routeDataState.getState().location.pathname;
413
416
  if (!options?.staleOnly) loaderMap.delete(pathname);
414
417
  const [path, search = ""] = pathname.split("?");
415
418
  const result = await revalidateCache({
@@ -419,17 +422,15 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
419
422
  search
420
423
  }
421
424
  });
422
- if (result && path === routePathname) {
423
- loaderState.setState({
425
+ if (result && path === routePathname) routeDataState.setState((prevState) => ({
426
+ ...prevState,
427
+ loaderState: {
424
428
  data: result.data,
425
429
  loaderError: result.error,
426
430
  beforeLoadError: null
427
- });
428
- routeItemDataState.setState((prevState) => ({
429
- ...prevState,
430
- status: result.error ? "error" : "active"
431
- }));
432
- }
431
+ },
432
+ status: result.error ? "error" : "active"
433
+ }));
433
434
  return {
434
435
  path: pathname,
435
436
  ...result
@@ -448,7 +449,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
448
449
  return [...currentResults, ...childResults.flat()];
449
450
  };
450
451
  return async (pathList, options) => {
451
- const { pathname, search } = routeItemDataState.getState().location;
452
+ const { pathname, search } = routeDataState.getState().location;
452
453
  const routePathname = `${pathname}${search}`;
453
454
  const pathnameList = Array.isArray(pathList) ? pathList : pathList ? [pathList] : [routePathname];
454
455
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
@@ -456,10 +457,10 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalida
456
457
  };
457
458
  //#endregion
458
459
  //#region runtime/prefetch.ts
459
- var createPrefetch = ({ routeItemDataState }, revalidateCache) => async (location) => {
460
+ var createPrefetch = ({ routeDataState }, revalidateCache) => async (location) => {
460
461
  const item = findRoute(location.pathname);
461
462
  if (item) {
462
- const currentLocation = routeItemDataState.getState().location;
463
+ const currentLocation = routeDataState.getState().location;
463
464
  if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
464
465
  await item.preloadElement?.();
465
466
  await revalidateCache({
@@ -540,7 +541,8 @@ var createRevalidateCache = (routerState) => {
540
541
  try {
541
542
  const result = await routeItem?.loader({
542
543
  ...getPartialLoaderArgs(contextState, location, routeItem),
543
- signal: effectiveSignal
544
+ signal: effectiveSignal,
545
+ attempt: retried + 1
544
546
  });
545
547
  loaderMap.set(path, {
546
548
  state: {
@@ -594,15 +596,15 @@ var createRevalidateCache = (routerState) => {
594
596
  //#region creators/createRouterInstance.ts
595
597
  var createRouterInstance = (synchronizer) => {
596
598
  const routerState = {
597
- routeItemDataState: create({
599
+ routeDataState: create({
598
600
  routeItem: void 0,
599
601
  location: {},
600
- status: "idle"
602
+ status: "idle",
603
+ loaderState: EMPTY_LOADER_STATE
601
604
  }),
602
605
  scrollMapState: create({}),
603
606
  contextState: create({}),
604
607
  blockerState: create("unblocked"),
605
- loaderState: create(EMPTY_LOADER_STATE),
606
608
  blockedTargetState: create(null),
607
609
  loaderMap: /* @__PURE__ */ new Map(),
608
610
  loadingPromises: /* @__PURE__ */ new Map()
@@ -612,7 +614,7 @@ var createRouterInstance = (synchronizer) => {
612
614
  const invalidate = createInvalidate(routerState, revalidateCache);
613
615
  const prefetch = createPrefetch(routerState, revalidateCache);
614
616
  const getCurrentAction = (actionKey) => {
615
- const { routeItem, location } = routerState.routeItemDataState.getState();
617
+ const { routeItem, location } = routerState.routeDataState.getState();
616
618
  if (!routeItem) throw new Error("Route not found");
617
619
  if (!routeItem.actions) throw new Error("Route action creator not found");
618
620
  const context = routerState.contextState.getState();
@@ -637,17 +639,15 @@ var createRouterInstance = (synchronizer) => {
637
639
  },
638
640
  hooks: {
639
641
  useBlockerState: () => useGlobalState(routerState.blockerState, synchronizer),
640
- useRouteItemData: () => useGlobalState(routerState.routeItemDataState, synchronizer),
641
642
  useScrollMap: () => useGlobalState(routerState.scrollMapState, synchronizer),
642
643
  useContextState: () => useGlobalState(routerState.contextState, synchronizer),
643
644
  useBlockedTargetState: () => useGlobalState(routerState.blockedTargetState, synchronizer),
644
- useLoaderState: () => useGlobalState(routerState.loaderState, synchronizer)[0],
645
645
  useParams: () => {
646
- const { routeItem, location } = routerState.routeItemDataState.getState();
646
+ const { routeItem, location } = routerState.routeDataState.getState();
647
647
  return getParams(location, routeItem);
648
648
  },
649
649
  useNavigate: () => async (arg) => {
650
- const { location } = routerState.routeItemDataState.getState();
650
+ const { location } = routerState.routeDataState.getState();
651
651
  const prevLocation = {
652
652
  pathname: location.pathname,
653
653
  search: location.search
@@ -689,7 +689,7 @@ var createRouterInstance = (synchronizer) => {
689
689
  };
690
690
  },
691
691
  useScrollRestoration: (restorationBehavior) => () => {
692
- const { routeItem, location: { pathname } } = routerState.routeItemDataState.getState();
692
+ const { routeItem, location: { pathname } } = routerState.routeDataState.getState();
693
693
  const scrollMap = routerState.scrollMapState.getState();
694
694
  if (!routeItem || routeItem.scrollRestoration === false || !scrollMap[pathname]) return;
695
695
  const behavior = routeItem.scrollRestorationBehavior ?? restorationBehavior;
@@ -714,10 +714,14 @@ var createRouterInstance = (synchronizer) => {
714
714
  });
715
715
  });
716
716
  },
717
- useRouteItemDataSelector: (callback) => {
718
- const state = routerState.routeItemDataState;
717
+ useRouteDataSelector: (callback) => {
718
+ const state = routerState.routeDataState;
719
719
  return synchronizer(state.subscribe, () => callback(state.getState()));
720
- }
720
+ },
721
+ useSetLocation: () => (location) => routerState.routeDataState.setState((prevState) => ({
722
+ ...prevState,
723
+ location
724
+ }))
721
725
  }
722
726
  };
723
727
  };
@@ -728,8 +732,8 @@ var router = createRouterInstance(useSyncExternalStore);
728
732
  //#region hooks/useNavigation.ts
729
733
  var useNavigation = () => {
730
734
  const { navigate } = router.runtime;
731
- const { useRouteItemData, useBlockerState } = router.hooks;
732
- const [{ location }] = useRouteItemData();
735
+ const { useRouteDataSelector, useBlockerState } = router.hooks;
736
+ const location = useRouteDataSelector((state) => state.location);
733
737
  const [blockerState] = useBlockerState();
734
738
  useEffect(() => {
735
739
  const handler = async (event) => {
@@ -777,10 +781,10 @@ var useRestoreScroll = (behavior) => {
777
781
  return useScrollRestoration(behavior ?? defaultScrollRestorationBehavior);
778
782
  };
779
783
  //#endregion
780
- //#region hooks/usePreserveScroll.ts
781
- var usePreserveScroll = (behavior) => {
784
+ //#region hooks/useRestoreRouteScroll.ts
785
+ var useRestoreRouteScroll = (behavior) => {
782
786
  const restoreScroll = useRestoreScroll(behavior);
783
- useEffect(() => restoreScroll?.(), [restoreScroll]);
787
+ useEffect(restoreScroll, [restoreScroll]);
784
788
  };
785
789
  //#endregion
786
790
  //#region hooks/useSetRouterConfig.ts
@@ -828,8 +832,10 @@ var IS_MOBILE = isMobile();
828
832
  var MOBILE_CACHE_SIZE = 60;
829
833
  var DESKTOP_CACHE_SIZE = 150;
830
834
  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 }) => {
831
- const { useRouteItemData } = router.hooks;
832
- const [{ routeItem, status, location }] = useRouteItemData();
835
+ const { useRouteDataSelector } = router.hooks;
836
+ const routeItem = useRouteDataSelector((state) => state.routeItem);
837
+ const location = useRouteDataSelector((state) => state.location);
838
+ const status = useRouteDataSelector((state) => state.status);
833
839
  const isError = status === "error";
834
840
  const isLoading = status === "pending";
835
841
  useNavigation();
@@ -850,7 +856,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
850
856
  });
851
857
  useApplyCustomAnimation(animationDuration);
852
858
  useSetInitialContext(initialContext);
853
- usePreserveScroll(defaultScrollRestorationBehavior);
859
+ useRestoreRouteScroll(defaultScrollRestorationBehavior);
854
860
  useReload();
855
861
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
856
862
  if (!routeItem) return null;
@@ -861,12 +867,6 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
861
867
  });
862
868
  };
863
869
  //#endregion
864
- //#region hooks/useIsRoutePending.ts
865
- var useIsRoutePending = (routePath) => {
866
- const { useRouteItemDataSelector } = router.hooks;
867
- return useRouteItemDataSelector(({ location: { pathname }, status }) => pathname === routePath && status === "pending");
868
- };
869
- //#endregion
870
870
  //#region hooks/useNavigate.ts
871
871
  var useNavigate = router.hooks.useNavigate;
872
872
  //#endregion
@@ -874,15 +874,14 @@ var useNavigate = router.hooks.useNavigate;
874
874
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
875
875
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
876
876
  var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
877
- const { useRouteItemDataSelector } = router.hooks;
878
- const isPending = useIsRoutePending(to);
877
+ const { useRouteDataSelector } = router.hooks;
878
+ const isPending = useRouteDataSelector(({ location: { pathname }, status }) => pathname === to && status === "pending");
879
879
  const navigate = useNavigate();
880
- const isActive = useRouteItemDataSelector(({ location: { pathname } }) => comparator(to, pathname, exact));
880
+ const isActive = useRouteDataSelector(({ location: { pathname } }) => comparator(to, pathname, exact));
881
881
  const timeout = useRef(0);
882
882
  const elementRef = useRef(null);
883
- const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
884
- const prefetch = linkPrefetch || configPrefetch;
885
- const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
883
+ const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
884
+ const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
886
885
  const searchString = typeof search === "object" ? formatSearchObject(search) : search;
887
886
  const location = useMemo(() => ({
888
887
  pathname: to,
@@ -894,29 +893,30 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
894
893
  to
895
894
  ]);
896
895
  const onMouseEnter = useCallback(() => {
897
- if (prefetch !== "hover" || !prefetchDelay) return;
896
+ const prefetchDelay = getPrefetchDelay();
897
+ if (getPrefetchStrategy() !== "hover" || !prefetchDelay) return;
898
898
  if (timeout.current) clearTimeout(timeout.current);
899
899
  timeout.current = window.setTimeout(() => router.runtime.prefetch(location), prefetchDelay);
900
900
  }, [
901
- prefetch,
902
- prefetchDelay,
901
+ getPrefetchStrategy,
902
+ getPrefetchDelay,
903
903
  location
904
904
  ]);
905
905
  const onMouseLeave = useCallback(() => {
906
- if (prefetch !== "hover" || !prefetchDelay) return;
906
+ if (getPrefetchStrategy() !== "hover" || !getPrefetchDelay()) return;
907
907
  if (timeout.current) {
908
908
  clearTimeout(timeout.current);
909
909
  timeout.current = 0;
910
910
  }
911
- }, [prefetch, prefetchDelay]);
911
+ }, [getPrefetchStrategy, getPrefetchDelay]);
912
912
  useEffect(() => {
913
- if (prefetch !== "render") return;
913
+ if (getPrefetchStrategy() !== "render") return;
914
914
  (async () => {
915
915
  await router.runtime.prefetch(location);
916
916
  })();
917
- }, [prefetch, location]);
917
+ }, [getPrefetchStrategy, location]);
918
918
  useEffect(() => {
919
- if (prefetch !== "viewport") return;
919
+ if (getPrefetchStrategy() !== "viewport") return;
920
920
  const element = elementRef.current;
921
921
  if (!element) return;
922
922
  const observer = new IntersectionObserver(async ([entry]) => {
@@ -926,7 +926,7 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
926
926
  });
927
927
  observer.observe(element);
928
928
  return () => observer.disconnect();
929
- }, [prefetch, location]);
929
+ }, [getPrefetchStrategy, location]);
930
930
  useEffect(() => () => {
931
931
  if (timeout.current) clearTimeout(timeout.current);
932
932
  }, []);
@@ -971,10 +971,13 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
971
971
  var useParams = router.hooks.useParams;
972
972
  //#endregion
973
973
  //#region hooks/useLocation.ts
974
- var useLocation = () => router.hooks.useRouteItemDataSelector((state) => state.location);
974
+ var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
975
975
  //#endregion
976
976
  //#region hooks/useLoaderState.ts
977
- var useLoaderState = router.hooks.useLoaderState;
977
+ var useLoaderState = () => {
978
+ const { useRouteDataSelector } = router.hooks;
979
+ return useRouteDataSelector((state) => state.loaderState);
980
+ };
978
981
  //#endregion
979
982
  //#region hooks/useInvalidate.ts
980
983
  var useInvalidate = () => router.runtime.invalidate;
@@ -1018,8 +1021,8 @@ var useAction = router.hooks.useAction;
1018
1021
  //#endregion
1019
1022
  //#region hooks/useRouteStatus.ts
1020
1023
  function useRouteStatus(predicate) {
1021
- const { useRouteItemDataSelector } = router.hooks;
1022
- return useRouteItemDataSelector(({ status }) => predicate ? predicate(status) : status);
1024
+ const { useRouteDataSelector } = router.hooks;
1025
+ return useRouteDataSelector(({ status }) => predicate ? predicate(status) : status);
1023
1026
  }
1024
1027
  //#endregion
1025
1028
  //#region hooks/useRouterContext.ts
@@ -1040,8 +1043,10 @@ var useLatest = (value) => {
1040
1043
  return ref;
1041
1044
  };
1042
1045
  var useSearchParams = () => {
1043
- const [{ location }, setRouteItemData] = router.hooks.useRouteItemData();
1044
- const { search = window.location.search, pathname = window.location.pathname } = location;
1046
+ const { useRouteDataSelector, useSetLocation } = router.hooks;
1047
+ const location = useRouteDataSelector((state) => state.location);
1048
+ const { search = window.location.search } = location;
1049
+ const setLocation = useSetLocation();
1045
1050
  const searchRef = useLatest(search);
1046
1051
  const searchParams = useMemo(() => new URLSearchParams(search), [search]);
1047
1052
  const getSearchParams = useCallback((param) => {
@@ -1051,15 +1056,12 @@ var useSearchParams = () => {
1051
1056
  const navigateWithSearchParams = useCallback((params) => {
1052
1057
  const newSearch = params.toString();
1053
1058
  const search = newSearch ? `?${newSearch}` : "";
1054
- history.replaceState(history.state, "", pathname + search);
1055
- setRouteItemData((prevState) => ({
1056
- ...prevState,
1057
- location: {
1058
- ...prevState.location,
1059
- search
1060
- }
1061
- }));
1062
- }, [pathname, setRouteItemData]);
1059
+ history.replaceState(history.state, "", (location ?? window.location).pathname + search);
1060
+ setLocation({
1061
+ ...location,
1062
+ search
1063
+ });
1064
+ }, [location, setLocation]);
1063
1065
  return {
1064
1066
  searchParams,
1065
1067
  getSearchParams,
@@ -1121,15 +1123,16 @@ var createLazyComponent = (importFn, fallback) => {
1121
1123
  var LAZY_MARKER = Symbol("clear-router-lazy");
1122
1124
  //#endregion
1123
1125
  //#region creators/createRouter.ts
1124
- var isLazy = (el) => typeof el.element === "object" && el.element !== null && LAZY_MARKER in el.element;
1126
+ var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
1127
+ var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
1125
1128
  var parseClientRouteItem = (el, parentPattern = "") => {
1126
1129
  const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
1127
- const preloadElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
1128
- const resolvedElement = isLazy(el) ? createLazyComponent(el.element.importFn, el.fallback).Component : el.element;
1130
+ const preloadElement = isLazy(el.element) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
1129
1131
  return [{
1130
1132
  ...el,
1131
1133
  pattern,
1132
- element: resolvedElement,
1134
+ element: resolve(el.element, el.fallback),
1135
+ errorElement: resolve(el.errorElement, el.fallback),
1133
1136
  preloadElement
1134
1137
  }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern)) ?? []];
1135
1138
  };
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
@@ -1,2 +1,2 @@
1
1
  import { RevalidateCache, RouterState, Location } from '../types';
2
- export declare const createPrefetch: ({ routeItemDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
2
+ export declare const createPrefetch: ({ routeDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
package/dist/types.d.ts CHANGED
@@ -24,9 +24,10 @@ export type ClientRouteItem = {
24
24
  element: RenderElement | LazyComponent;
25
25
  loader?(arg: LoaderArgs & {
26
26
  signal: AbortSignal;
27
+ attempt: number;
27
28
  }): Promise<unknown>;
28
29
  loaderFallback?: RenderElement;
29
- errorElement?: RenderElement;
30
+ errorElement?: RenderElement | LazyComponent;
30
31
  fallback?: RenderElement;
31
32
  children?: ClientRouteItem[];
32
33
  staleTime?: number;
@@ -72,10 +73,11 @@ export type LoaderState<T = unknown> = {
72
73
  beforeLoadError: Error | null;
73
74
  };
74
75
  export type Status = 'idle' | 'pending' | 'active' | 'optimistic' | 'error';
75
- export type RouteItemData = {
76
+ export type RouteData = {
76
77
  location: Location;
77
78
  routeItem: RouteItem | undefined;
78
79
  status: Status;
80
+ loaderState: LoaderState;
79
81
  };
80
82
  type ObjectRetry = {
81
83
  count: number;
@@ -117,11 +119,10 @@ export type LoadingPromise = Promise<{
117
119
  } | undefined>;
118
120
  export type ScrollMap = Record<string, [string, number][]>;
119
121
  export type RouterState = {
120
- routeItemDataState: Store<RouteItemData>;
122
+ routeDataState: Store<RouteData>;
121
123
  scrollMapState: Store<ScrollMap>;
122
124
  contextState: Store<Record<string, unknown>>;
123
125
  blockerState: Store<BlockerState>;
124
- loaderState: Store<LoaderState>;
125
126
  blockedTargetState: Store<Location | null>;
126
127
  loaderMap: Map<string, LoaderStateItem>;
127
128
  loadingPromises: Map<string, LoadingPromise>;
@@ -134,11 +135,9 @@ export type RouterType = {
134
135
  };
135
136
  hooks: {
136
137
  useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
137
- useRouteItemData(): ReturnType<typeof useGlobalState<RouteItemData>>;
138
138
  useScrollMap(): ReturnType<typeof useGlobalState<ScrollMap>>;
139
139
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
140
140
  useBlockedTargetState(): ReturnType<typeof useGlobalState<Location | null>>;
141
- useLoaderState<T>(): LoaderState<T>;
142
141
  useParams<T>(): T;
143
142
  useNavigate(): (arg: NavigationLocation | string | -1) => Promise<void>;
144
143
  useAction(action: string, options?: Options): (arg: Record<string, unknown>) => Promise<{
@@ -146,7 +145,8 @@ export type RouterType = {
146
145
  error: Error | null;
147
146
  }>;
148
147
  useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
149
- useRouteItemDataSelector<T>(callback: (arg: RouteItemData) => T): T;
148
+ useRouteDataSelector<T>(callback: (arg: RouteData) => T): T;
149
+ useSetLocation(): (location: Location) => void;
150
150
  };
151
151
  };
152
152
  export type InvalidateOptions = {
@@ -4,5 +4,5 @@ type CommitState = {
4
4
  loaderStateValue: LoaderState;
5
5
  routeItem?: RouteItem;
6
6
  };
7
- export declare const createCommitState: ({ loaderState, routeItemDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
7
+ export declare const createCommitState: ({ routeDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
8
8
  export {};
@@ -1,5 +1,5 @@
1
1
  import { Store } from '../create';
2
- import { Location, RouteItem, RouteItemData, RouterState, ScrollMap, SearchObject } from '../types';
2
+ import { Location, RouteItem, RouteData, RouterState, ScrollMap, SearchObject } from '../types';
3
3
  export declare const getParams: (location: Location, routeItem?: RouteItem) => Record<string, string>;
4
4
  export declare const parseWindowLocation: (location: typeof window.location) => Location;
5
5
  export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
@@ -13,5 +13,5 @@ export declare const getPartialLoaderArgs: (contextState: RouterState["contextSt
13
13
  location: Location;
14
14
  };
15
15
  export declare const isVerticalScroll: (el: Element | null) => boolean;
16
- export declare const updateScrollMap: (routeItemDataState: Store<RouteItemData>, scrollMapState: Store<ScrollMap>) => void;
16
+ export declare const updateScrollMap: (routeDataState: Store<RouteData>, scrollMapState: Store<ScrollMap>) => void;
17
17
  export declare const formatSearchObject: (searchObject: SearchObject) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.3.2",
3
+ "version": "2.4.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 useIsRoutePending: (routePath: string) => boolean;
@@ -1,2 +0,0 @@
1
- import { ScrollRestorationBehavior } from '../types';
2
- export declare const usePreserveScroll: (behavior?: ScrollRestorationBehavior) => void;