@tanstack/router-core 1.114.7 → 1.114.15

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.
@@ -12,6 +12,7 @@ const searchParams = require("./searchParams.cjs");
12
12
  const utils = require("./utils.cjs");
13
13
  const redirect = require("./redirect.cjs");
14
14
  const notFound = require("./not-found.cjs");
15
+ const scrollRestoration = require("./scroll-restoration.cjs");
15
16
  exports.TSR_DEFERRED_PROMISE = defer.TSR_DEFERRED_PROMISE;
16
17
  exports.defer = defer.defer;
17
18
  exports.preloadWarning = link.preloadWarning;
@@ -55,4 +56,10 @@ exports.isResolvedRedirect = redirect.isResolvedRedirect;
55
56
  exports.redirect = redirect.redirect;
56
57
  exports.isNotFound = notFound.isNotFound;
57
58
  exports.notFound = notFound.notFound;
59
+ exports.defaultGetScrollRestorationKey = scrollRestoration.defaultGetScrollRestorationKey;
60
+ exports.getCssSelector = scrollRestoration.getCssSelector;
61
+ exports.restoreScroll = scrollRestoration.restoreScroll;
62
+ exports.scrollRestorationCache = scrollRestoration.scrollRestorationCache;
63
+ exports.setupScrollRestoration = scrollRestoration.setupScrollRestoration;
64
+ exports.storageKey = scrollRestoration.storageKey;
58
65
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -35,3 +35,5 @@ export type { Redirect, ResolvedRedirect, AnyRedirect } from './redirect.cjs';
35
35
  export { redirect, isRedirect, isResolvedRedirect } from './redirect.cjs';
36
36
  export type { NotFoundError } from './not-found.cjs';
37
37
  export { isNotFound, notFound } from './not-found.cjs';
38
+ export { defaultGetScrollRestorationKey, restoreScroll, storageKey, getCssSelector, scrollRestorationCache, setupScrollRestoration, } from './scroll-restoration.cjs';
39
+ export type { ScrollRestorationOptions, ScrollRestorationEntry, } from './scroll-restoration.cjs';
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const utils = require("./utils.cjs");
4
+ const storageKey = "tsr-scroll-restoration-v1_3";
5
+ let sessionsStorage = false;
6
+ try {
7
+ sessionsStorage = typeof window !== "undefined" && typeof window.sessionStorage === "object";
8
+ } catch {
9
+ }
10
+ const throttle = (fn, wait) => {
11
+ let timeout;
12
+ return (...args) => {
13
+ if (!timeout) {
14
+ timeout = setTimeout(() => {
15
+ fn(...args);
16
+ timeout = null;
17
+ }, wait);
18
+ }
19
+ };
20
+ };
21
+ const scrollRestorationCache = sessionsStorage ? (() => {
22
+ const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
23
+ return {
24
+ state,
25
+ // This setter is simply to make sure that we set the sessionStorage right
26
+ // after the state is updated. It doesn't necessarily need to be a functional
27
+ // update.
28
+ set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
29
+ utils.functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
30
+ storageKey,
31
+ JSON.stringify(scrollRestorationCache.state)
32
+ ))
33
+ };
34
+ })() : void 0;
35
+ const defaultGetScrollRestorationKey = (location) => {
36
+ return location.state.key || location.href;
37
+ };
38
+ function getCssSelector(el) {
39
+ const path = [];
40
+ let parent;
41
+ while (parent = el.parentNode) {
42
+ path.unshift(
43
+ `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
44
+ );
45
+ el = parent;
46
+ }
47
+ return `${path.join(" > ")}`.toLowerCase();
48
+ }
49
+ let ignoreScroll = false;
50
+ function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration, scrollToTopSelectors) {
51
+ var _a;
52
+ let byKey;
53
+ try {
54
+ byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
55
+ } catch (error) {
56
+ console.error(error);
57
+ return;
58
+ }
59
+ const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
60
+ const elementEntries = byKey[resolvedKey];
61
+ ignoreScroll = true;
62
+ (() => {
63
+ if (shouldScrollRestoration && elementEntries) {
64
+ for (const elementSelector in elementEntries) {
65
+ const entry = elementEntries[elementSelector];
66
+ if (elementSelector === "window") {
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;
77
+ }
78
+ }
79
+ }
80
+ return;
81
+ }
82
+ const hash = window.location.hash.split("#")[1];
83
+ if (hash) {
84
+ const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
85
+ if (hashScrollIntoViewOptions) {
86
+ const el = document.getElementById(hash);
87
+ if (el) {
88
+ el.scrollIntoView(hashScrollIntoViewOptions);
89
+ }
90
+ }
91
+ return;
92
+ }
93
+ [
94
+ "window",
95
+ ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
96
+ ].forEach((selector) => {
97
+ const element = selector === "window" ? window : document.querySelector(selector);
98
+ if (element) {
99
+ element.scrollTo({
100
+ top: 0,
101
+ left: 0,
102
+ behavior
103
+ });
104
+ }
105
+ });
106
+ })();
107
+ ignoreScroll = false;
108
+ }
109
+ function setupScrollRestoration(router, force) {
110
+ const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
111
+ if (shouldScrollRestoration) {
112
+ router.isScrollRestoring = true;
113
+ }
114
+ if (typeof document === "undefined" || router.isScrollRestorationSetup) {
115
+ return;
116
+ }
117
+ router.isScrollRestorationSetup = true;
118
+ ignoreScroll = false;
119
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
120
+ window.history.scrollRestoration = "manual";
121
+ const onScroll = (event) => {
122
+ if (ignoreScroll || !router.isScrollRestoring) {
123
+ return;
124
+ }
125
+ let elementSelector = "";
126
+ if (event.target === document || event.target === window) {
127
+ elementSelector = "window";
128
+ } else {
129
+ const attrId = event.target.getAttribute(
130
+ "data-scroll-restoration-id"
131
+ );
132
+ if (attrId) {
133
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
134
+ } else {
135
+ elementSelector = getCssSelector(event.target);
136
+ }
137
+ }
138
+ const restoreKey = getKey(router.state.location);
139
+ scrollRestorationCache.set((state) => {
140
+ const keyEntry = state[restoreKey] = state[restoreKey] || {};
141
+ const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
142
+ if (elementSelector === "window") {
143
+ elementEntry.scrollX = window.scrollX || 0;
144
+ elementEntry.scrollY = window.scrollY || 0;
145
+ } else if (elementSelector) {
146
+ const element = document.querySelector(elementSelector);
147
+ if (element) {
148
+ elementEntry.scrollX = element.scrollLeft || 0;
149
+ elementEntry.scrollY = element.scrollTop || 0;
150
+ }
151
+ }
152
+ return state;
153
+ });
154
+ };
155
+ if (typeof document !== "undefined") {
156
+ document.addEventListener("scroll", throttle(onScroll, 100), true);
157
+ }
158
+ router.subscribe("onRendered", (event) => {
159
+ const cacheKey = getKey(event.toLocation);
160
+ if (!router.resetNextScroll) {
161
+ router.resetNextScroll = true;
162
+ return;
163
+ }
164
+ restoreScroll(
165
+ storageKey,
166
+ cacheKey,
167
+ router.options.scrollRestorationBehavior || void 0,
168
+ router.isScrollRestoring || void 0,
169
+ router.options.scrollToTopSelectors || void 0
170
+ );
171
+ if (router.isScrollRestoring) {
172
+ scrollRestorationCache.set((state) => {
173
+ state[cacheKey] = state[cacheKey] || {};
174
+ return state;
175
+ });
176
+ }
177
+ });
178
+ }
179
+ exports.defaultGetScrollRestorationKey = defaultGetScrollRestorationKey;
180
+ exports.getCssSelector = getCssSelector;
181
+ exports.restoreScroll = restoreScroll;
182
+ exports.scrollRestorationCache = scrollRestorationCache;
183
+ exports.setupScrollRestoration = setupScrollRestoration;
184
+ exports.storageKey = storageKey;
185
+ //# sourceMappingURL=scroll-restoration.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.ts"],"sourcesContent":["import { functionalUpdate } from './utils'\nimport type { AnyRouter } from './router'\nimport type { ParsedLocation } from './location'\nimport type { NonNullableUpdater } from './utils'\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'\nlet sessionsStorage = false\ntry {\n sessionsStorage =\n typeof window !== 'undefined' && typeof window.sessionStorage === 'object'\n} catch {}\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 | undefined,\n behavior: ScrollToOptions['behavior'] | undefined,\n shouldScrollRestoration: boolean | undefined,\n scrollToTopSelectors: Array<string> | undefined,\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 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 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 for every scrollToTop element\n ;[\n 'window',\n ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),\n ].forEach((selector) => {\n const element =\n selector === 'window' ? window : document.querySelector(selector)\n if (element) {\n element.scrollTo({\n top: 0,\n left: 0,\n behavior,\n })\n }\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 || undefined,\n router.isScrollRestoring || undefined,\n router.options.scrollToTopSelectors || undefined,\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"],"names":["functionalUpdate","storageKey"],"mappings":";;;AAoBO,MAAM,aAAa;AAC1B,IAAI,kBAAkB;AACtB,IAAI;AACF,oBACE,OAAO,WAAW,eAAe,OAAO,OAAO,mBAAmB;A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AGF;AAAA,MACE;AAAA,MACA;AAAA,MACA,OAAO,QAAQ,6BAA6B;AAAA,MAC5C,OAAO,qBAAqB;AAAA,MAC5B,OAAO,QAAQ,wBAAwB;AAAA,IACzC;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;;;;;;;"}
@@ -0,0 +1,29 @@
1
+ import { AnyRouter } from './router.cjs';
2
+ import { ParsedLocation } from './location.cjs';
3
+ import { NonNullableUpdater } from './utils.cjs';
4
+ export type ScrollRestorationEntry = {
5
+ scrollX: number;
6
+ scrollY: number;
7
+ };
8
+ export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
9
+ export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
10
+ export type ScrollRestorationCache = {
11
+ state: ScrollRestorationByKey;
12
+ set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
13
+ };
14
+ export type ScrollRestorationOptions = {
15
+ getKey?: (location: ParsedLocation) => string;
16
+ scrollBehavior?: ScrollToOptions['behavior'];
17
+ };
18
+ export declare const storageKey = "tsr-scroll-restoration-v1_3";
19
+ export declare const scrollRestorationCache: ScrollRestorationCache;
20
+ /**
21
+ * The default `getKey` function for `useScrollRestoration`.
22
+ * It returns the `key` from the location state or the `href` of the location.
23
+ *
24
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
25
+ */
26
+ export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
27
+ export declare function getCssSelector(el: any): string;
28
+ export declare function restoreScroll(storageKey: string, key: string | undefined, behavior: ScrollToOptions['behavior'] | undefined, shouldScrollRestoration: boolean | undefined, scrollToTopSelectors: Array<string> | undefined): void;
29
+ export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
@@ -35,3 +35,5 @@ export type { Redirect, ResolvedRedirect, AnyRedirect } from './redirect.js';
35
35
  export { redirect, isRedirect, isResolvedRedirect } from './redirect.js';
36
36
  export type { NotFoundError } from './not-found.js';
37
37
  export { isNotFound, notFound } from './not-found.js';
38
+ export { defaultGetScrollRestorationKey, restoreScroll, storageKey, getCssSelector, scrollRestorationCache, setupScrollRestoration, } from './scroll-restoration.js';
39
+ export type { ScrollRestorationOptions, ScrollRestorationEntry, } from './scroll-restoration.js';
package/dist/esm/index.js CHANGED
@@ -10,12 +10,14 @@ import { defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifyS
10
10
  import { createControlledPromise, deepEqual, escapeJSON, functionalUpdate, isPlainArray, isPlainObject, last, pick, replaceEqualDeep, shallow } from "./utils.js";
11
11
  import { isRedirect, isResolvedRedirect, redirect } from "./redirect.js";
12
12
  import { isNotFound, notFound } from "./not-found.js";
13
+ import { defaultGetScrollRestorationKey, getCssSelector, restoreScroll, scrollRestorationCache, setupScrollRestoration, storageKey } from "./scroll-restoration.js";
13
14
  export {
14
15
  TSR_DEFERRED_PROMISE,
15
16
  cleanPath,
16
17
  createControlledPromise,
17
18
  decode,
18
19
  deepEqual,
20
+ defaultGetScrollRestorationKey,
19
21
  defaultParseSearch,
20
22
  defaultSerializeError,
21
23
  defaultStringifySearch,
@@ -24,6 +26,7 @@ export {
24
26
  escapeJSON,
25
27
  exactPathTest,
26
28
  functionalUpdate,
29
+ getCssSelector,
27
30
  getLocationChangeInfo,
28
31
  interpolatePath,
29
32
  isMatch,
@@ -46,9 +49,13 @@ export {
46
49
  removeTrailingSlash,
47
50
  replaceEqualDeep,
48
51
  resolvePath,
52
+ restoreScroll,
49
53
  retainSearchParams,
50
54
  rootRouteId,
55
+ scrollRestorationCache,
56
+ setupScrollRestoration,
51
57
  shallow,
58
+ storageKey,
52
59
  stringifySearchWith,
53
60
  stripSearchParams,
54
61
  trimPath,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;"}
@@ -0,0 +1,29 @@
1
+ import { AnyRouter } from './router.js';
2
+ import { ParsedLocation } from './location.js';
3
+ import { NonNullableUpdater } from './utils.js';
4
+ export type ScrollRestorationEntry = {
5
+ scrollX: number;
6
+ scrollY: number;
7
+ };
8
+ export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
9
+ export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
10
+ export type ScrollRestorationCache = {
11
+ state: ScrollRestorationByKey;
12
+ set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
13
+ };
14
+ export type ScrollRestorationOptions = {
15
+ getKey?: (location: ParsedLocation) => string;
16
+ scrollBehavior?: ScrollToOptions['behavior'];
17
+ };
18
+ export declare const storageKey = "tsr-scroll-restoration-v1_3";
19
+ export declare const scrollRestorationCache: ScrollRestorationCache;
20
+ /**
21
+ * The default `getKey` function for `useScrollRestoration`.
22
+ * It returns the `key` from the location state or the `href` of the location.
23
+ *
24
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
25
+ */
26
+ export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
27
+ export declare function getCssSelector(el: any): string;
28
+ export declare function restoreScroll(storageKey: string, key: string | undefined, behavior: ScrollToOptions['behavior'] | undefined, shouldScrollRestoration: boolean | undefined, scrollToTopSelectors: Array<string> | undefined): void;
29
+ export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
@@ -0,0 +1,185 @@
1
+ import { functionalUpdate } from "./utils.js";
2
+ const storageKey = "tsr-scroll-restoration-v1_3";
3
+ let sessionsStorage = false;
4
+ try {
5
+ sessionsStorage = typeof window !== "undefined" && typeof window.sessionStorage === "object";
6
+ } catch {
7
+ }
8
+ const throttle = (fn, wait) => {
9
+ let timeout;
10
+ return (...args) => {
11
+ if (!timeout) {
12
+ timeout = setTimeout(() => {
13
+ fn(...args);
14
+ timeout = null;
15
+ }, wait);
16
+ }
17
+ };
18
+ };
19
+ const scrollRestorationCache = sessionsStorage ? (() => {
20
+ const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
21
+ return {
22
+ state,
23
+ // This setter is simply to make sure that we set the sessionStorage right
24
+ // after the state is updated. It doesn't necessarily need to be a functional
25
+ // update.
26
+ set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
27
+ functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
28
+ storageKey,
29
+ JSON.stringify(scrollRestorationCache.state)
30
+ ))
31
+ };
32
+ })() : void 0;
33
+ const defaultGetScrollRestorationKey = (location) => {
34
+ return location.state.key || location.href;
35
+ };
36
+ function getCssSelector(el) {
37
+ const path = [];
38
+ let parent;
39
+ while (parent = el.parentNode) {
40
+ path.unshift(
41
+ `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
42
+ );
43
+ el = parent;
44
+ }
45
+ return `${path.join(" > ")}`.toLowerCase();
46
+ }
47
+ let ignoreScroll = false;
48
+ function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration, scrollToTopSelectors) {
49
+ var _a;
50
+ let byKey;
51
+ try {
52
+ byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
53
+ } catch (error) {
54
+ console.error(error);
55
+ return;
56
+ }
57
+ const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
58
+ const elementEntries = byKey[resolvedKey];
59
+ ignoreScroll = true;
60
+ (() => {
61
+ if (shouldScrollRestoration && elementEntries) {
62
+ for (const elementSelector in elementEntries) {
63
+ const entry = elementEntries[elementSelector];
64
+ if (elementSelector === "window") {
65
+ window.scrollTo({
66
+ top: entry.scrollY,
67
+ left: entry.scrollX,
68
+ behavior
69
+ });
70
+ } else if (elementSelector) {
71
+ const element = document.querySelector(elementSelector);
72
+ if (element) {
73
+ element.scrollLeft = entry.scrollX;
74
+ element.scrollTop = entry.scrollY;
75
+ }
76
+ }
77
+ }
78
+ return;
79
+ }
80
+ const hash = window.location.hash.split("#")[1];
81
+ if (hash) {
82
+ const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
83
+ if (hashScrollIntoViewOptions) {
84
+ const el = document.getElementById(hash);
85
+ if (el) {
86
+ el.scrollIntoView(hashScrollIntoViewOptions);
87
+ }
88
+ }
89
+ return;
90
+ }
91
+ [
92
+ "window",
93
+ ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
94
+ ].forEach((selector) => {
95
+ const element = selector === "window" ? window : document.querySelector(selector);
96
+ if (element) {
97
+ element.scrollTo({
98
+ top: 0,
99
+ left: 0,
100
+ behavior
101
+ });
102
+ }
103
+ });
104
+ })();
105
+ ignoreScroll = false;
106
+ }
107
+ function setupScrollRestoration(router, force) {
108
+ const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
109
+ if (shouldScrollRestoration) {
110
+ router.isScrollRestoring = true;
111
+ }
112
+ if (typeof document === "undefined" || router.isScrollRestorationSetup) {
113
+ return;
114
+ }
115
+ router.isScrollRestorationSetup = true;
116
+ ignoreScroll = false;
117
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
118
+ window.history.scrollRestoration = "manual";
119
+ const onScroll = (event) => {
120
+ if (ignoreScroll || !router.isScrollRestoring) {
121
+ return;
122
+ }
123
+ let elementSelector = "";
124
+ if (event.target === document || event.target === window) {
125
+ elementSelector = "window";
126
+ } else {
127
+ const attrId = event.target.getAttribute(
128
+ "data-scroll-restoration-id"
129
+ );
130
+ if (attrId) {
131
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
132
+ } else {
133
+ elementSelector = getCssSelector(event.target);
134
+ }
135
+ }
136
+ const restoreKey = getKey(router.state.location);
137
+ scrollRestorationCache.set((state) => {
138
+ const keyEntry = state[restoreKey] = state[restoreKey] || {};
139
+ const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
140
+ if (elementSelector === "window") {
141
+ elementEntry.scrollX = window.scrollX || 0;
142
+ elementEntry.scrollY = window.scrollY || 0;
143
+ } else if (elementSelector) {
144
+ const element = document.querySelector(elementSelector);
145
+ if (element) {
146
+ elementEntry.scrollX = element.scrollLeft || 0;
147
+ elementEntry.scrollY = element.scrollTop || 0;
148
+ }
149
+ }
150
+ return state;
151
+ });
152
+ };
153
+ if (typeof document !== "undefined") {
154
+ document.addEventListener("scroll", throttle(onScroll, 100), true);
155
+ }
156
+ router.subscribe("onRendered", (event) => {
157
+ const cacheKey = getKey(event.toLocation);
158
+ if (!router.resetNextScroll) {
159
+ router.resetNextScroll = true;
160
+ return;
161
+ }
162
+ restoreScroll(
163
+ storageKey,
164
+ cacheKey,
165
+ router.options.scrollRestorationBehavior || void 0,
166
+ router.isScrollRestoring || void 0,
167
+ router.options.scrollToTopSelectors || void 0
168
+ );
169
+ if (router.isScrollRestoring) {
170
+ scrollRestorationCache.set((state) => {
171
+ state[cacheKey] = state[cacheKey] || {};
172
+ return state;
173
+ });
174
+ }
175
+ });
176
+ }
177
+ export {
178
+ defaultGetScrollRestorationKey,
179
+ getCssSelector,
180
+ restoreScroll,
181
+ scrollRestorationCache,
182
+ setupScrollRestoration,
183
+ storageKey
184
+ };
185
+ //# sourceMappingURL=scroll-restoration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scroll-restoration.js","sources":["../../src/scroll-restoration.ts"],"sourcesContent":["import { functionalUpdate } from './utils'\nimport type { AnyRouter } from './router'\nimport type { ParsedLocation } from './location'\nimport type { NonNullableUpdater } from './utils'\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'\nlet sessionsStorage = false\ntry {\n sessionsStorage =\n typeof window !== 'undefined' && typeof window.sessionStorage === 'object'\n} catch {}\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 | undefined,\n behavior: ScrollToOptions['behavior'] | undefined,\n shouldScrollRestoration: boolean | undefined,\n scrollToTopSelectors: Array<string> | undefined,\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 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 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 for every scrollToTop element\n ;[\n 'window',\n ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),\n ].forEach((selector) => {\n const element =\n selector === 'window' ? window : document.querySelector(selector)\n if (element) {\n element.scrollTo({\n top: 0,\n left: 0,\n behavior,\n })\n }\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 || undefined,\n router.isScrollRestoring || undefined,\n router.options.scrollToTopSelectors || undefined,\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"],"names":["storageKey"],"mappings":";AAoBO,MAAM,aAAa;AAC1B,IAAI,kBAAkB;AACtB,IAAI;AACF,oBACE,OAAO,WAAW,eAAe,OAAO,OAAO,mBAAmB;AACtE,QAAQ;AAAC;AACT,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,IAEtB,iBAAiB,SAAS,uBAAuB,KAAK,KACtD,uBAAuB,OACzB,OAAO,eAAe;AAAA,MACpB;AAAA,MACA,KAAK,UAAU,uBAAuB,KAAK;AAAA,IAC7C;AAAA,EAEJ;AACF,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AAM,WAAY,MAAM,UAAU,IAChC,MAAM,UAAU,KAAM,CAAC;AAEzB,YAAM,eAAgB,SAAS,eAAe,IAC5C,SAAS,eAAe,KAAM,CAAC;AAEjC,UAAI,oBAAoB,UAAU;AACnB,qBAAA,UAAU,OAAO,WAAW;AAC5B,qBAAA,UAAU,OAAO,WAAW;AAAA,iBAChC,iBAAiB;AACpB,cAAA,UAAU,SAAS,cAAc,eAAe;AACtD,YAAI,SAAS;AACE,uBAAA,UAAU,QAAQ,cAAc;AAChC,uBAAA,UAAU,QAAQ,aAAa;AAAA,QAAA;AAAA,MAC9C;AAGK,aAAA;AAAA,IAAA,CACR;AAAA,EACH;AAGI,MAAA,OAAO,aAAa,aAAa;AACnC,aAAS,iBAAiB,UAAU,SAAS,UAAU,GAAG,GAAG,IAAI;AAAA,EAAA;AAG5D,SAAA,UAAU,cAAc,CAAC,UAAU;AAGlC,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,6BAA6B;AAAA,MAC5C,OAAO,qBAAqB;AAAA,MAC5B,OAAO,QAAQ,wBAAwB;AAAA,IACzC;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;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/router-core",
3
- "version": "1.114.7",
3
+ "version": "1.114.15",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@tanstack/store": "^0.7.0",
48
- "@tanstack/history": "1.114.6"
48
+ "@tanstack/history": "1.114.12"
49
49
  },
50
50
  "scripts": {}
51
51
  }
package/src/index.ts CHANGED
@@ -362,3 +362,17 @@ export { redirect, isRedirect, isResolvedRedirect } from './redirect'
362
362
 
363
363
  export type { NotFoundError } from './not-found'
364
364
  export { isNotFound, notFound } from './not-found'
365
+
366
+ export {
367
+ defaultGetScrollRestorationKey,
368
+ restoreScroll,
369
+ storageKey,
370
+ getCssSelector,
371
+ scrollRestorationCache,
372
+ setupScrollRestoration,
373
+ } from './scroll-restoration'
374
+
375
+ export type {
376
+ ScrollRestorationOptions,
377
+ ScrollRestorationEntry,
378
+ } from './scroll-restoration'
@@ -0,0 +1,319 @@
1
+ import { functionalUpdate } from './utils'
2
+ import type { AnyRouter } from './router'
3
+ import type { ParsedLocation } from './location'
4
+ import type { NonNullableUpdater } from './utils'
5
+
6
+ export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
7
+
8
+ export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
9
+
10
+ export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
11
+
12
+ export type ScrollRestorationCache = {
13
+ state: ScrollRestorationByKey
14
+ set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void
15
+ }
16
+ export type ScrollRestorationOptions = {
17
+ getKey?: (location: ParsedLocation) => string
18
+ scrollBehavior?: ScrollToOptions['behavior']
19
+ }
20
+
21
+ export const storageKey = 'tsr-scroll-restoration-v1_3'
22
+ let sessionsStorage = false
23
+ try {
24
+ sessionsStorage =
25
+ typeof window !== 'undefined' && typeof window.sessionStorage === 'object'
26
+ } catch {}
27
+ const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
28
+ let timeout: any
29
+ return (...args: Array<any>) => {
30
+ if (!timeout) {
31
+ timeout = setTimeout(() => {
32
+ fn(...args)
33
+ timeout = null
34
+ }, wait)
35
+ }
36
+ }
37
+ }
38
+ export const scrollRestorationCache: ScrollRestorationCache = sessionsStorage
39
+ ? (() => {
40
+ const state: ScrollRestorationByKey =
41
+ JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}
42
+
43
+ return {
44
+ state,
45
+ // This setter is simply to make sure that we set the sessionStorage right
46
+ // after the state is updated. It doesn't necessarily need to be a functional
47
+ // update.
48
+ set: (updater) => (
49
+ (scrollRestorationCache.state =
50
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
51
+ functionalUpdate(updater, scrollRestorationCache.state) ||
52
+ scrollRestorationCache.state),
53
+ window.sessionStorage.setItem(
54
+ storageKey,
55
+ JSON.stringify(scrollRestorationCache.state),
56
+ )
57
+ ),
58
+ }
59
+ })()
60
+ : (undefined as any)
61
+ /**
62
+ * The default `getKey` function for `useScrollRestoration`.
63
+ * It returns the `key` from the location state or the `href` of the location.
64
+ *
65
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
66
+ */
67
+
68
+ export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
69
+ return location.state.key! || location.href
70
+ }
71
+
72
+ export function getCssSelector(el: any): string {
73
+ const path = []
74
+ let parent
75
+ while ((parent = el.parentNode)) {
76
+ path.unshift(
77
+ `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
78
+ )
79
+ el = parent
80
+ }
81
+ return `${path.join(' > ')}`.toLowerCase()
82
+ }
83
+
84
+ let ignoreScroll = false
85
+
86
+ // NOTE: This function must remain pure and not use any outside variables
87
+ // unless they are passed in as arguments. Why? Because we need to be able to
88
+ // toString() it into a script tag to execute as early as possible in the browser
89
+ // during SSR. Additionally, we also call it from within the router lifecycle
90
+ export function restoreScroll(
91
+ storageKey: string,
92
+ key: string | undefined,
93
+ behavior: ScrollToOptions['behavior'] | undefined,
94
+ shouldScrollRestoration: boolean | undefined,
95
+ scrollToTopSelectors: Array<string> | undefined,
96
+ ) {
97
+ let byKey: ScrollRestorationByKey
98
+
99
+ try {
100
+ byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
101
+ } catch (error: any) {
102
+ console.error(error)
103
+ return
104
+ }
105
+
106
+ const resolvedKey = key || window.history.state?.key
107
+ const elementEntries = byKey[resolvedKey]
108
+
109
+ //
110
+ ignoreScroll = true
111
+
112
+ //
113
+ ;(() => {
114
+ // If we have a cached entry for this location state,
115
+ // we always need to prefer that over the hash scroll.
116
+ if (shouldScrollRestoration && elementEntries) {
117
+ for (const elementSelector in elementEntries) {
118
+ const entry = elementEntries[elementSelector]!
119
+ if (elementSelector === 'window') {
120
+ window.scrollTo({
121
+ top: entry.scrollY,
122
+ left: entry.scrollX,
123
+ behavior,
124
+ })
125
+ } else if (elementSelector) {
126
+ const element = document.querySelector(elementSelector)
127
+ if (element) {
128
+ element.scrollLeft = entry.scrollX
129
+ element.scrollTop = entry.scrollY
130
+ }
131
+ }
132
+ }
133
+
134
+ return
135
+ }
136
+
137
+ // If we don't have a cached entry for the hash,
138
+ // Which means we've never seen this location before,
139
+ // we need to check if there is a hash in the URL.
140
+ // If there is, we need to scroll it's ID into view.
141
+ const hash = window.location.hash.split('#')[1]
142
+
143
+ if (hash) {
144
+ const hashScrollIntoViewOptions =
145
+ (window.history.state || {}).__hashScrollIntoViewOptions ?? true
146
+
147
+ if (hashScrollIntoViewOptions) {
148
+ const el = document.getElementById(hash)
149
+ if (el) {
150
+ el.scrollIntoView(hashScrollIntoViewOptions)
151
+ }
152
+ }
153
+
154
+ return
155
+ }
156
+
157
+ // If there is no cached entry for the hash and there is no hash in the URL,
158
+ // we need to scroll to the top of the page for every scrollToTop element
159
+ ;[
160
+ 'window',
161
+ ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
162
+ ].forEach((selector) => {
163
+ const element =
164
+ selector === 'window' ? window : document.querySelector(selector)
165
+ if (element) {
166
+ element.scrollTo({
167
+ top: 0,
168
+ left: 0,
169
+ behavior,
170
+ })
171
+ }
172
+ })
173
+ })()
174
+
175
+ //
176
+ ignoreScroll = false
177
+ }
178
+
179
+ export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
180
+ const shouldScrollRestoration =
181
+ force ?? router.options.scrollRestoration ?? false
182
+
183
+ if (shouldScrollRestoration) {
184
+ router.isScrollRestoring = true
185
+ }
186
+
187
+ if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
188
+ return
189
+ }
190
+
191
+ router.isScrollRestorationSetup = true
192
+
193
+ //
194
+ ignoreScroll = false
195
+
196
+ const getKey =
197
+ router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
198
+
199
+ window.history.scrollRestoration = 'manual'
200
+
201
+ // // Create a MutationObserver to monitor DOM changes
202
+ // const mutationObserver = new MutationObserver(() => {
203
+ // ;ignoreScroll = true
204
+ // requestAnimationFrame(() => {
205
+ // ;ignoreScroll = false
206
+
207
+ // // Attempt to restore scroll position on each dom
208
+ // // mutation until the user scrolls. We do this
209
+ // // because dynamic content may come in at different
210
+ // // ticks after the initial render and we want to
211
+ // // keep up with that content as much as possible.
212
+ // // As soon as the user scrolls, we no longer need
213
+ // // to attempt router.
214
+ // // console.log('mutation observer restoreScroll')
215
+ // restoreScroll(
216
+ // storageKey,
217
+ // getKey(router.state.location),
218
+ // router.options.scrollRestorationBehavior,
219
+ // )
220
+ // })
221
+ // })
222
+
223
+ // const observeDom = () => {
224
+ // // Observe changes to the entire document
225
+ // mutationObserver.observe(document, {
226
+ // childList: true, // Detect added or removed child nodes
227
+ // subtree: true, // Monitor all descendants
228
+ // characterData: true, // Detect text content changes
229
+ // })
230
+ // }
231
+
232
+ // const unobserveDom = () => {
233
+ // mutationObserver.disconnect()
234
+ // }
235
+
236
+ // observeDom()
237
+
238
+ const onScroll = (event: Event) => {
239
+ // unobserveDom()
240
+
241
+ if (ignoreScroll || !router.isScrollRestoring) {
242
+ return
243
+ }
244
+
245
+ let elementSelector = ''
246
+
247
+ if (event.target === document || event.target === window) {
248
+ elementSelector = 'window'
249
+ } else {
250
+ const attrId = (event.target as Element).getAttribute(
251
+ 'data-scroll-restoration-id',
252
+ )
253
+
254
+ if (attrId) {
255
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`
256
+ } else {
257
+ elementSelector = getCssSelector(event.target)
258
+ }
259
+ }
260
+
261
+ const restoreKey = getKey(router.state.location)
262
+
263
+ scrollRestorationCache.set((state) => {
264
+ const keyEntry = (state[restoreKey] =
265
+ state[restoreKey] || ({} as ScrollRestorationByElement))
266
+
267
+ const elementEntry = (keyEntry[elementSelector] =
268
+ keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
269
+
270
+ if (elementSelector === 'window') {
271
+ elementEntry.scrollX = window.scrollX || 0
272
+ elementEntry.scrollY = window.scrollY || 0
273
+ } else if (elementSelector) {
274
+ const element = document.querySelector(elementSelector)
275
+ if (element) {
276
+ elementEntry.scrollX = element.scrollLeft || 0
277
+ elementEntry.scrollY = element.scrollTop || 0
278
+ }
279
+ }
280
+
281
+ return state
282
+ })
283
+ }
284
+
285
+ // Throttle the scroll event to avoid excessive updates
286
+ if (typeof document !== 'undefined') {
287
+ document.addEventListener('scroll', throttle(onScroll, 100), true)
288
+ }
289
+
290
+ router.subscribe('onRendered', (event) => {
291
+ // unobserveDom()
292
+
293
+ const cacheKey = getKey(event.toLocation)
294
+
295
+ // If the user doesn't want to restore the scroll position,
296
+ // we don't need to do anything.
297
+ if (!router.resetNextScroll) {
298
+ router.resetNextScroll = true
299
+ return
300
+ }
301
+
302
+ restoreScroll(
303
+ storageKey,
304
+ cacheKey,
305
+ router.options.scrollRestorationBehavior || undefined,
306
+ router.isScrollRestoring || undefined,
307
+ router.options.scrollToTopSelectors || undefined,
308
+ )
309
+
310
+ if (router.isScrollRestoring) {
311
+ // Mark the location as having been seen
312
+ scrollRestorationCache.set((state) => {
313
+ state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
314
+
315
+ return state
316
+ })
317
+ }
318
+ })
319
+ }