clear-react-router 2.0.8 → 2.0.9

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
@@ -1,5 +1,3 @@
1
- [![npm version](https://badge.fury.io/js/clear-react-router.svg)](https://www.npmjs.com/package/clear-react-router)
2
-
3
1
  # Clear Router
4
2
 
5
3
  A lightweight, type-safe routing library for client side React applications with nested routes, data loading, navigation blocking, prefetching, and route actions.
@@ -54,7 +52,7 @@ It provides first-class support for:
54
52
  | `defaultErrorElement` | `ReactElement \| () => ReactElement` | `optional` | Default error fallback for every route |
55
53
  | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
56
54
  | `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
57
- | `defaultBeforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
55
+ | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
58
56
  | `defaultAfterLoad` | `({ params, context, setContext }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
59
57
  | `defaultPreserveScroll` | `boolean \| undefined` | `true` | Default value for save and restore scroll position when navigating between pages |
60
58
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
@@ -71,7 +69,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
71
69
  |----------|------|-------------|
72
70
  | `path` | `string` | Route path, e.g., `/user/:userId` |
73
71
  | `element` | `ReactElement \| () => ReactElement \| LazyComponent` | Component to render |
74
- | `beforeLoad` | `({ params, context, redirect, setContext }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
72
+ | `beforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | Runs before every route navigation. Auth checks and redirects. Can update context via `setContext`. `redirect` is provided by the router |
75
73
  | `loader` | `({ params, context, setContext, searchParams, signal }) => Promise<unknown>` | Fetch data using route params, search params, abort controller signal and context. Can update context via `setContext` |
76
74
  | `afterLoad` | `({ params, context, setContext }) => Promise<void>` | Runs after a successful navigation once the route has finished loading. Analytics, side effects after data is loaded. Can update context via `setContext` |
77
75
  | `minLoaderDuration` | `number \| undefined` | `undefined` | Minimum time the loader fallback stays visible, to avoid flickering |
@@ -85,14 +83,31 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
85
83
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active |
86
84
  | `preserveScroll` | `boolean \| undefined` | Save and restore route scroll position when navigating between pages |
87
85
 
88
- Loader arguments:
86
+ Before load arguments (see [`redirect`](#redirect) for details on programmatic redirects):
87
+
88
+ `beforeLoad` and `loader` both receive:
89
+
90
+ ```ts
91
+ {
92
+ params: Record<string, string>; // Route parameters
93
+ context: Record<string, unknown>; // Router context
94
+ setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
95
+ searchParams: Record<string, string>; // URL search parameters
96
+ location: Location; // Route location
97
+ }
98
+ ```
99
+
100
+ `beforeLoad` additionally receives:
101
+ ```ts
102
+ {
103
+ redirect: (arg: Location | string) => Promise<void>; // Programmatic redirection, see [redirect](#redirect)
104
+ }
105
+ ```
106
+
107
+ `loader` additionally receives:
89
108
  ```ts
90
109
  {
91
- params: Record<string, string>; // Route parameters
92
- context: Record<string, unknown>; // Router context
93
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
94
- searchParams: Record<string, string>; // URL search parameters
95
- signal: AbortSignal; // AbortController signal
110
+ signal: AbortSignal; // Aborted if a newer navigation supersedes this one — pass to fetch() to cancel in-flight requests
96
111
  }
97
112
  ```
98
113
 
@@ -103,6 +118,8 @@ Component for client-side navigation with prefetch support, active state detecti
103
118
  | Prop | Type | Default | Description |
104
119
  |------|------|---------|-------------|
105
120
  | `to` | `string` | required | Target path |
121
+ | `search` | `string \| undefined` | `undefined` | Query string appended to the target path |
122
+ | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
106
123
  | `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
107
124
  | `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
108
125
  | `prefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `Router` config | Override the global prefetch strategy |
@@ -6,6 +6,8 @@ type ElementState = {
6
6
  };
7
7
  type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
8
8
  to: string;
9
+ search?: string;
10
+ state?: unknown;
9
11
  children?: ReactNode;
10
12
  as?: (props: ElementProps<T>, state: ElementState) => ReactElement;
11
13
  prefetch?: RouterProps['defaultPrefetch'];
@@ -17,5 +19,5 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
17
19
  style?: CSSProperties | ((arg: ElementState) => CSSProperties);
18
20
  exact?: boolean;
19
21
  };
20
- export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
22
+ export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
21
23
  export {};
package/dist/index.js CHANGED
@@ -30,17 +30,16 @@ var useGlobalState = ({ subscribe, getState, setState }) => {
30
30
  };
31
31
  //#endregion
32
32
  //#region utils/commitState.ts
33
- var createCommitState = ({ routeItemDataState, pendingState, isOptimisticLoading, loaderStateRef, loaderState }) => (nextLocation, routeItem) => {
33
+ var createCommitState = ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }) => (nextLocation, routeItem) => {
34
34
  routeItemDataState.setState({
35
35
  routeItem,
36
36
  location: nextLocation
37
37
  });
38
- pendingState.setState(void 0);
38
+ statusState.setState("active");
39
39
  isOptimisticLoading.setState(false);
40
40
  loaderState.setState(loaderStateRef.value);
41
- const fullPath = nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname;
42
- if (fullPath === window.location.pathname + window.location.search) return;
43
- history.pushState(null, "", fullPath);
41
+ if ((nextLocation.search ? `${nextLocation.pathname}${nextLocation.search}` : nextLocation.pathname) === window.location.pathname + window.location.search) return;
42
+ history.pushState(null, "", `${nextLocation.pathname}${nextLocation.search}`);
44
43
  };
45
44
  //#endregion
46
45
  //#region constants.ts
@@ -109,7 +108,9 @@ var routerConfig = new RouterConfig();
109
108
  var commitNavigation = (callback) => {
110
109
  if (!routerConfig.isAnimated) return callback();
111
110
  try {
112
- document.startViewTransition(callback);
111
+ const transition = document.startViewTransition(callback);
112
+ transition.ready.catch(() => {});
113
+ transition.finished.catch(() => {});
113
114
  } catch {
114
115
  callback();
115
116
  }
@@ -217,6 +218,17 @@ var isMobile = () => {
217
218
  return hasCoarsePointer && isSmallScreen;
218
219
  };
219
220
  var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
221
+ var getPartialBeforeLoadArgs = (location) => {
222
+ const params = getParamsObject();
223
+ const { contextState } = router.state;
224
+ return {
225
+ params,
226
+ context: contextState.getState(),
227
+ setContext: contextState.setState,
228
+ searchParams: Object.fromEntries(new URLSearchParams(location.search).entries()),
229
+ location
230
+ };
231
+ };
220
232
  var findRoute = (pathname, includeAll) => {
221
233
  if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
222
234
  return routerConfig.routes.find((el) => comparePaths(el, pathname));
@@ -227,7 +239,7 @@ var createNavigate = (routerState, revalidateCache) => {
227
239
  let navigationSeq = 0;
228
240
  let interval = 0;
229
241
  let abortController = null;
230
- const { loaderState, loaderStateRef, scrollMapState, pendingState, contextState, loaderMap, routeItemDataState, isOptimisticLoading } = routerState;
242
+ const { loaderState, loaderStateRef, scrollMapState, statusState, contextState, loaderMap, routeItemDataState, isOptimisticLoading } = routerState;
231
243
  const navigationExecutor = createCommitState(routerState);
232
244
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
233
245
  const createSignal = () => {
@@ -235,7 +247,7 @@ var createNavigate = (routerState, revalidateCache) => {
235
247
  abortController = new AbortController();
236
248
  return abortController.signal;
237
249
  };
238
- const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search ?? ""}`;
250
+ const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
239
251
  const getContext = () => ({
240
252
  context: contextState.getState(),
241
253
  setContext: contextState.setState
@@ -248,15 +260,14 @@ var createNavigate = (routerState, revalidateCache) => {
248
260
  params: getParamsObject(nextItem, location.pathname)
249
261
  };
250
262
  };
251
- const beforeLoad = async (routeItem, params) => {
263
+ const beforeLoad = async (routeItem, nextLocation) => {
252
264
  const { defaultBeforeLoad } = routerConfig;
253
265
  const runBeforeLoad = async (loaderFn) => {
254
266
  const redirect = async (redirected) => await navigate(typeof redirected === "string" ? { pathname: redirected } : redirected);
255
267
  try {
256
268
  await loaderFn({
257
- ...getContext(),
258
269
  redirect,
259
- params
270
+ ...getPartialBeforeLoadArgs(nextLocation)
260
271
  });
261
272
  loaderStateRef.set((prev) => ({
262
273
  ...prev,
@@ -291,19 +302,17 @@ var createNavigate = (routerState, revalidateCache) => {
291
302
  isOptimisticLoading.setState(true);
292
303
  const currentLoaderState = loaderMap.get(path)?.state;
293
304
  if (currentLoaderState) loaderState.setState(currentLoaderState);
294
- } else if (routeItem?.loader && !isCacheItemFresh(path)) commitNavigation(() => pendingState.setState({
295
- routeItem,
296
- location
297
- }));
298
- else pendingState.setState(void 0);
305
+ } else {
306
+ const pendingShouldExist = routeItem?.loader && !isCacheItemFresh(path);
307
+ commitNavigation(() => statusState.setState(pendingShouldExist ? "pending" : "active"));
308
+ }
299
309
  };
300
310
  const polling = (routeItem, nextLocation) => {
301
311
  if (!routeItem?.pollingInterval) return;
302
312
  const signal = createSignal();
303
313
  interval = window.setInterval(() => revalidateCache({
304
314
  routeItem,
305
- pathname: nextLocation.pathname,
306
- search: nextLocation.search,
315
+ location: nextLocation,
307
316
  signal
308
317
  }), routeItem.pollingInterval);
309
318
  };
@@ -317,8 +326,7 @@ var createNavigate = (routerState, revalidateCache) => {
317
326
  const signal = createSignal();
318
327
  const [result] = await Promise.all([revalidateCache({
319
328
  routeItem,
320
- pathname: nextLocation.pathname,
321
- search: nextLocation.search,
329
+ location: nextLocation,
322
330
  signal
323
331
  }), getLoaderDurationPromise(routeItem, nextLocation)]);
324
332
  if (result) loaderStateRef.set((prev) => ({
@@ -339,11 +347,15 @@ var createNavigate = (routerState, revalidateCache) => {
339
347
  params
340
348
  });
341
349
  };
342
- const navigate = async (nextLocation) => {
350
+ const navigate = async (rawLocation) => {
351
+ const nextLocation = {
352
+ ...rawLocation,
353
+ search: rawLocation.search ?? ""
354
+ };
343
355
  navigationSeq = navigationSeq + 1;
344
356
  const seq = navigationSeq;
345
357
  const { nextItem, params } = routeResolve(nextLocation);
346
- await beforeLoad(nextItem, params);
358
+ await beforeLoad(nextItem, nextLocation);
347
359
  if (seq !== navigationSeq) return;
348
360
  prepareNavigation(nextItem, nextLocation);
349
361
  await loader(nextItem, nextLocation, seq);
@@ -356,22 +368,20 @@ var createNavigate = (routerState, revalidateCache) => {
356
368
  //#endregion
357
369
  //#region runtime/invalidate.ts
358
370
  var redirect = Promise.resolve;
359
- var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextState }, revalidateCache) => {
371
+ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
360
372
  const invalidatePath = async (routeItem, pathname, options) => {
361
373
  const routePathname = routeItemDataState.getState().location.pathname;
362
374
  loaderMap.delete(pathname);
363
- const params = getParamsObject();
364
- try {
365
- if (routeItem?.beforeLoad && options?.withBeforeLoad) {
366
- const context = contextState.getState();
367
- const setContext = contextState.setState;
368
- await routeItem.beforeLoad({
369
- context,
370
- redirect,
371
- params,
372
- setContext
373
- });
374
- }
375
+ const [path, search = ""] = pathname.split("?");
376
+ const location = {
377
+ pathname: path,
378
+ search
379
+ };
380
+ if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
381
+ await routeItem.beforeLoad({
382
+ redirect,
383
+ ...getPartialBeforeLoadArgs(location)
384
+ });
375
385
  loaderState.setState((prev) => ({
376
386
  ...prev,
377
387
  beforeLoadError: null
@@ -384,7 +394,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
384
394
  }
385
395
  const result = await revalidateCache({
386
396
  routeItem,
387
- pathname
397
+ location
388
398
  });
389
399
  if (result && pathname === routePathname) loaderState.setState({
390
400
  data: result.data,
@@ -397,7 +407,7 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
397
407
  };
398
408
  };
399
409
  const invalidateItem = async (pathname, options) => {
400
- const routeItem = findRoute(pathname);
410
+ const routeItem = findRoute(pathname.split("?")[0]);
401
411
  if (!routeItem) return [];
402
412
  const pathnameSet = /* @__PURE__ */ new Set();
403
413
  for (const [key] of loaderMap) if (comparePaths(routeItem, key)) pathnameSet.add(key);
@@ -415,13 +425,15 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
415
425
  };
416
426
  //#endregion
417
427
  //#region runtime/prefetch.ts
418
- var createPrefetch = (revalidateCache) => async (pathname) => {
419
- const item = findRoute(pathname);
428
+ var createPrefetch = ({ routeItemDataState }, revalidateCache) => async (location) => {
429
+ const item = findRoute(location.pathname);
420
430
  if (item) {
431
+ const currentLocation = routeItemDataState.getState().location;
432
+ if (location.pathname === currentLocation.pathname && location.search === currentLocation.search) return;
421
433
  await item.preloadElement?.();
422
434
  await revalidateCache({
423
435
  routeItem: item,
424
- pathname
436
+ location
425
437
  });
426
438
  }
427
439
  };
@@ -459,9 +471,10 @@ var createRevalidateCache = (routerState) => {
459
471
  }
460
472
  return item;
461
473
  };
462
- const revalidateCache = async ({ routeItem, pathname, search = "", signal }, retried = 0) => {
474
+ const revalidateCache = async ({ routeItem, location, signal }, retried = 0) => {
463
475
  if (!routeItem?.loader) return;
464
476
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
477
+ const { pathname, search = "" } = location;
465
478
  const path = `${pathname}${search}`;
466
479
  if (loadingPromises.has(path)) {
467
480
  moveItemToLastPosition(path);
@@ -491,7 +504,8 @@ var createRevalidateCache = (routerState) => {
491
504
  context,
492
505
  setContext,
493
506
  searchParams,
494
- signal: effectiveSignal
507
+ signal: effectiveSignal,
508
+ location
495
509
  });
496
510
  loaderMap.set(path, {
497
511
  state: {
@@ -516,12 +530,15 @@ var createRevalidateCache = (routerState) => {
516
530
  if (retry && retry.count > retried) {
517
531
  loadingPromises.delete(path);
518
532
  if (retry.delay) await sleep(retry.delay);
519
- return revalidateCache({
533
+ await revalidateCache({
520
534
  routeItem,
521
- pathname,
522
- search,
535
+ location,
523
536
  signal
524
537
  }, retried + 1);
538
+ return {
539
+ data: null,
540
+ error
541
+ };
525
542
  } else return {
526
543
  data: null,
527
544
  error
@@ -557,7 +574,7 @@ var createRouterInstance = () => {
557
574
  routeItem: void 0,
558
575
  location: {}
559
576
  }),
560
- pendingState: create(void 0),
577
+ statusState: create("idle"),
561
578
  scrollMapState: create({}),
562
579
  contextState: create({}),
563
580
  blockedRouteState: create({
@@ -573,7 +590,7 @@ var createRouterInstance = () => {
573
590
  const revalidateCache = createRevalidateCache(routerState);
574
591
  const invalidate = createInvalidate(routerState, revalidateCache);
575
592
  const navigate = createNavigate(routerState, revalidateCache);
576
- const prefetch = createPrefetch(revalidateCache);
593
+ const prefetch = createPrefetch(routerState, revalidateCache);
577
594
  const useGetAction = (actionKey) => {
578
595
  const { routeItem } = routerState.routeItemDataState.getState();
579
596
  const context = routerState.contextState.getState();
@@ -604,7 +621,7 @@ var createRouterInstance = () => {
604
621
  useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
605
622
  useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
606
623
  useScrollMap: () => useGlobalState(routerState.scrollMapState),
607
- usePendingState: () => useGlobalState(routerState.pendingState),
624
+ useStatus: () => useGlobalState(routerState.statusState),
608
625
  useContextState: () => useGlobalState(routerState.contextState),
609
626
  useOptimisticLoading: () => useGlobalState(routerState.isOptimisticLoading),
610
627
  useLoaderState: () => useGlobalState(routerState.loaderState)[0],
@@ -764,12 +781,12 @@ var IS_MOBILE = isMobile();
764
781
  var MOBILE_CACHE_SIZE = 60;
765
782
  var DESKTOP_CACHE_SIZE = 150;
766
783
  var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, defaultPreserveScroll = true, defaultMinLoaderDuration = 0, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, errorBoundary: ErrorBoundary = EmptyBoundary }) => {
767
- const { useRouteItemData, usePendingState, useOptimisticLoading } = router.hooks;
784
+ const { useRouteItemData, useStatus, useOptimisticLoading } = router.hooks;
768
785
  const [routeItemData] = useRouteItemData();
769
- const [pendingRouteData] = usePendingState();
786
+ const [status] = useStatus();
770
787
  const [isOptimisticLoading] = useOptimisticLoading();
771
788
  const loaderState = useLoaderState();
772
- const isLoading = Boolean(pendingRouteData);
789
+ const isLoading = status === "pending";
773
790
  useNavigation();
774
791
  useSetRouterConfig({
775
792
  routes,
@@ -789,7 +806,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
789
806
  usePreserveScroll(routeItemData);
790
807
  const { routeItem, location } = routeItemData;
791
808
  const showErrorElement = !isLoading && Boolean(loaderState.loaderError || loaderState.beforeLoadError);
792
- if (!showErrorElement && isLoading) return renderElement(pendingRouteData?.routeItem?.loaderFallback || defaultLoaderFallback);
809
+ if (!showErrorElement && isLoading) return renderElement(routeItemData?.routeItem?.loaderFallback || defaultLoaderFallback);
793
810
  if (!routeItem) return null;
794
811
  if (showErrorElement) return renderElement(routeItem.errorElement || defaultErrorElement);
795
812
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
@@ -800,9 +817,10 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
800
817
  //#endregion
801
818
  //#region hooks/useIsRoutePending.ts
802
819
  var useIsRoutePending = (routePath) => {
803
- const { usePendingState } = router.hooks;
804
- const [pendingState] = usePendingState();
805
- return pendingState?.location.pathname === routePath;
820
+ const { useStatus, useRouteItemData } = router.hooks;
821
+ const [routeItemData] = useRouteItemData();
822
+ const [status] = useStatus();
823
+ return status === "pending" && routeItemData?.location.pathname === routePath;
806
824
  };
807
825
  //#endregion
808
826
  //#region hooks/useNavigate.ts
@@ -816,7 +834,7 @@ var useLocation = () => {
816
834
  //#endregion
817
835
  //#region components/Link.tsx
818
836
  var defaultAs = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...props });
819
- var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
837
+ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
820
838
  const isPending = useIsRoutePending(to);
821
839
  const { pathname } = useLocation();
822
840
  const navigate = useNavigate();
@@ -825,14 +843,23 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
825
843
  const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
826
844
  const prefetch = linkPrefetch || configPrefetch;
827
845
  const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
846
+ const location = useMemo(() => ({
847
+ pathname: to,
848
+ search,
849
+ state
850
+ }), [
851
+ search,
852
+ state,
853
+ to
854
+ ]);
828
855
  const onMouseEnter = useCallback(() => {
829
856
  if (prefetch !== "hover" || !prefetchDelay) return;
830
857
  if (timeout.current) clearTimeout(timeout.current);
831
- timeout.current = window.setTimeout(() => router.runtime.prefetch(to), prefetchDelay);
858
+ timeout.current = window.setTimeout(() => router.runtime.prefetch(location), prefetchDelay);
832
859
  }, [
833
860
  prefetch,
834
861
  prefetchDelay,
835
- to
862
+ location
836
863
  ]);
837
864
  const onMouseLeave = useCallback(() => {
838
865
  if (prefetch !== "hover" || !prefetchDelay) return;
@@ -844,21 +871,21 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
844
871
  useEffect(() => {
845
872
  if (prefetch !== "render") return;
846
873
  (async () => {
847
- await router.runtime.prefetch(to);
874
+ await router.runtime.prefetch(location);
848
875
  })();
849
- }, [prefetch, to]);
876
+ }, [prefetch, location]);
850
877
  useEffect(() => {
851
878
  if (prefetch !== "viewport") return;
852
879
  const element = elementRef.current;
853
880
  if (!element) return;
854
881
  const observer = new IntersectionObserver(async ([entry]) => {
855
882
  if (!entry.isIntersecting) return;
856
- await router.runtime.prefetch(to);
883
+ await router.runtime.prefetch(location);
857
884
  observer.disconnect();
858
885
  });
859
886
  observer.observe(element);
860
887
  return () => observer.disconnect();
861
- }, [prefetch, to]);
888
+ }, [prefetch, location]);
862
889
  useEffect(() => () => {
863
890
  if (timeout.current) clearTimeout(timeout.current);
864
891
  }, []);
@@ -880,7 +907,7 @@ var Link = ({ children, to, as = defaultAs, prefetch: linkPrefetch, hoverPrefetc
880
907
  if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
881
908
  event.preventDefault();
882
909
  await beforeNavigate?.();
883
- await navigate(to);
910
+ await navigate(location);
884
911
  };
885
912
  return as({
886
913
  ref: elementRef,
@@ -988,9 +1015,9 @@ var useAction = router.hooks.useAction;
988
1015
  //#endregion
989
1016
  //#region hooks/useIsDataLoading.ts
990
1017
  var useIsDataLoading = () => {
991
- const { usePendingState } = router.hooks;
992
- const [pendingState] = usePendingState();
993
- return Boolean(pendingState);
1018
+ const { useStatus } = router.hooks;
1019
+ const [status] = useStatus();
1020
+ return status === "pending";
994
1021
  };
995
1022
  //#endregion
996
1023
  //#region hooks/useRouterContext.ts
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap, contextState }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeItemDataState, loaderState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
@@ -1,2 +1,2 @@
1
1
  import { Location, RevalidateCache, RouterState } from '../types';
2
- export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (nextLocation: Location) => Promise<void>;
2
+ export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (rawLocation: Location) => Promise<void>;
@@ -1,2 +1,2 @@
1
- import { RevalidateCache } from '../types';
2
- export declare const createPrefetch: (revalidateCache: RevalidateCache) => (pathname: string) => Promise<void>;
1
+ import { RevalidateCache, RouterState } from '../types';
2
+ export declare const createPrefetch: ({ routeItemDataState }: RouterState, revalidateCache: RevalidateCache) => (location: Location) => Promise<void>;
package/dist/types.d.ts CHANGED
@@ -14,6 +14,8 @@ export type BeforeLoad = (arg: {
14
14
  redirect: (arg: Location | string) => Promise<void>;
15
15
  params: Record<string, string>;
16
16
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
17
+ searchParams: Record<string, string>;
18
+ location: Location;
17
19
  }) => Promise<unknown> | undefined | void;
18
20
  export type ClientRouteItem = {
19
21
  path: string;
@@ -24,6 +26,7 @@ export type ClientRouteItem = {
24
26
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
25
27
  searchParams: Record<string, string>;
26
28
  signal: AbortSignal;
29
+ location: Location;
27
30
  }): Promise<unknown>;
28
31
  loaderFallback?: RenderElement;
29
32
  errorElement?: RenderElement;
@@ -63,9 +66,8 @@ export type Location = {
63
66
  };
64
67
  export type BlockerState = 'blocked' | 'unblocked' | 'charged';
65
68
  export type RevalidateCacheArgs = {
66
- pathname: string;
69
+ location: Location;
67
70
  routeItem?: RouteItem;
68
- search?: string;
69
71
  signal?: AbortSignal;
70
72
  };
71
73
  export type LoaderState<T = unknown> = {
@@ -115,9 +117,10 @@ export type LoadingPromise = Promise<{
115
117
  data: null;
116
118
  error: unknown;
117
119
  } | undefined>;
120
+ export type Status = 'idle' | 'pending' | 'active';
118
121
  export type RouterState = {
119
122
  routeItemDataState: Store<RouteItemData>;
120
- pendingState: Store<RouteItemData | undefined>;
123
+ statusState: Store<Status>;
121
124
  scrollMapState: Store<Record<string, number>>;
122
125
  contextState: Store<Record<string, unknown>>;
123
126
  blockedRouteState: Store<{
@@ -135,7 +138,7 @@ export type RouterType = {
135
138
  runtime: {
136
139
  navigate(arg: Location): Promise<void>;
137
140
  invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
138
- prefetch(pathname: string): Promise<void>;
141
+ prefetch(location: Location): Promise<void>;
139
142
  };
140
143
  hooks: {
141
144
  useBlockedRoute: () => ReturnType<typeof useGlobalState<{
@@ -144,7 +147,7 @@ export type RouterType = {
144
147
  }>>;
145
148
  useRouteItemData: () => ReturnType<typeof useGlobalState<RouteItemData>>;
146
149
  useScrollMap: () => ReturnType<typeof useGlobalState<Record<string, number>>>;
147
- usePendingState: () => ReturnType<typeof useGlobalState<RouteItemData | undefined>>;
150
+ useStatus: () => ReturnType<typeof useGlobalState<Status>>;
148
151
  useContextState: () => ReturnType<typeof useGlobalState<Record<string, unknown>>>;
149
152
  useOptimisticLoading: () => ReturnType<typeof useGlobalState<boolean>>;
150
153
  useLoaderState: <T>() => LoaderState<T>;
@@ -1,2 +1,2 @@
1
1
  import { Location, RouteItem, RouterState } from '../types';
2
- export declare const createCommitState: ({ routeItemDataState, pendingState, isOptimisticLoading, loaderStateRef, loaderState }: RouterState) => (nextLocation: Location, routeItem: RouteItem | undefined) => void;
2
+ export declare const createCommitState: ({ routeItemDataState, statusState, isOptimisticLoading, loaderStateRef, loaderState }: RouterState) => (nextLocation: Location, routeItem: RouteItem | undefined) => void;
@@ -1,2 +1,2 @@
1
1
  import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
2
- export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, pathname, search, signal }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
2
+ export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
@@ -5,3 +5,10 @@ export declare const parseWindowLocation: (location: typeof window.location) =>
5
5
  export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
6
6
  export declare const isMobile: () => boolean;
7
7
  export declare const sleep: (ms: number) => Promise<unknown>;
8
+ export declare const getPartialBeforeLoadArgs: (location: Location) => {
9
+ params: Record<string, string>;
10
+ context: Record<string, unknown>;
11
+ setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
12
+ searchParams: Record<string, string>;
13
+ location: Location;
14
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.0.8",
3
+ "version": "2.0.9",
4
4
  "description": "A lightweight, type-safe routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
@@ -16,12 +16,14 @@
16
16
  "data-loading",
17
17
  "navigation-blocker",
18
18
  "scroll-restoration",
19
- "breadcrumbs",
20
19
  "search-params",
21
20
  "lazy-loading",
22
21
  "prefetching",
23
22
  "view-transitions",
24
- "animations"
23
+ "animations",
24
+ "retry",
25
+ "polling",
26
+ "cache-invalidation"
25
27
  ],
26
28
  "repository": {
27
29
  "type": "git",