clear-react-router 2.2.6 → 2.2.8

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Bubnov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
+ [![npm version](https://img.shields.io/npm/v/clear-react-router.svg)](https://www.npmjs.com/package/clear-react-router)
2
+ [![CI](https://github.com/AndrewBubnov/clear-react-router/actions/workflows/ci.yml/badge.svg)](https://github.com/AndrewBubnov/clear-react-router/actions/workflows/ci.yml)
3
+
1
4
  # Clear Router
2
5
 
3
6
  A lightweight routing library for client side React applications with nested routes, data loading, navigation blocking, prefetching, and route actions.
@@ -53,8 +56,7 @@ It provides first-class support for:
53
56
  | `defaultRetry` | `number \| { count: number; delay: number }` | `optional` | Default cache revalidation retry policy for all routes |
54
57
  | `defaultStaleTime` | `number` | `optional` | Default time in milliseconds before cached loader data is considered stale |
55
58
  | `defaultBeforeLoad` | `({ params, context, redirect, setContext, location }) => Promise<unknown> \| undefined \| void` | `undefined` | Runs before every navigation. Useful for authentication, analytics, or updating shared context. |
56
- | `defaultAfterLoad` | `({ params, context, setContext }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
57
- | `defaultPreserveScroll` | `boolean \| undefined` | `true` | Default value for save and restore scroll position when navigating between pages |
59
+ | `defaultAfterLoad` | `({ params, context, searchParams }) => Promise<void>` | `undefined` | Runs after every successful navigation. Useful for analytics, page tracking, or other global side effects. |
58
60
  | `defaultPrefetch` | `'hover' \| 'render' \| 'viewport' \| 'none'` | `'hover'` for desktop, `'viewport'` for mobile | Default prefetch strategy for all `<Link>` components |
59
61
  | `defaultHoverPrefetchDelay` | `number \| undefined` | `150` | Default delay in milliseconds before prefetching on hover (only for `'hover'` strategy) |
60
62
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
@@ -144,6 +146,20 @@ Component for client-side navigation with prefetch support, active state detecti
144
146
  | `isActive` | `boolean` | `true` when the link's `to` matches the current URL considering `exact` value |
145
147
  | `isPending` | `boolean` | `true` when the target route is currently loading (loader is running) |
146
148
 
149
+ ### Accessibility
150
+
151
+ Active links expose `aria-current="page"` so screen readers announce the current page, and links whose target is loading expose `aria-busy="true"` while the loader runs. Both attributes are omitted when inactive, keeping the DOM clean.
152
+
153
+ Extra `data-*` and `aria-*` props passed to `<Link>` (e.g. `data-testid`, `aria-label`) are forwarded to the rendered element:
154
+
155
+ ```tsx
156
+ <Link to="/about" aria-label="About section" data-testid="about-link">
157
+ About
158
+ </Link>
159
+ ```
160
+
161
+ When using a custom element via `as`, these attributes arrive in `props` together with everything else — spread them onto the host element as usual.
162
+
147
163
  ### Prefetch Strategies
148
164
 
149
165
  | Strategy | Behavior |
@@ -216,7 +232,7 @@ import { Button } from '@mui/material';
216
232
  ```
217
233
  ```tsx
218
234
  // Global prefetch: hover with 100ms delay
219
- <Router routes={routes} prefetch="hover" hoverPrefetchDelay={100} />
235
+ <Router routes={routes} defaultPrefetchh="hover" defaultHoverPrefetchDelay={100} />
220
236
 
221
237
  // Override for a specific link
222
238
  <Link to="/heavy-page" prefetch="viewport">
@@ -239,7 +255,7 @@ import { Button } from '@mui/material';
239
255
  </Link>
240
256
 
241
257
  // With dynamic style and search object
242
- <Link to={{ pathname: '/profile', search: { user: 'John Doe' } }} style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}>
258
+ <Link to='/profile' search={{ user: 'John Doe' }} style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}>
243
259
  Profile
244
260
  </Link>
245
261
 
@@ -821,6 +837,57 @@ const Blocker = ({ callback, children }: BlockerProps) => {
821
837
  </Blocker>
822
838
  ```
823
839
 
840
+ ### `useRestoreScroll()`
841
+
842
+ Returns a callback that restores the saved scroll position for the current route — the same restoration the router performs automatically after every navigation, but triggered manually whenever you need it.
843
+
844
+ The automatic restore covers content that is ready when navigation finishes (including route `loader` data). Call the callback yourself for content that arrives later:
845
+
846
+ * deferred data streamed via React 19 `use()`,
847
+ * lazily loaded route chunks,
848
+ * any container that mounts after the initial render.
849
+
850
+ ```tsx
851
+ import { useRestoreScroll, useLoaderState } from 'clear-react-router';
852
+
853
+ const SlowTable = () => {
854
+ const restoreScroll = useRestoreScroll();
855
+ const { data } = useLoaderState<{ rows: Promise<Row[]> }>();
856
+
857
+ return (
858
+ <Suspense fallback={<Skeleton />}>
859
+ <Table rows={data.rows} onReady={restoreScroll} />
860
+ </Suspense>
861
+ );
862
+ };
863
+ ```
864
+
865
+ Data fetched outside the route `loader` (e.g. a `useEffect` fetch inside the component) is invisible to the router, so the automatic restore can't account for it either. The rule of thumb is simple: whenever *your* data arrives and the scrollable content is in place, call the callback:
866
+
867
+ ```tsx
868
+ const Dashboard = () => {
869
+ const restoreScroll = useRestoreScroll();
870
+ const [rows, setRows] = useState<Row[] | null>(null);
871
+
872
+ useEffect(() => {
873
+ fetchRows().then(data => {
874
+ setRows(data);
875
+ // DOM updates after setState — wait a frame so the container exists
876
+ requestAnimationFrame(() => restoreScroll());
877
+ });
878
+ }, [restoreScroll]);
879
+
880
+ return rows ? <Table rows={rows} /> : <Skeleton />;
881
+ };
882
+ ```
883
+
884
+ Details worth knowing:
885
+
886
+ * The callback reads the latest saved positions at call time, not at render time — so it stays correct even if called long after mount, and repeated calls pick up the newest data. It also works from components outside `<Router>` (e.g. a static navbar), since it doesn't depend on the render tree.
887
+ * Calling it is always safe: it silently does nothing when there is nothing saved for the current route, or when the route opted out with `scrollRestoration: false`.
888
+ * An optional behavior argument on the hook overrides the scroll behavior for these calls (`useRestoreScroll('smooth')`); by default the route's `scrollRestorationBehavior`, then the router's `defaultScrollRestorationBehavior`, applies.
889
+ * For element-level restoration (`scrollRestoration: ['panel']`), container `id`s must be unique and stable across visits — a typo or a remounted `id` logs a warning and skips that container.
890
+
824
891
  ### `useIsDataLoading()`
825
892
 
826
893
  Returns a boolean indicating whether any route loader is currently fetching data. Useful for global loading indicators (progress bar, spinner in the layout, etc.).
@@ -947,7 +1014,7 @@ View Transitions API requires modern browsers:
947
1014
  For older browsers, the router gracefully falls back to regular navigation without animation.
948
1015
 
949
1016
  ## Requirements
950
- - React 16.6+ (for React.lazy and Suspense)
1017
+ - React 16.8+ (for React.lazy and Suspense)
951
1018
  - Use `default` export for your lazy-loaded components
952
1019
 
953
1020
  ## License
@@ -1,9 +1,21 @@
1
- import { type CSSProperties, ReactNode, ReactElement } from 'react';
2
- import { ElementProps, RouterProps, SearchObject } from '../types';
1
+ import { type CSSProperties, ReactNode, MouseEvent, ReactElement, Ref } from 'react';
2
+ import { RouterProps, SearchObject } from '../types';
3
3
  type ElementState = {
4
4
  isActive: boolean;
5
5
  isPending: boolean;
6
6
  };
7
+ export type ElementProps<T extends HTMLElement = HTMLElement> = {
8
+ 'ref': Ref<T>;
9
+ 'href': string;
10
+ 'className'?: string;
11
+ 'style'?: CSSProperties;
12
+ onClick(event: MouseEvent): void;
13
+ onMouseEnter(event: MouseEvent): void;
14
+ onMouseLeave(event: MouseEvent): void;
15
+ 'children'?: ReactNode;
16
+ 'aria-current'?: 'page';
17
+ 'aria-busy'?: boolean;
18
+ } & Record<`data-${string}` | `aria-${string}`, unknown>;
7
19
  type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
8
20
  to: string;
9
21
  search?: string | SearchObject;
@@ -18,6 +30,6 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
18
30
  beforeNavigate?(): Promise<void>;
19
31
  style?: CSSProperties | ((arg: ElementState) => CSSProperties);
20
32
  exact?: boolean;
21
- };
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>>;
33
+ } & Record<`data-${string}` | `aria-${string}`, unknown>;
34
+ export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, ...rest }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
23
35
  export {};
@@ -12,6 +12,7 @@ declare class RouterConfig {
12
12
  defaultRetry?: RouterProps['defaultRetry'];
13
13
  defaultStaleTime?: RouterProps['defaultStaleTime'];
14
14
  defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
15
+ defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
15
16
  configure(config: Partial<RouterConfig>): void;
16
17
  }
17
18
  export declare const routerConfig: RouterConfig;
package/dist/create.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- type SetStateAction<T> = ((prevState: T) => T) | T;
1
+ import type { SetStateFn, Synchronizer } from './types';
2
2
  type Listener<T> = (state: T, prevState: T) => void;
3
3
  export type Store<T> = {
4
4
  subscribe: (listener: Listener<T>) => () => void;
5
5
  getState: () => T;
6
- setState: (action: SetStateAction<T>) => void;
6
+ setState: SetStateFn<T>;
7
7
  };
8
8
  export declare const create: <T>(initialState: T) => Store<T>;
9
- export declare const useGlobalState: <T>({ subscribe, getState, setState }: Store<T>) => readonly [T, (action: SetStateAction<T>) => void];
9
+ export declare const useGlobalState: <T>({ subscribe, getState, setState }: Store<T>, synchronizer: Synchronizer) => readonly [T, SetStateFn<T>];
10
10
  export {};
@@ -1,2 +1,2 @@
1
- import { RouterType } from '../types';
2
- export declare const createRouterInstance: () => RouterType;
1
+ import { RouterType, Synchronizer } from '../types';
2
+ export declare const createRouterInstance: (synchronizer: Synchronizer) => RouterType;
@@ -1,2 +1,2 @@
1
1
  import { ScrollRestorationBehavior } from '../types';
2
- export declare const usePreserveScroll: (restorationBehavior: ScrollRestorationBehavior) => void;
2
+ export declare const usePreserveScroll: (behavior?: ScrollRestorationBehavior) => void;
@@ -0,0 +1,2 @@
1
+ import { ScrollRestorationBehavior } from '../types';
2
+ export declare const useRestoreScroll: (behavior?: ScrollRestorationBehavior) => () => void;
@@ -1,4 +1,4 @@
1
1
  export declare const useRouterContext: () => {
2
2
  context: Record<string, unknown>;
3
- setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
3
+ setContext: import("../types").SetStateFn<Record<string, unknown>>;
4
4
  };
package/dist/index.d.ts CHANGED
@@ -11,6 +11,8 @@ export { useIsDataLoading } from './hooks/useIsDataLoading';
11
11
  export { useRouterContext } from './hooks/useRouterContext';
12
12
  export { useSearchParams } from './hooks/useSearchParams';
13
13
  export { useSubmitAction } from './hooks/useSubmitAction';
14
+ export { useRestoreScroll } from './hooks/useRestoreScroll';
14
15
  export { createRouter } from './creators/createRouter';
15
16
  export { lazy } from './utils/lazy';
16
- export type { RouteItem, BlockerState, Location, RouterProps, ElementProps, NavigationLocation } from './types';
17
+ export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation } from './types';
18
+ export type { ElementProps } from './components/Link';
package/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
- //#region \0rolldown/runtime.js
3
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
- //#endregion
2
+ import { jsx, jsxs } from "react/jsx-runtime";
5
3
  //#region create.ts
