@tanstack/router-core 1.114.12 → 1.114.16

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,6 @@ 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';
40
+ export type { ValidateFromPath, ValidateToPath, ValidateSearch, ValidateParams, InferFrom, InferTo, InferMaskTo, InferMaskFrom, ValidateNavigateOptions, ValidateNavigateOptionsArray, ValidateRedirectOptions, ValidateRedirectOptionsArray, ValidateId, InferStrict, InferShouldThrow, InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, } from './typePrimitives.cjs';
@@ -0,0 +1,184 @@
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 = utils.functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
29
+ storageKey,
30
+ JSON.stringify(scrollRestorationCache.state)
31
+ ))
32
+ };
33
+ })() : void 0;
34
+ const defaultGetScrollRestorationKey = (location) => {
35
+ return location.state.key || location.href;
36
+ };
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, scrollToTopSelectors) {
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
+ window.scrollTo({
67
+ top: entry.scrollY,
68
+ left: entry.scrollX,
69
+ behavior
70
+ });
71
+ } else if (elementSelector) {
72
+ const element = document.querySelector(elementSelector);
73
+ if (element) {
74
+ element.scrollLeft = entry.scrollX;
75
+ element.scrollTop = entry.scrollY;
76
+ }
77
+ }
78
+ }
79
+ return;
80
+ }
81
+ const hash = window.location.hash.split("#")[1];
82
+ if (hash) {
83
+ const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
84
+ if (hashScrollIntoViewOptions) {
85
+ const el = document.getElementById(hash);
86
+ if (el) {
87
+ el.scrollIntoView(hashScrollIntoViewOptions);
88
+ }
89
+ }
90
+ return;
91
+ }
92
+ [
93
+ "window",
94
+ ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
95
+ ].forEach((selector) => {
96
+ const element = selector === "window" ? window : document.querySelector(selector);
97
+ if (element) {
98
+ element.scrollTo({
99
+ top: 0,
100
+ left: 0,
101
+ behavior
102
+ });
103
+ }
104
+ });
105
+ })();
106
+ ignoreScroll = false;
107
+ }
108
+ function setupScrollRestoration(router, force) {
109
+ const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
110
+ if (shouldScrollRestoration) {
111
+ router.isScrollRestoring = true;
112
+ }
113
+ if (typeof document === "undefined" || router.isScrollRestorationSetup) {
114
+ return;
115
+ }
116
+ router.isScrollRestorationSetup = true;
117
+ ignoreScroll = false;
118
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
119
+ window.history.scrollRestoration = "manual";
120
+ const onScroll = (event) => {
121
+ if (ignoreScroll || !router.isScrollRestoring) {
122
+ return;
123
+ }
124
+ let elementSelector = "";
125
+ if (event.target === document || event.target === window) {
126
+ elementSelector = "window";
127
+ } else {
128
+ const attrId = event.target.getAttribute(
129
+ "data-scroll-restoration-id"
130
+ );
131
+ if (attrId) {
132
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
133
+ } else {
134
+ elementSelector = getCssSelector(event.target);
135
+ }
136
+ }
137
+ const restoreKey = getKey(router.state.location);
138
+ scrollRestorationCache.set((state) => {
139
+ const keyEntry = state[restoreKey] = state[restoreKey] || {};
140
+ const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
141
+ if (elementSelector === "window") {
142
+ elementEntry.scrollX = window.scrollX || 0;
143
+ elementEntry.scrollY = window.scrollY || 0;
144
+ } else if (elementSelector) {
145
+ const element = document.querySelector(elementSelector);
146
+ if (element) {
147
+ elementEntry.scrollX = element.scrollLeft || 0;
148
+ elementEntry.scrollY = element.scrollTop || 0;
149
+ }
150
+ }
151
+ return state;
152
+ });
153
+ };
154
+ if (typeof document !== "undefined") {
155
+ document.addEventListener("scroll", throttle(onScroll, 100), true);
156
+ }
157
+ router.subscribe("onRendered", (event) => {
158
+ const cacheKey = getKey(event.toLocation);
159
+ if (!router.resetNextScroll) {
160
+ router.resetNextScroll = true;
161
+ return;
162
+ }
163
+ restoreScroll(
164
+ storageKey,
165
+ cacheKey,
166
+ router.options.scrollRestorationBehavior || void 0,
167
+ router.isScrollRestoring || void 0,
168
+ router.options.scrollToTopSelectors || void 0
169
+ );
170
+ if (router.isScrollRestoring) {
171
+ scrollRestorationCache.set((state) => {
172
+ state[cacheKey] = state[cacheKey] || {};
173
+ return state;
174
+ });
175
+ }
176
+ });
177
+ }
178
+ exports.defaultGetScrollRestorationKey = defaultGetScrollRestorationKey;
179
+ exports.getCssSelector = getCssSelector;
180
+ exports.restoreScroll = restoreScroll;
181
+ exports.scrollRestorationCache = scrollRestorationCache;
182
+ exports.setupScrollRestoration = setupScrollRestoration;
183
+ exports.storageKey = storageKey;
184
+ //# 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 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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,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;;;;;;;"}
@@ -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;
@@ -0,0 +1,65 @@
1
+ import { FromPathOption, NavigateOptions, PathParamOptions, SearchParamOptions, ToPathOption } from './link.cjs';
2
+ import { Redirect } from './redirect.cjs';
3
+ import { RouteIds } from './routeInfo.cjs';
4
+ import { AnyRouter, RegisteredRouter } from './router.cjs';
5
+ import { UseParamsResult } from './useParams.cjs';
6
+ import { UseSearchResult } from './useSearch.cjs';
7
+ import { Constrain, ConstrainLiteral } from './utils.cjs';
8
+ export type ValidateFromPath<TRouter extends AnyRouter = RegisteredRouter, TFrom = string> = FromPathOption<TRouter, TFrom>;
9
+ export type ValidateToPath<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = ToPathOption<TRouter, TFrom, TTo>;
10
+ export type ValidateSearch<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = SearchParamOptions<TRouter, TFrom, TTo>;
11
+ export type ValidateParams<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = PathParamOptions<TRouter, TFrom, TTo>;
12
+ /**
13
+ * @internal
14
+ */
15
+ export type InferFrom<TOptions, TDefaultFrom extends string = string> = TOptions extends {
16
+ from: infer TFrom extends string;
17
+ } ? TFrom : TDefaultFrom;
18
+ /**
19
+ * @internal
20
+ */
21
+ export type InferTo<TOptions> = TOptions extends {
22
+ to: infer TTo extends string;
23
+ } ? TTo : undefined;
24
+ /**
25
+ * @internal
26
+ */
27
+ export type InferMaskTo<TOptions> = TOptions extends {
28
+ mask: {
29
+ to: infer TTo extends string;
30
+ };
31
+ } ? TTo : '';
32
+ export type InferMaskFrom<TOptions> = TOptions extends {
33
+ mask: {
34
+ from: infer TFrom extends string;
35
+ };
36
+ } ? TFrom : string;
37
+ export type ValidateNavigateOptions<TRouter extends AnyRouter = RegisteredRouter, TOptions = unknown, TDefaultFrom extends string = string> = Constrain<TOptions, NavigateOptions<TRouter, InferFrom<TOptions, TDefaultFrom>, InferTo<TOptions>, InferMaskFrom<TOptions>, InferMaskTo<TOptions>>>;
38
+ export type ValidateNavigateOptionsArray<TRouter extends AnyRouter = RegisteredRouter, TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>, TDefaultFrom extends string = string> = {
39
+ [K in keyof TOptions]: ValidateNavigateOptions<TRouter, TOptions[K], TDefaultFrom>;
40
+ };
41
+ export type ValidateRedirectOptions<TRouter extends AnyRouter = RegisteredRouter, TOptions = unknown, TDefaultFrom extends string = string> = Constrain<TOptions, Redirect<TRouter, InferFrom<TOptions, TDefaultFrom>, InferTo<TOptions>, InferMaskFrom<TOptions>, InferMaskTo<TOptions>>>;
42
+ export type ValidateRedirectOptionsArray<TRouter extends AnyRouter = RegisteredRouter, TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>, TDefaultFrom extends string = string> = {
43
+ [K in keyof TOptions]: ValidateRedirectOptions<TRouter, TOptions[K], TDefaultFrom>;
44
+ };
45
+ export type ValidateId<TRouter extends AnyRouter = RegisteredRouter, TId extends string = string> = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>;
46
+ /**
47
+ * @internal
48
+ */
49
+ export type InferStrict<TOptions> = TOptions extends {
50
+ strict: infer TStrict extends boolean;
51
+ } ? TStrict : true;
52
+ /**
53
+ * @internal
54
+ */
55
+ export type InferShouldThrow<TOptions> = TOptions extends {
56
+ shouldThrow: infer TShouldThrow extends boolean;
57
+ } ? TShouldThrow : true;
58
+ /**
59
+ * @internal
60
+ */
61
+ export type InferSelected<TOptions> = TOptions extends {
62
+ select: (...args: Array<any>) => infer TSelected;
63
+ } ? TSelected : unknown;
64
+ export type ValidateUseSearchResult<TOptions, TRouter extends AnyRouter = RegisteredRouter> = UseSearchResult<TRouter, InferFrom<TOptions>, InferStrict<TOptions>, InferSelected<TOptions>>;
65
+ export type ValidateUseParamsResult<TOptions, TRouter extends AnyRouter = RegisteredRouter> = Constrain<TOptions, UseParamsResult<TRouter, InferFrom<TOptions>, InferStrict<TOptions>, InferSelected<TOptions>>>;
@@ -35,3 +35,6 @@ 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';
40
+ export type { ValidateFromPath, ValidateToPath, ValidateSearch, ValidateParams, InferFrom, InferTo, InferMaskTo, InferMaskFrom, ValidateNavigateOptions, ValidateNavigateOptionsArray, ValidateRedirectOptions, ValidateRedirectOptionsArray, ValidateId, InferStrict, InferShouldThrow, InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, } from './typePrimitives.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,184 @@
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 = functionalUpdate(updater, scrollRestorationCache.state) || scrollRestorationCache.state, window.sessionStorage.setItem(
27
+ storageKey,
28
+ JSON.stringify(scrollRestorationCache.state)
29
+ ))
30
+ };
31
+ })() : void 0;
32
+ const defaultGetScrollRestorationKey = (location) => {
33
+ return location.state.key || location.href;
34
+ };
35
+ function getCssSelector(el) {
36
+ const path = [];
37
+ let parent;
38
+ while (parent = el.parentNode) {
39
+ path.unshift(
40
+ `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
41
+ );
42
+ el = parent;
43
+ }
44
+ return `${path.join(" > ")}`.toLowerCase();
45
+ }
46
+ let ignoreScroll = false;
47
+ function restoreScroll(storageKey2, key, behavior, shouldScrollRestoration, scrollToTopSelectors) {
48
+ var _a;
49
+ let byKey;
50
+ try {
51
+ byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
52
+ } catch (error) {
53
+ console.error(error);
54
+ return;
55
+ }
56
+ const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
57
+ const elementEntries = byKey[resolvedKey];
58
+ ignoreScroll = true;
59
+ (() => {
60
+ if (shouldScrollRestoration && elementEntries) {
61
+ for (const elementSelector in elementEntries) {
62
+ const entry = elementEntries[elementSelector];
63
+ if (elementSelector === "window") {
64
+ window.scrollTo({
65
+ top: entry.scrollY,
66
+ left: entry.scrollX,
67
+ behavior
68
+ });
69
+ } else if (elementSelector) {
70
+ const element = document.querySelector(elementSelector);
71
+ if (element) {
72
+ element.scrollLeft = entry.scrollX;
73
+ element.scrollTop = entry.scrollY;
74
+ }
75
+ }
76
+ }
77
+ return;
78
+ }
79
+ const hash = window.location.hash.split("#")[1];
80
+ if (hash) {
81
+ const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
82
+ if (hashScrollIntoViewOptions) {
83
+ const el = document.getElementById(hash);
84
+ if (el) {
85
+ el.scrollIntoView(hashScrollIntoViewOptions);
86
+ }
87
+ }
88
+ return;
89
+ }
90
+ [
91
+ "window",
92
+ ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
93
+ ].forEach((selector) => {
94
+ const element = selector === "window" ? window : document.querySelector(selector);
95
+ if (element) {
96
+ element.scrollTo({
97
+ top: 0,
98
+ left: 0,
99
+ behavior
100
+ });
101
+ }
102
+ });
103
+ })();
104
+ ignoreScroll = false;
105
+ }
106
+ function setupScrollRestoration(router, force) {
107
+ const shouldScrollRestoration = force ?? router.options.scrollRestoration ?? false;
108
+ if (shouldScrollRestoration) {
109
+ router.isScrollRestoring = true;
110
+ }
111
+ if (typeof document === "undefined" || router.isScrollRestorationSetup) {
112
+ return;
113
+ }
114
+ router.isScrollRestorationSetup = true;
115
+ ignoreScroll = false;
116
+ const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
117
+ window.history.scrollRestoration = "manual";
118
+ const onScroll = (event) => {
119
+ if (ignoreScroll || !router.isScrollRestoring) {
120
+ return;
121
+ }
122
+ let elementSelector = "";
123
+ if (event.target === document || event.target === window) {
124
+ elementSelector = "window";
125
+ } else {
126
+ const attrId = event.target.getAttribute(
127
+ "data-scroll-restoration-id"
128
+ );
129
+ if (attrId) {
130
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`;
131
+ } else {
132
+ elementSelector = getCssSelector(event.target);
133
+ }
134
+ }
135
+ const restoreKey = getKey(router.state.location);
136
+ scrollRestorationCache.set((state) => {
137
+ const keyEntry = state[restoreKey] = state[restoreKey] || {};
138
+ const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
139
+ if (elementSelector === "window") {
140
+ elementEntry.scrollX = window.scrollX || 0;
141
+ elementEntry.scrollY = window.scrollY || 0;
142
+ } else if (elementSelector) {
143
+ const element = document.querySelector(elementSelector);
144
+ if (element) {
145
+ elementEntry.scrollX = element.scrollLeft || 0;
146
+ elementEntry.scrollY = element.scrollTop || 0;
147
+ }
148
+ }
149
+ return state;
150
+ });
151
+ };
152
+ if (typeof document !== "undefined") {
153
+ document.addEventListener("scroll", throttle(onScroll, 100), true);
154
+ }
155
+ router.subscribe("onRendered", (event) => {
156
+ const cacheKey = getKey(event.toLocation);
157
+ if (!router.resetNextScroll) {
158
+ router.resetNextScroll = true;
159
+ return;
160
+ }
161
+ restoreScroll(
162
+ storageKey,
163
+ cacheKey,
164
+ router.options.scrollRestorationBehavior || void 0,
165
+ router.isScrollRestoring || void 0,
166
+ router.options.scrollToTopSelectors || void 0
167
+ );
168
+ if (router.isScrollRestoring) {
169
+ scrollRestorationCache.set((state) => {
170
+ state[cacheKey] = state[cacheKey] || {};
171
+ return state;
172
+ });
173
+ }
174
+ });
175
+ }
176
+ export {
177
+ defaultGetScrollRestorationKey,
178
+ getCssSelector,
179
+ restoreScroll,
180
+ scrollRestorationCache,
181
+ setupScrollRestoration,
182
+ storageKey
183
+ };
184
+ //# 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 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,MAA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H,CACD;AACH;"}
@@ -0,0 +1,65 @@
1
+ import { FromPathOption, NavigateOptions, PathParamOptions, SearchParamOptions, ToPathOption } from './link.js';
2
+ import { Redirect } from './redirect.js';
3
+ import { RouteIds } from './routeInfo.js';
4
+ import { AnyRouter, RegisteredRouter } from './router.js';
5
+ import { UseParamsResult } from './useParams.js';
6
+ import { UseSearchResult } from './useSearch.js';
7
+ import { Constrain, ConstrainLiteral } from './utils.js';
8
+ export type ValidateFromPath<TRouter extends AnyRouter = RegisteredRouter, TFrom = string> = FromPathOption<TRouter, TFrom>;
9
+ export type ValidateToPath<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = ToPathOption<TRouter, TFrom, TTo>;
10
+ export type ValidateSearch<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = SearchParamOptions<TRouter, TFrom, TTo>;
11
+ export type ValidateParams<TRouter extends AnyRouter = RegisteredRouter, TTo extends string | undefined = undefined, TFrom extends string = string> = PathParamOptions<TRouter, TFrom, TTo>;
12
+ /**
13
+ * @internal
14
+ */
15
+ export type InferFrom<TOptions, TDefaultFrom extends string = string> = TOptions extends {
16
+ from: infer TFrom extends string;
17
+ } ? TFrom : TDefaultFrom;
18
+ /**
19
+ * @internal
20
+ */
21
+ export type InferTo<TOptions> = TOptions extends {
22
+ to: infer TTo extends string;
23
+ } ? TTo : undefined;
24
+ /**
25
+ * @internal
26
+ */
27
+ export type InferMaskTo<TOptions> = TOptions extends {
28
+ mask: {
29
+ to: infer TTo extends string;
30
+ };
31
+ } ? TTo : '';
32
+ export type InferMaskFrom<TOptions> = TOptions extends {
33
+ mask: {
34
+ from: infer TFrom extends string;
35
+ };
36
+ } ? TFrom : string;
37
+ export type ValidateNavigateOptions<TRouter extends AnyRouter = RegisteredRouter, TOptions = unknown, TDefaultFrom extends string = string> = Constrain<TOptions, NavigateOptions<TRouter, InferFrom<TOptions, TDefaultFrom>, InferTo<TOptions>, InferMaskFrom<TOptions>, InferMaskTo<TOptions>>>;
38
+ export type ValidateNavigateOptionsArray<TRouter extends AnyRouter = RegisteredRouter, TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>, TDefaultFrom extends string = string> = {
39
+ [K in keyof TOptions]: ValidateNavigateOptions<TRouter, TOptions[K], TDefaultFrom>;
40
+ };
41
+ export type ValidateRedirectOptions<TRouter extends AnyRouter = RegisteredRouter, TOptions = unknown, TDefaultFrom extends string = string> = Constrain<TOptions, Redirect<TRouter, InferFrom<TOptions, TDefaultFrom>, InferTo<TOptions>, InferMaskFrom<TOptions>, InferMaskTo<TOptions>>>;
42
+ export type ValidateRedirectOptionsArray<TRouter extends AnyRouter = RegisteredRouter, TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>, TDefaultFrom extends string = string> = {
43
+ [K in keyof TOptions]: ValidateRedirectOptions<TRouter, TOptions[K], TDefaultFrom>;
44
+ };
45
+ export type ValidateId<TRouter extends AnyRouter = RegisteredRouter, TId extends string = string> = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>;
46
+ /**
47
+ * @internal
48
+ */
49
+ export type InferStrict<TOptions> = TOptions extends {
50
+ strict: infer TStrict extends boolean;
51
+ } ? TStrict : true;
52
+ /**
53
+ * @internal
54
+ */
55
+ export type InferShouldThrow<TOptions> = TOptions extends {
56
+ shouldThrow: infer TShouldThrow extends boolean;
57
+ } ? TShouldThrow : true;
58
+ /**
59
+ * @internal
60
+ */
61
+ export type InferSelected<TOptions> = TOptions extends {
62
+ select: (...args: Array<any>) => infer TSelected;
63
+ } ? TSelected : unknown;
64
+ export type ValidateUseSearchResult<TOptions, TRouter extends AnyRouter = RegisteredRouter> = UseSearchResult<TRouter, InferFrom<TOptions>, InferStrict<TOptions>, InferSelected<TOptions>>;
65
+ export type ValidateUseParamsResult<TOptions, TRouter extends AnyRouter = RegisteredRouter> = Constrain<TOptions, UseParamsResult<TRouter, InferFrom<TOptions>, InferStrict<TOptions>, InferSelected<TOptions>>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/router-core",
3
- "version": "1.114.12",
3
+ "version": "1.114.16",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -362,3 +362,38 @@ 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'
379
+
380
+ export type {
381
+ ValidateFromPath,
382
+ ValidateToPath,
383
+ ValidateSearch,
384
+ ValidateParams,
385
+ InferFrom,
386
+ InferTo,
387
+ InferMaskTo,
388
+ InferMaskFrom,
389
+ ValidateNavigateOptions,
390
+ ValidateNavigateOptionsArray,
391
+ ValidateRedirectOptions,
392
+ ValidateRedirectOptionsArray,
393
+ ValidateId,
394
+ InferStrict,
395
+ InferShouldThrow,
396
+ InferSelected,
397
+ ValidateUseSearchResult,
398
+ ValidateUseParamsResult,
399
+ } from './typePrimitives'
@@ -0,0 +1,318 @@
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
+ functionalUpdate(updater, scrollRestorationCache.state) ||
51
+ scrollRestorationCache.state),
52
+ window.sessionStorage.setItem(
53
+ storageKey,
54
+ JSON.stringify(scrollRestorationCache.state),
55
+ )
56
+ ),
57
+ }
58
+ })()
59
+ : (undefined as any)
60
+ /**
61
+ * The default `getKey` function for `useScrollRestoration`.
62
+ * It returns the `key` from the location state or the `href` of the location.
63
+ *
64
+ * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
65
+ */
66
+
67
+ export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
68
+ return location.state.key! || location.href
69
+ }
70
+
71
+ export function getCssSelector(el: any): string {
72
+ const path = []
73
+ let parent
74
+ while ((parent = el.parentNode)) {
75
+ path.unshift(
76
+ `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,
77
+ )
78
+ el = parent
79
+ }
80
+ return `${path.join(' > ')}`.toLowerCase()
81
+ }
82
+
83
+ let ignoreScroll = false
84
+
85
+ // NOTE: This function must remain pure and not use any outside variables
86
+ // unless they are passed in as arguments. Why? Because we need to be able to
87
+ // toString() it into a script tag to execute as early as possible in the browser
88
+ // during SSR. Additionally, we also call it from within the router lifecycle
89
+ export function restoreScroll(
90
+ storageKey: string,
91
+ key: string | undefined,
92
+ behavior: ScrollToOptions['behavior'] | undefined,
93
+ shouldScrollRestoration: boolean | undefined,
94
+ scrollToTopSelectors: Array<string> | undefined,
95
+ ) {
96
+ let byKey: ScrollRestorationByKey
97
+
98
+ try {
99
+ byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
100
+ } catch (error: any) {
101
+ console.error(error)
102
+ return
103
+ }
104
+
105
+ const resolvedKey = key || window.history.state?.key
106
+ const elementEntries = byKey[resolvedKey]
107
+
108
+ //
109
+ ignoreScroll = true
110
+
111
+ //
112
+ ;(() => {
113
+ // If we have a cached entry for this location state,
114
+ // we always need to prefer that over the hash scroll.
115
+ if (shouldScrollRestoration && elementEntries) {
116
+ for (const elementSelector in elementEntries) {
117
+ const entry = elementEntries[elementSelector]!
118
+ if (elementSelector === 'window') {
119
+ window.scrollTo({
120
+ top: entry.scrollY,
121
+ left: entry.scrollX,
122
+ behavior,
123
+ })
124
+ } else if (elementSelector) {
125
+ const element = document.querySelector(elementSelector)
126
+ if (element) {
127
+ element.scrollLeft = entry.scrollX
128
+ element.scrollTop = entry.scrollY
129
+ }
130
+ }
131
+ }
132
+
133
+ return
134
+ }
135
+
136
+ // If we don't have a cached entry for the hash,
137
+ // Which means we've never seen this location before,
138
+ // we need to check if there is a hash in the URL.
139
+ // If there is, we need to scroll it's ID into view.
140
+ const hash = window.location.hash.split('#')[1]
141
+
142
+ if (hash) {
143
+ const hashScrollIntoViewOptions =
144
+ (window.history.state || {}).__hashScrollIntoViewOptions ?? true
145
+
146
+ if (hashScrollIntoViewOptions) {
147
+ const el = document.getElementById(hash)
148
+ if (el) {
149
+ el.scrollIntoView(hashScrollIntoViewOptions)
150
+ }
151
+ }
152
+
153
+ return
154
+ }
155
+
156
+ // If there is no cached entry for the hash and there is no hash in the URL,
157
+ // we need to scroll to the top of the page for every scrollToTop element
158
+ ;[
159
+ 'window',
160
+ ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),
161
+ ].forEach((selector) => {
162
+ const element =
163
+ selector === 'window' ? window : document.querySelector(selector)
164
+ if (element) {
165
+ element.scrollTo({
166
+ top: 0,
167
+ left: 0,
168
+ behavior,
169
+ })
170
+ }
171
+ })
172
+ })()
173
+
174
+ //
175
+ ignoreScroll = false
176
+ }
177
+
178
+ export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
179
+ const shouldScrollRestoration =
180
+ force ?? router.options.scrollRestoration ?? false
181
+
182
+ if (shouldScrollRestoration) {
183
+ router.isScrollRestoring = true
184
+ }
185
+
186
+ if (typeof document === 'undefined' || router.isScrollRestorationSetup) {
187
+ return
188
+ }
189
+
190
+ router.isScrollRestorationSetup = true
191
+
192
+ //
193
+ ignoreScroll = false
194
+
195
+ const getKey =
196
+ router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
197
+
198
+ window.history.scrollRestoration = 'manual'
199
+
200
+ // // Create a MutationObserver to monitor DOM changes
201
+ // const mutationObserver = new MutationObserver(() => {
202
+ // ;ignoreScroll = true
203
+ // requestAnimationFrame(() => {
204
+ // ;ignoreScroll = false
205
+
206
+ // // Attempt to restore scroll position on each dom
207
+ // // mutation until the user scrolls. We do this
208
+ // // because dynamic content may come in at different
209
+ // // ticks after the initial render and we want to
210
+ // // keep up with that content as much as possible.
211
+ // // As soon as the user scrolls, we no longer need
212
+ // // to attempt router.
213
+ // // console.log('mutation observer restoreScroll')
214
+ // restoreScroll(
215
+ // storageKey,
216
+ // getKey(router.state.location),
217
+ // router.options.scrollRestorationBehavior,
218
+ // )
219
+ // })
220
+ // })
221
+
222
+ // const observeDom = () => {
223
+ // // Observe changes to the entire document
224
+ // mutationObserver.observe(document, {
225
+ // childList: true, // Detect added or removed child nodes
226
+ // subtree: true, // Monitor all descendants
227
+ // characterData: true, // Detect text content changes
228
+ // })
229
+ // }
230
+
231
+ // const unobserveDom = () => {
232
+ // mutationObserver.disconnect()
233
+ // }
234
+
235
+ // observeDom()
236
+
237
+ const onScroll = (event: Event) => {
238
+ // unobserveDom()
239
+
240
+ if (ignoreScroll || !router.isScrollRestoring) {
241
+ return
242
+ }
243
+
244
+ let elementSelector = ''
245
+
246
+ if (event.target === document || event.target === window) {
247
+ elementSelector = 'window'
248
+ } else {
249
+ const attrId = (event.target as Element).getAttribute(
250
+ 'data-scroll-restoration-id',
251
+ )
252
+
253
+ if (attrId) {
254
+ elementSelector = `[data-scroll-restoration-id="${attrId}"]`
255
+ } else {
256
+ elementSelector = getCssSelector(event.target)
257
+ }
258
+ }
259
+
260
+ const restoreKey = getKey(router.state.location)
261
+
262
+ scrollRestorationCache.set((state) => {
263
+ const keyEntry = (state[restoreKey] =
264
+ state[restoreKey] || ({} as ScrollRestorationByElement))
265
+
266
+ const elementEntry = (keyEntry[elementSelector] =
267
+ keyEntry[elementSelector] || ({} as ScrollRestorationEntry))
268
+
269
+ if (elementSelector === 'window') {
270
+ elementEntry.scrollX = window.scrollX || 0
271
+ elementEntry.scrollY = window.scrollY || 0
272
+ } else if (elementSelector) {
273
+ const element = document.querySelector(elementSelector)
274
+ if (element) {
275
+ elementEntry.scrollX = element.scrollLeft || 0
276
+ elementEntry.scrollY = element.scrollTop || 0
277
+ }
278
+ }
279
+
280
+ return state
281
+ })
282
+ }
283
+
284
+ // Throttle the scroll event to avoid excessive updates
285
+ if (typeof document !== 'undefined') {
286
+ document.addEventListener('scroll', throttle(onScroll, 100), true)
287
+ }
288
+
289
+ router.subscribe('onRendered', (event) => {
290
+ // unobserveDom()
291
+
292
+ const cacheKey = getKey(event.toLocation)
293
+
294
+ // If the user doesn't want to restore the scroll position,
295
+ // we don't need to do anything.
296
+ if (!router.resetNextScroll) {
297
+ router.resetNextScroll = true
298
+ return
299
+ }
300
+
301
+ restoreScroll(
302
+ storageKey,
303
+ cacheKey,
304
+ router.options.scrollRestorationBehavior || undefined,
305
+ router.isScrollRestoring || undefined,
306
+ router.options.scrollToTopSelectors || undefined,
307
+ )
308
+
309
+ if (router.isScrollRestoring) {
310
+ // Mark the location as having been seen
311
+ scrollRestorationCache.set((state) => {
312
+ state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)
313
+
314
+ return state
315
+ })
316
+ }
317
+ })
318
+ }
@@ -0,0 +1,181 @@
1
+ import type {
2
+ FromPathOption,
3
+ NavigateOptions,
4
+ PathParamOptions,
5
+ SearchParamOptions,
6
+ ToPathOption,
7
+ } from './link'
8
+ import type { Redirect } from './redirect'
9
+ import type { RouteIds } from './routeInfo'
10
+ import type { AnyRouter, RegisteredRouter } from './router'
11
+ import type { UseParamsResult } from './useParams'
12
+ import type { UseSearchResult } from './useSearch'
13
+ import type { Constrain, ConstrainLiteral } from './utils'
14
+
15
+ export type ValidateFromPath<
16
+ TRouter extends AnyRouter = RegisteredRouter,
17
+ TFrom = string,
18
+ > = FromPathOption<TRouter, TFrom>
19
+
20
+ export type ValidateToPath<
21
+ TRouter extends AnyRouter = RegisteredRouter,
22
+ TTo extends string | undefined = undefined,
23
+ TFrom extends string = string,
24
+ > = ToPathOption<TRouter, TFrom, TTo>
25
+
26
+ export type ValidateSearch<
27
+ TRouter extends AnyRouter = RegisteredRouter,
28
+ TTo extends string | undefined = undefined,
29
+ TFrom extends string = string,
30
+ > = SearchParamOptions<TRouter, TFrom, TTo>
31
+
32
+ export type ValidateParams<
33
+ TRouter extends AnyRouter = RegisteredRouter,
34
+ TTo extends string | undefined = undefined,
35
+ TFrom extends string = string,
36
+ > = PathParamOptions<TRouter, TFrom, TTo>
37
+
38
+ /**
39
+ * @internal
40
+ */
41
+ export type InferFrom<
42
+ TOptions,
43
+ TDefaultFrom extends string = string,
44
+ > = TOptions extends {
45
+ from: infer TFrom extends string
46
+ }
47
+ ? TFrom
48
+ : TDefaultFrom
49
+
50
+ /**
51
+ * @internal
52
+ */
53
+ export type InferTo<TOptions> = TOptions extends {
54
+ to: infer TTo extends string
55
+ }
56
+ ? TTo
57
+ : undefined
58
+
59
+ /**
60
+ * @internal
61
+ */
62
+ export type InferMaskTo<TOptions> = TOptions extends {
63
+ mask: { to: infer TTo extends string }
64
+ }
65
+ ? TTo
66
+ : ''
67
+
68
+ export type InferMaskFrom<TOptions> = TOptions extends {
69
+ mask: { from: infer TFrom extends string }
70
+ }
71
+ ? TFrom
72
+ : string
73
+
74
+ export type ValidateNavigateOptions<
75
+ TRouter extends AnyRouter = RegisteredRouter,
76
+ TOptions = unknown,
77
+ TDefaultFrom extends string = string,
78
+ > = Constrain<
79
+ TOptions,
80
+ NavigateOptions<
81
+ TRouter,
82
+ InferFrom<TOptions, TDefaultFrom>,
83
+ InferTo<TOptions>,
84
+ InferMaskFrom<TOptions>,
85
+ InferMaskTo<TOptions>
86
+ >
87
+ >
88
+
89
+ export type ValidateNavigateOptionsArray<
90
+ TRouter extends AnyRouter = RegisteredRouter,
91
+ TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
92
+ TDefaultFrom extends string = string,
93
+ > = {
94
+ [K in keyof TOptions]: ValidateNavigateOptions<
95
+ TRouter,
96
+ TOptions[K],
97
+ TDefaultFrom
98
+ >
99
+ }
100
+
101
+ export type ValidateRedirectOptions<
102
+ TRouter extends AnyRouter = RegisteredRouter,
103
+ TOptions = unknown,
104
+ TDefaultFrom extends string = string,
105
+ > = Constrain<
106
+ TOptions,
107
+ Redirect<
108
+ TRouter,
109
+ InferFrom<TOptions, TDefaultFrom>,
110
+ InferTo<TOptions>,
111
+ InferMaskFrom<TOptions>,
112
+ InferMaskTo<TOptions>
113
+ >
114
+ >
115
+
116
+ export type ValidateRedirectOptionsArray<
117
+ TRouter extends AnyRouter = RegisteredRouter,
118
+ TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
119
+ TDefaultFrom extends string = string,
120
+ > = {
121
+ [K in keyof TOptions]: ValidateRedirectOptions<
122
+ TRouter,
123
+ TOptions[K],
124
+ TDefaultFrom
125
+ >
126
+ }
127
+
128
+ export type ValidateId<
129
+ TRouter extends AnyRouter = RegisteredRouter,
130
+ TId extends string = string,
131
+ > = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>
132
+
133
+ /**
134
+ * @internal
135
+ */
136
+ export type InferStrict<TOptions> = TOptions extends {
137
+ strict: infer TStrict extends boolean
138
+ }
139
+ ? TStrict
140
+ : true
141
+
142
+ /**
143
+ * @internal
144
+ */
145
+ export type InferShouldThrow<TOptions> = TOptions extends {
146
+ shouldThrow: infer TShouldThrow extends boolean
147
+ }
148
+ ? TShouldThrow
149
+ : true
150
+
151
+ /**
152
+ * @internal
153
+ */
154
+ export type InferSelected<TOptions> = TOptions extends {
155
+ select: (...args: Array<any>) => infer TSelected
156
+ }
157
+ ? TSelected
158
+ : unknown
159
+
160
+ export type ValidateUseSearchResult<
161
+ TOptions,
162
+ TRouter extends AnyRouter = RegisteredRouter,
163
+ > = UseSearchResult<
164
+ TRouter,
165
+ InferFrom<TOptions>,
166
+ InferStrict<TOptions>,
167
+ InferSelected<TOptions>
168
+ >
169
+
170
+ export type ValidateUseParamsResult<
171
+ TOptions,
172
+ TRouter extends AnyRouter = RegisteredRouter,
173
+ > = Constrain<
174
+ TOptions,
175
+ UseParamsResult<
176
+ TRouter,
177
+ InferFrom<TOptions>,
178
+ InferStrict<TOptions>,
179
+ InferSelected<TOptions>
180
+ >
181
+ >