@tanstack/react-router 1.114.13 → 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.
@@ -1,28 +1 @@
1
- import { AnyRouter, NonNullableUpdater, ParsedLocation } from '@tanstack/router-core';
2
- export type ScrollRestorationEntry = {
3
- scrollX: number;
4
- scrollY: number;
5
- };
6
- export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
7
- export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
8
- export type ScrollRestorationCache = {
9
- state: ScrollRestorationByKey;
10
- set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
11
- };
12
- export type ScrollRestorationOptions = {
13
- getKey?: (location: ParsedLocation) => string;
14
- scrollBehavior?: ScrollToOptions['behavior'];
15
- };
16
- export declare const storageKey = "tsr-scroll-restoration-v1_3";
17
- export declare const scrollRestorationCache: ScrollRestorationCache;
18
- /**
19
- * The default `getKey` function for `useScrollRestoration`.
20
- * It returns the `key` from the location state or the `href` of the location.
21
- *
22
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
23
- */
24
- export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
25
- export declare function getCssSelector(el: any): string;
26
- export declare function restoreScroll(storageKey: string, key: string | undefined, behavior: ScrollToOptions['behavior'] | undefined, shouldScrollRestoration: boolean | undefined, scrollToTopSelectors: Array<string> | undefined): void;
27
- export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
28
1
  export declare function ScrollRestoration(): import("react/jsx-runtime").JSX.Element | null;
@@ -1,182 +1,7 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
- import { functionalUpdate } from "@tanstack/router-core";
2
+ import { defaultGetScrollRestorationKey, restoreScroll, storageKey } from "@tanstack/router-core";
3
3
  import { useRouter } from "./useRouter.js";
4
4
  import { ScriptOnce } from "./ScriptOnce.js";
5
- const storageKey = "tsr-scroll-restoration-v1_3";
6
- let sessionsStorage = false;
7
- try {
8
- sessionsStorage = typeof window !== "undefined" && typeof window.sessionStorage === "object";
9
- } catch {
10
- }
11
- const throttle = (fn, wait) => {
12
- let timeout;
13
- return (...args) => {
14
- if (!timeout) {
15
- timeout = setTimeout(() => {
16
- fn(...args);
17
- timeout = null;
18
- }, wait);
19
- }
20
- };
21
- };
22
- const scrollRestorationCache = sessionsStorage ? (() => {
23
- const state = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") || {};
24
- return {
25
- state,
26
- // This setter is simply to make sure that we set the sessionStorage right
27
- // after the state is updated. It doesn't necessarily need to be a functional
28
- // update.
29
- set: (updater) => (scrollRestorationCache.state = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
30
- functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
31
- storageKey,
32
- JSON.stringify(scrollRestorationCache.state)
33
- ))
34
- };
35
- })() : void 0;
36
- const defaultGetScrollRestorationKey = (location) => {
37
- return location.state.key || location.href;
38
- };
39
- function getCssSelector(el) {
40
- const path = [];
41
- let parent;
42
- while (parent = el.parentNode) {
43
- path.unshift(
44
- `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
45
- );
46
- el = parent;
47
- }
48
- return `${path.join(" > ")}`.toLowerCase();
49
- }
50
- let ignoreScroll = false;
51
- function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration, scrollToTopSelectors) {
52
- var _a;
53
- let byKey;
54
- try {
55
- byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
56
- } catch (error) {
57
- console.error(error);
58
- return;
59
- }
60
- const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
61
- const elementEntries = byKey[resolvedKey];
62
- ignoreScroll = true;
63
- (() => {
64
- if (shouldScrollRestoration && elementEntries) {
65
- for (const elementSelector in elementEntries) {
66
- const entry = elementEntries[elementSelector];
67
- if (elementSelector === "window") {
68
- window.scrollTo({
69
- top: entry.scrollY,
70
- left: entry.scrollX,
71
- behavior
72
- });
73
- } else if (elementSelector) {
74
- const element = document.querySelector(elementSelector);
75
- if (element) {
76
- element.scrollLeft = entry.scrollX;
77
- element.scrollTop = entry.scrollY;
78
- }
79
- }
80
- }
81
- return;
82
- }
83
- const hash = window.location.hash.split("#")[1];
84
- if (hash) {
85
- const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
86
- if (hashScrollIntoViewOptions) {
87
- const el = document.getElementById(hash);
88
- if (el) {
89
- el.scrollIntoView(hashScrollIntoViewOptions);
90
- }
91
- }
92
- return;
93
- }
94
- [
95
- "window",
96
- ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
97
- ].forEach((selector) => {
98
- const element = selector === "window" ? window : document.querySelector(selector);
99
- if (element) {
100
- element.scrollTo({
101
- top: 0,
102
- left: 0,
103
- behavior
104
- });
105
- }
106
- });
107
- })();
108
- ignoreScroll = false;
109
- }
110
- function setupScrollRestoration(router, force) {
111
- const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
112
- if (shouldScrollRestoration) {
113
- router.isScrollRestoring = true;
114
- }
115
- if (typeof document === "undefined" || router.isScrollRestorationSetup) {
116
- return;
117
- }
118
- router.isScrollRestorationSetup = true;
119
- ignoreScroll = false;
120
- const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
121
- window.history.scrollRestoration = "manual";
122
- const onScroll = (event) => {
123
- if (ignoreScroll || !router.isScrollRestoring) {
124
- return;
125
- }
126
- let elementSelector = "";
127
- if (event.target === document || event.target === window) {
128
- elementSelector = "window";
129
- } else {
130
- const attrId = event.target.getAttribute(
131
- "data-scroll-restoration-id"
132
- );
133
- if (attrId) {
134
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
135
- } else {
136
- elementSelector = getCssSelector(event.target);
137
- }
138
- }
139
- const restoreKey = getKey(router.state.location);
140
- scrollRestorationCache.set((state) => {
141
- const keyEntry = state[restoreKey] = state[restoreKey] || {};
142
- const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
143
- if (elementSelector === "window") {
144
- elementEntry.scrollX = window.scrollX || 0;
145
- elementEntry.scrollY = window.scrollY || 0;
146
- } else if (elementSelector) {
147
- const element = document.querySelector(elementSelector);
148
- if (element) {
149
- elementEntry.scrollX = element.scrollLeft || 0;
150
- elementEntry.scrollY = element.scrollTop || 0;
151
- }
152
- }
153
- return state;
154
- });
155
- };
156
- if (typeof document !== "undefined") {
157
- document.addEventListener("scroll", throttle(onScroll, 100), true);
158
- }
159
- router.subscribe("onRendered", (event) => {
160
- const cacheKey = getKey(event.toLocation);
161
- if (!router.resetNextScroll) {
162
- router.resetNextScroll = true;
163
- return;
164
- }
165
- restoreScroll(
166
- storageKey,
167
- cacheKey,
168
- router.options.scrollRestorationBehavior || void 0,
169
- router.isScrollRestoring || void 0,
170
- router.options.scrollToTopSelectors || void 0
171
- );
172
- if (router.isScrollRestoring) {
173
- scrollRestorationCache.set((state) => {
174
- state[cacheKey] = state[cacheKey] || {};
175
- return state;
176
- });
177
- }
178
- });
179
- }
180
5
  function ScrollRestoration() {
181
6
  const router = useRouter();
182
7
  const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
@@ -194,12 +19,6 @@ function ScrollRestoration() {
194
19
  );
195
20
  }
196
21
  export {
197
- ScrollRestoration,
198
- defaultGetScrollRestorationKey,
199
- getCssSelector,
200
- restoreScroll,
201
- scrollRestorationCache,
202
- setupScrollRestoration,
203
- storageKey
22
+ ScrollRestoration
204
23
  };
205
24
  //# sourceMappingURL=scroll-restoration.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"scroll-restoration.js","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import { functionalUpdate } from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\nimport type {\n AnyRouter,\n NonNullableUpdater,\n ParsedLocation,\n} 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'\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\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":["storageKey"],"mappings":";;;;AAwBO,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,SA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,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;AAEO,SAAS,oBAAoB;AAClC,QAAM,SAAS,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,SAAA;AAAA,IAAC;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
+ {"version":3,"file":"scroll-restoration.js","sources":["../../src/scroll-restoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n restoreScroll,\n storageKey,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport { ScriptOnce } from './ScriptOnce'\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":[],"mappings":";;;;AAQO,SAAS,oBAAoB;AAClC,QAAM,SAAS,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,SAAA;AAAA,IAAC;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;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-router",
3
- "version": "1.114.13",
3
+ "version": "1.114.15",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -54,7 +54,7 @@
54
54
  "tiny-invariant": "^1.3.3",
55
55
  "tiny-warning": "^1.0.3",
56
56
  "@tanstack/history": "1.114.12",
57
- "@tanstack/router-core": "1.114.12"
57
+ "@tanstack/router-core": "1.114.15"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@testing-library/jest-dom": "^6.6.3",
@@ -1,12 +1,15 @@
1
- import { useRouter } from './useRouter'
2
1
  import {
3
2
  defaultGetScrollRestorationKey,
4
3
  getCssSelector,
5
4
  scrollRestorationCache,
6
5
  setupScrollRestoration,
7
- } from './scroll-restoration'
8
- import type { ScrollRestorationOptions } from './scroll-restoration'
9
- import type { ParsedLocation } from '@tanstack/router-core'
6
+ } from '@tanstack/router-core'
7
+ import { useRouter } from './useRouter'
8
+ import type {
9
+ ParsedLocation,
10
+ ScrollRestorationEntry,
11
+ ScrollRestorationOptions,
12
+ } from '@tanstack/router-core'
10
13
 
11
14
  function useScrollRestoration() {
12
15
  const router = useRouter()
@@ -32,16 +35,16 @@ export function useElementScrollRestoration(
32
35
  options: (
33
36
  | {
34
37
  id: string
35
- getElement?: () => Element | undefined | null
38
+ getElement?: () => Window | Element | undefined | null
36
39
  }
37
40
  | {
38
41
  id?: string
39
- getElement: () => Element | undefined | null
42
+ getElement: () => Window | Element | undefined | null
40
43
  }
41
44
  ) & {
42
45
  getKey?: (location: ParsedLocation) => string
43
46
  },
44
- ) {
47
+ ): ScrollRestorationEntry | undefined {
45
48
  useScrollRestoration()
46
49
 
47
50
  const router = useRouter()
@@ -56,7 +59,8 @@ export function useElementScrollRestoration(
56
59
  if (!element) {
57
60
  return
58
61
  }
59
- elementSelector = getCssSelector(element)
62
+ elementSelector =
63
+ element instanceof Window ? 'window' : getCssSelector(element)
60
64
  }
61
65
 
62
66
  const restoreKey = getKey(router.latestLocation)
package/src/router.ts CHANGED
@@ -25,12 +25,12 @@ import {
25
25
  replaceEqualDeep,
26
26
  resolvePath,
27
27
  rootRouteId,
28
+ setupScrollRestoration,
28
29
  trimPath,
29
30
  trimPathLeft,
30
31
  trimPathRight,
31
32
  } from '@tanstack/router-core'
32
33
 
33
- import { setupScrollRestoration } from './scroll-restoration'
34
34
  import type * as React from 'react'
35
35
  import type { HistoryLocation, RouterHistory } from '@tanstack/history'
36
36
 
@@ -1,326 +1,10 @@
1
- import { functionalUpdate } from '@tanstack/router-core'
1
+ import {
2
+ defaultGetScrollRestorationKey,
3
+ restoreScroll,
4
+ storageKey,
5
+ } from '@tanstack/router-core'
2
6
  import { useRouter } from './useRouter'
3
7
  import { ScriptOnce } from './ScriptOnce'
4
- import type {
5
- AnyRouter,
6
- NonNullableUpdater,
7
- ParsedLocation,
8
- } from '@tanstack/router-core'
9
-
10
- export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
11
-
12
- export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
13
-
14
- export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
15
-
16
- export type ScrollRestorationCache = {
17
- state: ScrollRestorationByKey
18
- set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void
19
- }
20
- export type ScrollRestorationOptions = {
21
- getKey?: (location: ParsedLocation) => string
22
- scrollBehavior?: ScrollToOptions['behavior']
23
- }
24
-
25
- export const storageKey = 'tsr-scroll-restoration-v1_3'
26
- let sessionsStorage = false
27
- try {
28
- sessionsStorage =
29
- typeof window !== 'undefined' && typeof window.sessionStorage === 'object'
30
- } catch {}
31
- const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
32
- let timeout: any
33
- return (...args: Array<any>) => {
34
- if (!timeout) {
35
- timeout = setTimeout(() => {
36
- fn(...args)
37
- timeout = null
38
- }, wait)
39
- }
40
- }
41
- }
42
- export const scrollRestorationCache: ScrollRestorationCache = sessionsStorage
43
- ? (() => {
44
- const state: ScrollRestorationByKey =
45
- JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {}
46
-
47
- return {
48
- state,
49
- // This setter is simply to make sure that we set the sessionStorage right
50
- // after the state is updated. It doesn't necessarily need to be a functional
51
- // update.
52
- set: (updater) => (
53
- (scrollRestorationCache.state =
54
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
55
- functionalUpdate(updater, scrollRestorationCache.state) ||
56
- scrollRestorationCache.state),
57
- window.sessionStorage.setItem(
58
- storageKey,
59
- JSON.stringify(scrollRestorationCache.state),
60
- )
61
- ),
62
- }
63
- })()
64
- : (undefined as any)
65
- /**
66
- * The default `getKey` function for `useScrollRestoration`.
67
- * It returns the `key` from the location state or the `href` of the location.
68
- *
69
- * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
70
- */
71
-
72
- export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
73
- return location.state.key! || location.href
74
- }
75
-
76
- export function getCssSelector(el: any): string {
77
- const path = []
78
- let parent
79
- while ((parent = el.parentNode)) {
80
- path.unshift(
81
- `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
82
- )
83
- el = parent
84
- }
85
- return `${path.join(' > ')}`.toLowerCase()
86
- }
87
-
88
- let ignoreScroll = false
89
-
90
- // NOTE: This function must remain pure and not use any outside variables
91
- // unless they are passed in as arguments. Why? Because we need to be able to
92
- // toString() it into a script tag to execute as early as possible in the browser
93
- // during SSR. Additionally, we also call it from within the router lifecycle
94
- export function restoreScroll(
95
- storageKey: string,
96
- key: string | undefined,
97
- behavior: ScrollToOptions['behavior'] | undefined,
98
- shouldScrollRestoration: boolean | undefined,
99
- scrollToTopSelectors: Array<string> | undefined,
100
- ) {
101
- let byKey: ScrollRestorationByKey
102
-
103
- try {
104
- byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
105
- } catch (error: any) {
106
- console.error(error)
107
- return
108
- }
109
-
110
- const resolvedKey = key || window.history.state?.key
111
- const elementEntries = byKey[resolvedKey]
112
-
113
- //
114
- ignoreScroll = true
115
-
116
- //
117
- ;(() => {
118
- // If we have a cached entry for this location state,
119
- // we always need to prefer that over the hash scroll.
120
- if (shouldScrollRestoration && elementEntries) {
121
- for (const elementSelector in elementEntries) {
122
- const entry = elementEntries[elementSelector]!
123
- if (elementSelector === 'window') {
124
- window.scrollTo({
125
- top: entry.scrollY,
126
- left: entry.scrollX,
127
- behavior,
128
- })
129
- } else if (elementSelector) {
130
- const element = document.querySelector(elementSelector)
131
- if (element) {
132
- element.scrollLeft = entry.scrollX
133
- element.scrollTop = entry.scrollY
134
- }
135
- }
136
- }
137
-
138
- return
139
- }
140
-
141
- // If we don't have a cached entry for the hash,
142
- // Which means we've never seen this location before,
143
- // we need to check if there is a hash in the URL.
144
- // If there is, we need to scroll it's ID into view.
145
- const hash = window.location.hash.split('#')[1]
146
-
147
- if (hash) {
148
- const hashScrollIntoViewOptions =
149
- (window.history.state || {}).__hashScrollIntoViewOptions ?? true
150
-
151
- if (hashScrollIntoViewOptions) {
152
- const el = document.getElementById(hash)
153
- if (el) {
154
- el.scrollIntoView(hashScrollIntoViewOptions)
155
- }
156
- }
157
-
158
- return
159
- }
160
-
161
- // If there is no cached entry for the hash and there is no hash in the URL,
162
- // we need to scroll to the top of the page for every scrollToTop element
163
- ;[
164
- 'window',
165
- ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
166
- ].forEach((selector) => {
167
- const element =
168
- selector === 'window' ? window : document.querySelector(selector)
169
- if (element) {
170
- element.scrollTo({
171
- top: 0,
172
- left: 0,
173
- behavior,
174
- })
175
- }
176
- })
177
- })()
178
-
179
- //
180
- ignoreScroll = false
181
- }
182
-
183
- export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
184
- const shouldScrollRestoration =
185
- force ?? router.options.scrollRestoration ?? false
186
-
187
- if (shouldScrollRestoration) {
188
- router.isScrollRestoring = true
189
- }
190
-
191
- if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
192
- return
193
- }
194
-
195
- router.isScrollRestorationSetup = true
196
-
197
- //
198
- ignoreScroll = false
199
-
200
- const getKey =
201
- router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
202
-
203
- window.history.scrollRestoration = 'manual'
204
-
205
- // // Create a MutationObserver to monitor DOM changes
206
- // const mutationObserver = new MutationObserver(() => {
207
- // ;ignoreScroll = true
208
- // requestAnimationFrame(() => {
209
- // ;ignoreScroll = false
210
-
211
- // // Attempt to restore scroll position on each dom
212
- // // mutation until the user scrolls. We do this
213
- // // because dynamic content may come in at different
214
- // // ticks after the initial render and we want to
215
- // // keep up with that content as much as possible.
216
- // // As soon as the user scrolls, we no longer need
217
- // // to attempt router.
218
- // // console.log('mutation observer restoreScroll')
219
- // restoreScroll(
220
- // storageKey,
221
- // getKey(router.state.location),
222
- // router.options.scrollRestorationBehavior,
223
- // )
224
- // })
225
- // })
226
-
227
- // const observeDom = () => {
228
- // // Observe changes to the entire document
229
- // mutationObserver.observe(document, {
230
- // childList: true, // Detect added or removed child nodes
231
- // subtree: true, // Monitor all descendants
232
- // characterData: true, // Detect text content changes
233
- // })
234
- // }
235
-
236
- // const unobserveDom = () => {
237
- // mutationObserver.disconnect()
238
- // }
239
-
240
- // observeDom()
241
-
242
- const onScroll = (event: Event) => {
243
- // unobserveDom()
244
-
245
- if (ignoreScroll || !router.isScrollRestoring) {
246
- return
247
- }
248
-
249
- let elementSelector = ''
250
-
251
- if (event.target === document || event.target === window) {
252
- elementSelector = 'window'
253
- } else {
254
- const attrId = (event.target as Element).getAttribute(
255
- 'data-scroll-restoration-id',
256
- )
257
-
258
- if (attrId) {
259
- elementSelector = `[data-scroll-restoration-id="${attrId}"]`
260
- } else {
261
- elementSelector = getCssSelector(event.target)
262
- }
263
- }
264
-
265
- const restoreKey = getKey(router.state.location)
266
-
267
- scrollRestorationCache.set((state) => {
268
- const keyEntry = (state[restoreKey] =
269
- state[restoreKey] || ({} as ScrollRestorationByElement))
270
-
271
- const elementEntry = (keyEntry[elementSelector] =
272
- keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
273
-
274
- if (elementSelector === 'window') {
275
- elementEntry.scrollX = window.scrollX || 0
276
- elementEntry.scrollY = window.scrollY || 0
277
- } else if (elementSelector) {
278
- const element = document.querySelector(elementSelector)
279
- if (element) {
280
- elementEntry.scrollX = element.scrollLeft || 0
281
- elementEntry.scrollY = element.scrollTop || 0
282
- }
283
- }
284
-
285
- return state
286
- })
287
- }
288
-
289
- // Throttle the scroll event to avoid excessive updates
290
- if (typeof document !== 'undefined') {
291
- document.addEventListener('scroll', throttle(onScroll, 100), true)
292
- }
293
-
294
- router.subscribe('onRendered', (event) => {
295
- // unobserveDom()
296
-
297
- const cacheKey = getKey(event.toLocation)
298
-
299
- // If the user doesn't want to restore the scroll position,
300
- // we don't need to do anything.
301
- if (!router.resetNextScroll) {
302
- router.resetNextScroll = true
303
- return
304
- }
305
-
306
- restoreScroll(
307
- storageKey,
308
- cacheKey,
309
- router.options.scrollRestorationBehavior || undefined,
310
- router.isScrollRestoring || undefined,
311
- router.options.scrollToTopSelectors || undefined,
312
- )
313
-
314
- if (router.isScrollRestoring) {
315
- // Mark the location as having been seen
316
- scrollRestorationCache.set((state) => {
317
- state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
318
-
319
- return state
320
- })
321
- }
322
- })
323
- }
324
8
 
325
9
  export function ScrollRestoration() {
326
10
  const router = useRouter()