@tanstack/router-core 1.133.27 → 1.133.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/path.cjs +1 -1
- package/dist/cjs/path.cjs.map +1 -1
- package/dist/cjs/path.d.cts +22 -0
- package/dist/cjs/qss.cjs.map +1 -1
- package/dist/cjs/rewrite.cjs.map +1 -1
- package/dist/cjs/rewrite.d.cts +4 -0
- package/dist/cjs/router.cjs +12 -10
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/cjs/scroll-restoration.d.cts +14 -0
- package/dist/cjs/searchParams.cjs.map +1 -1
- package/dist/cjs/searchParams.d.cts +2 -0
- package/dist/cjs/utils.cjs +44 -0
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +24 -0
- package/dist/esm/path.d.ts +22 -0
- package/dist/esm/path.js +2 -2
- package/dist/esm/path.js.map +1 -1
- package/dist/esm/qss.js.map +1 -1
- package/dist/esm/rewrite.d.ts +4 -0
- package/dist/esm/rewrite.js.map +1 -1
- package/dist/esm/router.js +13 -11
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/scroll-restoration.d.ts +14 -0
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/dist/esm/searchParams.d.ts +2 -0
- package/dist/esm/searchParams.js.map +1 -1
- package/dist/esm/utils.d.ts +24 -0
- package/dist/esm/utils.js +44 -0
- package/dist/esm/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/path.ts +24 -7
- package/src/qss.ts +1 -0
- package/src/rewrite.ts +4 -0
- package/src/router.ts +13 -10
- package/src/scroll-restoration.ts +14 -0
- package/src/searchParams.ts +2 -0
- package/src/utils.ts +93 -0
|
@@ -18,9 +18,11 @@ export type ScrollRestorationOptions = {
|
|
|
18
18
|
};
|
|
19
19
|
/** SessionStorage key used to persist scroll restoration state. */
|
|
20
20
|
/** SessionStorage key used to store scroll positions across navigations. */
|
|
21
|
+
/** SessionStorage key used to store scroll positions across navigations. */
|
|
21
22
|
export declare const storageKey = "tsr-scroll-restoration-v1_3";
|
|
22
23
|
/** In-memory handle to the persisted scroll restoration cache. */
|
|
23
24
|
/** In-memory handle to the persisted scroll restoration cache. */
|
|
25
|
+
/** In-memory handle to the persisted scroll restoration cache. */
|
|
24
26
|
export declare const scrollRestorationCache: ScrollRestorationCache | null;
|
|
25
27
|
/**
|
|
26
28
|
* The default `getKey` function for `useScrollRestoration`.
|
|
@@ -34,9 +36,15 @@ export declare const scrollRestorationCache: ScrollRestorationCache | null;
|
|
|
34
36
|
/**
|
|
35
37
|
* Default scroll restoration cache key: location state key or full href.
|
|
36
38
|
*/
|
|
39
|
+
/**
|
|
40
|
+
* Default scroll restoration cache key: location state key or full href.
|
|
41
|
+
*/
|
|
37
42
|
export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
|
|
38
43
|
/** Best-effort nth-child CSS selector for a given element. */
|
|
39
44
|
export declare function getCssSelector(el: any): string;
|
|
45
|
+
/**
|
|
46
|
+
* Restore scroll positions for window/elements based on cached entries.
|
|
47
|
+
*/
|
|
40
48
|
/**
|
|
41
49
|
* Restore scroll positions for window/elements based on cached entries.
|
|
42
50
|
*/
|
|
@@ -49,6 +57,7 @@ export declare function restoreScroll({ storageKey, key, behavior, shouldScrollR
|
|
|
49
57
|
location?: HistoryLocation;
|
|
50
58
|
}): void;
|
|
51
59
|
/** Setup global listeners and hooks to support scroll restoration. */
|
|
60
|
+
/** Setup global listeners and hooks to support scroll restoration. */
|
|
52
61
|
export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
|
|
53
62
|
/**
|
|
54
63
|
* @private
|
|
@@ -66,4 +75,9 @@ export declare function setupScrollRestoration(router: AnyRouter, force?: boolea
|
|
|
66
75
|
* Provides hash scrolling for programmatic navigation when default browser handling is prevented.
|
|
67
76
|
* @param router The router instance containing current location and state
|
|
68
77
|
*/
|
|
78
|
+
/**
|
|
79
|
+
* @private
|
|
80
|
+
* Handles hash-based scrolling after navigation completes.
|
|
81
|
+
* To be used in framework-specific Transitioners.
|
|
82
|
+
*/
|
|
69
83
|
export declare function handleHashScroll(router: AnyRouter): void;
|
|
@@ -1 +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'\nimport type { HistoryLocation } from '@tanstack/history'\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\nfunction getSafeSessionStorage() {\n try {\n if (\n typeof window !== 'undefined' &&\n typeof window.sessionStorage === 'object'\n ) {\n return window.sessionStorage\n }\n } catch {\n // silent\n }\n return undefined\n}\n\n/** SessionStorage key used to persist scroll restoration state. */\n/** SessionStorage key used to store scroll positions across navigations. */\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\n\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}\n\nfunction createScrollRestorationCache(): ScrollRestorationCache | null {\n const safeSessionStorage = getSafeSessionStorage()\n if (!safeSessionStorage) {\n return null\n }\n\n const persistedState = safeSessionStorage.getItem(storageKey)\n let state: ScrollRestorationByKey = persistedState\n ? JSON.parse(persistedState)\n : {}\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 (state = functionalUpdate(updater, state) || state),\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n ),\n }\n}\n\n/** In-memory handle to the persisted scroll restoration cache. */\n/** In-memory handle to the persisted scroll restoration cache. */\nexport const scrollRestorationCache = createScrollRestorationCache()\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\n/**\n * Default scroll restoration cache key: location state key or full href.\n */\n/**\n * Default scroll restoration cache key: location state key or full href.\n */\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.__TSR_key! || location.href\n}\n\n/** Best-effort nth-child CSS selector for a given element. */\nexport function getCssSelector(el: any): string {\n const path = []\n let parent: HTMLElement\n while ((parent = el.parentNode)) {\n path.push(\n `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.reverse().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\n/**\n * Restore scroll positions for window/elements based on cached entries.\n */\nexport function restoreScroll({\n storageKey,\n key,\n behavior,\n shouldScrollRestoration,\n scrollToTopSelectors,\n location,\n}: {\n storageKey: string\n key?: string\n behavior?: ScrollToOptions['behavior']\n shouldScrollRestoration?: boolean\n scrollToTopSelectors?: Array<string | (() => Element | null | undefined)>\n location?: HistoryLocation\n}) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.__TSR_key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n scroll: {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (\n shouldScrollRestoration &&\n elementEntries &&\n Object.keys(elementEntries).length > 0\n ) {\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 break scroll\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 = (location ?? window.location).hash.split('#', 2)[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 break scroll\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 const scrollOptions = { top: 0, left: 0, behavior }\n window.scrollTo(scrollOptions)\n if (scrollToTopSelectors) {\n for (const selector of scrollToTopSelectors) {\n if (selector === 'window') continue\n const element =\n typeof selector === 'function'\n ? selector()\n : document.querySelector(selector)\n if (element) element.scrollTo(scrollOptions)\n }\n }\n }\n\n //\n ignoreScroll = false\n}\n\n/** Setup global listeners and hooks to support scroll restoration. */\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n if (!scrollRestorationCache && !router.isServer) {\n return\n }\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (\n router.isServer ||\n router.isScrollRestorationSetup ||\n !scrollRestorationCache\n ) {\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] ||= {} as ScrollRestorationByElement)\n\n const elementEntry = (keyEntry[elementSelector] ||=\n {} 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 if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return\n }\n }\n\n restoreScroll({\n storageKey,\n key: cacheKey,\n behavior: router.options.scrollRestorationBehavior,\n shouldScrollRestoration: router.isScrollRestoring,\n scrollToTopSelectors: router.options.scrollToTopSelectors,\n location: router.history.location,\n })\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] ||= {} as ScrollRestorationByElement\n\n return state\n })\n }\n })\n}\n\n/**\n * @private\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\n/**\n * @private\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\nexport function handleHashScroll(router: AnyRouter) {\n if (typeof document !== 'undefined' && (document as any).querySelector) {\n const hashScrollIntoViewOptions =\n router.state.location.state.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions && router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n }\n}\n"],"names":["storageKey"],"mappings":";AAqBA,SAAS,wBAAwB;AAC/B,MAAI;AACF,QACE,OAAO,WAAW,eAClB,OAAO,OAAO,mBAAmB,UACjC;AACA,aAAO,OAAO;AAAA,IAChB;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAIO,MAAM,aAAa;AAE1B,MAAM,WAAW,CAAC,I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c,CAAC,UAAU;AAGxC,UAAM,WAAW,OAAO,MAAM,UAAU;AAIxC,QAAI,CAAC,OAAO,iBAAiB;AAC3B,aAAO,kBAAkB;AACzB;AAAA,IACF;AACA,QAAI,OAAO,OAAO,QAAQ,sBAAsB,YAAY;AAC1D,YAAM,gBAAgB,OAAO,QAAQ,kBAAkB;AAAA,QACrD,UAAU,OAAO;AAAA,MAAA,CAClB;AACD,UAAI,CAAC,eAAe;AAClB;AAAA,MACF;AAAA,IACF;AAEA,kBAAc;AAAA,MACZ;AAAA,MACA,KAAK;AAAA,MACL,UAAU,OAAO,QAAQ;AAAA,MACzB,yBAAyB,OAAO;AAAA,MAChC,sBAAsB,OAAO,QAAQ;AAAA,MACrC,UAAU,OAAO,QAAQ;AAAA,IAAA,CAC1B;AAED,QAAI,OAAO,mBAAmB;AAE5B,6BAAuB,IAAI,CAAC,UAAU;AACpC,cAAM,QAAQ,MAAM,CAAA;AAEpB,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAkBO,SAAS,iBAAiB,QAAmB;AAClD,MAAI,OAAO,aAAa,eAAgB,SAAiB,eAAe;AACtE,UAAM,4BACJ,OAAO,MAAM,SAAS,MAAM,+BAA+B;AAE7D,QAAI,6BAA6B,OAAO,MAAM,SAAS,SAAS,IAAI;AAClE,YAAM,KAAK,SAAS,eAAe,OAAO,MAAM,SAAS,IAAI;AAC7D,UAAI,IAAI;AACN,WAAG,eAAe,yBAAyB;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;"}
|
|
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'\nimport type { HistoryLocation } from '@tanstack/history'\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\nfunction getSafeSessionStorage() {\n try {\n if (\n typeof window !== 'undefined' &&\n typeof window.sessionStorage === 'object'\n ) {\n return window.sessionStorage\n }\n } catch {\n // silent\n }\n return undefined\n}\n\n/** SessionStorage key used to persist scroll restoration state. */\n/** SessionStorage key used to store scroll positions across navigations. */\n/** SessionStorage key used to store scroll positions across navigations. */\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\n\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}\n\nfunction createScrollRestorationCache(): ScrollRestorationCache | null {\n const safeSessionStorage = getSafeSessionStorage()\n if (!safeSessionStorage) {\n return null\n }\n\n const persistedState = safeSessionStorage.getItem(storageKey)\n let state: ScrollRestorationByKey = persistedState\n ? JSON.parse(persistedState)\n : {}\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 (state = functionalUpdate(updater, state) || state),\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n ),\n }\n}\n\n/** In-memory handle to the persisted scroll restoration cache. */\n/** In-memory handle to the persisted scroll restoration cache. */\n/** In-memory handle to the persisted scroll restoration cache. */\nexport const scrollRestorationCache = createScrollRestorationCache()\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\n/**\n * Default scroll restoration cache key: location state key or full href.\n */\n/**\n * Default scroll restoration cache key: location state key or full href.\n */\n/**\n * Default scroll restoration cache key: location state key or full href.\n */\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.__TSR_key! || location.href\n}\n\n/** Best-effort nth-child CSS selector for a given element. */\nexport function getCssSelector(el: any): string {\n const path = []\n let parent: HTMLElement\n while ((parent = el.parentNode)) {\n path.push(\n `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.reverse().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\n/**\n * Restore scroll positions for window/elements based on cached entries.\n */\n/**\n * Restore scroll positions for window/elements based on cached entries.\n */\nexport function restoreScroll({\n storageKey,\n key,\n behavior,\n shouldScrollRestoration,\n scrollToTopSelectors,\n location,\n}: {\n storageKey: string\n key?: string\n behavior?: ScrollToOptions['behavior']\n shouldScrollRestoration?: boolean\n scrollToTopSelectors?: Array<string | (() => Element | null | undefined)>\n location?: HistoryLocation\n}) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.__TSR_key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n scroll: {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (\n shouldScrollRestoration &&\n elementEntries &&\n Object.keys(elementEntries).length > 0\n ) {\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 break scroll\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 = (location ?? window.location).hash.split('#', 2)[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 break scroll\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 const scrollOptions = { top: 0, left: 0, behavior }\n window.scrollTo(scrollOptions)\n if (scrollToTopSelectors) {\n for (const selector of scrollToTopSelectors) {\n if (selector === 'window') continue\n const element =\n typeof selector === 'function'\n ? selector()\n : document.querySelector(selector)\n if (element) element.scrollTo(scrollOptions)\n }\n }\n }\n\n //\n ignoreScroll = false\n}\n\n/** Setup global listeners and hooks to support scroll restoration. */\n/** Setup global listeners and hooks to support scroll restoration. */\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n if (!scrollRestorationCache && !router.isServer) {\n return\n }\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (\n router.isServer ||\n router.isScrollRestorationSetup ||\n !scrollRestorationCache\n ) {\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] ||= {} as ScrollRestorationByElement)\n\n const elementEntry = (keyEntry[elementSelector] ||=\n {} 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 if (typeof router.options.scrollRestoration === 'function') {\n const shouldRestore = router.options.scrollRestoration({\n location: router.latestLocation,\n })\n if (!shouldRestore) {\n return\n }\n }\n\n restoreScroll({\n storageKey,\n key: cacheKey,\n behavior: router.options.scrollRestorationBehavior,\n shouldScrollRestoration: router.isScrollRestoring,\n scrollToTopSelectors: router.options.scrollToTopSelectors,\n location: router.history.location,\n })\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] ||= {} as ScrollRestorationByElement\n\n return state\n })\n }\n })\n}\n\n/**\n * @private\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\n/**\n * @private\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\n/**\n * @private\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific Transitioners.\n */\nexport function handleHashScroll(router: AnyRouter) {\n if (typeof document !== 'undefined' && (document as any).querySelector) {\n const hashScrollIntoViewOptions =\n router.state.location.state.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions && router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n }\n}\n"],"names":["storageKey"],"mappings":";AAqBA,SAAS,wBAAwB;AAC/B,MAAI;AACF,QACE,OAAO,WAAW,eAClB,OAAO,OAAO,mBAAmB,UACjC;AACA,aAAO,OAAO;AAAA,IAChB;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAKO,MAAM,aAAa;AAE1B,MAAM,WAAW,CAAC,IAAmC,SAAiB;AACpE,MAAI;AACJ,SAAO,IAAI,SAAqB;AAC9B,QAAI,CAAC,SAAS;AACZ,gBAAU,WAAW,MAAM;AACzB,WAAG,GAAG,IAAI;AACV,kBAAU;AAAA,MACZ,GAAG,IAAI;AAAA,IACT;AAAA,EACF;AACF;AAEA,SAAS,+BAA8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kBAAkB;AAAA,QACrD,UAAU,OAAO;AAAA,MAAA,CAClB;AACD,UAAI,CAAC,eAAe;AAClB;AAAA,MACF;AAAA,IACF;AAEA,kBAAc;AAAA,MACZ;AAAA,MACA,KAAK;AAAA,MACL,UAAU,OAAO,QAAQ;AAAA,MACzB,yBAAyB,OAAO;AAAA,MAChC,sBAAsB,OAAO,QAAQ;AAAA,MACrC,UAAU,OAAO,QAAQ;AAAA,IAAA,CAC1B;AAED,QAAI,OAAO,mBAAmB;AAE5B,6BAAuB,IAAI,CAAC,UAAU;AACpC,cAAM,QAAQ,MAAM,CAAA;AAEpB,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAuBO,SAAS,iBAAiB,QAAmB;AAClD,MAAI,OAAO,aAAa,eAAgB,SAAiB,eAAe;AACtE,UAAM,4BACJ,OAAO,MAAM,SAAS,MAAM,+BAA+B;AAE7D,QAAI,6BAA6B,OAAO,MAAM,SAAS,SAAS,IAAI;AAClE,YAAM,KAAK,SAAS,eAAe,OAAO,MAAM,SAAS,IAAI;AAC7D,UAAI,IAAI;AACN,WAAG,eAAe,yBAAyB;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AACF;"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { AnySchema } from './validators.js';
|
|
2
2
|
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
3
3
|
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
4
|
+
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
4
5
|
export declare const defaultParseSearch: (searchStr: string) => AnySchema;
|
|
6
|
+
/** Default `stringifySearch` using JSON.stringify for complex values. */
|
|
5
7
|
export declare const defaultStringifySearch: (search: Record<string, any>) => string;
|
|
6
8
|
/**
|
|
7
9
|
* Build a `parseSearch` function using a provided JSON-like parser.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"searchParams.js","sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\n/**\n * Build a `parseSearch` function using a provided JSON-like parser.\n *\n * The returned function strips a leading `?`, decodes values, and attempts to\n * JSON-parse string values using the given `parser`.\n *\n * @param parser Function to parse a string value (e.g. `JSON.parse`).\n * @returns A `parseSearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\n/** Build a parseSearch function using a provided JSON-like parser. */\nexport function parseSearchWith(parser: (str: string) => any) {\n return (searchStr: string): AnySchema => {\n if (searchStr[0] === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n try {\n query[key] = parser(value)\n } catch (_err) {\n // silent\n }\n }\n }\n\n return query\n }\n}\n\n/**\n * Build a `stringifySearch` function using a provided serializer.\n *\n * Non-primitive values are serialized with `stringify`. If a `parser` is\n * supplied, string values that are parseable are re-serialized to ensure\n * symmetry with `parseSearch`.\n *\n * @param stringify Function to serialize a value (e.g. `JSON.stringify`).\n * @param parser Optional parser to detect parseable strings.\n * @returns A `stringifySearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\n/** Build a stringifySearch function using a provided serializer/parser. */\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n const hasParser = typeof parser === 'function'\n function stringifyValue(val: any) {\n if (typeof val === 'object' && val !== null) {\n try {\n return stringify(val)\n } catch (_err) {\n // silent\n }\n } else if (hasParser && typeof val === 'string') {\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (_err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n const searchStr = encode(search, stringifyValue)\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"searchParams.js","sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\n/** Default `stringifySearch` using JSON.stringify for complex values. */\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\n/**\n * Build a `parseSearch` function using a provided JSON-like parser.\n *\n * The returned function strips a leading `?`, decodes values, and attempts to\n * JSON-parse string values using the given `parser`.\n *\n * @param parser Function to parse a string value (e.g. `JSON.parse`).\n * @returns A `parseSearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\n/** Build a parseSearch function using a provided JSON-like parser. */\nexport function parseSearchWith(parser: (str: string) => any) {\n return (searchStr: string): AnySchema => {\n if (searchStr[0] === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n try {\n query[key] = parser(value)\n } catch (_err) {\n // silent\n }\n }\n }\n\n return query\n }\n}\n\n/**\n * Build a `stringifySearch` function using a provided serializer.\n *\n * Non-primitive values are serialized with `stringify`. If a `parser` is\n * supplied, string values that are parseable are re-serialized to ensure\n * symmetry with `parseSearch`.\n *\n * @param stringify Function to serialize a value (e.g. `JSON.stringify`).\n * @param parser Optional parser to detect parseable strings.\n * @returns A `stringifySearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\n/** Build a stringifySearch function using a provided serializer/parser. */\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n const hasParser = typeof parser === 'function'\n function stringifyValue(val: any) {\n if (typeof val === 'object' && val !== null) {\n try {\n return stringify(val)\n } catch (_err) {\n // silent\n }\n } else if (hasParser && typeof val === 'string') {\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (_err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n const searchStr = encode(search, stringifyValue)\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"names":[],"mappings":";AAMO,MAAM,qBAAqB,gBAAgB,KAAK,KAAK;AAErD,MAAM,yBAAyB;AAAA,EACpC,KAAK;AAAA,EACL,KAAK;AACP;AAaO,SAAS,gBAAgB,QAA8B;AAC5D,SAAO,CAAC,cAAiC;AACvC,QAAI,UAAU,CAAC,MAAM,KAAK;AACxB,kBAAY,UAAU,UAAU,CAAC;AAAA,IACnC;AAEA,UAAM,QAAiC,OAAO,SAAS;AAGvD,eAAW,OAAO,OAAO;AACvB,YAAM,QAAQ,MAAM,GAAG;AACvB,UAAI,OAAO,UAAU,UAAU;AAC7B,YAAI;AACF,gBAAM,GAAG,IAAI,OAAO,KAAK;AAAA,QAC3B,SAAS,MAAM;AAAA,QAEf;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;AAeO,SAAS,oBACd,WACA,QACA;AACA,QAAM,YAAY,OAAO,WAAW;AACpC,WAAS,eAAe,KAAU;AAChC,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AAC3C,UAAI;AACF,eAAO,UAAU,GAAG;AAAA,MACtB,SAAS,MAAM;AAAA,MAEf;AAAA,IACF,WAAW,aAAa,OAAO,QAAQ,UAAU;AAC/C,UAAI;AAGF,eAAO,GAAG;AACV,eAAO,UAAU,GAAG;AAAA,MACtB,SAAS,MAAM;AAAA,MAEf;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAEA,SAAO,CAAC,WAAgC;AACtC,UAAM,YAAY,OAAO,QAAQ,cAAc;AAC/C,WAAO,YAAY,IAAI,SAAS,KAAK;AAAA,EACvC;AACF;"}
|
package/dist/esm/utils.d.ts
CHANGED
|
@@ -53,7 +53,15 @@ export type ValidateJSON<T> = ((...args: Array<any>) => any) extends T ? unknown
|
|
|
53
53
|
};
|
|
54
54
|
export type LooseReturnType<T> = T extends (...args: Array<any>) => infer TReturn ? TReturn : never;
|
|
55
55
|
export type LooseAsyncReturnType<T> = T extends (...args: Array<any>) => infer TReturn ? TReturn extends Promise<infer TReturn> ? TReturn : TReturn : never;
|
|
56
|
+
/**
|
|
57
|
+
* Return the last element of an array.
|
|
58
|
+
* Intended for non-empty arrays used within router internals.
|
|
59
|
+
*/
|
|
56
60
|
export declare function last<T>(arr: Array<T>): T | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* Apply a value-or-updater to a previous value.
|
|
63
|
+
* Accepts either a literal value or a function of the previous value.
|
|
64
|
+
*/
|
|
57
65
|
export declare function functionalUpdate<TPrevious, TResult = TPrevious>(updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>, previous: TPrevious): TResult;
|
|
58
66
|
/**
|
|
59
67
|
* This function returns `prev` if `_next` is deeply equal.
|
|
@@ -63,7 +71,14 @@ export declare function functionalUpdate<TPrevious, TResult = TPrevious>(updater
|
|
|
63
71
|
*/
|
|
64
72
|
export declare function replaceEqualDeep<T>(prev: any, _next: T): T;
|
|
65
73
|
export declare function isPlainObject(o: any): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Check if a value is a "plain" array (no extra enumerable keys).
|
|
76
|
+
*/
|
|
66
77
|
export declare function isPlainArray(value: unknown): value is Array<unknown>;
|
|
78
|
+
/**
|
|
79
|
+
* Perform a deep equality check with options for partial comparison and
|
|
80
|
+
* ignoring `undefined` values. Optimized for router state comparisons.
|
|
81
|
+
*/
|
|
67
82
|
export declare function deepEqual(a: any, b: any, opts?: {
|
|
68
83
|
partial?: boolean;
|
|
69
84
|
ignoreUndefined?: boolean;
|
|
@@ -84,7 +99,16 @@ export type ControlledPromise<T> = Promise<T> & {
|
|
|
84
99
|
status: 'pending' | 'resolved' | 'rejected';
|
|
85
100
|
value?: T;
|
|
86
101
|
};
|
|
102
|
+
/**
|
|
103
|
+
* Create a promise with exposed resolve/reject and status fields.
|
|
104
|
+
* Useful for coordinating async router lifecycle operations.
|
|
105
|
+
*/
|
|
87
106
|
export declare function createControlledPromise<T>(onResolve?: (value: T) => void): ControlledPromise<T>;
|
|
107
|
+
/**
|
|
108
|
+
* Heuristically detect dynamic import "module not found" errors
|
|
109
|
+
* across major browsers for lazy route component handling.
|
|
110
|
+
*/
|
|
88
111
|
export declare function isModuleNotFoundError(error: any): boolean;
|
|
89
112
|
export declare function isPromise<T>(value: Promise<Awaited<T>> | T): value is Promise<Awaited<T>>;
|
|
90
113
|
export declare function findLast<T>(array: ReadonlyArray<T>, predicate: (item: T) => boolean): T | undefined;
|
|
114
|
+
export declare function decodePathSegment(part: string, decodeIgnore?: Array<string>, startIndex?: number): string;
|
package/dist/esm/utils.js
CHANGED
|
@@ -161,8 +161,52 @@ function findLast(array, predicate) {
|
|
|
161
161
|
}
|
|
162
162
|
return void 0;
|
|
163
163
|
}
|
|
164
|
+
const DECODE_IGNORE_LIST = Array.from(
|
|
165
|
+
(/* @__PURE__ */ new Map([
|
|
166
|
+
["%", "%25"],
|
|
167
|
+
["\\", "%5C"],
|
|
168
|
+
["/", "%2F"],
|
|
169
|
+
[";", "%3B"],
|
|
170
|
+
[":", "%3A"],
|
|
171
|
+
["@", "%40"],
|
|
172
|
+
["&", "%26"],
|
|
173
|
+
["=", "%3D"],
|
|
174
|
+
["+", "%2B"],
|
|
175
|
+
["$", "%24"],
|
|
176
|
+
[",", "%2C"]
|
|
177
|
+
])).values()
|
|
178
|
+
);
|
|
179
|
+
function decodePathSegment(part, decodeIgnore = DECODE_IGNORE_LIST, startIndex = 0) {
|
|
180
|
+
function decode(part2) {
|
|
181
|
+
try {
|
|
182
|
+
return decodeURIComponent(part2);
|
|
183
|
+
} catch {
|
|
184
|
+
return part2.replaceAll(/%[0-9A-Fa-f]{2}/g, (match) => {
|
|
185
|
+
try {
|
|
186
|
+
return decodeURIComponent(match);
|
|
187
|
+
} catch {
|
|
188
|
+
return match;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (part === "" || !part.match(/%[0-9A-Fa-f]{2}/g)) return part;
|
|
194
|
+
for (let i = startIndex; i < decodeIgnore.length; i++) {
|
|
195
|
+
const char = decodeIgnore[i];
|
|
196
|
+
if (char && part.includes(char)) {
|
|
197
|
+
const partsToDecode = part.split(char);
|
|
198
|
+
const partsToJoin = [];
|
|
199
|
+
for (const partToDecode of partsToDecode) {
|
|
200
|
+
partsToJoin.push(decodePathSegment(partToDecode, decodeIgnore, i + 1));
|
|
201
|
+
}
|
|
202
|
+
return partsToJoin.join(char);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return decode(part);
|
|
206
|
+
}
|
|
164
207
|
export {
|
|
165
208
|
createControlledPromise,
|
|
209
|
+
decodePathSegment,
|
|
166
210
|
deepEqual,
|
|
167
211
|
findLast,
|
|
168
212
|
functionalUpdate,
|
package/dist/esm/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import type { RouteIds } from './routeInfo'\nimport type { AnyRouter } from './router'\n\nexport type Awaitable<T> = T | Promise<T>\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\n\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\nexport type PickOptional<T> = {\n [K in keyof T as undefined extends T[K] ? K : never]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &\n keyof TRight extends never\n ? TRight\n : Omit<TRight, keyof TLeft & keyof TRight> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n }\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type IsNonEmptyObject<T> = T extends object\n ? keyof T extends never\n ? false\n : true\n : false\n\nexport type Assign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n : never\n : never\n\nexport type IntersectAssign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : TRight & TLeft\n : never\n : never\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive\n ? never\n : TUnion\n\nexport type PartialMergeAllObject<TUnion> =\n ExtractObjects<TUnion> extends infer TObj\n ? [TObj] extends [never]\n ? never\n : {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeAllPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n | undefined\n | null\n\nexport type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type PartialMergeAll<TUnion> =\n | ExtractPrimitives<TUnion>\n | PartialMergeAllObject<TUnion>\n\nexport type Constrain<T, TConstraint, TDefault = TConstraint> =\n | (T extends TConstraint ? T : never)\n | TDefault\n\nexport type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =\n | (T & TConstraint)\n | TDefault\n\n/**\n * To be added to router types\n */\nexport type UnionToIntersection<T> = (\n T extends any ? (arg: T) => any : never\n) extends (arg: infer T) => any\n ? T\n : never\n\n/**\n * Merges everything in a union into one object.\n * This mapped type is homomorphic which means it preserves stuff! :)\n */\nexport type MergeAllObjects<\n TUnion,\n TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,\n> = [keyof TIntersected] extends [never]\n ? never\n : {\n [TKey in keyof TIntersected]: TUnion extends any\n ? TUnion[TKey & keyof TUnion]\n : never\n }\n\nexport type MergeAll<TUnion> =\n | MergeAllObjects<TUnion>\n | ExtractPrimitives<TUnion>\n\nexport type ValidateJSON<T> = ((...args: Array<any>) => any) extends T\n ? unknown extends T\n ? never\n : 'Function is not serializable'\n : { [K in keyof T]: ValidateJSON<T[K]> }\n\nexport type LooseReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn\n : never\n\nexport type LooseAsyncReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn extends Promise<infer TReturn>\n ? TReturn\n : TReturn\n : never\n\nexport function last<T>(arr: Array<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\nexport function functionalUpdate<TPrevious, TResult = TPrevious>(\n updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,\n previous: TPrevious,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(prev: any, _next: T): T {\n if (prev === _next) {\n return prev\n }\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next\n\n const prevItems = array ? prev : getEnumerableOwnKeys(prev)\n if (!prevItems) return next\n const nextItems = array ? next : getEnumerableOwnKeys(next)\n if (!nextItems) return next\n const prevSize = prevItems.length\n const nextSize = nextItems.length\n const copy: any = array ? new Array(nextSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n const p = prev[key]\n const n = next[key]\n\n if (p === n) {\n copy[key] = p\n if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++\n continue\n }\n\n if (\n p === null ||\n n === null ||\n typeof p !== 'object' ||\n typeof n !== 'object'\n ) {\n copy[key] = n\n continue\n }\n\n const v = replaceEqualDeep(p, n)\n copy[key] = v\n if (v === p) equalItems++\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n}\n\n/**\n * Equivalent to `Reflect.ownKeys`, but ensures that objects are \"clone-friendly\":\n * will return false if object has any non-enumerable properties.\n */\nfunction getEnumerableOwnKeys(o: object) {\n const keys = []\n const names = Object.getOwnPropertyNames(o)\n for (const name of names) {\n if (!Object.prototype.propertyIsEnumerable.call(o, name)) return false\n keys.push(name)\n }\n const symbols = Object.getOwnPropertySymbols(o)\n for (const symbol of symbols) {\n if (!Object.prototype.propertyIsEnumerable.call(o, symbol)) return false\n keys.push(symbol)\n }\n return keys\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\nexport function deepEqual(\n a: any,\n b: any,\n opts?: { partial?: boolean; ignoreUndefined?: boolean },\n): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0, l = a.length; i < l; i++) {\n if (!deepEqual(a[i], b[i], opts)) return false\n }\n return true\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const ignoreUndefined = opts?.ignoreUndefined ?? true\n\n if (opts?.partial) {\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n if (!deepEqual(a[k], b[k], opts)) return false\n }\n }\n return true\n }\n\n let aCount = 0\n if (!ignoreUndefined) {\n aCount = Object.keys(a).length\n } else {\n for (const k in a) {\n if (a[k] !== undefined) aCount++\n }\n }\n\n let bCount = 0\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n bCount++\n if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false\n }\n }\n\n return aCount === bCount\n }\n\n return false\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true\n ? T\n : T | undefined\n\nexport type StrictOrFrom<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>\n strict?: TStrict\n }\n\nexport type ThrowConstraint<\n TStrict extends boolean,\n TThrow extends boolean,\n> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow\n\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\nexport function isModuleNotFoundError(error: any): boolean {\n // chrome: \"Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // firefox: \"error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // safari: \"Importing a module script failed.\"\n if (typeof error?.message !== 'string') return false\n return (\n error.message.startsWith('Failed to fetch dynamically imported module') ||\n error.message.startsWith('error loading dynamically imported module') ||\n error.message.startsWith('Importing a module script failed')\n )\n}\n\nexport function isPromise<T>(\n value: Promise<Awaited<T>> | T,\n): value is Promise<Awaited<T>> {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as Promise<T>).then === 'function',\n )\n}\n\nexport function findLast<T>(\n array: ReadonlyArray<T>,\n predicate: (item: T) => boolean,\n): T | undefined {\n for (let i = array.length - 1; i >= 0; i--) {\n const item = array[i]!\n if (predicate(item)) return item\n }\n return undefined\n}\n"],"names":[],"mappings":"AA0LO,SAAS,KAAQ,KAAe;AACrC,SAAO,IAAI,IAAI,SAAS,CAAC;AAC3B;AAEA,SAAS,WAAW,GAAuB;AACzC,SAAO,OAAO,MAAM;AACtB;AAEO,SAAS,iBACd,SACA,UACS;AACT,MAAI,WAAW,OAAO,GAAG;AACvB,WAAO,QAAQ,QAAQ;AAAA,EACzB;AAEA,SAAO;AACT;AAEA,MAAM,SAAS,OAAO,UAAU;AAQzB,SAAS,iBAAoB,MAAW,OAAa;AAC1D,MAAI,SAAS,OAAO;AAClB,WAAO;AAAA,EACT;AAEA,QAAM,OAAO;AAEb,QAAM,QAAQ,aAAa,IAAI,KAAK,aAAa,IAAI;AAErD,MAAI,CAAC,SAAS,EAAE,cAAc,IAAI,KAAK,cAAc,IAAI,GAAI,QAAO;AAEpE,QAAM,YAAY,QAAQ,OAAO,qBAAqB,IAAI;AAC1D,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,YAAY,QAAQ,OAAO,qBAAqB,IAAI;AAC1D,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,WAAW,UAAU;AAC3B,QAAM,WAAW,UAAU;AAC3B,QAAM,OAAY,QAAQ,IAAI,MAAM,QAAQ,IAAI,CAAA;AAEhD,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,UAAU,KAAK;AACjC,UAAM,MAAM,QAAQ,IAAK,UAAU,CAAC;AACpC,UAAM,IAAI,KAAK,GAAG;AAClB,UAAM,IAAI,KAAK,GAAG;AAElB,QAAI,MAAM,GAAG;AACX,WAAK,GAAG,IAAI;AACZ,UAAI,QAAQ,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AAM,oBAAoB,IAAI,QAAW,CAAC,SAAS,WAAW;AAC5D,yBAAqB;AACrB,wBAAoB;AAAA,EACtB,CAAC;AAED,oBAAkB,SAAS;AAE3B,oBAAkB,UAAU,CAAC,UAAa;AACxC,sBAAkB,SAAS;AAC3B,sBAAkB,QAAQ;AAC1B,uBAAmB,KAAK;AACxB,gBAAY,KAAK;AAAA,EACnB;AAEA,oBAAkB,SAAS,CAAC,MAAM;AAChC,sBAAkB,SAAS;AAC3B,sBAAkB,CAAC;AAAA,EACrB;AAEA,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAqB;AAIzD,MAAI,OAAO,OAAO,YAAY,SAAU,QAAO;AAC/C,SACE,MAAM,QAAQ,WAAW,6CAA6C,KACtE,MAAM,QAAQ,WAAW,2CAA2C,KACpE,MAAM,QAAQ,WAAW,kCAAkC;AAE/D;AAEO,SAAS,UACd,OAC8B;AAC9B,SAAO;AAAA,IACL,SACE,OAAO,UAAU,YACjB,OAAQ,MAAqB,SAAS;AAAA,EAAA;AAE5C;AAEO,SAAS,SACd,OACA,WACe;AACf,WAAS,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;AAC1C,UAAM,OAAO,MAAM,CAAC;AACpB,QAAI,UAAU,IAAI,EAAG,QAAO;AAAA,EAC9B;AACA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["import type { RouteIds } from './routeInfo'\nimport type { AnyRouter } from './router'\n\nexport type Awaitable<T> = T | Promise<T>\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\n\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\nexport type PickOptional<T> = {\n [K in keyof T as undefined extends T[K] ? K : never]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &\n keyof TRight extends never\n ? TRight\n : Omit<TRight, keyof TLeft & keyof TRight> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n }\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type IsNonEmptyObject<T> = T extends object\n ? keyof T extends never\n ? false\n : true\n : false\n\nexport type Assign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n : never\n : never\n\nexport type IntersectAssign<TLeft, TRight> = TLeft extends any\n ? TRight extends any\n ? IsNonEmptyObject<TLeft> extends false\n ? TRight\n : IsNonEmptyObject<TRight> extends false\n ? TLeft\n : TRight & TLeft\n : never\n : never\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive\n ? never\n : TUnion\n\nexport type PartialMergeAllObject<TUnion> =\n ExtractObjects<TUnion> extends infer TObj\n ? [TObj] extends [never]\n ? never\n : {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeAllPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n | undefined\n | null\n\nexport type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type PartialMergeAll<TUnion> =\n | ExtractPrimitives<TUnion>\n | PartialMergeAllObject<TUnion>\n\nexport type Constrain<T, TConstraint, TDefault = TConstraint> =\n | (T extends TConstraint ? T : never)\n | TDefault\n\nexport type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =\n | (T & TConstraint)\n | TDefault\n\n/**\n * To be added to router types\n */\nexport type UnionToIntersection<T> = (\n T extends any ? (arg: T) => any : never\n) extends (arg: infer T) => any\n ? T\n : never\n\n/**\n * Merges everything in a union into one object.\n * This mapped type is homomorphic which means it preserves stuff! :)\n */\nexport type MergeAllObjects<\n TUnion,\n TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,\n> = [keyof TIntersected] extends [never]\n ? never\n : {\n [TKey in keyof TIntersected]: TUnion extends any\n ? TUnion[TKey & keyof TUnion]\n : never\n }\n\nexport type MergeAll<TUnion> =\n | MergeAllObjects<TUnion>\n | ExtractPrimitives<TUnion>\n\nexport type ValidateJSON<T> = ((...args: Array<any>) => any) extends T\n ? unknown extends T\n ? never\n : 'Function is not serializable'\n : { [K in keyof T]: ValidateJSON<T[K]> }\n\nexport type LooseReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn\n : never\n\nexport type LooseAsyncReturnType<T> = T extends (\n ...args: Array<any>\n) => infer TReturn\n ? TReturn extends Promise<infer TReturn>\n ? TReturn\n : TReturn\n : never\n\n/**\n * Return the last element of an array.\n * Intended for non-empty arrays used within router internals.\n */\nexport function last<T>(arr: Array<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\n/**\n * Apply a value-or-updater to a previous value.\n * Accepts either a literal value or a function of the previous value.\n */\nexport function functionalUpdate<TPrevious, TResult = TPrevious>(\n updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,\n previous: TPrevious,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(prev: any, _next: T): T {\n if (prev === _next) {\n return prev\n }\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next\n\n const prevItems = array ? prev : getEnumerableOwnKeys(prev)\n if (!prevItems) return next\n const nextItems = array ? next : getEnumerableOwnKeys(next)\n if (!nextItems) return next\n const prevSize = prevItems.length\n const nextSize = nextItems.length\n const copy: any = array ? new Array(nextSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n const p = prev[key]\n const n = next[key]\n\n if (p === n) {\n copy[key] = p\n if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++\n continue\n }\n\n if (\n p === null ||\n n === null ||\n typeof p !== 'object' ||\n typeof n !== 'object'\n ) {\n copy[key] = n\n continue\n }\n\n const v = replaceEqualDeep(p, n)\n copy[key] = v\n if (v === p) equalItems++\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n}\n\n/**\n * Equivalent to `Reflect.ownKeys`, but ensures that objects are \"clone-friendly\":\n * will return false if object has any non-enumerable properties.\n */\nfunction getEnumerableOwnKeys(o: object) {\n const keys = []\n const names = Object.getOwnPropertyNames(o)\n for (const name of names) {\n if (!Object.prototype.propertyIsEnumerable.call(o, name)) return false\n keys.push(name)\n }\n const symbols = Object.getOwnPropertySymbols(o)\n for (const symbol of symbols) {\n if (!Object.prototype.propertyIsEnumerable.call(o, symbol)) return false\n keys.push(symbol)\n }\n return keys\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Check if a value is a \"plain\" array (no extra enumerable keys).\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n/**\n * Perform a deep equality check with options for partial comparison and\n * ignoring `undefined` values. Optimized for router state comparisons.\n */\nexport function deepEqual(\n a: any,\n b: any,\n opts?: { partial?: boolean; ignoreUndefined?: boolean },\n): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n for (let i = 0, l = a.length; i < l; i++) {\n if (!deepEqual(a[i], b[i], opts)) return false\n }\n return true\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const ignoreUndefined = opts?.ignoreUndefined ?? true\n\n if (opts?.partial) {\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n if (!deepEqual(a[k], b[k], opts)) return false\n }\n }\n return true\n }\n\n let aCount = 0\n if (!ignoreUndefined) {\n aCount = Object.keys(a).length\n } else {\n for (const k in a) {\n if (a[k] !== undefined) aCount++\n }\n }\n\n let bCount = 0\n for (const k in b) {\n if (!ignoreUndefined || b[k] !== undefined) {\n bCount++\n if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false\n }\n }\n\n return aCount === bCount\n }\n\n return false\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true\n ? T\n : T | undefined\n\nexport type StrictOrFrom<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>\n strict?: TStrict\n }\n\nexport type ThrowConstraint<\n TStrict extends boolean,\n TThrow extends boolean,\n> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow\n\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\n/**\n * Create a promise with exposed resolve/reject and status fields.\n * Useful for coordinating async router lifecycle operations.\n */\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\n/**\n * Heuristically detect dynamic import \"module not found\" errors\n * across major browsers for lazy route component handling.\n */\nexport function isModuleNotFoundError(error: any): boolean {\n // chrome: \"Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // firefox: \"error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split\"\n // safari: \"Importing a module script failed.\"\n if (typeof error?.message !== 'string') return false\n return (\n error.message.startsWith('Failed to fetch dynamically imported module') ||\n error.message.startsWith('error loading dynamically imported module') ||\n error.message.startsWith('Importing a module script failed')\n )\n}\n\nexport function isPromise<T>(\n value: Promise<Awaited<T>> | T,\n): value is Promise<Awaited<T>> {\n return Boolean(\n value &&\n typeof value === 'object' &&\n typeof (value as Promise<T>).then === 'function',\n )\n}\n\nexport function findLast<T>(\n array: ReadonlyArray<T>,\n predicate: (item: T) => boolean,\n): T | undefined {\n for (let i = array.length - 1; i >= 0; i--) {\n const item = array[i]!\n if (predicate(item)) return item\n }\n return undefined\n}\n\nconst DECODE_IGNORE_LIST = Array.from(\n new Map([\n ['%', '%25'],\n ['\\\\', '%5C'],\n ['/', '%2F'],\n [';', '%3B'],\n [':', '%3A'],\n ['@', '%40'],\n ['&', '%26'],\n ['=', '%3D'],\n ['+', '%2B'],\n ['$', '%24'],\n [',', '%2C'],\n ]).values(),\n)\n\nexport function decodePathSegment(\n part: string,\n decodeIgnore: Array<string> = DECODE_IGNORE_LIST,\n startIndex = 0,\n): string {\n function decode(part: string): string {\n try {\n return decodeURIComponent(part)\n } catch {\n // if the decoding fails, try to decode the various parts leaving the malformed tags in place\n return part.replaceAll(/%[0-9A-Fa-f]{2}/g, (match) => {\n try {\n return decodeURIComponent(match)\n } catch {\n return match\n }\n })\n }\n }\n\n // if the path segment does not contain any encoded uri components return the path as is\n if (part === '' || !part.match(/%[0-9A-Fa-f]{2}/g)) return part\n\n // decode the path / path segment by splitting it into parts defined by the ignore list.\n // once these pieces have been decoded, join them back together to form the final decoded path segment with the ignored character in place.\n // we walk through the ignore list linearly, breaking the segment up into pieces and decoding each piece individually.\n // use index traversal to avoid making unnecessary copies of the array.\n for (let i = startIndex; i < decodeIgnore.length; i++) {\n const char = decodeIgnore[i]\n\n // check if the part includes the current ignore character\n // if it doesn't continue to the next ignore character\n if (char && part.includes(char)) {\n // split the part into pieces that needs to be checked and decoded\n const partsToDecode = part.split(char)\n const partsToJoin: Array<string> = []\n\n // now check and decode each piece individually taking into consideration the remaining ignored characters.\n // since we are walking through the list linearly, we only need to consider ignore items not yet traversed.\n for (const partToDecode of partsToDecode) {\n // once we have traversed the entire ignore list, each decoded part is returned.\n partsToJoin.push(decodePathSegment(partToDecode, decodeIgnore, i + 1))\n }\n\n // and join them back together to form the final decoded path segment with the ignored character in place.\n return partsToJoin.join(char)\n }\n }\n\n // once we have reached the end of the ignore list, we start walking back returning each decoded part.\n // should there be no matching characters, the path segment as a whole will be decoded.\n return decode(part)\n}\n"],"names":["part"],"mappings":"AA8LO,SAAS,KAAQ,KAAe;AACrC,SAAO,IAAI,IAAI,SAAS,CAAC;AAC3B;AAEA,SAAS,WAAW,GAAuB;AACzC,SAAO,OAAO,MAAM;AACtB;AAMO,SAAS,iBACd,SACA,UACS;AACT,MAAI,WAAW,OAAO,GAAG;AACvB,WAAO,QAAQ,QAAQ;AAAA,EACzB;AAEA,SAAO;AACT;AAEA,MAAM,SAAS,OAAO,UAAU;AAQzB,SAAS,iBAAoB,MAAW,OAAa;AAC1D,MAAI,SAAS,OAAO;AAClB,WAAO;AAAA,EACT;AAEA,QAAM,OAAO;AAEb,QAAM,QAAQ,aAAa,IAAI,KAAK,aAAa,IAAI;AAErD,MAAI,CAAC,SAAS,EAAE,cAAc,IAAI,KAAK,cAAc,IAAI,GAAI,QAAO;AAEpE,QAAM,YAAY,QAAQ,OAAO,qBAAqB,IAAI;AAC1D,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,YAAY,QAAQ,OAAO,qBAAqB,IAAI;AAC1D,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,WAAW,UAAU;AAC3B,QAAM,WAAW,UAAU;AAC3B,QAAM,OAAY,QAAQ,IAAI,MAAM,QAAQ,IAAI,CAAA;AAEhD,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,UAAU,KAAK;AACjC,UAAM,MAAM,QAAQ,IAAK,UAAU,CAAC;AACpC,UAAM,IAAI,KAAK,GAAG;AAClB,UAAM,IAA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;AAAA,IACX,CAAC,KAAK,KAAK;AAAA,EAAA,CACZ,GAAE,OAAA;AACL;AAEO,SAAS,kBACd,MACA,eAA8B,oBAC9B,aAAa,GACL;AACR,WAAS,OAAOA,OAAsB;AACpC,QAAI;AACF,aAAO,mBAAmBA,KAAI;AAAA,IAChC,QAAQ;AAEN,aAAOA,MAAK,WAAW,oBAAoB,CAAC,UAAU;AACpD,YAAI;AACF,iBAAO,mBAAmB,KAAK;AAAA,QACjC,QAAQ;AACN,iBAAO;AAAA,QACT;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAGA,MAAI,SAAS,MAAM,CAAC,KAAK,MAAM,kBAAkB,EAAG,QAAO;AAM3D,WAAS,IAAI,YAAY,IAAI,aAAa,QAAQ,KAAK;AACrD,UAAM,OAAO,aAAa,CAAC;AAI3B,QAAI,QAAQ,KAAK,SAAS,IAAI,GAAG;AAE/B,YAAM,gBAAgB,KAAK,MAAM,IAAI;AACrC,YAAM,cAA6B,CAAA;AAInC,iBAAW,gBAAgB,eAAe;AAExC,oBAAY,KAAK,kBAAkB,cAAc,cAAc,IAAI,CAAC,CAAC;AAAA,MACvE;AAGA,aAAO,YAAY,KAAK,IAAI;AAAA,IAC9B;AAAA,EACF;AAIA,SAAO,OAAO,IAAI;AACpB;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/router-core",
|
|
3
|
-
"version": "1.133.
|
|
3
|
+
"version": "1.133.35",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"seroval-plugins": "^1.3.2",
|
|
71
71
|
"tiny-invariant": "^1.3.3",
|
|
72
72
|
"tiny-warning": "^1.0.3",
|
|
73
|
-
"@tanstack/history": "1.133.
|
|
73
|
+
"@tanstack/history": "1.133.28"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"esbuild": "^0.25.0"
|
package/src/path.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { last } from './utils'
|
|
1
|
+
import { decodePathSegment, last } from './utils'
|
|
2
2
|
import type { LRUCache } from './lru-cache'
|
|
3
3
|
import type { MatchLocation } from './RouterProvider'
|
|
4
4
|
import type { AnyPathParams } from './route'
|
|
@@ -21,6 +21,7 @@ export interface Segment {
|
|
|
21
21
|
readonly hasStaticAfter?: boolean
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/** Join path segments, cleaning duplicate slashes between parts. */
|
|
24
25
|
/** Join path segments, cleaning duplicate slashes between parts. */
|
|
25
26
|
export function joinPaths(paths: Array<string | undefined>) {
|
|
26
27
|
return cleanPath(
|
|
@@ -32,22 +33,26 @@ export function joinPaths(paths: Array<string | undefined>) {
|
|
|
32
33
|
)
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
/** Remove repeated slashes from a path string. */
|
|
35
37
|
/** Remove repeated slashes from a path string. */
|
|
36
38
|
export function cleanPath(path: string) {
|
|
37
39
|
// remove double slashes
|
|
38
40
|
return path.replace(/\/{2,}/g, '/')
|
|
39
41
|
}
|
|
40
42
|
|
|
43
|
+
/** Trim leading slashes (except preserving root '/'). */
|
|
41
44
|
/** Trim leading slashes (except preserving root '/'). */
|
|
42
45
|
export function trimPathLeft(path: string) {
|
|
43
46
|
return path === '/' ? path : path.replace(/^\/{1,}/, '')
|
|
44
47
|
}
|
|
45
48
|
|
|
49
|
+
/** Trim trailing slashes (except preserving root '/'). */
|
|
46
50
|
/** Trim trailing slashes (except preserving root '/'). */
|
|
47
51
|
export function trimPathRight(path: string) {
|
|
48
52
|
return path === '/' ? path : path.replace(/\/{1,}$/, '')
|
|
49
53
|
}
|
|
50
54
|
|
|
55
|
+
/** Trim both leading and trailing slashes. */
|
|
51
56
|
/** Trim both leading and trailing slashes. */
|
|
52
57
|
export function trimPath(path: string) {
|
|
53
58
|
return trimPathRight(trimPathLeft(path))
|
|
@@ -65,6 +70,10 @@ export function removeTrailingSlash(value: string, basepath: string): string {
|
|
|
65
70
|
// see the usage in the isActive under useLinkProps
|
|
66
71
|
// /sample/path1 = /sample/path1/
|
|
67
72
|
// /sample/path1/some <> /sample/path1
|
|
73
|
+
/**
|
|
74
|
+
* Compare two pathnames for exact equality after normalizing trailing slashes
|
|
75
|
+
* relative to the provided `basepath`.
|
|
76
|
+
*/
|
|
68
77
|
/**
|
|
69
78
|
* Compare two pathnames for exact equality after normalizing trailing slashes
|
|
70
79
|
* relative to the provided `basepath`.
|
|
@@ -215,6 +224,10 @@ export function resolvePath({
|
|
|
215
224
|
|
|
216
225
|
export type ParsePathnameCache = LRUCache<string, ReadonlyArray<Segment>>
|
|
217
226
|
|
|
227
|
+
/**
|
|
228
|
+
* Parse a pathname into an array of typed segments used by the router's
|
|
229
|
+
* matcher. Results are optionally cached via an LRU cache.
|
|
230
|
+
*/
|
|
218
231
|
/**
|
|
219
232
|
* Parse a pathname into an array of typed segments used by the router's
|
|
220
233
|
* matcher. Results are optionally cached via an LRU cache.
|
|
@@ -345,12 +358,7 @@ function baseParsePathname(pathname: string): ReadonlyArray<Segment> {
|
|
|
345
358
|
// Handle regular pathname segment
|
|
346
359
|
return {
|
|
347
360
|
type: SEGMENT_TYPE_PATHNAME,
|
|
348
|
-
value: part
|
|
349
|
-
? part
|
|
350
|
-
.split('%25')
|
|
351
|
-
.map((segment) => decodeURI(segment))
|
|
352
|
-
.join('%25')
|
|
353
|
-
: decodeURI(part),
|
|
361
|
+
value: decodePathSegment(part),
|
|
354
362
|
}
|
|
355
363
|
}),
|
|
356
364
|
)
|
|
@@ -388,6 +396,10 @@ type InterPolatePathResult = {
|
|
|
388
396
|
* - Supports `{-$optional}` segments, `{prefix{$id}suffix}` and `{$}` wildcards
|
|
389
397
|
* - Optionally leaves placeholders or wildcards in place
|
|
390
398
|
*/
|
|
399
|
+
/**
|
|
400
|
+
* Interpolate params and wildcards into a route path template.
|
|
401
|
+
* Encodes safely and supports optional params and custom decode char maps.
|
|
402
|
+
*/
|
|
391
403
|
export function interpolatePath({
|
|
392
404
|
path,
|
|
393
405
|
params,
|
|
@@ -514,6 +526,10 @@ function encodePathParam(value: string, decodeCharMap?: Map<string, string>) {
|
|
|
514
526
|
return encoded
|
|
515
527
|
}
|
|
516
528
|
|
|
529
|
+
/**
|
|
530
|
+
* Match a pathname against a route destination and return extracted params
|
|
531
|
+
* or `undefined`. Uses the same parsing as the router for consistency.
|
|
532
|
+
*/
|
|
517
533
|
/**
|
|
518
534
|
* Match a pathname against a route destination and return extracted params
|
|
519
535
|
* or `undefined`. Uses the same parsing as the router for consistency.
|
|
@@ -533,6 +549,7 @@ export function matchPathname(
|
|
|
533
549
|
return pathParams ?? {}
|
|
534
550
|
}
|
|
535
551
|
|
|
552
|
+
/** Low-level matcher that compares two path strings and extracts params. */
|
|
536
553
|
/** Low-level matcher that compares two path strings and extracts params. */
|
|
537
554
|
export function matchByPath(
|
|
538
555
|
from: string,
|
package/src/qss.ts
CHANGED
package/src/rewrite.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { joinPaths, trimPath } from './path'
|
|
2
2
|
import type { LocationRewrite } from './router'
|
|
3
3
|
|
|
4
|
+
/** Compose multiple rewrite pairs into a single in/out rewrite. */
|
|
4
5
|
/** Compose multiple rewrite pairs into a single in/out rewrite. */
|
|
5
6
|
export function composeRewrites(rewrites: Array<LocationRewrite>) {
|
|
6
7
|
return {
|
|
@@ -19,6 +20,7 @@ export function composeRewrites(rewrites: Array<LocationRewrite>) {
|
|
|
19
20
|
} satisfies LocationRewrite
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
/** Create a rewrite pair that strips/adds a basepath on input/output. */
|
|
22
24
|
/** Create a rewrite pair that strips/adds a basepath on input/output. */
|
|
23
25
|
export function rewriteBasepath(opts: {
|
|
24
26
|
basepath: string
|
|
@@ -56,6 +58,7 @@ export function rewriteBasepath(opts: {
|
|
|
56
58
|
} satisfies LocationRewrite
|
|
57
59
|
}
|
|
58
60
|
|
|
61
|
+
/** Execute a location input rewrite if provided. */
|
|
59
62
|
/** Execute a location input rewrite if provided. */
|
|
60
63
|
export function executeRewriteInput(
|
|
61
64
|
rewrite: LocationRewrite | undefined,
|
|
@@ -72,6 +75,7 @@ export function executeRewriteInput(
|
|
|
72
75
|
return url
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
/** Execute a location output rewrite if provided. */
|
|
75
79
|
/** Execute a location output rewrite if provided. */
|
|
76
80
|
export function executeRewriteOutput(
|
|
77
81
|
rewrite: LocationRewrite | undefined,
|
package/src/router.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Store, batch } from '@tanstack/store'
|
|
|
2
2
|
import { createBrowserHistory, parseHref } from '@tanstack/history'
|
|
3
3
|
import {
|
|
4
4
|
createControlledPromise,
|
|
5
|
+
decodePathSegment,
|
|
5
6
|
deepEqual,
|
|
6
7
|
findLast,
|
|
7
8
|
functionalUpdate,
|
|
@@ -1670,16 +1671,18 @@ export class RouterCore<
|
|
|
1670
1671
|
}
|
|
1671
1672
|
}
|
|
1672
1673
|
|
|
1673
|
-
const nextPathname =
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1674
|
+
const nextPathname = decodePathSegment(
|
|
1675
|
+
interpolatePath({
|
|
1676
|
+
// Use the original template path for interpolation
|
|
1677
|
+
// This preserves the original parameter syntax including optional parameters
|
|
1678
|
+
path: nextTo,
|
|
1679
|
+
params: nextParams,
|
|
1680
|
+
leaveWildcards: false,
|
|
1681
|
+
leaveParams: opts.leaveParams,
|
|
1682
|
+
decodeCharMap: this.pathParamsDecodeCharMap,
|
|
1683
|
+
parseCache: this.parsePathnameCache,
|
|
1684
|
+
}).interpolatedPath,
|
|
1685
|
+
)
|
|
1683
1686
|
|
|
1684
1687
|
// Resolve the next search
|
|
1685
1688
|
let nextSearch = fromSearch
|
|
@@ -35,6 +35,7 @@ function getSafeSessionStorage() {
|
|
|
35
35
|
|
|
36
36
|
/** SessionStorage key used to persist scroll restoration state. */
|
|
37
37
|
/** SessionStorage key used to store scroll positions across navigations. */
|
|
38
|
+
/** SessionStorage key used to store scroll positions across navigations. */
|
|
38
39
|
export const storageKey = 'tsr-scroll-restoration-v1_3'
|
|
39
40
|
|
|
40
41
|
const throttle = (fn: (...args: Array<any>) => void, wait: number) => {
|
|
@@ -72,6 +73,7 @@ function createScrollRestorationCache(): ScrollRestorationCache | null {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/** In-memory handle to the persisted scroll restoration cache. */
|
|
75
77
|
/** In-memory handle to the persisted scroll restoration cache. */
|
|
76
78
|
/** In-memory handle to the persisted scroll restoration cache. */
|
|
77
79
|
export const scrollRestorationCache = createScrollRestorationCache()
|
|
@@ -89,6 +91,9 @@ export const scrollRestorationCache = createScrollRestorationCache()
|
|
|
89
91
|
/**
|
|
90
92
|
* Default scroll restoration cache key: location state key or full href.
|
|
91
93
|
*/
|
|
94
|
+
/**
|
|
95
|
+
* Default scroll restoration cache key: location state key or full href.
|
|
96
|
+
*/
|
|
92
97
|
export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
|
|
93
98
|
return location.state.__TSR_key! || location.href
|
|
94
99
|
}
|
|
@@ -112,6 +117,9 @@ let ignoreScroll = false
|
|
|
112
117
|
// unless they are passed in as arguments. Why? Because we need to be able to
|
|
113
118
|
// toString() it into a script tag to execute as early as possible in the browser
|
|
114
119
|
// during SSR. Additionally, we also call it from within the router lifecycle
|
|
120
|
+
/**
|
|
121
|
+
* Restore scroll positions for window/elements based on cached entries.
|
|
122
|
+
*/
|
|
115
123
|
/**
|
|
116
124
|
* Restore scroll positions for window/elements based on cached entries.
|
|
117
125
|
*/
|
|
@@ -214,6 +222,7 @@ export function restoreScroll({
|
|
|
214
222
|
ignoreScroll = false
|
|
215
223
|
}
|
|
216
224
|
|
|
225
|
+
/** Setup global listeners and hooks to support scroll restoration. */
|
|
217
226
|
/** Setup global listeners and hooks to support scroll restoration. */
|
|
218
227
|
export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
|
|
219
228
|
if (!scrollRestorationCache && !router.isServer) {
|
|
@@ -388,6 +397,11 @@ export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
|
|
|
388
397
|
* Provides hash scrolling for programmatic navigation when default browser handling is prevented.
|
|
389
398
|
* @param router The router instance containing current location and state
|
|
390
399
|
*/
|
|
400
|
+
/**
|
|
401
|
+
* @private
|
|
402
|
+
* Handles hash-based scrolling after navigation completes.
|
|
403
|
+
* To be used in framework-specific Transitioners.
|
|
404
|
+
*/
|
|
391
405
|
export function handleHashScroll(router: AnyRouter) {
|
|
392
406
|
if (typeof document !== 'undefined' && (document as any).querySelector) {
|
|
393
407
|
const hashScrollIntoViewOptions =
|
package/src/searchParams.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { decode, encode } from './qss'
|
|
2
2
|
import type { AnySchema } from './validators'
|
|
3
3
|
|
|
4
|
+
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
4
5
|
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
5
6
|
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
|
6
7
|
export const defaultParseSearch = parseSearchWith(JSON.parse)
|
|
8
|
+
/** Default `stringifySearch` using JSON.stringify for complex values. */
|
|
7
9
|
export const defaultStringifySearch = stringifySearchWith(
|
|
8
10
|
JSON.stringify,
|
|
9
11
|
JSON.parse,
|