@tanstack/react-router 1.98.0 → 1.98.1

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.
Files changed (48) hide show
  1. package/dist/cjs/Match.cjs +60 -22
  2. package/dist/cjs/Match.cjs.map +1 -1
  3. package/dist/cjs/Matches.cjs +4 -1
  4. package/dist/cjs/Matches.cjs.map +1 -1
  5. package/dist/cjs/ScriptOnce.cjs +1 -1
  6. package/dist/cjs/ScriptOnce.cjs.map +1 -1
  7. package/dist/cjs/ScrollRestoration.cjs +39 -0
  8. package/dist/cjs/ScrollRestoration.cjs.map +1 -0
  9. package/dist/cjs/ScrollRestoration.d.cts +15 -0
  10. package/dist/cjs/Transitioner.cjs +3 -33
  11. package/dist/cjs/Transitioner.cjs.map +1 -1
  12. package/dist/cjs/index.cjs +3 -4
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/index.d.cts +1 -2
  15. package/dist/cjs/router.cjs +14 -12
  16. package/dist/cjs/router.cjs.map +1 -1
  17. package/dist/cjs/router.d.cts +26 -26
  18. package/dist/cjs/scroll-restoration.cjs +168 -165
  19. package/dist/cjs/scroll-restoration.cjs.map +1 -1
  20. package/dist/cjs/scroll-restoration.d.cts +25 -15
  21. package/dist/esm/Match.js +62 -24
  22. package/dist/esm/Match.js.map +1 -1
  23. package/dist/esm/Matches.js +4 -1
  24. package/dist/esm/Matches.js.map +1 -1
  25. package/dist/esm/ScriptOnce.js +1 -1
  26. package/dist/esm/ScriptOnce.js.map +1 -1
  27. package/dist/esm/ScrollRestoration.d.ts +15 -0
  28. package/dist/esm/ScrollRestoration.js +39 -0
  29. package/dist/esm/ScrollRestoration.js.map +1 -0
  30. package/dist/esm/Transitioner.js +4 -34
  31. package/dist/esm/Transitioner.js.map +1 -1
  32. package/dist/esm/index.d.ts +1 -2
  33. package/dist/esm/index.js +1 -2
  34. package/dist/esm/router.d.ts +26 -26
  35. package/dist/esm/router.js +15 -13
  36. package/dist/esm/router.js.map +1 -1
  37. package/dist/esm/scroll-restoration.d.ts +25 -15
  38. package/dist/esm/scroll-restoration.js +168 -148
  39. package/dist/esm/scroll-restoration.js.map +1 -1
  40. package/package.json +3 -3
  41. package/src/Match.tsx +79 -48
  42. package/src/Matches.tsx +1 -1
  43. package/src/ScriptOnce.tsx +1 -1
  44. package/src/ScrollRestoration.tsx +65 -0
  45. package/src/Transitioner.tsx +4 -40
  46. package/src/index.tsx +1 -3
  47. package/src/router.ts +43 -38
  48. package/src/scroll-restoration.tsx +271 -183
@@ -332,6 +332,14 @@ export interface RouterOptions<TRouteTree extends AnyRoute, TTrailingSlashOption
332
332
  */
333
333
  pathParamsAllowedCharacters?: Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>;
334
334
  defaultRemountDeps?: (opts: MakeRemountDepsOptionsUnion<TRouteTree>) => any;
335
+ /**
336
+ * If `false`, scroll restoration will be disabled
337
+ *
338
+ * @default true
339
+ */
340
+ scrollRestoration?: boolean;
341
+ getScrollRestorationKey?: (location: ParsedLocation) => string;
342
+ scrollRestorationBehavior?: ScrollBehavior;
335
343
  }
336
344
  export interface RouterErrorSerializer<TSerializedError> {
337
345
  serialize: (err: unknown) => TSerializedError;
@@ -346,7 +354,7 @@ export interface RouterState<TRouteTree extends AnyRoute = AnyRoute, TRouteMatch
346
354
  pendingMatches?: Array<TRouteMatch>;
347
355
  cachedMatches: Array<TRouteMatch>;
348
356
  location: ParsedLocation<FullSearchSchema<TRouteTree>>;
349
- resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>;
357
+ resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
350
358
  statusCode: number;
351
359
  redirect?: ResolvedRedirect;
352
360
  }
@@ -375,46 +383,36 @@ export interface MatchedRoutesResult {
375
383
  }
376
384
  export type RouterConstructorOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = Omit<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'context'> & RouterContextOptions<TRouteTree>;
377
385
  export declare const componentTypes: readonly ["component", "errorComponent", "pendingComponent", "notFoundComponent"];
386
+ type NavigationEventInfo = {
387
+ fromLocation?: ParsedLocation;
388
+ toLocation: ParsedLocation;
389
+ pathChanged: boolean;
390
+ hrefChanged: boolean;
391
+ hashChanged: boolean;
392
+ };
378
393
  export type RouterEvents = {
379
394
  onBeforeNavigate: {
380
395
  type: 'onBeforeNavigate';
381
- fromLocation: ParsedLocation;
382
- toLocation: ParsedLocation;
383
- pathChanged: boolean;
384
- hrefChanged: boolean;
385
- };
396
+ } & NavigationEventInfo;
386
397
  onBeforeLoad: {
387
398
  type: 'onBeforeLoad';
388
- fromLocation: ParsedLocation;
389
- toLocation: ParsedLocation;
390
- pathChanged: boolean;
391
- hrefChanged: boolean;
392
- };
399
+ } & NavigationEventInfo;
393
400
  onLoad: {
394
401
  type: 'onLoad';
395
- fromLocation: ParsedLocation;
396
- toLocation: ParsedLocation;
397
- pathChanged: boolean;
398
- hrefChanged: boolean;
399
- };
402
+ } & NavigationEventInfo;
400
403
  onResolved: {
401
404
  type: 'onResolved';
402
- fromLocation: ParsedLocation;
403
- toLocation: ParsedLocation;
404
- pathChanged: boolean;
405
- hrefChanged: boolean;
406
- };
405
+ } & NavigationEventInfo;
407
406
  onBeforeRouteMount: {
408
407
  type: 'onBeforeRouteMount';
409
- fromLocation: ParsedLocation;
410
- toLocation: ParsedLocation;
411
- pathChanged: boolean;
412
- hrefChanged: boolean;
413
- };
408
+ } & NavigationEventInfo;
414
409
  onInjectedHtml: {
415
410
  type: 'onInjectedHtml';
416
411
  promise: Promise<string>;
417
412
  };
413
+ onRendered: {
414
+ type: 'onRendered';
415
+ } & NavigationEventInfo;
418
416
  };
419
417
  export type RouterEvent = RouterEvents[keyof RouterEvents];
420
418
  export type RouterListener<TRouterEvent extends RouterEvent> = {
@@ -435,6 +433,8 @@ export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailing
435
433
  isViewTransitionTypesSupported?: boolean;
436
434
  subscribers: Set<RouterListener<RouterEvent>>;
437
435
  viewTransitionPromise?: ControlledPromise<true>;
436
+ isScrollRestoring: boolean;
437
+ isScrollRestorationSetup: boolean;
438
438
  __store: Store<RouterState<TRouteTree>>;
439
439
  options: PickAsRequired<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'stringifySearch' | 'parseSearch' | 'context'>;
440
440
  history: TRouterHistory;
@@ -1,191 +1,194 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const React = require("react");
3
+ const jsxRuntime = require("react/jsx-runtime");
4
4
  const routerCore = require("@tanstack/router-core");
5
5
  const useRouter = require("./useRouter.cjs");
6
- function _interopNamespaceDefault(e) {
7
- const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
8
- if (e) {
9
- for (const k in e) {
10
- if (k !== "default") {
11
- const d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: () => e[k]
15
- });
16
- }
17
- }
18
- }
19
- n.default = e;
20
- return Object.freeze(n);
21
- }
22
- const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
23
- const useLayoutEffect = typeof window !== "undefined" ? React__namespace.useLayoutEffect : React__namespace.useEffect;
24
- const windowKey = "window";
25
- const delimiter = "___";
26
- let weakScrolledElements = /* @__PURE__ */ new WeakSet();
6
+ const ScriptOnce = require("./ScriptOnce.cjs");
7
+ const storageKey = "tsr-scroll-restoration-v1_3";
27
8
  const sessionsStorage = typeof window !== "undefined" && window.sessionStorage;
28
- const cache = sessionsStorage ? (() => {
29
- const storageKey = "tsr-scroll-restoration-v2";
30
- const state = JSON.parse(
31
- window.sessionStorage.getItem(storageKey) || "null"
32
- ) || { cached: {}, next: {} };
9
+ const throttle = (fn, wait) => {
10
+ let timeout;
11
+ return (...args) => {
12
+ if (!timeout) {
13
+ timeout = setTimeout(() => {
14
+ fn(...args);
15
+ timeout = null;
16
+ }, wait);
17
+ }
18
+ };
19
+ };
20
+ const scrollRestorationCache = sessionsStorage ? (() => {
21
+ const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
33
22
  return {
34
23
  state,
35
- set: (updater) => {
36
- cache.state = routerCore.functionalUpdate(updater, cache.state);
37
- window.sessionStorage.setItem(storageKey, JSON.stringify(cache.state));
38
- }
24
+ // This setter is simply to make sure that we set the sessionStorage right
25
+ // after the state is updated. It doesn't necessarily need to be a functional
26
+ // update.
27
+ set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
28
+ routerCore.functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
29
+ storageKey,
30
+ JSON.stringify(scrollRestorationCache.state)
31
+ ))
39
32
  };
40
33
  })() : void 0;