6
4
  var create = (initialState) => {
7
5
  let state = initialState;
@@ -25,8 +23,8 @@ var create = (initialState) => {
25
23
  setState
26
24
  };
27
25
  };
28
- var useGlobalState = ({ subscribe, getState, setState }) => {
29
- return [useSyncExternalStore(subscribe, getState), setState];
26
+ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
27
+ return [synchronizer(subscribe, getState), setState];
30
28
  };
31
29
  //#endregion
32
30
  //#region utils/commitState.ts
@@ -40,7 +38,7 @@ var createCommitState = ({ loaderState, routeItemDataState, blockerState }) => (
40
38
  loaderState.setState(loaderStateValue);
41
39
  if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
42
40
  if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
43
- history.pushState(null, "", `${location.pathname}${location.search}`);
41
+ history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
44
42
  };
45
43
  //#endregion
46
44
  //#region constants.ts
@@ -101,6 +99,7 @@ var RouterConfig = class {
101
99
  _defineProperty(this, "defaultRetry", void 0);
102
100
  _defineProperty(this, "defaultStaleTime", void 0);
103
101
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
102
+ _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
104
103
  }
105
104
  configure(config) {
106
105
  Object.assign(this, config);
@@ -140,7 +139,8 @@ var getParams = (location, routeItem) => {
140
139
  };
141
140
  var parseWindowLocation = (location) => ({
142
141
  pathname: location.pathname,
143
- search: location.search
142
+ search: location.search,
143
+ state: history.state ?? void 0
144
144
  });
145
145
  var comparePaths = (route, pathname) => {
146
146
  const pattern = route.pattern.split("/").filter(Boolean);
@@ -188,28 +188,6 @@ var updateScrollMap = (routeItemDataState, scrollMapState) => {
188
188
  };
189
189
  });
190
190
  };
191
- var restoreScroll = (scrollMap, pathname, behavior) => {
192
- scrollMap[pathname].forEach(([key, scrollPosition]) => {
193
- if (key === "__window_top__" || key === "__window_left__") {
194
- requestAnimationFrame(() => {
195
- window.scrollTo({
196
- [key === "__window_top__" ? "top" : "left"]: scrollPosition,
197
- behavior
198
- });
199
- });
200
- return;
201
- }
202
- const element = document.getElementById(key);
203
- if (!element) return;
204
- const axis = isVerticalScroll(element) ? "top" : "left";
205
- requestAnimationFrame(() => {
206
- element.scrollTo({
207
- [axis]: scrollPosition,
208
- behavior
209
- });
210
- });
211
- });
212
- };
213
191
  var formatSearchObject = (searchObject) => {
214
192
  const params = new URLSearchParams();
215
193
  Object.entries(searchObject).forEach(([key, value]) => {
@@ -228,6 +206,13 @@ var createNavigate = (routerState, revalidateCache) => {
228
206
  let navigationSeq = 0;
229
207
  let interval = 0;
230
208
  let abortController = null;
209
+ let pollingController = null;
210
+ const stopPolling = () => {
211
+ window.clearInterval(interval);
212
+ interval = 0;
213
+ pollingController?.abort();
214
+ pollingController = null;
215
+ };
231
216
  const { loaderState, contextState, loaderMap, routeItemDataState, scrollMapState, blockerState, blockedTargetState } = routerState;
232
217
  const commitState = createCommitState(routerState);
233
218
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
@@ -312,7 +297,9 @@ var createNavigate = (routerState, revalidateCache) => {
312
297
  };
313
298
  const polling = (routeItem, nextLocation) => {
314
299
  if (!routeItem?.pollingInterval) return;
315
- const signal = createSignal();
300
+ pollingController?.abort();
301
+ pollingController = new AbortController();
302
+ const signal = pollingController.signal;
316
303
  interval = window.setInterval(() => revalidateCache({
317
304
  routeItem,
318
305
  location: nextLocation,
@@ -325,7 +312,6 @@ var createNavigate = (routerState, revalidateCache) => {
325
312
  };
326
313
  const loader = async (routeItem, nextLocation, seq) => {
327
314
  if (!routeItem?.loader) return;
328
- window.clearInterval(interval);
329
315
  const signal = createSignal();
330
316
  const [result] = await Promise.all([revalidateCache({
331
317
  routeItem,
@@ -336,7 +322,7 @@ var createNavigate = (routerState, revalidateCache) => {
336
322
  polling(routeItem, nextLocation);
337
323
  return result;
338
324
  };
339
- const afterLoad = async (routeItem, params) => {
325
+ const afterLoad = async (routeItem, location, params) => {
340
326
  const { defaultAfterLoad } = routerConfig;
341
327
  const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
342
328
  const args = {
@@ -372,6 +358,7 @@ var createNavigate = (routerState, revalidateCache) => {
372
358
  search: rawLocation.search ?? ""
373
359
  };
374
360
  if (checkBlocked(nextLocation)) return;
361
+ stopPolling();
375
362
  navigationSeq = navigationSeq + 1;
376
363
  const seq = navigationSeq;
377
364
  const { nextItem, params } = routeResolve(nextLocation);
@@ -395,7 +382,7 @@ var createNavigate = (routerState, revalidateCache) => {
395
382
  loaderStateValue
396
383
  }));
397
384
  clearCurrentGcTimeout(nextItem, nextLocation);
398
- afterLoad(nextItem, params);
385
+ afterLoad(nextItem, nextLocation, params);
399
386
  };
400
387
  return navigate;
401
388
  };
@@ -478,6 +465,7 @@ var getRetry = (routeItem) => {
478
465
  };
479
466
  var createRevalidateCache = (routerState) => {
480
467
  const { loaderMap, loadingPromises, contextState } = routerState;
468
+ const flightOwners = /* @__PURE__ */ new Map();
481
469
  const evict = () => {
482
470
  if (loaderMap.size <= routerConfig.maxCacheSize) return;
483
471
  const oldestKey = loaderMap.keys().next().value;
@@ -497,8 +485,15 @@ var createRevalidateCache = (routerState) => {
497
485
  const { pathname, search = "" } = location;
498
486
  const path = `${pathname}${search}`;
499
487
  if (loadingPromises.has(path)) {
500
- moveItemToLastPosition(path);
501
- return loadingPromises.get(path);
488
+ const owner = flightOwners.get(path);
489
+ if (signal && owner instanceof AbortController) {
490
+ owner.abort();
491
+ loadingPromises.delete(path);
492
+ flightOwners.delete(path);
493
+ } else {
494
+ moveItemToLastPosition(path);
495
+ return loadingPromises.get(path);
496
+ }
502
497
  }
503
498
  if (isCacheItemFresh(path)) {
504
499
  const item = moveItemToLastPosition(path);
@@ -513,7 +508,11 @@ var createRevalidateCache = (routerState) => {
513
508
  }
514
509
  const promise = (async () => {
515
510
  if (!routeItem?.loader) return;
516
- const effectiveSignal = signal ?? new AbortController().signal;
511
+ const prefetchController = signal ? null : new AbortController();
512
+ const effectiveSignal = signal ?? prefetchController.signal;
513
+ const ownerToken = prefetchController ?? signal;
514
+ flightOwners.set(path, ownerToken);
515
+ const isOwner = () => flightOwners.get(path) === ownerToken;
517
516
  try {
518
517
  const result = await routeItem?.loader({
519
518
  ...getPartialLoaderArgs(contextState, location, routeItem),
@@ -540,7 +539,10 @@ var createRevalidateCache = (routerState) => {
540
539
  };
541
540
  const retry = getRetry(routeItem);
542
541
  if (retry && retry.count > retried) {
543
- loadingPromises.delete(path);
542
+ if (isOwner()) {
543
+ loadingPromises.delete(path);
544
+ flightOwners.delete(path);
545
+ }
544
546
  if (retry.delay) await sleep(retry.delay);
545
547
  return revalidateCache({
546
548
  routeItem,
@@ -552,7 +554,10 @@ var createRevalidateCache = (routerState) => {
552
554
  error
553
555
  };
554
556
  } finally {
555
- loadingPromises.delete(path);
557
+ if (isOwner()) {
558
+ loadingPromises.delete(path);
559
+ flightOwners.delete(path);
560
+ }
556
561
  }
557
562
  })();
558
563
  loadingPromises.set(path, promise);
@@ -562,7 +567,7 @@ var createRevalidateCache = (routerState) => {
562
567
  };
563
568
  //#endregion
564
569
  //#region creators/createRouterInstance.ts
565
- var createRouterInstance = () => {
570
+ var createRouterInstance = (synchronizer) => {
566
571
  const routerState = {
567
572
  routeItemDataState: create({
568
573
  routeItem: void 0,
@@ -606,12 +611,12 @@ var createRouterInstance = () => {
606
611
  prefetch
607
612
  },
608
613
  hooks: {
609
- useBlockerState: () => useGlobalState(routerState.blockerState),
610
- useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
611
- useScrollMap: () => useGlobalState(routerState.scrollMapState),
612
- useContextState: () => useGlobalState(routerState.contextState),
613
- useBlockedTargetState: () => useGlobalState(routerState.blockedTargetState),
614
- useLoaderState: () => useGlobalState(routerState.loaderState)[0],
614
+ useBlockerState: () => useGlobalState(routerState.blockerState, synchronizer),
615
+ useRouteItemData: () => useGlobalState(routerState.routeItemDataState, synchronizer),
616
+ useScrollMap: () => useGlobalState(routerState.scrollMapState, synchronizer),
617
+ useContextState: () => useGlobalState(routerState.contextState, synchronizer),
618
+ useBlockedTargetState: () => useGlobalState(routerState.blockedTargetState, synchronizer),
619
+ useLoaderState: () => useGlobalState(routerState.loaderState, synchronizer)[0],
615
620
  useParams: () => {
616
621
  const { routeItem, location } = routerState.routeItemDataState.getState();
617
622
  return getParams(location, routeItem);
@@ -640,10 +645,9 @@ var createRouterInstance = () => {
640
645
  });
641
646
  },
642
647
  useAction: (action, options = {}) => {
643
- const currentAction = getCurrentAction(action);
644
648
  return async (input) => {
645
649
  try {
646
- const data = await currentAction(input);
650
+ const data = await getCurrentAction(action)(input);
647
651
  await invalidate();
648
652
  options.onSuccess?.(data);
649
653
  return {
@@ -659,18 +663,38 @@ var createRouterInstance = () => {
659
663
  }
660
664
  };
661
665
  },
662
- useRestoreScroll: (restorationBehavior) => {
666
+ useScrollRestoration: (restorationBehavior) => () => {
663
667
  const { routeItem, location: { pathname } } = routerState.routeItemDataState.getState();
664
668
  const scrollMap = routerState.scrollMapState.getState();
665
669
  if (!routeItem || routeItem.scrollRestoration === false || !scrollMap[pathname]) return;
666
- return () => restoreScroll(scrollMap, pathname, routeItem.scrollRestorationBehavior ?? restorationBehavior);
670
+ const behavior = routeItem.scrollRestorationBehavior ?? restorationBehavior;
671
+ scrollMap[pathname].forEach(([key, scrollPosition]) => {
672
+ if (key === "__window_top__" || key === "__window_left__") {
673
+ requestAnimationFrame(() => {
674
+ window.scrollTo({
675
+ [key === "__window_top__" ? "top" : "left"]: scrollPosition,
676
+ behavior
677
+ });
678
+ });
679
+ return;
680
+ }
681
+ const element = document.getElementById(key);
682
+ if (!element) return;
683
+ const axis = isVerticalScroll(element) ? "top" : "left";
684
+ requestAnimationFrame(() => {
685
+ element.scrollTo({
686
+ [axis]: scrollPosition,
687
+ behavior
688
+ });
689
+ });
690
+ });
667
691
  }
668
692
  }
669
693
  };
670
694
  };
671
695
  //#endregion
672
696
  //#region instance.ts
673
- var router = createRouterInstance();
697
+ var router = createRouterInstance(useSyncExternalStore);
674
698
  //#endregion
675
699
  //#region hooks/useNavigation.ts
676
700
  var useNavigation = () => {
@@ -685,7 +709,7 @@ var useNavigation = () => {
685
709
  pathname: location.pathname,
686
710
  search: location.search
687
711
  };
688
- if (blockerState === "charged") history.pushState(null, "", location.pathname);
712
+ if (blockerState === "charged") history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
689
713
  await navigate({
690
714
  ...newLocation,
691
715
  prevLocation
@@ -697,6 +721,7 @@ var useNavigation = () => {
697
721
  blockerState,
698
722
  location.pathname,
699
723
  location.search,
724
+ location.state,
700
725
  navigate
701
726
  ]);
702
727
  useEffect(() => {
@@ -741,13 +766,17 @@ var useApplyCustomAnimation = (animationDuration) => {
741
766
  }, [animationDuration]);
742
767
  };
743
768
  //#endregion
769
+ //#region hooks/useRestoreScroll.ts
770
+ var useRestoreScroll = (behavior) => {
771
+ const { useScrollRestoration } = router.hooks;
772
+ const { defaultScrollRestorationBehavior = "auto" } = routerConfig;
773
+ return useScrollRestoration(behavior ?? defaultScrollRestorationBehavior);
774
+ };
775
+ //#endregion
744
776
  //#region hooks/usePreserveScroll.ts
745
- var usePreserveScroll = (restorationBehavior) => {
746
- const { useRestoreScroll } = router.hooks;
747
- const restoreScroll = useRestoreScroll(restorationBehavior);
748
- useEffect(() => {
749
- restoreScroll?.();
750
- }, [restoreScroll]);
777
+ var usePreserveScroll = (behavior) => {
778
+ const restoreScroll = useRestoreScroll(behavior);
779
+ useEffect(() => restoreScroll?.(), [restoreScroll]);
751
780
  };
752
781
  //#endregion
753
782
  //#region hooks/useSetRouterConfig.ts
@@ -769,62 +798,31 @@ var useReload = () => {
769
798
  useEffect(() => {
770
799
  if (!routerConfig.revalidateOnFocus) return;
771
800
  const handler = () => {
772
- if (document.visibilityState === "visible") invalidate("", { staleOnly: true });
801
+ if (document.visibilityState === "visible") invalidate(void 0, { staleOnly: true });
773
802
  };
774
803
  document.addEventListener("visibilitychange", handler);
775
804
  return () => document.removeEventListener("visibilitychange", handler);
776
805
  }, [invalidate]);
777
806
  useEffect(() => {
778
807
  if (!routerConfig.revalidateOnReconnect) return;
779
- const handler = () => invalidate("", { staleOnly: true });
808
+ const handler = () => invalidate(void 0, { staleOnly: true });
780
809
  window.addEventListener("online", handler);
781
810
  return () => window.removeEventListener("online", handler);
782
811
  }, [invalidate]);
783
812
  };
784
813
  //#endregion
785
- //#region ../../node_modules/react/cjs/react-jsx-runtime.production.js
786
- /**
787
- * @license React
788
- * react-jsx-runtime.production.js
789
- *
790
- * Copyright (c) Meta Platforms, Inc. and affiliates.
791
- *
792
- * This source code is licensed under the MIT license found in the
793
- * LICENSE file in the root directory of this source tree.
794
- */
795
- var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
796
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element");
797
- function jsxProd(type, config, maybeKey) {
798
- var key = null;
799
- void 0 !== maybeKey && (key = "" + maybeKey);
800
- void 0 !== config.key && (key = "" + config.key);
801
- if ("key" in config) {
802
- maybeKey = {};
803
- for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
804
- } else maybeKey = config;
805
- config = maybeKey.ref;
806
- return {
807
- $$typeof: REACT_ELEMENT_TYPE,
808
- type,
809
- key,
810
- ref: void 0 !== config ? config : null,
811
- props: maybeKey
812
- };
813
- }
814
- exports.jsx = jsxProd;
815
- exports.jsxs = jsxProd;
816
- }));
817
- //#endregion
818
814
  //#region components/Spinner.tsx
819
- var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
820
- module.exports = require_react_jsx_runtime_production();
821
- })))();
822
- var Spinner = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cr-spinner" });
815
+ var Spinner = () => /* @__PURE__ */ jsx("span", {
816
+ className: "cr-spinner",
817
+ role: "status",
818
+ "aria-label": "Loading"
819
+ });
823
820
  //#endregion
824
821
  //#region utils/renderElement.tsx
825
822
  var renderElement = (Component) => {
826
823
  if (!Component) return null;
827
- return typeof Component === "function" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, {}) : Component;
824
+ if (typeof Component !== "function") return Component;
825
+ return /* @__PURE__ */ jsx(Component, {});
828
826
  };
829
827
  //#endregion
830
828
  //#region components/Router.tsx
@@ -851,7 +849,8 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
851
849
  defaultMinLoaderDuration,
852
850
  maxCacheSize,
853
851
  revalidateOnFocus,
854
- revalidateOnReconnect
852
+ revalidateOnReconnect,
853
+ defaultScrollRestorationBehavior
855
854
  });
856
855
  useApplyCustomAnimation(animationDuration);
857
856
  useSetInitialContext(initialContext);
@@ -860,9 +859,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
860
859
  if (isLoading && !isError) return renderElement(routeItem?.loaderFallback || defaultLoaderFallback);
861
860
  if (!routeItem) return null;
862
861
  if (isError) return renderElement(routeItem.errorElement || defaultErrorElement);
863
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
862
+ return /* @__PURE__ */ jsxs("div", {
864
863
  style: { viewTransitionName: "page" },
865
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname), optimisticSpinner && isOptimistic && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Spinner, {})]
864
+ children: [/* @__PURE__ */ jsx(ErrorBoundary, { children: renderElement(routeItem.element) }, location.pathname), optimisticSpinner && isOptimistic && /* @__PURE__ */ jsx(Spinner, {})]
866
865
  });
867
866
  };
868
867
  //#endregion
@@ -883,8 +882,8 @@ var useLocation = () => {
883
882
  };
884
883
  //#endregion
885
884
  //#region components/Link.tsx
886
- var defaultAs = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { ...props });
887
- var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link" }) => {
885
+ var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
886
+ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
888
887
  const isPending = useIsRoutePending(to);
889
888
  const { pathname } = useLocation();
890
889
  const navigate = useNavigate();
@@ -968,7 +967,10 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
968
967
  href: `${to}${searchString}`,
969
968
  onMouseEnter,
970
969
  onMouseLeave,
971
- children
970
+ children,
971
+ ...rest,
972
+ "aria-current": isActive ? "page" : void 0,
973
+ "aria-busy": isPending || void 0
972
974
  }, {
973
975
  isActive,
974
976
  isPending
@@ -1037,65 +1039,47 @@ var useRouterContext = () => {
1037
1039
  };
1038
1040
  };
1039
1041
  //#endregion
1040
- //#region hooks/useSearch.ts
1041
- var isPatched = false;
1042
- var notify = () => {
1043
- window.dispatchEvent(new Event("locationChange"));
1044
- };
1045
- var patchHistory = () => {
1046
- if (isPatched) return;
1047
- isPatched = true;
1048
- const push = history.pushState;
1049
- const replace = history.replaceState;
1050
- history.pushState = function(...args) {
1051
- const result = push.apply(this, args);
1052
- notify();
1053
- return result;
1054
- };
1055
- history.replaceState = function(...args) {
1056
- const result = replace.apply(this, args);
1057
- notify();
1058
- return result;
1059
- };
1060
- window.addEventListener("popstate", notify);
1061
- };
1062
- var subscribe = (onChange) => {
1063
- window.addEventListener("locationChange", onChange);
1064
- return () => window.removeEventListener("locationChange", onChange);
1065
- };
1066
- var getSnapshot = () => window.location.search;
1067
- var useSearch = () => {
1068
- useEffect(patchHistory, []);
1069
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
1070
- };
1071
- //#endregion
1072
1042
  //#region hooks/useSearchParams.ts
1043
+ var useLatest = (value) => {
1044
+ const ref = useRef(value);
1045
+ useEffect(() => {
1046
+ ref.current = value;
1047
+ }, [value]);
1048
+ return ref;
1049
+ };
1073
1050
  var useSearchParams = () => {
1074
- const search = useSearch();
1075
- const searchString = search ? search.replace("?", "") : window.location.pathname.split("?")?.[1] ?? "";
1076
- const searchParams = useMemo(() => new URLSearchParams(searchString), [searchString]);
1051
+ const [{ location }, setRouteItemData] = router.hooks.useRouteItemData();
1052
+ const { search = window.location.search, pathname = window.location.pathname } = location;
1053
+ const searchRef = useLatest(search);
1054
+ const searchParams = useMemo(() => new URLSearchParams(search), [search]);
1077
1055
  const getSearchParams = useCallback((param) => {
1078
1056
  const allValues = searchParams.getAll(param);
1079
1057
  return allValues.length > 1 ? allValues : allValues[0] ?? "";
1080
1058
  }, [searchParams]);
1081
1059
  const navigateWithSearchParams = useCallback((params) => {
1082
1060
  const newSearch = params.toString();
1083
- const { pathname } = window.location;
1084
1061
  const search = newSearch ? `?${newSearch}` : "";
1085
- history.replaceState(null, "", pathname + search);
1086
- }, []);
1062
+ history.replaceState(history.state, "", pathname + search);
1063
+ setRouteItemData((prevState) => ({
1064
+ ...prevState,
1065
+ location: {
1066
+ ...prevState.location,
1067
+ search
1068
+ }
1069
+ }));
1070
+ }, [pathname, setRouteItemData]);
1087
1071
  return {
1088
1072
  searchParams,
1089
1073
  getSearchParams,
1090
1074
  setSearchParams: useCallback((param, value) => {
1091
- const currentParams = new URLSearchParams(search);
1075
+ const currentParams = new URLSearchParams(searchRef.current);
1092
1076
  if (typeof param === "string" && value !== void 0) {
1093
1077
  currentParams.delete(param);
1094
1078
  (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1095
1079
  navigateWithSearchParams(currentParams);
1096
1080
  } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1097
1081
  else throw new Error("useSearchParams first argument must be either function or string");
1098
- }, [navigateWithSearchParams, search])
1082
+ }, [navigateWithSearchParams, searchRef])
1099
1083
  };
1100
1084
  };
1101
1085
  //#endregion
@@ -1131,9 +1115,9 @@ var useSubmitAction = (action, options) => {
1131
1115
  var createLazyComponent = (importFn, fallback) => {
1132
1116
  const load = () => importFn().then((module) => ({ default: module.default || module }));
1133
1117
  const LazyComp = lazy$1(load);
1134
- const Component = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Suspense, {
1118
+ const Component = () => /* @__PURE__ */ jsx(Suspense, {
1135
1119
  fallback: typeof fallback === "function" ? fallback() : fallback || null,
1136
- children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LazyComp, {})
1120
+ children: /* @__PURE__ */ jsx(LazyComp, {})
1137
1121
  });
1138
1122
  return {
1139
1123
  Component,
@@ -1165,4 +1149,4 @@ var lazy = (importFn) => ({
1165
1149
  importFn
1166
1150
  });
1167
1151
  //#endregion
1168
- export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRouterContext, useSearchParams, useSubmitAction };
1152
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useIsDataLoading, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouterContext, useSearchParams, useSubmitAction };
package/dist/types.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- import { ComponentType, type CSSProperties, Dispatch, MouseEvent, ReactElement, ReactNode, Ref, SetStateAction } from 'react';
2
- import { Store, useGlobalState } from './create';
1
+ import type { Store, useGlobalState } from './create';
3
2
  export declare const LAZY_MARKER: unique symbol;
3
+ export type SetStateFn<T> = (action: T | ((prevState: T) => T)) => void;
4
4
  export type LazyComponent = {
5
5
  readonly [LAZY_MARKER]: true;
6
6
  importFn: () => Promise<{
7
- default: ComponentType<unknown>;
7
+ default: unknown;
8
8
  }>;
9
9
  };
10
- export type RenderElement = (() => ReactElement) | ReactElement;
10
+ export type RenderElement = unknown;
11
11
  type LoaderArgs = {
12
12
  context: Record<string, unknown>;
13
13
  params: Record<string, string>;
14
- setContext: Dispatch<SetStateAction<Record<string, unknown>>>;
14
+ setContext: SetStateFn<Record<string, unknown>>;
15
15
  searchParams: Record<string, string>;
16
16
  location: Location;
17
17
  };
@@ -50,7 +50,7 @@ export type RouteItem = ClientRouteItem & {
50
50
  pattern: string;
51
51
  cacheTimestamp?: number;
52
52
  preloadElement?(): Promise<{
53
- default: ComponentType<unknown>;
53
+ default: unknown;
54
54
  }>;
55
55
  };
56
56
  export type Location = {
@@ -93,9 +93,7 @@ export type RouterProps = {
93
93
  defaultHoverPrefetchDelay?: number;
94
94
  defaultMinLoaderDuration?: number;
95
95
  maxCacheSize?: number;
96
- errorBoundary?: ComponentType<{
97
- children: ReactNode;
98
- }>;
96
+ errorBoundary?: unknown;
99
97
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
100
98
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
101
99
  defaultScrollRestorationBehavior?: ScrollRestorationBehavior;
@@ -146,7 +144,7 @@ export type RouterType = {
146
144
  data: unknown;
147
145
  error: Error | null;
148
146
  }>;
149
- useRestoreScroll(restorationBehavior: ScrollRestorationBehavior): (() => void) | undefined;
147
+ useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
150
148
  };
151
149
  };
152
150
  export type InvalidateOptions = {
@@ -162,19 +160,11 @@ export type Options = Partial<{
162
160
  export type InvalidateResult = {
163
161
  path: string;
164
162
  data: unknown;
165
- };
166
- export type ElementProps<T extends HTMLElement = HTMLElement> = {
167
- ref: Ref<T>;
168
- href: string;
169
- className?: string;
170
- style?: CSSProperties;
171
- onClick(event: MouseEvent): void;
172
- onMouseEnter(event: MouseEvent): void;
173
- onMouseLeave(event: MouseEvent): void;
174
- children?: ReactNode;
163
+ error: Error | null;
175
164
  };
176
165
  export type SearchObject = Record<string, string | number | boolean | null | undefined>;
177
166
  export type NavigationLocation = Omit<Location, 'search'> & {
178
167
  search?: string | SearchObject;
179
168
  };
169
+ export type Synchronizer = <T>(subscribe: (updater: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
180
170
  export {};
@@ -1,7 +1,7 @@
1
- import { type ComponentType, type ReactElement } from 'react';
1
+ import { type ComponentType } from 'react';
2
2
  export declare const createLazyComponent: (importFn: () => Promise<{
3
- default: ComponentType<unknown>;
4
- }>, fallback?: ReactElement | (() => ReactElement)) => {
3
+ default: unknown;
4
+ }>, fallback?: unknown) => {
5
5
  Component: () => import("react/jsx-runtime").JSX.Element;
6
6
  preloadElement: () => Promise<{
7
7
  default: ComponentType<unknown>;
@@ -1,2 +1,3 @@
1
- import { RenderElement } from '../types';
2
- export declare const renderElement: (Component?: RenderElement) => import("react/jsx-runtime").JSX.Element | null;
1
+ import type { ReactElement } from 'react';
2
+ import type { RenderElement } from '../types';
3
+ export declare const renderElement: (Component?: RenderElement) => ReactElement | null;
@@ -1,5 +1,5 @@
1
1
  import { Store } from '../create';
2
- import { Location, RouteItem, RouteItemData, RouterState, ScrollMap, ScrollRestorationBehavior, SearchObject } from '../types';
2
+ import { Location, RouteItem, RouteItemData, RouterState, ScrollMap, SearchObject } from '../types';
3
3
  export declare const getParams: (location: Location, routeItem?: RouteItem) => Record<string, string>;
4
4
  export declare const parseWindowLocation: (location: typeof window.location) => Location;
5
5
  export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
@@ -8,11 +8,10 @@ export declare const sleep: (ms: number) => Promise<unknown>;
8
8
  export declare const getPartialLoaderArgs: (contextState: RouterState["contextState"], location: Location, routeItem?: RouteItem) => {
9
9
  params: Record<string, string>;
10
10
  context: Record<string, unknown>;
11
- setContext: (action: Record<string, unknown> | ((prevState: Record<string, unknown>) => Record<string, unknown>)) => void;
11
+ setContext: import("../types").SetStateFn<Record<string, unknown>>;
12
12
  searchParams: Record<string, string>;
13
13
  location: Location;
14
14
  };
15
15
  export declare const isVerticalScroll: (el: Element | null) => boolean;
16
16
  export declare const updateScrollMap: (routeItemDataState: Store<RouteItemData>, scrollMapState: Store<ScrollMap>) => void;
17
- export declare const restoreScroll: (scrollMap: ScrollMap, pathname: string, behavior: ScrollRestorationBehavior) => void;
18
17
  export declare const formatSearchObject: (searchObject: SearchObject) => string;
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.6",
3
+ "version": "2.2.8",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
7
- "build": "vite build && tsc --emitDeclarationOnly"
7
+ "build": "vite build && tsc --emitDeclarationOnly",
8
+ "prepublishOnly": "npm run build"
8
9
  },
9
10
  "keywords": [
10
11
  "react",
@@ -1 +0,0 @@
1
- export declare const useSearch: () => string;