@tanstack/router-core 1.154.13 → 1.155.0
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/index.d.cts +1 -1
- package/dist/cjs/location.d.cts +0 -27
- package/dist/cjs/new-process-route-tree.cjs +47 -42
- package/dist/cjs/new-process-route-tree.cjs.map +1 -1
- package/dist/cjs/path.cjs +18 -14
- package/dist/cjs/path.cjs.map +1 -1
- package/dist/cjs/path.d.cts +11 -2
- package/dist/cjs/router.cjs +75 -213
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +6 -38
- package/dist/cjs/scroll-restoration.cjs +2 -2
- package/dist/cjs/scroll-restoration.cjs.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/location.d.ts +0 -27
- package/dist/esm/new-process-route-tree.js +47 -42
- package/dist/esm/new-process-route-tree.js.map +1 -1
- package/dist/esm/path.d.ts +11 -2
- package/dist/esm/path.js +18 -14
- package/dist/esm/path.js.map +1 -1
- package/dist/esm/router.d.ts +6 -38
- package/dist/esm/router.js +76 -214
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/scroll-restoration.js +2 -2
- package/dist/esm/scroll-restoration.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +1 -5
- package/src/location.ts +0 -35
- package/src/new-process-route-tree.ts +66 -46
- package/src/path.ts +36 -16
- package/src/router.ts +91 -341
- package/src/scroll-restoration.ts +2 -2
package/dist/cjs/router.d.cts
CHANGED
|
@@ -5,7 +5,7 @@ import { SearchParser, SearchSerializer } from './searchParams.cjs';
|
|
|
5
5
|
import { AnyRedirect, ResolvedRedirect } from './redirect.cjs';
|
|
6
6
|
import { HistoryLocation, HistoryState, ParsedHistoryState, RouterHistory } from '@tanstack/history';
|
|
7
7
|
import { Awaitable, Constrain, ControlledPromise, NoInfer, NonNullableUpdater, PickAsRequired, Updater } from './utils.cjs';
|
|
8
|
-
import {
|
|
8
|
+
import { ParsedLocation } from './location.cjs';
|
|
9
9
|
import { AnyContext, AnyRoute, AnyRouteWithContext, MakeRemountDepsOptionsUnion, RouteLike, RouteMask } from './route.cjs';
|
|
10
10
|
import { FullSearchSchema, RouteById, RoutePaths, RoutesById, RoutesByPath } from './routeInfo.cjs';
|
|
11
11
|
import { AnyRouteMatch, MakeRouteMatchUnion, MatchRouteOptions } from './Matches.cjs';
|
|
@@ -441,13 +441,6 @@ export interface MatchRoutesOpts {
|
|
|
441
441
|
throwOnError?: boolean;
|
|
442
442
|
_buildLocation?: boolean;
|
|
443
443
|
dest?: BuildNextOptions;
|
|
444
|
-
/** Optional match snapshot hint for fast-path (skips path matching) */
|
|
445
|
-
snapshot?: MatchSnapshot;
|
|
446
|
-
}
|
|
447
|
-
export interface MatchRoutesResult {
|
|
448
|
-
matches: Array<AnyRouteMatch>;
|
|
449
|
-
/** Raw string params extracted from path (before parsing) */
|
|
450
|
-
rawParams: Record<string, string>;
|
|
451
444
|
}
|
|
452
445
|
export type InferRouterContext<TRouteTree extends AnyRoute> = TRouteTree['types']['routerContext'];
|
|
453
446
|
export type RouterContextOptions<TRouteTree extends AnyRoute> = AnyContext extends InferRouterContext<TRouteTree> ? {
|
|
@@ -470,14 +463,13 @@ export type GetMatchRoutesFn = (pathname: string) => {
|
|
|
470
463
|
/** exhaustive params, still in their string form */
|
|
471
464
|
routeParams: Record<string, string>;
|
|
472
465
|
/** partial params, parsed from routeParams during matching */
|
|
473
|
-
parsedParams: Record<string, unknown
|
|
466
|
+
parsedParams: Record<string, unknown> | undefined;
|
|
474
467
|
foundRoute: AnyRoute | undefined;
|
|
475
468
|
parseError?: unknown;
|
|
476
469
|
};
|
|
477
470
|
export type EmitFn = (routerEvent: RouterEvent) => void;
|
|
478
471
|
export type LoadFn = (opts?: {
|
|
479
472
|
sync?: boolean;
|
|
480
|
-
_skipUpdateLatestLocation?: boolean;
|
|
481
473
|
}) => Promise<void>;
|
|
482
474
|
export type CommitLocationFn = ({ viewTransition, ignoreBlocker, ...next }: ParsedLocation & CommitLocationOptions) => Promise<void>;
|
|
483
475
|
export type StartTransitionFn = (fn: () => void) => void;
|
|
@@ -574,6 +566,7 @@ export type CreateRouterFn = <TRouteTree extends AnyRoute, TTrailingSlashOption
|
|
|
574
566
|
*/
|
|
575
567
|
export declare class RouterCore<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption, in out TDefaultStructuralSharingOption extends boolean, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> {
|
|
576
568
|
tempLocationKey: string | undefined;
|
|
569
|
+
resetNextScroll: boolean;
|
|
577
570
|
shouldViewTransition?: boolean | ViewTransitionOptions;
|
|
578
571
|
isViewTransitionTypesSupported?: boolean;
|
|
579
572
|
subscribers: Set<RouterListener<RouterEvent>>;
|
|
@@ -587,15 +580,13 @@ export declare class RouterCore<in out TRouteTree extends AnyRoute, in out TTrai
|
|
|
587
580
|
origin?: string;
|
|
588
581
|
latestLocation: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
|
589
582
|
pendingBuiltLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
|
590
|
-
/** Session id for cached history snapshots */
|
|
591
|
-
private sessionId;
|
|
592
583
|
basepath: string;
|
|
593
584
|
routeTree: TRouteTree;
|
|
594
585
|
routesById: RoutesById<TRouteTree>;
|
|
595
586
|
routesByPath: RoutesByPath<TRouteTree>;
|
|
596
587
|
processedTree: ProcessedTree<TRouteTree, any, any>;
|
|
597
588
|
isServer: boolean;
|
|
598
|
-
|
|
589
|
+
pathParamsDecoder?: (encoded: string) => string;
|
|
599
590
|
/**
|
|
600
591
|
* @deprecated Use the `createRouter` function instead
|
|
601
592
|
*/
|
|
@@ -654,9 +645,7 @@ export declare class RouterCore<in out TRouteTree extends AnyRoute, in out TTrai
|
|
|
654
645
|
*/
|
|
655
646
|
navigate: NavigateFn;
|
|
656
647
|
latestLoadPromise: undefined | Promise<void>;
|
|
657
|
-
beforeLoad: (
|
|
658
|
-
_skipUpdateLatestLocation?: boolean;
|
|
659
|
-
}) => void;
|
|
648
|
+
beforeLoad: () => void;
|
|
660
649
|
load: LoadFn;
|
|
661
650
|
startViewTransition: (fn: () => Promise<void>) => void;
|
|
662
651
|
updateMatch: UpdateMatchFn;
|
|
@@ -708,27 +697,6 @@ export declare function getMatchedRoutes<TRouteLike extends RouteLike>({ pathnam
|
|
|
708
697
|
matchedRoutes: readonly TRouteLike[];
|
|
709
698
|
routeParams: Record<string, string>;
|
|
710
699
|
foundRoute: TRouteLike | undefined;
|
|
711
|
-
parsedParams: Record<string, unknown
|
|
700
|
+
parsedParams: Record<string, unknown> | undefined;
|
|
712
701
|
};
|
|
713
|
-
/**
|
|
714
|
-
* Build a MatchSnapshot from a getMatchedRoutes result.
|
|
715
|
-
* Determines globalNotFoundRouteId using the same logic as matchRoutesInternal.
|
|
716
|
-
*/
|
|
717
|
-
export declare function buildMatchSnapshot({ matchResult, pathname, searchStr, notFoundRoute, notFoundMode, }: {
|
|
718
|
-
matchResult: ReturnType<typeof getMatchedRoutes>;
|
|
719
|
-
pathname: string;
|
|
720
|
-
searchStr?: string;
|
|
721
|
-
notFoundRoute?: AnyRoute;
|
|
722
|
-
notFoundMode?: 'root' | 'fuzzy';
|
|
723
|
-
}): MatchSnapshot;
|
|
724
|
-
/**
|
|
725
|
-
* Build a MatchSnapshot from routes and params directly.
|
|
726
|
-
* Used by buildLocation to avoid duplicate getMatchedRoutes call.
|
|
727
|
-
*/
|
|
728
|
-
export declare function buildMatchSnapshotFromRoutes({ routes, params, searchStr, globalNotFoundRouteId, }: {
|
|
729
|
-
routes: ReadonlyArray<AnyRoute>;
|
|
730
|
-
params: Record<string, unknown>;
|
|
731
|
-
searchStr?: string;
|
|
732
|
-
globalNotFoundRouteId?: string;
|
|
733
|
-
}): MatchSnapshot;
|
|
734
702
|
export {};
|
|
@@ -177,8 +177,8 @@ function setupScrollRestoration(router, force) {
|
|
|
177
177
|
}
|
|
178
178
|
router.subscribe("onRendered", (event) => {
|
|
179
179
|
const cacheKey = getKey(event.toLocation);
|
|
180
|
-
|
|
181
|
-
|
|
180
|
+
if (!router.resetNextScroll) {
|
|
181
|
+
router.resetNextScroll = true;
|
|
182
182
|
return;
|
|
183
183
|
}
|
|
184
184
|
if (typeof router.options.scrollRestoration === "function") {
|
|
@@ -1 +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'\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 try {\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n } catch {\n console.warn(\n '[ts-router] Could not persist scroll restoration state to sessionStorage.',\n )\n }\n },\n }\n}\n\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 */\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\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 const resetScroll = event.toLocation.state.__TSR_resetScroll ?? true\n if (!resetScroll) {\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 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":["functionalUpdate","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,SA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AAEA,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAGA,MAAI,OAAO,aAAa,aAAa;AACnC,aAAS,iBAAiB,UAAU,SAAS,UAAU,GAAG,GAAG,IAAI;AAAA,EACnE;AAEA,SAAO,UAAU,cAAc,CAAC,UAAU;AAGxC,UAAM,WAAW,OAAO,MAAM,UAAU;AAIxC,UAAM,cAAc,MAAM,WAAW,MAAM,qBAAqB;AAChE,QAAI,CAAC,aAAa;AAChB;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;AAeO,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.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'\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 try {\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n } catch {\n console.warn(\n '[ts-router] Could not persist scroll restoration state to sessionStorage.',\n )\n }\n },\n }\n}\n\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 */\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\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 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":["functionalUpdate","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,+BAA8D;AACrE,QAAM,qBAAqB,sBAAA;AAC3B,MAAI,CAAC,oBAAoB;AACvB,WAAO;AAAA,EACT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AM,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;AAeO,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;;;;;;;;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export type { IsRequiredParams, AddTrailingSlash, RemoveTrailingSlashes, AddLead
|
|
|
6
6
|
export { componentTypes } from './load-matches.js';
|
|
7
7
|
export type { RouteToPath, TrailingSlashOptionByRouter, ParseRoute, CodeRouteToPath, RouteIds, FullSearchSchema, FullSearchSchemaInput, AllParams, RouteById, AllContext, RoutePaths, RoutesById, RoutesByPath, AllLoaderData, RouteByPath, } from './routeInfo.js';
|
|
8
8
|
export type { InferFileRouteTypes, FileRouteTypes, FileRoutesByPath, CreateFileRoute, LazyRoute, LazyRouteOptions, CreateLazyFileRoute, } from './fileRoute.js';
|
|
9
|
-
export type {
|
|
9
|
+
export type { ParsedLocation } from './location.js';
|
|
10
10
|
export type { Manifest, RouterManagedTag } from './manifest.js';
|
|
11
11
|
export { isMatch } from './Matches.js';
|
|
12
12
|
export type { AnyMatchAndValue, FindValueByIndex, FindValueByKey, CreateMatchAndValue, NextMatchAndValue, IsMatchKeyOf, IsMatchPath, IsMatchResult, IsMatchParse, IsMatch, RouteMatch, RouteMatchExtensions, MakeRouteMatchUnion, MakeRouteMatch, AnyRouteMatch, MakeRouteMatchFromRoute, MatchRouteOptions, } from './Matches.js';
|
package/dist/esm/location.d.ts
CHANGED
|
@@ -1,32 +1,5 @@
|
|
|
1
1
|
import { ParsedHistoryState } from '@tanstack/history';
|
|
2
2
|
import { AnySchema } from './validators.js';
|
|
3
|
-
/**
|
|
4
|
-
* Per-route validated search result cached in snapshot.
|
|
5
|
-
*/
|
|
6
|
-
export interface ValidatedSearchEntry {
|
|
7
|
-
/** Merged search (parent + this route's validated) */
|
|
8
|
-
search: Record<string, unknown>;
|
|
9
|
-
/** Strict search (only this route's validated fields) */
|
|
10
|
-
strictSearch: Record<string, unknown>;
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Match snapshot stored in history state for fast-path on back/forward navigation.
|
|
14
|
-
* Allows skipping path matching by storing route IDs and params.
|
|
15
|
-
*/
|
|
16
|
-
export interface MatchSnapshot {
|
|
17
|
-
/** Ordered route IDs that matched */
|
|
18
|
-
routeIds: Array<string>;
|
|
19
|
-
/** Raw path params extracted from the URL */
|
|
20
|
-
params: Record<string, string>;
|
|
21
|
-
/** Parsed/validated path params */
|
|
22
|
-
parsedParams: Record<string, unknown>;
|
|
23
|
-
/** Route ID that should show global not found, if any */
|
|
24
|
-
globalNotFoundRouteId?: string;
|
|
25
|
-
/** Search string when snapshot was created (for cache invalidation) */
|
|
26
|
-
searchStr?: string;
|
|
27
|
-
/** Per-route validated search results (parallel to routeIds) */
|
|
28
|
-
validatedSearches?: Array<ValidatedSearchEntry>;
|
|
29
|
-
}
|
|
30
3
|
export interface ParsedLocation<TSearchObj extends AnySchema = {}> {
|
|
31
4
|
/**
|
|
32
5
|
* The full path of the location, including pathname, search, and hash.
|
|
@@ -7,9 +7,15 @@ const SEGMENT_TYPE_WILDCARD = 2;
|
|
|
7
7
|
const SEGMENT_TYPE_OPTIONAL_PARAM = 3;
|
|
8
8
|
const SEGMENT_TYPE_INDEX = 4;
|
|
9
9
|
const SEGMENT_TYPE_PATHLESS = 5;
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
10
|
+
function getOpenAndCloseBraces(part) {
|
|
11
|
+
const openBrace = part.indexOf("{");
|
|
12
|
+
if (openBrace === -1) return null;
|
|
13
|
+
const closeBrace = part.indexOf("}", openBrace);
|
|
14
|
+
if (closeBrace === -1) return null;
|
|
15
|
+
const afterOpen = openBrace + 1;
|
|
16
|
+
if (afterOpen >= part.length) return null;
|
|
17
|
+
return [openBrace, closeBrace];
|
|
18
|
+
}
|
|
13
19
|
function parseSegment(path, start, output = new Uint16Array(6)) {
|
|
14
20
|
const next = path.indexOf("/", start);
|
|
15
21
|
const end = next === -1 ? path.length : next;
|
|
@@ -42,45 +48,44 @@ function parseSegment(path, start, output = new Uint16Array(6)) {
|
|
|
42
48
|
output[5] = end;
|
|
43
49
|
return output;
|
|
44
50
|
}
|
|
45
|
-
const
|
|
46
|
-
if (
|
|
47
|
-
const
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
return output;
|
|
51
|
+
const braces = getOpenAndCloseBraces(part);
|
|
52
|
+
if (braces) {
|
|
53
|
+
const [openBrace, closeBrace] = braces;
|
|
54
|
+
const firstChar = part.charCodeAt(openBrace + 1);
|
|
55
|
+
if (firstChar === 45) {
|
|
56
|
+
if (openBrace + 2 < part.length && part.charCodeAt(openBrace + 2) === 36) {
|
|
57
|
+
const paramStart = openBrace + 3;
|
|
58
|
+
const paramEnd = closeBrace;
|
|
59
|
+
if (paramStart < paramEnd) {
|
|
60
|
+
output[0] = SEGMENT_TYPE_OPTIONAL_PARAM;
|
|
61
|
+
output[1] = start + openBrace;
|
|
62
|
+
output[2] = start + paramStart;
|
|
63
|
+
output[3] = start + paramEnd;
|
|
64
|
+
output[4] = start + closeBrace + 1;
|
|
65
|
+
output[5] = end;
|
|
66
|
+
return output;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} else if (firstChar === 36) {
|
|
70
|
+
const dollarPos = openBrace + 1;
|
|
71
|
+
const afterDollar = openBrace + 2;
|
|
72
|
+
if (afterDollar === closeBrace) {
|
|
73
|
+
output[0] = SEGMENT_TYPE_WILDCARD;
|
|
74
|
+
output[1] = start + openBrace;
|
|
75
|
+
output[2] = start + dollarPos;
|
|
76
|
+
output[3] = start + afterDollar;
|
|
77
|
+
output[4] = start + closeBrace + 1;
|
|
78
|
+
output[5] = path.length;
|
|
79
|
+
return output;
|
|
80
|
+
}
|
|
81
|
+
output[0] = SEGMENT_TYPE_PARAM;
|
|
82
|
+
output[1] = start + openBrace;
|
|
83
|
+
output[2] = start + afterDollar;
|
|
84
|
+
output[3] = start + closeBrace;
|
|
85
|
+
output[4] = start + closeBrace + 1;
|
|
86
|
+
output[5] = end;
|
|
87
|
+
return output;
|
|
88
|
+
}
|
|
84
89
|
}
|
|
85
90
|
output[0] = SEGMENT_TYPE_PATHNAME;
|
|
86
91
|
output[1] = start;
|