41
- const defaultGetKey = (location) => {
34
+ const defaultGetScrollRestorationKey = (location) => {
42
35
  return location.state.key || location.href;
43
36
  };
44
- function useScrollRestoration(options) {
45
- const router = useRouter.useRouter();
46
- useLayoutEffect(() => {
47
- const getKey = (options == null ? void 0 : options.getKey) || defaultGetKey;
48
- const { history } = window;
49
- history.scrollRestoration = "manual";
50
- const onScroll = (event) => {
51
- if (weakScrolledElements.has(event.target)) return;
52
- weakScrolledElements.add(event.target);
53
- let elementSelector = "";
54
- if (event.target === document || event.target === window) {
55
- elementSelector = windowKey;
56
- } else {
57
- const attrId = event.target.getAttribute(
58
- "data-scroll-restoration-id"
59
- );
60
- if (attrId) {
61
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
62
- } else {
63
- elementSelector = getCssSelector(event.target);
64
- }
65
- }
66
- if (!cache.state.next[elementSelector]) {
67
- cache.set((c) => ({
68
- ...c,
69
- next: {
70
- ...c.next,
71
- [elementSelector]: {
72
- scrollX: NaN,
73
- scrollY: NaN
74
- }
37
+ function getCssSelector(el) {
38
+ const path = [];
39
+ let parent;
40
+ while (parent = el.parentNode) {
41
+ path.unshift(
42
+ `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
43
+ );
44
+ el = parent;
45
+ }
46
+ return `${path.join(" > ")}`.toLowerCase();
47
+ }
48
+ let ignoreScroll = false;
49
+ function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration) {
50
+ var _a;
51
+ let byKey;
52
+ try {
53
+ byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
54
+ } catch (error) {
55
+ console.error(error);
56
+ return;
57
+ }
58
+ const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
59
+ const elementEntries = byKey[resolvedKey];
60
+ ignoreScroll = true;
61
+ (() => {
62
+ if (shouldScrollRestoration && elementEntries) {
63
+ for (const elementSelector in elementEntries) {
64
+ const entry = elementEntries[elementSelector];
65
+ if (elementSelector === "window") {
66
+ console.log("windowRestored", entry);
67
+ window.scrollTo({
68
+ top: entry.scrollY,
69
+ left: entry.scrollX,
70
+ behavior
71
+ });
72
+ } else if (elementSelector) {
73
+ const element = document.querySelector(elementSelector);
74
+ if (element) {
75
+ element.scrollLeft = entry.scrollX;
76
+ element.scrollTop = entry.scrollY;
75
77
  }
76
- }));
78
+ }
77
79
  }
78
- };
79
- if (typeof document !== "undefined") {
80
- document.addEventListener("scroll", onScroll, true);
80
+ return;
81
81
  }
82
- const unsubOnBeforeLoad = router.subscribe("onBeforeLoad", (event) => {
83
- if (event.hrefChanged) {
84
- const restoreKey = getKey(event.fromLocation);
85
- for (const elementSelector in cache.state.next) {
86
- const entry = cache.state.next[elementSelector];
87
- if (elementSelector === windowKey) {
88
- entry.scrollX = window.scrollX || 0;
89
- entry.scrollY = window.scrollY || 0;
90
- } else if (elementSelector) {
91
- const element = document.querySelector(elementSelector);
92
- entry.scrollX = (element == null ? void 0 : element.scrollLeft) || 0;
93
- entry.scrollY = (element == null ? void 0 : element.scrollTop) || 0;
94
- }
95
- cache.set((c) => {
96
- const next = { ...c.next };
97
- delete next[elementSelector];
98
- return {
99
- ...c,
100
- next,
101
- cached: {
102
- ...c.cached,
103
- [[restoreKey, elementSelector].join(delimiter)]: entry
104
- }
105
- };
106
- });
82
+ const hash = window.location.hash.split("#")[1];
83
+ if (hash) {
84
+ const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
85
+ if (hashScrollIntoViewOptions) {
86
+ console.log("scrollIntoView");
87
+ const el = document.getElementById(hash);
88
+ if (el) {
89
+ el.scrollIntoView(hashScrollIntoViewOptions);
107
90
  }
108
91
  }
92
+ return;
93
+ }
94
+ window.scrollTo({
95
+ top: 0,
96
+ left: 0,
97
+ behavior
109
98
  });
110
- const unsubOnBeforeRouteMount = router.subscribe(
111
- "onBeforeRouteMount",
112
- (event) => {
113
- if (event.hrefChanged) {
114
- if (!router.resetNextScroll) {
115
- return;
116
- }
117
- router.resetNextScroll = true;
118
- const restoreKey = getKey(event.toLocation);
119
- let windowRestored = false;
120
- for (const cacheKey in cache.state.cached) {
121
- const entry = cache.state.cached[cacheKey];
122
- const [key, elementSelector] = cacheKey.split(delimiter);
123
- if (key === restoreKey) {
124
- if (elementSelector === windowKey) {
125
- windowRestored = true;
126
- window.scrollTo({
127
- top: entry.scrollY,
128
- left: entry.scrollX,
129
- behavior: options == null ? void 0 : options.scrollBehavior
130
- });
131
- } else if (elementSelector) {
132
- const element = document.querySelector(elementSelector);
133
- if (element) {
134
- element.scrollLeft = entry.scrollX;
135
- element.scrollTop = entry.scrollY;
136
- }
137
- }
138
- }
139
- }
140
- if (!windowRestored) {
141
- window.scrollTo(0, 0);
142
- }
143
- cache.set((c) => ({ ...c, next: {} }));
144
- weakScrolledElements = /* @__PURE__ */ new WeakSet();
145
- }
146
- }
147
- );
148
- return () => {
149
- document.removeEventListener("scroll", onScroll);
150
- unsubOnBeforeLoad();
151
- unsubOnBeforeRouteMount();
152
- };
153
- }, [options == null ? void 0 : options.getKey, options == null ? void 0 : options.scrollBehavior, router]);
154
- }
155
- function ScrollRestoration(props) {
156
- useScrollRestoration(props);
157
- return null;
99
+ })();
100
+ ignoreScroll = false;
158
101
  }
159
- function useElementScrollRestoration(options) {
160
- var _a;
161
- const router = useRouter.useRouter();
162
- const getKey = options.getKey || defaultGetKey;
163
- let elementSelector = "";
164
- if (options.id) {
165
- elementSelector = `[data-scroll-restoration-id="${options.id}"]`;
166
- } else {
167
- const element = (_a = options.getElement) == null ? void 0 : _a.call(options);
168
- if (!element) {
102
+ function setupScrollRestoration(router, force) {
103
+ const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
104
+ if (shouldScrollRestoration) {
105
+ router.isScrollRestoring = true;
106
+ }
107
+ if (typeof document === "undefined" || router.isScrollRestorationSetup) {
108
+ return;
109
+ }
110
+ router.isScrollRestorationSetup = true;
111
+ ignoreScroll = false;
112
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
113
+ window.history.scrollRestoration = "manual";
114
+ const onScroll = (event) => {
115
+ if (ignoreScroll || !router.isScrollRestoring) {
169
116
  return;
170
117
  }
171
- elementSelector = getCssSelector(element);
118
+ let elementSelector = "";
119
+ if (event.target === document || event.target === window) {
120
+ elementSelector = "window";
121
+ } else {
122
+ const attrId = event.target.getAttribute(
123
+ "data-scroll-restoration-id"
124
+ );
125
+ if (attrId) {
126
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
127
+ } else {
128
+ elementSelector = getCssSelector(event.target);
129
+ }
130
+ }
131
+ const restoreKey = getKey(router.state.location);
132
+ scrollRestorationCache.set((state) => {
133
+ const keyEntry = state[restoreKey] = state[restoreKey] || {};
134
+ const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
135
+ if (elementSelector === "window") {
136
+ elementEntry.scrollX = window.scrollX || 0;
137
+ elementEntry.scrollY = window.scrollY || 0;
138
+ } else if (elementSelector) {
139
+ const element = document.querySelector(elementSelector);
140
+ if (element) {
141
+ elementEntry.scrollX = element.scrollLeft || 0;
142
+ elementEntry.scrollY = element.scrollTop || 0;
143
+ }
144
+ }
145
+ return state;
146
+ });
147
+ };
148
+ if (typeof document !== "undefined") {
149
+ document.addEventListener("scroll", throttle(onScroll, 100), true);
172
150
  }
173
- const restoreKey = getKey(router.latestLocation);
174
- const cacheKey = [restoreKey, elementSelector].join(delimiter);
175
- return cache.state.cached[cacheKey];
176
- }
177
- function getCssSelector(el) {
178
- const path = [];
179
- let parent;
180
- while (parent = el.parentNode) {
181
- path.unshift(
182
- `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
151
+ router.subscribe("onRendered", (event) => {
152
+ const cacheKey = getKey(event.toLocation);
153
+ if (!router.resetNextScroll) {
154
+ router.resetNextScroll = true;
155
+ return;
156
+ }
157
+ restoreScroll(
158
+ storageKey,
159
+ cacheKey,
160
+ router.options.scrollRestorationBehavior,
161
+ router.isScrollRestoring
183
162
  );
184
- el = parent;
163
+ if (router.isScrollRestoring) {
164
+ scrollRestorationCache.set((state) => {
165
+ state[cacheKey] = state[cacheKey] || {};
166
+ return state;
167
+ });
168
+ }
169
+ });
170
+ }
171
+ function ScrollRestoration() {
172
+ const router = useRouter.useRouter();
173
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
174
+ const userKey = getKey(router.latestLocation);
175
+ const resolvedKey = userKey !== defaultGetScrollRestorationKey(router.latestLocation) ? userKey : null;
176
+ if (!router.isScrollRestoring || !router.isServer) {
177
+ return null;
185
178
  }
186
- return `${path.join(" > ")}`.toLowerCase();
179
+ return /* @__PURE__ */ jsxRuntime.jsx(
180
+ ScriptOnce.ScriptOnce,
181
+ {
182
+ children: `(${restoreScroll.toString()})(${JSON.stringify(storageKey)},${JSON.stringify(resolvedKey)}, undefined, true)`,
183
+ log: false
184
+ }
185
+ );
187
186
  }
188
187
  exports.ScrollRestoration = ScrollRestoration;
189
- exports.useElementScrollRestoration = useElementScrollRestoration;
190
- exports.useScrollRestoration = useScrollRestoration;
188
+ exports.defaultGetScrollRestorationKey = defaultGetScrollRestorationKey;
189
+ exports.getCssSelector = getCssSelector;
190
+ exports.restoreScroll = restoreScroll;
191
+ exports.scrollRestorationCache = scrollRestorationCache;
192
+ exports.setupScrollRestoration = setupScrollRestoration;
193
+ exports.storageKey = storageKey;
191
194
  //# sourceMappingURL=scroll-restoration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import * as React from 'react'\nimport { functionalUpdate } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core'\n\nconst useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nconst windowKey = 'window'\nconst delimiter = '___'\n\nlet weakScrolledElements = new WeakSet<any>()\n\ntype CacheValue = Record<string, { scrollX: number; scrollY: number }>\ntype CacheState = {\n cached: CacheValue\n next: CacheValue\n}\n\ntype Cache = {\n state: CacheState\n set: (updater: NonNullableUpdater<CacheState>) => void\n}\n\nconst sessionsStorage = typeof window !== 'undefined' && window.sessionStorage\n\nconst cache: Cache = sessionsStorage\n ? (() => {\n const storageKey = 'tsr-scroll-restoration-v2'\n\n const state: CacheState = JSON.parse(\n window.sessionStorage.getItem(storageKey) || 'null',\n ) || { cached: {}, next: {} }\n\n return {\n state,\n set: (updater) => {\n cache.state = functionalUpdate(updater, cache.state)\n window.sessionStorage.setItem(storageKey, JSON.stringify(cache.state))\n },\n }\n })()\n : (undefined as any)\n\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\nconst defaultGetKey = (location: ParsedLocation) => {\n return location.state.key! || location.href\n}\n\nexport function useScrollRestoration(options?: ScrollRestorationOptions) {\n const router = useRouter()\n\n useLayoutEffect(() => {\n const getKey = options?.getKey || defaultGetKey\n\n const { history } = window\n history.scrollRestoration = 'manual'\n\n const onScroll = (event: Event) => {\n if (weakScrolledElements.has(event.target)) return\n weakScrolledElements.add(event.target)\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = windowKey\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n if (!cache.state.next[elementSelector]) {\n cache.set((c) => ({\n ...c,\n next: {\n ...c.next,\n [elementSelector]: {\n scrollX: NaN,\n scrollY: NaN,\n },\n },\n }))\n }\n }\n\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', onScroll, true)\n }\n\n const unsubOnBeforeLoad = router.subscribe('onBeforeLoad', (event) => {\n if (event.hrefChanged) {\n const restoreKey = getKey(event.fromLocation)\n for (const elementSelector in cache.state.next) {\n const entry = cache.state.next[elementSelector]!\n if (elementSelector === windowKey) {\n entry.scrollX = window.scrollX || 0\n entry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n entry.scrollX = element?.scrollLeft || 0\n entry.scrollY = element?.scrollTop || 0\n }\n\n cache.set((c) => {\n const next = { ...c.next }\n delete next[elementSelector]\n\n return {\n ...c,\n next,\n cached: {\n ...c.cached,\n [[restoreKey, elementSelector].join(delimiter)]: entry,\n },\n }\n })\n }\n }\n })\n\n const unsubOnBeforeRouteMount = router.subscribe(\n 'onBeforeRouteMount',\n (event) => {\n if (event.hrefChanged) {\n if (!router.resetNextScroll) {\n return\n }\n\n router.resetNextScroll = true\n\n const restoreKey = getKey(event.toLocation)\n let windowRestored = false\n\n for (const cacheKey in cache.state.cached) {\n const entry = cache.state.cached[cacheKey]!\n const [key, elementSelector] = cacheKey.split(delimiter)\n if (key === restoreKey) {\n if (elementSelector === windowKey) {\n windowRestored = true\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior: options?.scrollBehavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n }\n\n if (!windowRestored) {\n window.scrollTo(0, 0)\n }\n\n cache.set((c) => ({ ...c, next: {} }))\n weakScrolledElements = new WeakSet<any>()\n }\n },\n )\n\n return () => {\n document.removeEventListener('scroll', onScroll)\n unsubOnBeforeLoad()\n unsubOnBeforeRouteMount()\n }\n }, [options?.getKey, options?.scrollBehavior, router])\n}\n\nexport function ScrollRestoration(props: ScrollRestorationOptions) {\n useScrollRestoration(props)\n return null\n}\n\nexport function useElementScrollRestoration(\n options: (\n | {\n id: string\n getElement?: () => Element | undefined | null\n }\n | {\n id?: string\n getElement: () => Element | undefined | null\n }\n ) & {\n getKey?: (location: ParsedLocation) => string\n },\n) {\n const router = useRouter()\n const getKey = options.getKey || defaultGetKey\n\n let elementSelector = ''\n\n if (options.id) {\n elementSelector = `[data-scroll-restoration-id=\"${options.id}\"]`\n } else {\n const element = options.getElement?.()\n if (!element) {\n return\n }\n elementSelector = getCssSelector(element)\n }\n\n const restoreKey = getKey(router.latestLocation)\n const cacheKey = [restoreKey, elementSelector].join(delimiter)\n return cache.state.cached[cacheKey]\n}\n\nfunction getCssSelector(el: any): string {\n const path = []\n let parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${\n ([].indexOf as any).call(parent.children, el) + 1\n })`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n}\n"],"names":["React","functionalUpdate","useRouter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,kBACJ,OAAO,WAAW,cAAcA,iBAAM,kBAAkBA,iBAAM;AAEhE,MAAM,YAAY;AAClB,MAAM,YAAY;AAElB,IAAI,2CAA2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AA,MAAM,MAAM,OAAO,QAAQ;AACpC;AAEA,SAAS,eAAe,IAAiB;AACvC,QAAM,OAAO,CAAC;AACV,MAAA;AACI,SAAA,SAAS,GAAG,YAAa;AAC1B,SAAA;AAAA,MACH,GAAG,GAAG,OAAO,cACV,CAAA,EAAG,QAAgB,KAAK,OAAO,UAAU,EAAE,IAAI,CAClD;AAAA,IACF;AACK,SAAA;AAAA,EAAA;AAEP,SAAO,GAAG,KAAK,KAAK,KAAK,CAAC,GAAG,YAAY;AAC3C;;;;"}
1
+ {"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import { functionalUpdate } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\nimport type { AnyRouter } from './router'\nimport type { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core'\n\nexport type ScrollRestorationEntry = { scrollX: number; scrollY: number }\n\nexport type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>\n\nexport type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>\n\nexport type ScrollRestorationCache = {\n state: ScrollRestorationByKey\n set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void\n}\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\nconst sessionsStorage = typeof window !== 'undefined' && window.sessionStorage\nconst throttle = (fn: (...args: Array<any>) => void, wait: number) => {\n let timeout: any\n return (...args: Array<any>) => {\n if (!timeout) {\n timeout = setTimeout(() => {\n fn(...args)\n timeout = null\n }, wait)\n }\n }\n}\nexport const scrollRestorationCache: ScrollRestorationCache = sessionsStorage\n ? (() => {\n const state: ScrollRestorationByKey =\n JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}\n\n return {\n state,\n // This setter is simply to make sure that we set the sessionStorage right\n // after the state is updated. It doesn't necessarily need to be a functional\n // update.\n set: (updater) => (\n (scrollRestorationCache.state =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n functionalUpdate(updater, scrollRestorationCache.state) ||\n scrollRestorationCache.state),\n window.sessionStorage.setItem(\n storageKey,\n JSON.stringify(scrollRestorationCache.state),\n )\n ),\n }\n })()\n : (undefined as any)\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.key! || location.href\n}\n\nexport function getCssSelector(el: any): string {\n const path = []\n let parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n}\n\nlet ignoreScroll = false\n\n// NOTE: This function must remain pure and not use any outside variables\n// unless they are passed in as arguments. Why? Because we need to be able to\n// toString() it into a script tag to execute as early as possible in the browser\n// during SSR. Additionally, we also call it from within the router lifecycle\nexport function restoreScroll(\n storageKey: string,\n key?: string,\n behavior?: ScrollToOptions['behavior'],\n shouldScrollRestoration?: boolean,\n) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error: any) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n ;(() => {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (shouldScrollRestoration && elementEntries) {\n for (const elementSelector in elementEntries) {\n const entry = elementEntries[elementSelector]!\n if (elementSelector === 'window') {\n console.log('windowRestored', entry)\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n\n return\n }\n\n // If we don't have a cached entry for the hash,\n // Which means we've never seen this location before,\n // we need to check if there is a hash in the URL.\n // If there is, we need to scroll it's ID into view.\n const hash = window.location.hash.split('#')[1]\n\n if (hash) {\n const hashScrollIntoViewOptions =\n (window.history.state || {}).__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions) {\n console.log('scrollIntoView')\n const el = document.getElementById(hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n\n return\n }\n\n // If there is no cached entry for the hash and there is no hash in the URL,\n // we need to scroll to the top of the page.\n window.scrollTo({\n top: 0,\n left: 0,\n behavior,\n })\n })()\n\n //\n ignoreScroll = false\n}\n\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (typeof document === 'undefined' || router.isScrollRestorationSetup) {\n return\n }\n\n router.isScrollRestorationSetup = true\n\n //\n ignoreScroll = false\n\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n\n window.history.scrollRestoration = 'manual'\n\n // // Create a MutationObserver to monitor DOM changes\n // const mutationObserver = new MutationObserver(() => {\n // ;ignoreScroll = true\n // requestAnimationFrame(() => {\n // ;ignoreScroll = false\n\n // // Attempt to restore scroll position on each dom\n // // mutation until the user scrolls. We do this\n // // because dynamic content may come in at different\n // // ticks after the initial render and we want to\n // // keep up with that content as much as possible.\n // // As soon as the user scrolls, we no longer need\n // // to attempt router.\n // // console.log('mutation observer restoreScroll')\n // restoreScroll(\n // storageKey,\n // getKey(router.state.location),\n // router.options.scrollRestorationBehavior,\n // )\n // })\n // })\n\n // const observeDom = () => {\n // // Observe changes to the entire document\n // mutationObserver.observe(document, {\n // childList: true, // Detect added or removed child nodes\n // subtree: true, // Monitor all descendants\n // characterData: true, // Detect text content changes\n // })\n // }\n\n // const unobserveDom = () => {\n // mutationObserver.disconnect()\n // }\n\n // observeDom()\n\n const onScroll = (event: Event) => {\n // unobserveDom()\n\n if (ignoreScroll || !router.isScrollRestoring) {\n return\n }\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = 'window'\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n const restoreKey = getKey(router.state.location)\n\n scrollRestorationCache.set((state) => {\n const keyEntry = (state[restoreKey] =\n state[restoreKey] || ({} as ScrollRestorationByElement))\n\n const elementEntry = (keyEntry[elementSelector] =\n keyEntry[elementSelector] || ({} as ScrollRestorationEntry))\n\n if (elementSelector === 'window') {\n elementEntry.scrollX = window.scrollX || 0\n elementEntry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n elementEntry.scrollX = element.scrollLeft || 0\n elementEntry.scrollY = element.scrollTop || 0\n }\n }\n\n return state\n })\n }\n\n // Throttle the scroll event to avoid excessive updates\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', throttle(onScroll, 100), true)\n }\n\n router.subscribe('onRendered', (event) => {\n // unobserveDom()\n\n const cacheKey = getKey(event.toLocation)\n\n // If the user doesn't want to restore the scroll position,\n // we don't need to do anything.\n if (!router.resetNextScroll) {\n router.resetNextScroll = true\n return\n }\n\n restoreScroll(\n storageKey,\n cacheKey,\n router.options.scrollRestorationBehavior,\n router.isScrollRestoring,\n )\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)\n\n return state\n })\n }\n })\n}\n\nexport function ScrollRestoration() {\n const router = useRouter()\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n const userKey = getKey(router.latestLocation)\n const resolvedKey =\n userKey !== defaultGetScrollRestorationKey(router.latestLocation)\n ? userKey\n : null\n\n if (!router.isScrollRestoring || !router.isServer) {\n return null\n }\n\n return (\n <ScriptOnce\n children={`(${restoreScroll.toString()})(${JSON.stringify(storageKey)},${JSON.stringify(resolvedKey)}, undefined, true)`}\n log={false}\n />\n )\n}\n"],"names":["functionalUpdate","storageKey","useRouter","jsx","ScriptOnce"],"mappings":";;;;;;AAqBO,MAAM,aAAa;AAC1B,MAAM,kBAAkB,OAAO,WAAW,eAAe,OAAO;AAChE,MAAM,WAAW,CAAC,IAAmC,SAAiB;AAChE,MAAA;AACJ,SAAO,IAAI,SAAqB;AAC9B,QAAI,CAAC,SAAS;AACZ,gBAAU,WAAW,MAAM;AACzB,WAAG,GAAG,IAAI;AACA,kBAAA;AAAA,SACT,IAAI;AAAA,IAAA;AAAA,EAEX;AACF;AACa,MAAA,yBAAiD,mBACzD,MAAM;AACC,QAAA,QACJ,KAAK,MAAM,OAAO,eAAe,QAAQ,UAAU,KAAK,MAAM,KAAK,CAAC;AAE/D,SAAA;AAAA,IACL;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,CAAC,aACH,uBAAuB;AAAA,IAEtBA,4BAAiB,SAAS,uBAAuB,KAAK,KACtD,uBAAuB,OACzB,OAAO,eAAe;AAAA,MACpB;AAAA,MACA,KAAK,UAAU,uBAAuB,KAAK;AAAA,IAC7C;AAAA,EAEJ;AACF,OACC;AAQQ,MAAA,iCAAiC,CAAC,aAA6B;AACnE,SAAA,SAAS,MAAM,OAAQ,SAAS;AACzC;AAEO,SAAS,eAAe,IAAiB;AAC9C,QAAM,OAAO,CAAC;AACV,MAAA;AACI,SAAA,SAAS,GAAG,YAAa;AAC1B,SAAA;AAAA,MACH,GAAG,GAAG,OAAO,cAAe,CAAA,EAAG,QAAgB,KAAK,OAAO,UAAU,EAAE,IAAI,CAAC;AAAA,IAC9E;AACK,SAAA;AAAA,EAAA;AAEP,SAAO,GAAG,KAAK,KAAK,KAAK,CAAC,GAAG,YAAY;AAC3C;AAEA,IAAI,eAAe;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C,UAAA,WAAW,OAAO,MAAM,UAAU;AAIpC,QAAA,CAAC,OAAO,iBAAiB;AAC3B,aAAO,kBAAkB;AACzB;AAAA,IAAA;AAGF;AAAA,MACE;AAAA,MACA;AAAA,MACA,OAAO,QAAQ;AAAA,MACf,OAAO;AAAA,IACT;AAEA,QAAI,OAAO,mBAAmB;AAEL,6BAAA,IAAI,CAAC,UAAU;AACpC,cAAM,QAAQ,IAAI,MAAM,QAAQ,KAAM,CAAC;AAEhC,eAAA;AAAA,MAAA,CACR;AAAA,IAAA;AAAA,EACH,CACD;AACH;AAEO,SAAS,oBAAoB;AAClC,QAAM,SAASC,UAAAA,UAAU;AACnB,QAAA,SACJ,OAAO,QAAQ,2BAA2B;AACtC,QAAA,UAAU,OAAO,OAAO,cAAc;AAC5C,QAAM,cACJ,YAAY,+BAA+B,OAAO,cAAc,IAC5D,UACA;AAEN,MAAI,CAAC,OAAO,qBAAqB,CAAC,OAAO,UAAU;AAC1C,WAAA;AAAA,EAAA;AAIP,SAAAC,2BAAA;AAAA,IAACC,WAAA;AAAA,IAAA;AAAA,MACC,UAAU,IAAI,cAAc,SAAU,CAAA,KAAK,KAAK,UAAU,UAAU,CAAC,IAAI,KAAK,UAAU,WAAW,CAAC;AAAA,MACpG,KAAK;AAAA,IAAA;AAAA,EACP;AAEJ;;;;;;;;"}
@@ -1,19 +1,29 @@
1
- import { ParsedLocation } from '@tanstack/router-core';
1
+ import { AnyRouter } from './router.cjs';
2
+ import { NonNullableUpdater, ParsedLocation } from '@tanstack/router-core';
3
+ export type ScrollRestorationEntry = {
4
+ scrollX: number;
5
+ scrollY: number;
6
+ };
7
+ export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
8
+ export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
9
+ export type ScrollRestorationCache = {
10
+ state: ScrollRestorationByKey;
11
+ set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
12
+ };
2
13
  export type ScrollRestorationOptions = {
3
14
  getKey?: (location: ParsedLocation) => string;
4
15
  scrollBehavior?: ScrollToOptions['behavior'];
5
16
  };
6
- export declare function useScrollRestoration(options?: ScrollRestorationOptions): void;
7
- export declare function ScrollRestoration(props: ScrollRestorationOptions): null;
8
- export declare function useElementScrollRestoration(options: ({
9
- id: string;
10
- getElement?: () => Element | undefined | null;
11
- } | {
12
- id?: string;
13
- getElement: () => Element | undefined | null;
14
- }) & {
15
- getKey?: (location: ParsedLocation) => string;
16
- }): {
17
- scrollX: number;
18
- scrollY: number;
19
- } | undefined;
17
+ export declare const storageKey = "tsr-scroll-restoration-v1_3";
18
+ export declare const scrollRestorationCache: ScrollRestorationCache;
19
+ /**
20
+ * The default `getKey` function for `useScrollRestoration`.
21
+ * It returns the `key` from the location state or the `href` of the location.
22
+ *
23
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
24
+ */
25
+ export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
26
+ export declare function getCssSelector(el: any): string;
27
+ export declare function restoreScroll(storageKey: string, key?: string, behavior?: ScrollToOptions['behavior'], shouldScrollRestoration?: boolean): void;
28
+ export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
29
+ export declare function ScrollRestoration(): import("react/jsx-runtime").JSX.Element | null;