clear-react-router 2.1.8 → 2.2.0

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
@@ -121,7 +121,7 @@ Component for client-side navigation with prefetch support, active state detecti
121
121
  | Prop | Type | Default | Description |
122
122
  |------|------|---------|-------------|
123
123
  | `to` | `string` | required | Target path |
124
- | `search` | `string \| undefined` | `undefined` | Query string appended to the target path |
124
+ | `search` | `string \| Record<string, string \| number \| boolean \| null \| undefined> \| undefined` | `undefined` | Query string or object appended to the target path |
125
125
  | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
126
126
  | `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 |
127
127
  | `exact` | `boolean` | `false` | When `false`, the link is also considered active if the current URL starts with `to` (useful for nested routes) |
@@ -235,8 +235,8 @@ import { Button } from '@mui/material';
235
235
  Dashboard
236
236
  </Link>
237
237
 
238
- // With dynamic style
239
- <Link to="/profile" style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}>
238
+ // With dynamic style and search object
239
+ <Link to={{ pathname: '/profile', search: { user: 'John Doe' } }} style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}>
240
240
  Profile
241
241
  </Link>
242
242
 
@@ -538,16 +538,16 @@ const App = () => <Router routes={routes} errorBoundary={ErrorBoundary} />
538
538
 
539
539
  ### `useNavigate()`
540
540
 
541
- Returns function to navigate programmatically. Accepts a string (pathname), an object of type Location, or `-1` to go back.
541
+ Returns a function to navigate programmatically. Accepts a string (pathname, optionally with a `?query`), a `NavigationLocation` object, or `-1` to go back.
542
542
 
543
543
  ```tsx
544
- type Location = { pathname: string; search?: string; state?: unknown }
544
+ type NavigationLocation = { pathname: string; search?: string | Record<string, string | number | boolean | null | undefined>; state?: unknown }
545
545
 
546
546
  const navigate = useNavigate();
547
547
 
548
- navigate('/about'); // string
549
- navigate({ pathname: '/user/123', state: { from: 'home' } }); // Location
550
- navigate(-1); // go back
548
+ navigate('/about'); // string
549
+ navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
550
+ navigate(-1); // go back
551
551
  ```
552
552
 
553
553
  **Note:** Navigation state can be accessed via `useLocation()`:
@@ -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,12 +1,12 @@
1
1
  import { type CSSProperties, ReactNode, ReactElement } from 'react';
2
- import { ElementProps, RouterProps } from '../types';
2
+ import { ElementProps, RouterProps, SearchObject } from '../types';
3
3
  type ElementState = {
4
4
  isActive: boolean;
5
5
  isPending: boolean;
6
6
  };
7
7
  type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
8
8
  to: string;
9
- search?: string;
9
+ search?: string | SearchObject;
10
10
  state?: unknown;
11
11
  children?: ReactNode;
12
12
  as?: (props: ElementProps<T>, state: ElementState) => ReactElement;
@@ -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 {};
@@ -1 +1 @@
1
- export declare const useNavigate: () => (arg: import("..").Location | string | -1) => Promise<void>;
1
+ export declare const useNavigate: () => (arg: import("..").NavigationLocation | string | -1) => Promise<void>;
package/dist/index.d.ts CHANGED
@@ -13,4 +13,4 @@ export { useSearchParams } from './hooks/useSearchParams';
13
13
  export { useSubmitAction } from './hooks/useSubmitAction';
14
14
  export { createRouter } from './creators/createRouter';
15
15
  export { lazy } from './utils/lazy';
16
- export type { RouteItem, BlockerState, Location, RouterProps, ElementProps } from './types';
16
+ export type { RouteItem, BlockerState, Location, RouterProps, ElementProps, NavigationLocation } from './types';
package/dist/index.js CHANGED
@@ -209,6 +209,14 @@ var restoreScroll = (scrollMap, pathname, behavior) => {
209
209
  });
210
210
  });
211
211
  };
212
+ var formatSearchObject = (searchObject) => {
213
+ const params = new URLSearchParams();
214
+ Object.entries(searchObject).forEach(([key, value]) => {
215
+ if (value !== void 0 && value !== null) params.set(key, String(value));
216
+ });
217
+ const result = params.toString();
218
+ return result ? `?${result}` : "";
219
+ };
212
220
  var findRoute = (pathname, includeAll) => {
213
221
  if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
214
222
  return routerConfig.routes.find((el) => comparePaths(el, pathname));
@@ -219,7 +227,7 @@ var createNavigate = (routerState, revalidateCache) => {
219
227
  let navigationSeq = 0;
220
228
  let interval = 0;
221
229
  let abortController = null;
222
- const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState } = routerState;
230
+ const { loaderState, loaderStateRef, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
223
231
  const commitState = createCommitState(routerState);
224
232
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
225
233
  const createSignal = () => {
@@ -323,11 +331,20 @@ var createNavigate = (routerState, revalidateCache) => {
323
331
  params
324
332
  });
325
333
  };
334
+ const checkBlocked = (nextLocation) => {
335
+ if (blockerState.getState() === "charged") {
336
+ blockerState.setState("blocked");
337
+ blockedTargetState.setState(nextLocation);
338
+ return true;
339
+ }
340
+ return false;
341
+ };
326
342
  const navigate = async (rawLocation) => {
327
343
  const nextLocation = {
328
344
  ...rawLocation,
329
345
  search: rawLocation.search ?? ""
330
346
  };
347
+ if (checkBlocked(nextLocation)) return;
331
348
  navigationSeq = navigationSeq + 1;
332
349
  const seq = navigationSeq;
333
350
  const { nextItem, params } = routeResolve(nextLocation);
@@ -531,12 +548,10 @@ var createRouterInstance = () => {
531
548
  }),
532
549
  scrollMapState: create({}),
533
550
  contextState: create({}),
534
- blockedRouteState: create({
535
- from: "",
536
- to: ""
537
- }),
551
+ blockerState: create("unblocked"),
538
552
  loaderState: create(EMPTY_LOADER_STATE),
539
553
  loaderStateRef: new Cell(EMPTY_LOADER_STATE),
554
+ blockedTargetState: create(null),
540
555
  loaderMap: /* @__PURE__ */ new Map(),
541
556
  loadingPromises: /* @__PURE__ */ new Map()
542
557
  };
@@ -570,7 +585,7 @@ var createRouterInstance = () => {
570
585
  prefetch
571
586
  },
572
587
  hooks: {
573
- useBlockedRoute: () => useGlobalState(routerState.blockedRouteState),
588
+ useBlockerState: () => useGlobalState(routerState.blockerState),
574
589
  useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
575
590
  useScrollMap: () => useGlobalState(routerState.scrollMapState),
576
591
  useContextState: () => useGlobalState(routerState.contextState),
@@ -580,21 +595,22 @@ var createRouterInstance = () => {
580
595
  return getParams(location, routeItem);
581
596
  },
582
597
  useNavigate: () => {
583
- const { blockedRouteState } = routerState;
584
598
  const { location } = routerState.routeItemDataState.getState();
585
599
  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
600
  if (arg === -1) return history.go(arg);
595
601
  if (typeof arg === "string") {
596
- if (arg !== location.pathname) await navigate({ pathname: arg });
597
- } else if (JSON.stringify(arg) !== JSON.stringify(location)) await navigate(arg);
602
+ const [pathname, search = ""] = arg.split("?");
603
+ if (pathname !== location.pathname || search !== location.search) await navigate({
604
+ pathname,
605
+ search
606
+ });
607
+ return;
608
+ }
609
+ const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
610
+ await navigate({
611
+ ...arg,
612
+ search
613
+ });
598
614
  };
599
615
  },
600
616
  useAction: (action, options = {}) => {
@@ -632,23 +648,19 @@ var router = createRouterInstance();
632
648
  //#endregion
633
649
  //#region hooks/useNavigation.ts
634
650
  var useNavigation = () => {
635
- const { state: { routeItemDataState, blockedRouteState }, runtime: { navigate } } = router;
651
+ const { navigate } = router.runtime;
652
+ const { blockerState, routeItemDataState } = router.state;
636
653
  useEffect(() => {
637
654
  const handler = async (event) => {
638
655
  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);
656
+ if (blockerState.getState() === "charged") history.pushState(null, "", routeItemDataState.getState().location.pathname);
657
+ await navigate(newLocation);
646
658
  };
647
659
  window.addEventListener("popstate", handler);
648
660
  return () => window.removeEventListener("popstate", handler);
649
661
  }, [
650
- blockedRouteState,
651
662
  navigate,
663
+ blockerState,
652
664
  routeItemDataState
653
665
  ]);
654
666
  useEffect(() => {
@@ -845,12 +857,13 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
845
857
  const { defaultPrefetch: configPrefetch, defaultHoverPrefetchDelay: configPrefetchDelay } = routerConfig;
846
858
  const prefetch = linkPrefetch || configPrefetch;
847
859
  const prefetchDelay = hoverPrefetchDelay ?? configPrefetchDelay;
860
+ const searchString = typeof search === "object" ? formatSearchObject(search) : search;
848
861
  const location = useMemo(() => ({
849
862
  pathname: to,
850
- search,
863
+ search: searchString,
851
864
  state
852
865
  }), [
853
- search,
866
+ searchString,
854
867
  state,
855
868
  to
856
869
  ]);
@@ -937,45 +950,37 @@ var useInvalidate = () => router.runtime.invalidate;
937
950
  //#endregion
938
951
  //#region hooks/useBlocker.ts
939
952
  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
- ]);
953
+ const { hooks: { useBlockerState, useContextState }, runtime: { navigate }, state: { blockedTargetState } } = router;
954
+ const [nextLocation, setNextLocation] = useGlobalState(blockedTargetState);
955
+ const [blockerState, setBlockerState] = useBlockerState();
956
+ const [context] = useContextState();
957
+ const location = useLocation();
958
+ const shouldBlock = blockerFn(useMemo(() => ({
959
+ location,
960
+ nextLocation,
961
+ context
962
+ }), [
963
+ context,
964
+ location,
965
+ nextLocation
966
+ ]));
967
+ useEffect(() => setBlockerState(shouldBlock ? "charged" : "unblocked"), [setBlockerState, shouldBlock]);
975
968
  return {
976
969
  state: blockerState,
977
- process: () => updateBlockedRoute({ type: "process" }),
978
- reset: () => updateBlockedRoute({ type: "reset" })
970
+ process: useCallback(async () => {
971
+ if (nextLocation) await navigate(nextLocation);
972
+ setBlockerState("unblocked");
973
+ setNextLocation(null);
974
+ }, [
975
+ navigate,
976
+ nextLocation,
977
+ setBlockerState,
978
+ setNextLocation
979
+ ]),
980
+ reset: useCallback(() => {
981
+ setBlockerState("charged");
982
+ setNextLocation(null);
983
+ }, [setBlockerState, setNextLocation])
979
984
  };
980
985
  };
981
986
  //#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,16 +134,13 @@ 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>>>;
146
141
  useLoaderState<T>(): LoaderState<T>;
147
142
  useParams<T>(): T;
148
- useNavigate(): (arg: Location | string | -1) => Promise<void>;
143
+ useNavigate(): (arg: NavigationLocation | string | -1) => Promise<void>;
149
144
  useAction(action: string, options?: Options): (arg: FormData) => Promise<{
150
145
  data: unknown;
151
146
  error: Error | null;
@@ -177,4 +172,8 @@ export type ElementProps<T extends HTMLElement = HTMLElement> = {
177
172
  onMouseLeave(event: MouseEvent): void;
178
173
  children?: ReactNode;
179
174
  };
175
+ export type SearchObject = Record<string, string | number | boolean | null | undefined>;
176
+ export type NavigationLocation = Omit<Location, 'search'> & {
177
+ search?: string | SearchObject;
178
+ };
180
179
  export {};
@@ -1,5 +1,5 @@
1
- import { Location, RouteItem, RouteItemData, RouterState, ScrollMap, ScrollRestorationBehavior } from '../types';
2
1
  import { Store } from '../create';
2
+ import { Location, RouteItem, RouteItemData, RouterState, ScrollMap, ScrollRestorationBehavior, 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;
@@ -15,3 +15,4 @@ export declare const getPartialLoaderArgs: (contextState: RouterState["contextSt
15
15
  export declare const isVerticalScroll: (el: Element | null) => boolean;
16
16
  export declare const updateScrollMap: (routeItemDataState: Store<RouteItemData>, scrollMapState: Store<ScrollMap>) => void;
17
17
  export declare const restoreScroll: (scrollMap: ScrollMap, pathname: string, behavior: ScrollRestorationBehavior) => void;
18
+ 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.1.8",
3
+ "version": "2.2.0",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {