clear-react-router 2.2.7 → 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/README.md CHANGED
@@ -837,6 +837,57 @@ const Blocker = ({ callback, children }: BlockerProps) => {
837
837
  </Blocker>
838
838
  ```
839
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
+
840
891
  ### `useIsDataLoading()`
841
892
 
842
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.).
@@ -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;
@@ -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
@@ -23,8 +23,8 @@ var create = (initialState) => {
23
23
  setState
24
24
  };
25
25
  };
26
- var useGlobalState = ({ subscribe, getState, setState }) => {
27
- return [useSyncExternalStore(subscribe, getState), setState];
26
+ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
27
+ return [synchronizer(subscribe, getState), setState];
28
28
  };
29
29
  //#endregion
30
30
  //#region utils/commitState.ts
@@ -99,6 +99,7 @@ var RouterConfig = class {
99
99
  _defineProperty(this, "defaultRetry", void 0);
100
100
  _defineProperty(this, "defaultStaleTime", void 0);
101
101
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
102
+ _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
102
103
  }
103
104
  configure(config) {
104
105
  Object.assign(this, config);
@@ -187,28 +188,6 @@ var updateScrollMap = (routeItemDataState, scrollMapState) => {
187
188
  };
188
189
  });
189
190
  };
190
- var restoreScroll = (scrollMap, pathname, behavior) => {
191
- scrollMap[pathname].forEach(([key, scrollPosition]) => {
192
- if (key === "__window_top__" || key === "__window_left__") {
193
- requestAnimationFrame(() => {
194
- window.scrollTo({
195
- [key === "__window_top__" ? "top" : "left"]: scrollPosition,
196
- behavior
197
- });
198
- });
199
- return;
200
- }
201
- const element = document.getElementById(key);
202
- if (!element) return;
203
- const axis = isVerticalScroll(element) ? "top" : "left";
204
- requestAnimationFrame(() => {
205
- element.scrollTo({
206
- [axis]: scrollPosition,
207
- behavior
208
- });
209
- });
210
- });
211
- };
212
191
  var formatSearchObject = (searchObject) => {
213
192
  const params = new URLSearchParams();
214
193
  Object.entries(searchObject).forEach(([key, value]) => {
@@ -588,7 +567,7 @@ var createRevalidateCache = (routerState) => {
588
567
  };
589
568
  //#endregion
590
569
  //#region creators/createRouterInstance.ts
591
- var createRouterInstance = () => {
570
+ var createRouterInstance = (synchronizer) => {
592
571
  const routerState = {
593
572
  routeItemDataState: create({
594
573
  routeItem: void 0,
@@ -632,12 +611,12 @@ var createRouterInstance = () => {
632
611
  prefetch
633
612
  },
634
613
  hooks: {
635
- useBlockerState: () => useGlobalState(routerState.blockerState),
636
- useRouteItemData: () => useGlobalState(routerState.routeItemDataState),
637
- useScrollMap: () => useGlobalState(routerState.scrollMapState),
638
- useContextState: () => useGlobalState(routerState.contextState),
639
- useBlockedTargetState: () => useGlobalState(routerState.blockedTargetState),
640
- 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],
641
620
  useParams: () => {
642
621
  const { routeItem, location } = routerState.routeItemDataState.getState();
643
622
  return getParams(location, routeItem);
@@ -684,18 +663,38 @@ var createRouterInstance = () => {
684
663
  }
685
664
  };
686
665
  },
687
- useRestoreScroll: (restorationBehavior) => {
666
+ useScrollRestoration: (restorationBehavior) => () => {
688
667
  const { routeItem, location: { pathname } } = routerState.routeItemDataState.getState();
689
668
  const scrollMap = routerState.scrollMapState.getState();
690
669
  if (!routeItem || routeItem.scrollRestoration === false || !scrollMap[pathname]) return;
691
- 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
+ });
692
691
  }
693
692
  }
694
693
  };
695
694
  };
696
695
  //#endregion
697
696
  //#region instance.ts
698
- var router = createRouterInstance();
697
+ var router = createRouterInstance(useSyncExternalStore);
699
698
  //#endregion
700
699
  //#region hooks/useNavigation.ts
701
700
  var useNavigation = () => {
@@ -767,13 +766,17 @@ var useApplyCustomAnimation = (animationDuration) => {
767
766
  }, [animationDuration]);
768
767
  };
769
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
770
776
  //#region hooks/usePreserveScroll.ts
771
- var usePreserveScroll = (restorationBehavior) => {
772
- const { useRestoreScroll } = router.hooks;
773
- const restoreScroll = useRestoreScroll(restorationBehavior);
774
- useEffect(() => {
775
- restoreScroll?.();
776
- }, [restoreScroll]);
777
+ var usePreserveScroll = (behavior) => {
778
+ const restoreScroll = useRestoreScroll(behavior);
779
+ useEffect(() => restoreScroll?.(), [restoreScroll]);
777
780
  };
778
781
  //#endregion
779
782
  //#region hooks/useSetRouterConfig.ts
@@ -818,7 +821,8 @@ var Spinner = () => /* @__PURE__ */ jsx("span", {
818
821
  //#region utils/renderElement.tsx
819
822
  var renderElement = (Component) => {
820
823
  if (!Component) return null;
821
- return typeof Component === "function" ? /* @__PURE__ */ jsx(Component, {}) : Component;
824
+ if (typeof Component !== "function") return Component;
825
+ return /* @__PURE__ */ jsx(Component, {});
822
826
  };
823
827
  //#endregion
824
828
  //#region components/Router.tsx
@@ -845,7 +849,8 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
845
849
  defaultMinLoaderDuration,
846
850
  maxCacheSize,
847
851
  revalidateOnFocus,
848
- revalidateOnReconnect
852
+ revalidateOnReconnect,
853
+ defaultScrollRestorationBehavior
849
854
  });
850
855
  useApplyCustomAnimation(animationDuration);
851
856
  useSetInitialContext(initialContext);
@@ -1144,4 +1149,4 @@ var lazy = (importFn) => ({
1144
1149
  importFn
1145
1150
  });
1146
1151
  //#endregion
1147
- 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 = {
@@ -164,20 +162,9 @@ export type InvalidateResult = {
164
162
  data: unknown;
165
163
  error: Error | null;
166
164
  };
167
- export type ElementProps<T extends HTMLElement = HTMLElement> = {
168
- 'ref': Ref<T>;
169
- 'href': string;
170
- 'className'?: string;
171
- 'style'?: CSSProperties;
172
- onClick(event: MouseEvent): void;
173
- onMouseEnter(event: MouseEvent): void;
174
- onMouseLeave(event: MouseEvent): void;
175
- 'children'?: ReactNode;
176
- 'aria-current'?: 'page';
177
- 'aria-busy'?: boolean;
178
- } & Record<`data-${string}` | `aria-${string}`, unknown>;
179
165
  export type SearchObject = Record<string, string | number | boolean | null | undefined>;
180
166
  export type NavigationLocation = Omit<Location, 'search'> & {
181
167
  search?: string | SearchObject;
182
168
  };
169
+ export type Synchronizer = <T>(subscribe: (updater: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
183
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,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.2.7",
3
+ "version": "2.2.8",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {