clear-react-router 2.1.7 → 2.1.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
@@ -58,7 +58,8 @@ It provides first-class support for:
58
58
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
59
59
  | `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
60
60
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
61
-
61
+ | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
62
+ | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
62
63
 
63
64
  > **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
64
65
 
@@ -497,14 +498,10 @@ Return value:
497
498
  | Argument | Type | Description |
498
499
  |----------|------|-------------|
499
500
  | `action` | `string` | Name of the route action to execute. Must match a key returned from the route's `actions` configuration. |
500
- | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails and `withBeforeLoad` value to set route's `beforeLoad` to run. |
501
+ | `options` | `Options` | Optional callbacks invoked after the action succeeds or fails. |
501
502
 
502
503
  ```ts
503
- type Options = Partial<{
504
- onSuccess: (args: unknown) => void;
505
- onError: (args: unknown) => void;
506
- withBeforeLoad?: boolean;
507
- }> | undefined;
504
+ type Options = { onSuccess?: (args: unknown) => void; onError?: (args: unknown) => void }> | undefined;
508
505
  ```
509
506
 
510
507
  ```tsx
@@ -619,7 +616,7 @@ const UserProfile = () => {
619
616
 
620
617
  ### `useInvalidate()`
621
618
 
622
- Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route loader again.
619
+ Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route `loader` again.
623
620
 
624
621
  #### Current route
625
622
 
@@ -680,6 +677,13 @@ await invalidate('/about', { force: true });
680
677
  await invalidate(['/about', '/post/10'], { force: true });
681
678
  ```
682
679
 
680
+ #### Stale-only revalidation
681
+ By default, `invalidate` deletes matching cache entries and refetches them.
682
+ Pass `{ staleOnly: true }` to only revalidate entries that are already stale, leaving fresh ones untouched:
683
+ ```tsx
684
+ await invalidate('/notes', { staleOnly: true });
685
+ ```
686
+
683
687
  #### Including child routes
684
688
 
685
689
  To revalidate routes together with their cached child routes, pass the `withChildren` option:
@@ -713,15 +717,6 @@ will revalidate the cached child routes:
713
717
  /post/23
714
718
  /post/42/comments
715
719
  ```
716
- #### Including `beforeLoad`
717
-
718
- To include the `beforeLoad` function in the revalidation process, pass the `withBeforeLoad` option:
719
-
720
- ```tsx
721
- await invalidate('/posts', { withBeforeLoad: true });
722
- await invalidate(['/posts', '/users'], { withBeforeLoad: true });
723
- ```
724
-
725
720
  #### Returns
726
721
 
727
722
  An array of objects with the following structure:
@@ -746,31 +741,65 @@ Passing `invalidate` directly (`onClick={invalidate}`) is not supported because
746
741
 
747
742
  ### `useBlocker(callback)`
748
743
 
749
- Blocks navigation when callback returns `true`.
744
+ Blocks navigation - including the browser's Back/Forward buttons - while `callback` returns `true`.
745
+
746
+ The library calls `callback` on every navigation attempt with the current, target location and router context, so you can decide whether to block based on where the user is headed, not just your app's internal state:
747
+
748
+ ```ts
749
+ callback: (arg: { location: Location; nextLocation: Location | null; context: Record<string, unknown> }) => boolean
750
+ ```
751
+
752
+ - `location` - the route the user is currently on.
753
+ - `nextLocation` - where they're trying to go. `null` when nothing is blocked yet.
754
+ - `context` - router context.
750
755
 
751
756
  **Returns:**
752
757
 
753
758
  | Property | Type | Description |
754
759
  |----------|------|-------------|
755
- | `state` | `'unblocked' \| 'charged' \| 'blocked'` | Current blocker state |
756
- | `process()` | `() => void` | Confirm navigation and proceed |
757
- | `reset()` | `() => void` | Cancel navigation |
760
+ | `state` | `'unblocked' \| 'charged' \| 'blocked'` | `'unblocked'` — `callback` returns `false`, navigation isn't intercepted. `'charged'` — `callback` returns `true`, blocking is armed, but no navigation has been attempted yet. `'blocked'` — a navigation attempt was just intercepted; `nextLocation` inside `callback` now points to the attempted target. |
761
+ | `process()` | `() => void` | Confirm and complete the blocked navigation |
762
+ | `reset()` | `() => void` | Cancel the blocked navigation and stay on the current route |
758
763
 
759
764
  ```tsx
760
- const { state, process, reset } = useBlocker(() => hasUnsavedChanges);
765
+ const { state, process, reset } = useBlocker(({ nextLocation }) => hasUnsavedChanges);
761
766
 
762
767
  useEffect(() => {
763
- if (state === 'blocked') {
764
- // Show your custom modal
765
- if (confirm('Leave without saving?')) {
766
- process();
767
- } else {
768
- reset();
769
- }
770
- }
768
+ if (state === 'blocked') {
769
+ // Show your custom modal
770
+ if (confirm('Leave without saving?')) {
771
+ process();
772
+ } else {
773
+ reset();
774
+ }
775
+ }
771
776
  }, [state, process, reset]);
772
777
  ```
773
778
 
779
+ > Works for programmatic navigation and browser Back/Forward alike — including the case where the URL already changed via Back/Forward, which the library reverts until `process()` or `reset()` is called.
780
+
781
+ ### Custom Blocker component
782
+
783
+ If you'd rather not manage the `useEffect` or conditional rendering yourself, you can wrap `useBlocker` in a small render-prop component:
784
+
785
+ ```tsx
786
+ type BlockerProps = {
787
+ children: (blocker: ReturnType<typeof useBlocker>) => ReactNode;
788
+ callback: (args: BlockerCallback) => boolean;
789
+ };
790
+
791
+ const Blocker = ({ callback, children }: BlockerProps) => {
792
+ const blocker = useBlocker(callback);
793
+ return blocker.state === 'blocked' ? children(blocker) : null;
794
+ };
795
+ ```
796
+
797
+ ```tsx
798
+ <Blocker callback={() => formState.isDirty}>
799
+ {({ process, reset }) => <Dialog onConfirm={process} onClose={reset} />}
800
+ </Blocker>
801
+ ```
802
+
774
803
  ### `useIsDataLoading()`
775
804
 
776
805
  Returns a boolean indicating whether any route loader is currently fetching data. Useful for global loading indicators (progress bar, spinner in the layout, etc.).
@@ -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, 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, optimisticSpinner, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, }: RouterProps) => import("react/jsx-runtime").JSX.Element | null;
@@ -4,6 +4,8 @@ declare class RouterConfig {
4
4
  maxCacheSize: number;
5
5
  defaultPrefetch: RouterProps['defaultPrefetch'];
6
6
  isAnimated: RouterProps['isAnimated'];
7
+ revalidateOnFocus: boolean;
8
+ revalidateOnReconnect: boolean;
7
9
  defaultHoverPrefetchDelay: number;
8
10
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
9
11
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
@@ -1,8 +1,13 @@
1
- import { BlockerState } from '../types';
1
+ import { BlockerState, Location } from '../types';
2
2
  type UseBlockerReturnValue = {
3
3
  state: BlockerState;
4
4
  process(): void;
5
5
  reset(): void;
6
6
  };
7
- export declare const useBlocker: (blockerFn: () => boolean) => UseBlockerReturnValue;
7
+ type BlockerCallback = {
8
+ location: Location;
9
+ nextLocation: Location | null;
10
+ context: Record<string, unknown>;
11
+ };
12
+ export declare const useBlocker: (blockerFn: (args: BlockerCallback) => boolean) => UseBlockerReturnValue;
8
13
  export {};
@@ -0,0 +1 @@
1
+ export declare const useReload: () => void;
package/dist/index.js CHANGED
@@ -92,6 +92,8 @@ var RouterConfig = class {
92
92
  _defineProperty(this, "maxCacheSize", 0);
93
93
  _defineProperty(this, "defaultPrefetch", "hover");
94
94
  _defineProperty(this, "isAnimated", false);
95
+ _defineProperty(this, "revalidateOnFocus", false);
96
+ _defineProperty(this, "revalidateOnReconnect", false);
95
97
  _defineProperty(this, "defaultHoverPrefetchDelay", 150);
96
98
  _defineProperty(this, "defaultBeforeLoad", void 0);
97
99
  _defineProperty(this, "defaultAfterLoad", void 0);
@@ -217,7 +219,7 @@ var createNavigate = (routerState, revalidateCache) => {
217
219
  let navigationSeq = 0;
218
220
  let interval = 0;
219
221
  let abortController = null;
220
- const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState } = routerState;
222
+ const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
221
223
  const commitState = createCommitState(routerState);
222
224
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
223
225
  const createSignal = () => {
@@ -321,11 +323,20 @@ var createNavigate = (routerState, revalidateCache) => {
321
323
  params
322
324
  });
323
325
  };
326
+ const checkBlocked = (nextLocation) => {
327
+ if (blockerState.getState() === "charged") {
328
+ blockerState.setState("blocked");
329
+ blockedTargetState.setState(nextLocation);
330
+ return true;
331
+ }
332
+ return false;
333
+ };
324
334
  const navigate = async (rawLocation) => {
325
335
  const nextLocation = {
326
336
  ...rawLocation,
327
337
  search: rawLocation.search ?? ""
328
338
  };
339
+ if (checkBlocked(nextLocation)) return;
329
340
  navigationSeq = navigationSeq + 1;
330
341
  const seq = navigationSeq;
331
342
  const { nextItem, params } = routeResolve(nextLocation);
@@ -341,36 +352,20 @@ var createNavigate = (routerState, revalidateCache) => {
341
352
  };
342
353
  //#endregion
343
354
  //#region runtime/invalidate.ts
344
- var redirect = Promise.resolve;
345
- var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextState }, revalidateCache) => {
355
+ var separatePathname = (text) => text.split("?")[0];
356
+ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap }, revalidateCache) => {
346
357
  const invalidatePath = async (routeItem, pathname, options) => {
347
358
  const routePathname = routeItemDataState.getState().location.pathname;
348
- loaderMap.delete(pathname);
359
+ if (!options?.staleOnly) loaderMap.delete(pathname);
349
360
  const [path, search = ""] = pathname.split("?");
350
- const location = {
351
- pathname: path,
352
- search
353
- };
354
- if (routeItem?.beforeLoad && options?.withBeforeLoad) try {
355
- await routeItem.beforeLoad({
356
- redirect,
357
- ...getPartialLoaderArgs(contextState, location, routeItem)
358
- });
359
- loaderState.setState((prev) => ({
360
- ...prev,
361
- beforeLoadError: null
362
- }));
363
- } catch (error) {
364
- loaderState.setState((prev) => ({
365
- ...prev,
366
- beforeLoadError: error
367
- }));
368
- }
369
361
  const result = await revalidateCache({
370
362
  routeItem,
371
- location
363
+ location: {
364
+ pathname: path,
365
+ search
366
+ }
372
367
  });
373
- if (result && pathname === routePathname) loaderState.setState({
368
+ if (result && path === routePathname) loaderState.setState({
374
369
  data: result.data,
375
370
  loaderError: result.error,
376
371
  beforeLoadError: null
@@ -381,18 +376,20 @@ var createInvalidate = ({ routeItemDataState, loaderState, loaderMap, contextSta
381
376
  };
382
377
  };
383
378
  const invalidateItem = async (pathname, options) => {
384
- const routeItem = findRoute(pathname.split("?")[0]);
379
+ const routeItem = findRoute(separatePathname(pathname));
385
380
  if (!routeItem) return [];
386
381
  const pathnameSet = /* @__PURE__ */ new Set();
387
- for (const [key] of loaderMap) if (comparePaths(routeItem, key)) pathnameSet.add(key);
382
+ for (const [key] of loaderMap) if (comparePaths(routeItem, separatePathname(key))) pathnameSet.add(key);
388
383
  if (options?.force) pathnameSet.add(pathname);
389
384
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
390
385
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
391
- const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${pathname}${child.path}`, options)));
386
+ const [parentPath] = pathname.split("?");
387
+ const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${parentPath}${child.path}`, options)));
392
388
  return [...currentResults, ...childResults.flat()];
393
389
  };
394
390
  return async (pathList, options) => {
395
- const routePathname = routeItemDataState.getState().location.pathname;
391
+ const { pathname, search } = routeItemDataState.getState().location;
392
+ const routePathname = `${pathname}${search}`;
396
393
  const pathnameList = Array.isArray(pathList) ? pathList : pathList ? [pathList] : [routePathname];
397
394
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
398
395
  };
@@ -543,18 +540,16 @@ var createRouterInstance = () => {
543
540
  }),
544
541
  scrollMapState: create({}),
545
542
  contextState: create({}),
546
- blockedRouteState: create({
547
- from: "",
548
- to: ""
549
- }),
543
+ blockerState: create("unblocked"),
550
544
  loaderState: create(EMPTY_LOADER_STATE),
551
545
  loaderStateRef: new Cell(EMPTY_LOADER_STATE),
546
+ blockedTargetState: create(null),
552
547
  loaderMap: /* @__PURE__ */ new Map(),
553
548
  loadingPromises: /* @__PURE__ */ new Map()
554
549
  };
555
550
  const revalidateCache = createRevalidateCache(routerState);
556
- const invalidate = createInvalidate(routerState, revalidateCache);
557
551
  const navigate = createNavigate(routerState, revalidateCache);
552
+ const invalidate = createInvalidate(routerState, revalidateCache);
558
553
  const prefetch = createPrefetch(routerState, revalidateCache);
559
554
  const getCurrentAction = (actionKey) => {
560
555
  const { routeItem, location } = routerState.routeItemDataState.getState();
@@ -582,7 +577,7 @@ var createRouterInstance = () => {
582
577
  prefetch
583
578
  },
584
579
  hooks: {
585
- useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
580
+ useBlockerState: () => useGlobalState(routerState.blockerState),
586
581
  useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
587
582
  useScrollMap: () => useGlobalState(routerState.scrollMapState),
588
583
  useContextState: () => useGlobalState(routerState.contextState),
@@ -592,17 +587,8 @@ var createRouterInstance = () => {
592
587
  return getParams(location, routeItem);
593
588
  },
594
589
  useNavigate: () => {
595
- const { blockedRouteState } = routerState;
596
590
  const { location } = routerState.routeItemDataState.getState();
597
591
  return async (arg) => {
598
- if (arg !== -1 && blockedRouteState.getState().from) {
599
- const to = typeof arg === "object" ? arg.pathname : arg;
600
- blockedRouteState.setState((prevState) => ({
601
- ...prevState,
602
- to
603
- }));
604
- return;
605
- }
606
592
  if (arg === -1) return history.go(arg);
607
593
  if (typeof arg === "string") {
608
594
  if (arg !== location.pathname) await navigate({ pathname: arg });
@@ -614,7 +600,7 @@ var createRouterInstance = () => {
614
600
  return async (formData) => {
615
601
  try {
616
602
  const data = await currentAction(formData);
617
- await invalidate("", { withBeforeLoad: options.withBeforeLoad });
603
+ await invalidate();
618
604
  options.onSuccess?.(data);
619
605
  return {
620
606
  data,
@@ -644,23 +630,19 @@ var router = createRouterInstance();
644
630
  //#endregion
645
631
  //#region hooks/useNavigation.ts
646
632
  var useNavigation = () => {
647
- const { state: { routeItemDataState, blockedRouteState }, runtime: { navigate } } = router;
633
+ const { navigate } = router.runtime;
634
+ const { blockerState, routeItemDataState } = router.state;
648
635
  useEffect(() => {
649
636
  const handler = async (event) => {
650
637
  const newLocation = parseWindowLocation(event.target.location);
651
- if (routeItemDataState.getState().location.pathname === blockedRouteState.getState().from) {
652
- blockedRouteState.setState({
653
- from: routeItemDataState.getState().location.pathname,
654
- to: newLocation.pathname
655
- });
656
- history.pushState(null, "", routeItemDataState.getState().location.pathname);
657
- } else navigate(newLocation);
638
+ if (blockerState.getState() === "charged") history.pushState(null, "", routeItemDataState.getState().location.pathname);
639
+ await navigate(newLocation);
658
640
  };
659
641
  window.addEventListener("popstate", handler);
660
642
  return () => window.removeEventListener("popstate", handler);
661
643
  }, [
662
- blockedRouteState,
663
644
  navigate,
645
+ blockerState,
664
646
  routeItemDataState
665
647
  ]);
666
648
  useEffect(() => {
@@ -727,6 +709,25 @@ var useSetInitialContext = (initialContext) => {
727
709
  }, [initialContext, setContext]);
728
710
  };
729
711
  //#endregion
712
+ //#region hooks/useReload.ts
713
+ var useReload = () => {
714
+ const { invalidate } = router.runtime;
715
+ useEffect(() => {
716
+ if (!routerConfig.revalidateOnFocus) return;
717
+ const handler = () => {
718
+ if (document.visibilityState === "visible") invalidate("", { staleOnly: true });
719
+ };
720
+ document.addEventListener("visibilitychange", handler);
721
+ return () => document.removeEventListener("visibilitychange", handler);
722
+ }, [invalidate]);
723
+ useEffect(() => {
724
+ if (!routerConfig.revalidateOnReconnect) return;
725
+ const handler = () => invalidate("", { staleOnly: true });
726
+ window.addEventListener("online", handler);
727
+ return () => window.removeEventListener("online", handler);
728
+ }, [invalidate]);
729
+ };
730
+ //#endregion
730
731
  //#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
731
732
  /**
732
733
  * @license React
@@ -777,7 +778,7 @@ var EmptyBoundary = ({ children }) => children;
777
778
  var IS_MOBILE = isMobile();
778
779
  var MOBILE_CACHE_SIZE = 60;
779
780
  var DESKTOP_CACHE_SIZE = 150;
780
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, optimisticSpinner = true, defaultMinLoaderDuration = 0, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary }) => {
781
+ 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 }) => {
781
782
  const { useRouteItemData } = router.hooks;
782
783
  const [{ routeItem, status, location }] = useRouteItemData();
783
784
  const isError = status === "error";
@@ -794,11 +795,14 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
794
795
  defaultRetry,
795
796
  defaultStaleTime,
796
797
  defaultMinLoaderDuration,
797
- maxCacheSize
798
+ maxCacheSize,
799
+ revalidateOnFocus,
800
+ revalidateOnReconnect
798
801
  });
799
802
  useApplyCustomAnimation(animationDuration);
800
803
  useSetInitialContext(initialContext);
801
804
  usePreserveScroll(defaultScrollRestorationBehavior);
805
+ useReload();
802
806
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
803
807
  if (!routeItem) return null;
804
808
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
@@ -927,45 +931,37 @@ var useInvalidate = () => router.runtime.invalidate;
927
931
  //#endregion
928
932
  //#region hooks/useBlocker.ts
929
933
  var useBlocker = (blockerFn) => {
930
- const { hooks: { useBlockedRoute, useRouteItemData }, runtime: { navigate } } = router;
931
- const [blockedRoute, setBlockedRoute] = useBlockedRoute();
932
- const [routeItemData] = useRouteItemData();
933
- const { location: { pathname } } = routeItemData;
934
- const updateBlockedRoute = useCallback(({ type, payload = "" }) => setBlockedRoute((prevState) => {
935
- if (prevState.from === payload && type === "charge") return prevState;
936
- if (payload && prevState.from !== payload && type === "charge") return {
937
- ...prevState,
938
- from: payload
939
- };
940
- if (type === "reset") return {
941
- ...prevState,
942
- to: ""
943
- };
944
- if (type === "process") navigate({ pathname: prevState.to });
945
- if (!prevState.from && !prevState.to) return prevState;
946
- return {
947
- from: "",
948
- to: ""
949
- };
950
- }), [navigate, setBlockedRoute]);
951
- const blockerState = useMemo(() => {
952
- if (blockedRoute.from && blockedRoute.to) return "blocked";
953
- if (blockedRoute.from) return "charged";
954
- return "unblocked";
955
- }, [blockedRoute]);
956
- const shouldBlock = blockerFn();
957
- useEffect(() => updateBlockedRoute(shouldBlock ? {
958
- type: "charge",
959
- payload: pathname
960
- } : { type: "unblock" }), [
961
- shouldBlock,
962
- pathname,
963
- updateBlockedRoute
964
- ]);
934
+ const { hooks: { useBlockerState, useContextState }, runtime: { navigate }, state: { blockedTargetState } } = router;
935
+ const [nextLocation, setNextLocation] = useGlobalState(blockedTargetState);
936
+ const [blockerState, setBlockerState] = useBlockerState();
937
+ const [context] = useContextState();
938
+ const location = useLocation();
939
+ const shouldBlock = blockerFn(useMemo(() => ({
940
+ location,
941
+ nextLocation,
942
+ context
943
+ }), [
944
+ context,
945
+ location,
946
+ nextLocation
947
+ ]));
948
+ useEffect(() => setBlockerState(shouldBlock ? "charged" : "unblocked"), [setBlockerState, shouldBlock]);
965
949
  return {
966
950
  state: blockerState,
967
- process: () => updateBlockedRoute({ type: "process" }),
968
- reset: () => updateBlockedRoute({ type: "reset" })
951
+ process: useCallback(async () => {
952
+ if (nextLocation) await navigate(nextLocation);
953
+ setBlockerState("unblocked");
954
+ setNextLocation(null);
955
+ }, [
956
+ navigate,
957
+ nextLocation,
958
+ setBlockerState,
959
+ setNextLocation
960
+ ]),
961
+ reset: useCallback(() => {
962
+ setBlockerState("charged");
963
+ setNextLocation(null);
964
+ }, [setBlockerState, setNextLocation])
969
965
  };
970
966
  };
971
967
  //#endregion
@@ -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[]>;
package/dist/types.d.ts CHANGED
@@ -98,6 +98,8 @@ export type RouterProps = {
98
98
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
99
99
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
100
100
  defaultScrollRestorationBehavior?: ScrollRestorationBehavior;
101
+ revalidateOnFocus?: boolean;
102
+ revalidateOnReconnect?: boolean;
101
103
  context?: Record<string, unknown>;
102
104
  };
103
105
  export type LoaderStateItem = {
@@ -117,11 +119,9 @@ export type RouterState = {
117
119
  routeItemDataState: Store<RouteItemData>;
118
120
  scrollMapState: Store<ScrollMap>;
119
121
  contextState: Store<Record<string, unknown>>;
120
- blockedRouteState: Store<{
121
- from: string;
122
- to: string;
123
- }>;
122
+ blockerState: Store<BlockerState>;
124
123
  loaderState: Store<LoaderState>;
124
+ blockedTargetState: Store<Location | null>;
125
125
  loaderStateRef: Cell<LoaderState>;
126
126
  loaderMap: Map<string, LoaderStateItem>;
127
127
  loadingPromises: Map<string, LoadingPromise>;
@@ -134,10 +134,7 @@ export type RouterType = {
134
134
  prefetch(location: Location): Promise<void>;
135
135
  };
136
136
  hooks: {
137
- useBlockedRoute(): ReturnType<typeof useGlobalState<{
138
- from: string;
139
- to: string;
140
- }>>;
137
+ useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
141
138
  useRouteItemData(): ReturnType<typeof useGlobalState<RouteItemData>>;
142
139
  useScrollMap(): ReturnType<typeof useGlobalState<ScrollMap>>;
143
140
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
@@ -153,14 +150,13 @@ export type RouterType = {
153
150
  };
154
151
  export type InvalidateOptions = {
155
152
  withChildren?: boolean;
156
- withBeforeLoad?: boolean;
157
153
  force?: boolean;
154
+ staleOnly?: boolean;
158
155
  };
159
156
  export type RevalidateCache = (args: RevalidateCacheArgs) => LoadingPromise;
160
157
  export type Options = Partial<{
161
158
  onSuccess: (args: unknown) => void;
162
159
  onError: (args: unknown) => void;
163
- withBeforeLoad?: boolean;
164
160
  }> | undefined;
165
161
  export type InvalidateResult = {
166
162
  path: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.1.7",
3
+ "version": "2.1.9",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {