clear-react-router 2.1.8 → 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
@@ -741,31 +741,65 @@ Passing `invalidate` directly (`onClick={invalidate}`) is not supported because
741
741
 
742
742
  ### `useBlocker(callback)`
743
743
 
744
- 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.
745
755
 
746
756
  **Returns:**
747
757
 
748
758
  | Property | Type | Description |
749
759
  |----------|------|-------------|
750
- | `state` | `'unblocked' \| 'charged' \| 'blocked'` | Current blocker state |
751
- | `process()` | `() => void` | Confirm navigation and proceed |
752
- | `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 |
753
763
 
754
764
  ```tsx
755
- const { state, process, reset } = useBlocker(() => hasUnsavedChanges);
765
+ const { state, process, reset } = useBlocker(({ nextLocation }) => hasUnsavedChanges);
756
766
 
757
767
  useEffect(() => {
758
- if (state === 'blocked') {
759
- // Show your custom modal
760
- if (confirm('Leave without saving?')) {
761
- process();
762
- } else {
763
- reset();
764
- }
765
- }
768
+ if (state === 'blocked') {
769
+ // Show your custom modal
770
+ if (confirm('Leave without saving?')) {
771
+ process();
772
+ } else {
773
+ reset();
774
+ }
775
+ }
766
776
  }, [state, process, reset]);
767
777
  ```
768
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
+
769
803
  ### `useIsDataLoading()`
770
804
 
771
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,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 {};
package/dist/index.js CHANGED
@@ -219,7 +219,7 @@ var createNavigate = (routerState, revalidateCache) => {
219
219
  let navigationSeq = 0;
220
220
  let interval = 0;
221
221
  let abortController = null;
222
- const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState } = routerState;
222
+ const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
223
223
  const commitState = createCommitState(routerState);
224
224
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
225
225
  const createSignal = () => {
@@ -323,11 +323,20 @@ var createNavigate = (routerState, revalidateCache) => {
323
323
  params
324
324
  });
325
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
+ };
326
334
  const navigate = async (rawLocation) => {
327
335
  const nextLocation = {
328
336
  ...rawLocation,
329
337
  search: rawLocation.search ?? ""
330
338
  };
339
+ if (checkBlocked(nextLocation)) return;
331
340
  navigationSeq = navigationSeq + 1;
332
341
  const seq = navigationSeq;
333
342
  const { nextItem, params } = routeResolve(nextLocation);
@@ -531,12 +540,10 @@ var createRouterInstance = () => {
531
540
  }),
532
541
  scrollMapState: create({}),
533
542
  contextState: create({}),
534
- blockedRouteState: create({
535
- from: "",
536
- to: ""
537
- }),
543
+ blockerState: create("unblocked"),
538
544
  loaderState: create(EMPTY_LOADER_STATE),
539
545
  loaderStateRef: new Cell(EMPTY_LOADER_STATE),
546
+ blockedTargetState: create(null),
540
547
  loaderMap: /* @__PURE__ */ new Map(),
541
548
  loadingPromises: /* @__PURE__ */ new Map()
542
549
  };
@@ -570,7 +577,7 @@ var createRouterInstance = () => {
570
577
  prefetch
571
578
  },
572
579
  hooks: {
573
- useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
580
+ useBlockerState: () => useGlobalState(routerState.blockerState),
574
581
  useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
575
582
  useScrollMap: () => useGlobalState(routerState.scrollMapState),
576
583
  useContextState: () => useGlobalState(routerState.contextState),
@@ -580,17 +587,8 @@ var createRouterInstance = () => {
580
587
  return getParams(location, routeItem);
581
588
  },
582
589
  useNavigate: () => {
583
- const { blockedRouteState } = routerState;
584
590
  const { location } = routerState.routeItemDataState.getState();
585
591
  return async (arg) => {
586
- if (arg !== -1 && blockedRouteState.getState().from) {
587
- const to = typeof arg === "object" ? arg.pathname : arg;
588
- blockedRouteState.setState((prevState) => ({
589
- ...prevState,
590
- to
591
- }));
592
- return;
593
- }
594
592
  if (arg === -1) return history.go(arg);
595
593
  if (typeof arg === "string") {
596
594
  if (arg !== location.pathname) await navigate({ pathname: arg });
@@ -632,23 +630,19 @@ var router = createRouterInstance();
632
630
  //#endregion
633
631
  //#region hooks/useNavigation.ts
634
632
  var useNavigation = () => {
635
- const { state: { routeItemDataState, blockedRouteState }, runtime: { navigate } } = router;
633
+ const { navigate } = router.runtime;
634
+ const { blockerState, routeItemDataState } = router.state;
636
635
  useEffect(() => {
637
636
  const handler = async (event) => {
638
637
  const newLocation = parseWindowLocation(event.target.location);
639
- if (routeItemDataState.getState().location.pathname === blockedRouteState.getState().from) {
640
- blockedRouteState.setState({
641
- from: routeItemDataState.getState().location.pathname,
642
- to: newLocation.pathname
643
- });
644
- history.pushState(null, "", routeItemDataState.getState().location.pathname);
645
- } else navigate(newLocation);
638
+ if (blockerState.getState() === "charged") history.pushState(null, "", routeItemDataState.getState().location.pathname);
639
+ await navigate(newLocation);
646
640
  };
647
641
  window.addEventListener("popstate", handler);
648
642
  return () => window.removeEventListener("popstate", handler);
649
643
  }, [
650
- blockedRouteState,
651
644
  navigate,
645
+ blockerState,
652
646
  routeItemDataState
653
647
  ]);
654
648
  useEffect(() => {
@@ -937,45 +931,37 @@ var useInvalidate = () => router.runtime.invalidate;
937
931
  //#endregion
938
932
  //#region hooks/useBlocker.ts
939
933
  var useBlocker = (blockerFn) => {
940
- const { hooks: { useBlockedRoute, useRouteItemData }, runtime: { navigate } } = router;
941
- const [blockedRoute, setBlockedRoute] = useBlockedRoute();
942
- const [routeItemData] = useRouteItemData();
943
- const { location: { pathname } } = routeItemData;
944
- const updateBlockedRoute = useCallback(({ type, payload = "" }) => setBlockedRoute((prevState) => {
945
- if (prevState.from === payload && type === "charge") return prevState;
946
- if (payload && prevState.from !== payload && type === "charge") return {
947
- ...prevState,
948
- from: payload
949
- };
950
- if (type === "reset") return {
951
- ...prevState,
952
- to: ""
953
- };
954
- if (type === "process") navigate({ pathname: prevState.to });
955
- if (!prevState.from && !prevState.to) return prevState;
956
- return {
957
- from: "",
958
- to: ""
959
- };
960
- }), [navigate, setBlockedRoute]);
961
- const blockerState = useMemo(() => {
962
- if (blockedRoute.from && blockedRoute.to) return "blocked";
963
- if (blockedRoute.from) return "charged";
964
- return "unblocked";
965
- }, [blockedRoute]);
966
- const shouldBlock = blockerFn();
967
- useEffect(() => updateBlockedRoute(shouldBlock ? {
968
- type: "charge",
969
- payload: pathname
970
- } : { type: "unblock" }), [
971
- shouldBlock,
972
- pathname,
973
- updateBlockedRoute
974
- ]);
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]);
975
949
  return {
976
950
  state: blockerState,
977
- process: () => updateBlockedRoute({ type: "process" }),
978
- 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])
979
965
  };
980
966
  };
981
967
  //#endregion
package/dist/types.d.ts CHANGED
@@ -119,11 +119,9 @@ export type RouterState = {
119
119
  routeItemDataState: Store<RouteItemData>;
120
120
  scrollMapState: Store<ScrollMap>;
121
121
  contextState: Store<Record<string, unknown>>;
122
- blockedRouteState: Store<{
123
- from: string;
124
- to: string;
125
- }>;
122
+ blockerState: Store<BlockerState>;
126
123
  loaderState: Store<LoaderState>;
124
+ blockedTargetState: Store<Location | null>;
127
125
  loaderStateRef: Cell<LoaderState>;
128
126
  loaderMap: Map<string, LoaderStateItem>;
129
127
  loadingPromises: Map<string, LoadingPromise>;
@@ -136,10 +134,7 @@ export type RouterType = {
136
134
  prefetch(location: Location): Promise<void>;
137
135
  };
138
136
  hooks: {
139
- useBlockedRoute(): ReturnType<typeof useGlobalState<{
140
- from: string;
141
- to: string;
142
- }>>;
137
+ useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
143
138
  useRouteItemData(): ReturnType<typeof useGlobalState<RouteItemData>>;
144
139
  useScrollMap(): ReturnType<typeof useGlobalState<ScrollMap>>;
145
140
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.1.8",
3
+ "version": "2.1.9",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {