@tanstack/react-router 1.0.0 → 1.0.1

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.
Files changed (136) hide show
  1. package/build/cjs/RouterProvider.js +3 -1
  2. package/build/cjs/RouterProvider.js.map +1 -1
  3. package/build/esm/index.js +3 -1
  4. package/build/esm/index.js.map +1 -1
  5. package/build/stats-html.html +1 -1
  6. package/build/stats-react.json +361 -361
  7. package/build/types/index.d.ts +24 -932
  8. package/build/umd/index.development.js +3 -1
  9. package/build/umd/index.development.js.map +1 -1
  10. package/build/umd/index.production.js +1 -1
  11. package/build/umd/index.production.js.map +1 -1
  12. package/package.json +2 -2
  13. package/src/RouterProvider.tsx +3 -1
  14. package/build/cjs/_virtual/with-selector.development.js +0 -16
  15. package/build/cjs/_virtual/with-selector.development.js.map +0 -1
  16. package/build/cjs/_virtual/with-selector.js +0 -16
  17. package/build/cjs/_virtual/with-selector.js.map +0 -1
  18. package/build/cjs/_virtual/with-selector.production.min.js +0 -16
  19. package/build/cjs/_virtual/with-selector.production.min.js.map +0 -1
  20. package/build/cjs/build/esm/index.js +0 -79
  21. package/build/cjs/build/esm/index.js.map +0 -1
  22. package/build/cjs/node_modules/.pnpm/@tanstack_react-store@0.2.1_react-dom@18.2.0_react@18.2.0/node_modules/@tanstack/react-store/build/modern/index.js +0 -47
  23. package/build/cjs/node_modules/.pnpm/@tanstack_react-store@0.2.1_react-dom@18.2.0_react@18.2.0/node_modules/@tanstack/react-store/build/modern/index.js.map +0 -1
  24. package/build/cjs/node_modules/.pnpm/@tanstack_store@0.1.3/node_modules/@tanstack/store/build/modern/index.js +0 -70
  25. package/build/cjs/node_modules/.pnpm/@tanstack_store@0.1.3/node_modules/@tanstack/store/build/modern/index.js.map +0 -1
  26. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js +0 -188
  27. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js.map +0 -1
  28. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js +0 -39
  29. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js.map +0 -1
  30. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/shim/with-selector.js +0 -26
  31. package/build/cjs/node_modules/.pnpm/use-sync-external-store@1.2.0_react@18.2.0/node_modules/use-sync-external-store/shim/with-selector.js.map +0 -1
  32. package/build/cjs/packages/react-router/src/CatchBoundary.js +0 -123
  33. package/build/cjs/packages/react-router/src/CatchBoundary.js.map +0 -1
  34. package/build/cjs/packages/react-router/src/Matches.js +0 -235
  35. package/build/cjs/packages/react-router/src/Matches.js.map +0 -1
  36. package/build/cjs/packages/react-router/src/RouterProvider.js +0 -144
  37. package/build/cjs/packages/react-router/src/RouterProvider.js.map +0 -1
  38. package/build/cjs/packages/react-router/src/awaited.js +0 -43
  39. package/build/cjs/packages/react-router/src/awaited.js.map +0 -1
  40. package/build/cjs/packages/react-router/src/defer.js +0 -37
  41. package/build/cjs/packages/react-router/src/defer.js.map +0 -1
  42. package/build/cjs/packages/react-router/src/fileRoute.js +0 -27
  43. package/build/cjs/packages/react-router/src/fileRoute.js.map +0 -1
  44. package/build/cjs/packages/react-router/src/index.js +0 -61
  45. package/build/cjs/packages/react-router/src/index.js.map +0 -1
  46. package/build/cjs/packages/react-router/src/lazyRouteComponent.js +0 -54
  47. package/build/cjs/packages/react-router/src/lazyRouteComponent.js.map +0 -1
  48. package/build/cjs/packages/react-router/src/link.js +0 -148
  49. package/build/cjs/packages/react-router/src/link.js.map +0 -1
  50. package/build/cjs/packages/react-router/src/path.js +0 -209
  51. package/build/cjs/packages/react-router/src/path.js.map +0 -1
  52. package/build/cjs/packages/react-router/src/qss.js +0 -63
  53. package/build/cjs/packages/react-router/src/qss.js.map +0 -1
  54. package/build/cjs/packages/react-router/src/react.js +0 -634
  55. package/build/cjs/packages/react-router/src/react.js.map +0 -1
  56. package/build/cjs/packages/react-router/src/redirects.js +0 -25
  57. package/build/cjs/packages/react-router/src/redirects.js.map +0 -1
  58. package/build/cjs/packages/react-router/src/route.js +0 -134
  59. package/build/cjs/packages/react-router/src/route.js.map +0 -1
  60. package/build/cjs/packages/react-router/src/router.js +0 -1111
  61. package/build/cjs/packages/react-router/src/router.js.map +0 -1
  62. package/build/cjs/packages/react-router/src/scroll-restoration.js +0 -53
  63. package/build/cjs/packages/react-router/src/scroll-restoration.js.map +0 -1
  64. package/build/cjs/packages/react-router/src/searchParams.js +0 -81
  65. package/build/cjs/packages/react-router/src/searchParams.js.map +0 -1
  66. package/build/cjs/packages/react-router/src/useBlocker.js +0 -61
  67. package/build/cjs/packages/react-router/src/useBlocker.js.map +0 -1
  68. package/build/cjs/packages/react-router/src/useNavigate.js +0 -75
  69. package/build/cjs/packages/react-router/src/useNavigate.js.map +0 -1
  70. package/build/cjs/packages/react-router/src/useParams.js +0 -26
  71. package/build/cjs/packages/react-router/src/useParams.js.map +0 -1
  72. package/build/cjs/packages/react-router/src/useSearch.js +0 -25
  73. package/build/cjs/packages/react-router/src/useSearch.js.map +0 -1
  74. package/build/cjs/packages/react-router/src/utils.js +0 -239
  75. package/build/cjs/packages/react-router/src/utils.js.map +0 -1
  76. package/build/cjs/react/CatchBoundary.js +0 -123
  77. package/build/cjs/react/CatchBoundary.js.map +0 -1
  78. package/build/cjs/react/awaited.js +0 -43
  79. package/build/cjs/react/awaited.js.map +0 -1
  80. package/build/cjs/react/defer.js +0 -37
  81. package/build/cjs/react/defer.js.map +0 -1
  82. package/build/cjs/react.js +0 -650
  83. package/build/cjs/react.js.map +0 -1
  84. package/build/cjs/routerConfig.js +0 -209
  85. package/build/cjs/routerConfig.js.map +0 -1
  86. package/build/cjs/src/CatchBoundary.js +0 -126
  87. package/build/cjs/src/CatchBoundary.js.map +0 -1
  88. package/build/cjs/src/Matches.js +0 -235
  89. package/build/cjs/src/Matches.js.map +0 -1
  90. package/build/cjs/src/RouterProvider.js +0 -1051
  91. package/build/cjs/src/RouterProvider.js.map +0 -1
  92. package/build/cjs/src/awaited.js +0 -45
  93. package/build/cjs/src/awaited.js.map +0 -1
  94. package/build/cjs/src/defer.js +0 -39
  95. package/build/cjs/src/defer.js.map +0 -1
  96. package/build/cjs/src/fileRoute.js +0 -29
  97. package/build/cjs/src/fileRoute.js.map +0 -1
  98. package/build/cjs/src/index.js +0 -134
  99. package/build/cjs/src/index.js.map +0 -1
  100. package/build/cjs/src/lazyRouteComponent.js +0 -57
  101. package/build/cjs/src/lazyRouteComponent.js.map +0 -1
  102. package/build/cjs/src/link.js +0 -151
  103. package/build/cjs/src/link.js.map +0 -1
  104. package/build/cjs/src/path.js +0 -211
  105. package/build/cjs/src/path.js.map +0 -1
  106. package/build/cjs/src/qss.js +0 -65
  107. package/build/cjs/src/qss.js.map +0 -1
  108. package/build/cjs/src/redirects.js +0 -27
  109. package/build/cjs/src/redirects.js.map +0 -1
  110. package/build/cjs/src/route.js +0 -139
  111. package/build/cjs/src/route.js.map +0 -1
  112. package/build/cjs/src/router.js +0 -203
  113. package/build/cjs/src/router.js.map +0 -1
  114. package/build/cjs/src/scroll-restoration.js +0 -186
  115. package/build/cjs/src/scroll-restoration.js.map +0 -1
  116. package/build/cjs/src/searchParams.js +0 -83
  117. package/build/cjs/src/searchParams.js.map +0 -1
  118. package/build/cjs/src/useBlocker.js +0 -64
  119. package/build/cjs/src/useBlocker.js.map +0 -1
  120. package/build/cjs/src/useNavigate.js +0 -78
  121. package/build/cjs/src/useNavigate.js.map +0 -1
  122. package/build/cjs/src/useParams.js +0 -28
  123. package/build/cjs/src/useParams.js.map +0 -1
  124. package/build/cjs/src/useSearch.js +0 -27
  125. package/build/cjs/src/useSearch.js.map +0 -1
  126. package/build/cjs/src/utils.js +0 -230
  127. package/build/cjs/src/utils.js.map +0 -1
  128. package/build/cjs/useStore.js +0 -99
  129. package/build/cjs/useStore.js.map +0 -1
  130. package/build/types/RouteMatch.d.ts +0 -23
  131. package/build/types/injectHtml.d.ts +0 -0
  132. package/build/types/react/CatchBoundary.d.ts +0 -33
  133. package/build/types/react/awaited.d.ts +0 -9
  134. package/build/types/react/defer.d.ts +0 -19
  135. package/build/types/react.d.ts +0 -141
  136. package/build/types/useStore.d.ts +0 -12
@@ -1,139 +0,0 @@
1
- /**
2
- * @tanstack/react-router/src/index.tsx
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var invariant = require('tiny-invariant');
16
- var Matches = require('./Matches.js');
17
- var path = require('./path.js');
18
- var useParams = require('./useParams.js');
19
- var useSearch = require('./useSearch.js');
20
-
21
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
22
-
23
- var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
24
-
25
- const rootRouteId = '__root__';
26
-
27
- // The parse type here allows a zod schema to be passed directly to the validator
28
-
29
- class Route {
30
- // Set up in this.init()
31
-
32
- // customId!: TCustomId
33
-
34
- // Optional
35
-
36
- constructor(options) {
37
- this.options = options || {};
38
- this.isRoot = !options?.getParentRoute;
39
- Route.__onInit(this);
40
- }
41
- init = opts => {
42
- this.originalIndex = opts.originalIndex;
43
- const options = this.options;
44
- const isRoot = !options?.path && !options?.id;
45
- this.parentRoute = this.options?.getParentRoute?.();
46
- if (isRoot) {
47
- this.path = rootRouteId;
48
- } else {
49
- invariant__default["default"](this.parentRoute, `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`);
50
- }
51
- let path$1 = isRoot ? rootRouteId : options.path;
52
-
53
- // If the path is anything other than an index path, trim it up
54
- if (path$1 && path$1 !== '/') {
55
- path$1 = path.trimPath(path$1);
56
- }
57
- const customId = options?.id || path$1;
58
-
59
- // Strip the parentId prefix from the first level of children
60
- let id = isRoot ? rootRouteId : path.joinPaths([this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, customId]);
61
- if (path$1 === rootRouteId) {
62
- path$1 = '/';
63
- }
64
- if (id !== rootRouteId) {
65
- id = path.joinPaths(['/', id]);
66
- }
67
- const fullPath = id === rootRouteId ? '/' : path.joinPaths([this.parentRoute.fullPath, path$1]);
68
- this.path = path$1;
69
- this.id = id;
70
- // this.customId = customId as TCustomId
71
- this.fullPath = fullPath;
72
- this.to = fullPath;
73
- };
74
- addChildren = children => {
75
- this.children = children;
76
- return this;
77
- };
78
- update = options => {
79
- Object.assign(this.options, options);
80
- return this;
81
- };
82
- static __onInit = route => {
83
- // This is a dummy static method that should get
84
- // replaced by a framework specific implementation if necessary
85
- };
86
- useMatch = opts => {
87
- return Matches.useMatch({
88
- ...opts,
89
- from: this.id
90
- });
91
- };
92
- useRouteContext = opts => {
93
- return Matches.useMatch({
94
- ...opts,
95
- from: this.id,
96
- select: d => opts?.select ? opts.select(d.context) : d.context
97
- });
98
- };
99
- useSearch = opts => {
100
- return useSearch.useSearch({
101
- ...opts,
102
- from: this.id
103
- });
104
- };
105
- useParams = opts => {
106
- return useParams.useParams({
107
- ...opts,
108
- from: this.id
109
- });
110
- };
111
- useLoaderData = opts => {
112
- return Matches.useLoaderData({
113
- ...opts,
114
- from: this.id
115
- });
116
- };
117
- }
118
- function rootRouteWithContext() {
119
- return options => {
120
- return new RootRoute(options);
121
- };
122
- }
123
- class RootRoute extends Route {
124
- constructor(options) {
125
- super(options);
126
- }
127
- }
128
- function createRouteMask(opts) {
129
- return opts;
130
- }
131
-
132
- //
133
-
134
- exports.RootRoute = RootRoute;
135
- exports.Route = Route;
136
- exports.createRouteMask = createRouteMask;
137
- exports.rootRouteId = rootRouteId;
138
- exports.rootRouteWithContext = rootRouteWithContext;
139
- //# sourceMappingURL=route.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"route.js","sources":["../../../src/route.ts"],"sourcesContent":["import { HistoryLocation } from '@tanstack/history'\nimport * as React from 'react'\nimport invariant from 'tiny-invariant'\nimport { useLoaderData, useMatch } from './Matches'\nimport { AnyRouteMatch } from './RouterProvider'\nimport { NavigateOptions, ParsePathParams, ToSubOptions } from './link'\nimport { ParsedLocation } from './location'\nimport { joinPaths, trimPath } from './path'\nimport { RoutePaths } from './routeInfo'\nimport { AnyRouter } from './router'\nimport { useParams } from './useParams'\nimport { useSearch } from './useSearch'\nimport {\n Assign,\n Expand,\n IsAny,\n NoInfer,\n PickRequired,\n UnionToIntersection,\n} from './utils'\nimport { BuildLocationFn, NavigateFn } from './RouterProvider'\n\nexport const rootRouteId = '__root__' as const\nexport type RootRouteId = typeof rootRouteId\nexport type AnyPathParams = {}\n\nexport type AnySearchSchema = {}\n\nexport type AnyContext = {}\n\nexport interface RouteContext {}\n\nexport interface RouteMeta {}\n\nexport type PreloadableObj = { preload?: () => Promise<void> }\n\nexport type RoutePathOptions<TCustomId, TPath> =\n | {\n path: TPath\n }\n | {\n id: TCustomId\n }\n\nexport type RoutePathOptionsIntersection<TCustomId, TPath> =\n UnionToIntersection<RoutePathOptions<TCustomId, TPath>>\n\nexport type MetaOptions = keyof PickRequired<RouteMeta> extends never\n ? {\n meta?: RouteMeta\n }\n : {\n meta: RouteMeta\n }\n\nexport type RouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TSearchSchema extends Record<string, any> = {},\n TFullSearchSchema extends Record<string, any> = TSearchSchema,\n TParams extends AnyPathParams = AnyPathParams,\n TAllParams extends AnyPathParams = TParams,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends Record<string, any> = AnyContext,\n TLoaderData extends any = unknown,\n> = BaseRouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TRouteContext,\n TAllContext,\n TLoaderData\n> &\n NoInfer<\n UpdatableRouteOptions<\n TFullSearchSchema,\n TAllParams,\n TAllContext,\n TLoaderData\n >\n >\n\nexport type ParamsFallback<\n TPath extends string,\n TParams,\n> = unknown extends TParams ? Record<ParsePathParams<TPath>, string> : TParams\n\ntype Prefix<T extends string, U extends string> = U extends `${T}${infer _}`\n ? U\n : never\n\nexport type BaseRouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TSearchSchema extends Record<string, any> = {},\n TFullSearchSchema extends Record<string, any> = TSearchSchema,\n TParams extends AnyPathParams = {},\n TAllParams = ParamsFallback<TPath, TParams>,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends Record<string, any> = AnyContext,\n TLoaderData extends any = unknown,\n> = RoutePathOptions<TCustomId, TPath> & {\n getParentRoute: () => TParentRoute\n validateSearch?: SearchSchemaValidator<TSearchSchema>\n shouldReload?:\n | boolean\n | ((\n match: LoaderFnContext<\n TAllParams,\n TFullSearchSchema,\n TAllContext,\n TRouteContext\n >,\n ) => any)\n} & (keyof PickRequired<RouteContext> extends never\n ? // This async function is called before a route is loaded.\n // If an error is thrown here, the route's loader will not be called.\n // If thrown during a navigation, the navigation will be cancelled and the error will be passed to the `onError` function.\n // If thrown during a preload event, the error will be logged to the console.\n {\n beforeLoad?: BeforeLoadFn<\n TFullSearchSchema,\n TParentRoute,\n TAllParams,\n TRouteContext\n >\n }\n : {\n beforeLoad: BeforeLoadFn<\n TFullSearchSchema,\n TParentRoute,\n TAllParams,\n TRouteContext\n >\n }) & {\n loader?: RouteLoadFn<\n TAllParams,\n TFullSearchSchema,\n NoInfer<TAllContext>,\n NoInfer<TRouteContext>,\n TLoaderData\n >\n } & (\n | {\n // Both or none\n parseParams?: (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n ) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n stringifyParams?: (\n params: NoInfer<ParamsFallback<TPath, TParams>>,\n ) => Record<ParsePathParams<TPath>, string>\n }\n | {\n stringifyParams?: never\n parseParams?: never\n }\n )\n\ntype BeforeLoadFn<\n TFullSearchSchema extends Record<string, any>,\n TParentRoute extends AnyRoute,\n TAllParams,\n TRouteContext,\n> = (opts: {\n search: TFullSearchSchema\n abortController: AbortController\n preload: boolean\n params: TAllParams\n context: TParentRoute['types']['allContext']\n location: ParsedLocation\n navigate: NavigateFn<AnyRoute>\n buildLocation: BuildLocationFn<AnyRoute>\n}) => Promise<TRouteContext> | TRouteContext | void\n\nexport type UpdatableRouteOptions<\n TFullSearchSchema extends Record<string, any>,\n TAllParams extends AnyPathParams,\n TAllContext extends AnyContext,\n TLoaderData extends any = unknown,\n> = MetaOptions & {\n // test?: (args: TAllContext) => void\n // If true, this route will be matched as case-sensitive\n caseSensitive?: boolean\n // If true, this route will be forcefully wrapped in a suspense boundary\n wrapInSuspense?: boolean\n // The content to be rendered when the route is matched. If no component is provided, defaults to `<Outlet />`\n component?: RouteComponent<\n TFullSearchSchema,\n TAllParams,\n TAllContext,\n TLoaderData\n >\n // The content to be rendered when the route encounters an error\n errorComponent?: ErrorRouteComponent<\n TFullSearchSchema,\n TAllParams,\n {}\n // TAllContext // TODO: I have no idea why this breaks the universe,\n // so we'll come back to it later.\n > //\n // If supported by your framework, the content to be rendered as the fallback content until the route is ready to render\n pendingComponent?: PendingRouteComponent<\n TFullSearchSchema,\n TAllParams,\n TAllContext\n >\n // Filter functions that can manipulate search params *before* they are passed to links and navigate\n // calls that match this route.\n preSearchFilters?: SearchFilter<TFullSearchSchema>[]\n // Filter functions that can manipulate search params *after* they are passed to links and navigate\n // calls that match this route.\n postSearchFilters?: SearchFilter<TFullSearchSchema>[]\n onError?: (err: any) => void\n // These functions are called as route matches are loaded, stick around and leave the active\n // matches\n onEnter?: (match: AnyRouteMatch) => void\n onTransition?: (match: AnyRouteMatch) => void\n onLeave?: (match: AnyRouteMatch) => void\n // Set this to true or false to specifically set whether or not this route should be preloaded. If unset, will\n // default to router.options.reloadOnWindowFocus\n reloadOnWindowFocus?: boolean\n}\n\nexport type ParseParamsOption<TPath extends string, TParams> = ParseParamsFn<\n TPath,\n TParams\n>\n\nexport type ParseParamsFn<TPath extends string, TParams> = (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n\nexport type ParseParamsObj<TPath extends string, TParams> = {\n parse?: ParseParamsFn<TPath, TParams>\n}\n\n// The parse type here allows a zod schema to be passed directly to the validator\nexport type SearchSchemaValidator<TReturn> =\n | SearchSchemaValidatorObj<TReturn>\n | SearchSchemaValidatorFn<TReturn>\n\nexport type SearchSchemaValidatorObj<TReturn> = {\n parse?: SearchSchemaValidatorFn<TReturn>\n}\n\nexport type SearchSchemaValidatorFn<TReturn> = (\n searchObj: Record<string, unknown>,\n) => TReturn\n\nexport type DefinedPathParamWarning =\n 'Path params cannot be redefined by child routes!'\n\nexport type ParentParams<TParentParams> = AnyPathParams extends TParentParams\n ? {}\n : {\n [Key in keyof TParentParams]?: DefinedPathParamWarning\n }\n\nexport type RouteLoadFn<\n TAllParams = {},\n TFullSearchSchema extends Record<string, any> = {},\n TAllContext extends Record<string, any> = AnyContext,\n TRouteContext extends Record<string, any> = AnyContext,\n TLoaderData extends any = unknown,\n> = (\n match: LoaderFnContext<\n TAllParams,\n TFullSearchSchema,\n TAllContext,\n TRouteContext\n >,\n) => Promise<TLoaderData> | TLoaderData\n\nexport interface LoaderFnContext<\n TAllParams = {},\n TFullSearchSchema extends Record<string, any> = {},\n TAllContext extends Record<string, any> = AnyContext,\n TRouteContext extends Record<string, any> = AnyContext,\n> {\n abortController: AbortController\n preload: boolean\n params: TAllParams\n search: TFullSearchSchema\n context: Expand<Assign<TAllContext, TRouteContext>>\n location: ParsedLocation<TFullSearchSchema>\n navigate: (opts: NavigateOptions<AnyRoute>) => Promise<void>\n parentMatchPromise?: Promise<void>\n cause: 'enter' | 'stay'\n}\n\nexport type SearchFilter<T, U = T> = (prev: T) => U\n\nexport type ResolveId<\n TParentRoute,\n TCustomId extends string,\n TPath extends string,\n> = TParentRoute extends { id: infer TParentId extends string }\n ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId>\n : RootRouteId\n\nexport type InferFullSearchSchema<TRoute> = TRoute extends {\n types: {\n fullSearchSchema: infer TFullSearchSchema\n }\n}\n ? TFullSearchSchema\n : {}\n\nexport type ResolveFullSearchSchema<TParentRoute, TSearchSchema> = Expand<\n Assign<InferFullSearchSchema<TParentRoute>, TSearchSchema>\n>\n\nexport interface AnyRoute\n extends Route<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n > {}\n\nexport type MergeFromFromParent<T, U> = IsAny<T, U, T & U>\n\nexport type StreamedPromise<T> = {\n promise: Promise<T>\n status: 'resolved' | 'pending'\n data: T\n resolve: (value: T) => void\n}\n\nexport type ResolveAllParams<\n TParentRoute extends AnyRoute,\n TParams extends AnyPathParams,\n> = Record<never, string> extends TParentRoute['types']['allParams']\n ? TParams\n : Expand<\n UnionToIntersection<TParentRoute['types']['allParams'] & TParams> & {}\n >\n\nexport type RouteConstraints = {\n TParentRoute: AnyRoute\n TPath: string\n TFullPath: string\n TCustomId: string\n TId: string\n TSearchSchema: AnySearchSchema\n TFullSearchSchema: AnySearchSchema\n TParams: Record<string, any>\n TAllParams: Record<string, any>\n TParentContext: AnyContext\n TRouteContext: RouteContext\n TAllContext: AnyContext\n TRouterContext: AnyContext\n TChildren: unknown\n TRouteTree: AnyRoute\n}\n\nexport class Route<\n TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,\n TPath extends RouteConstraints['TPath'] = '/',\n TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<\n TParentRoute,\n TPath\n >,\n TCustomId extends RouteConstraints['TCustomId'] = string,\n TId extends RouteConstraints['TId'] = ResolveId<\n TParentRoute,\n TCustomId,\n TPath\n >,\n TSearchSchema extends RouteConstraints['TSearchSchema'] = {},\n TFullSearchSchema extends RouteConstraints['TFullSearchSchema'] = ResolveFullSearchSchema<\n TParentRoute,\n TSearchSchema\n >,\n TParams extends RouteConstraints['TParams'] = Expand<\n Record<ParsePathParams<TPath>, string>\n >,\n TAllParams extends RouteConstraints['TAllParams'] = ResolveAllParams<\n TParentRoute,\n TParams\n >,\n TRouteContext extends RouteConstraints['TRouteContext'] = RouteContext,\n TAllContext extends Expand<\n Assign<IsAny<TParentRoute['types']['allContext'], {}>, TRouteContext>\n > = Expand<\n Assign<IsAny<TParentRoute['types']['allContext'], {}>, TRouteContext>\n >,\n TRouterContext extends RouteConstraints['TRouterContext'] = AnyContext,\n TLoaderData extends any = unknown,\n TChildren extends RouteConstraints['TChildren'] = unknown,\n TRouteTree extends RouteConstraints['TRouteTree'] = AnyRoute,\n> {\n isRoot: TParentRoute extends Route<any> ? true : false\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TRouteContext,\n TAllContext,\n TLoaderData\n >\n\n test!: Expand<\n Assign<IsAny<TParentRoute['types']['allContext'], {}>, TRouteContext>\n >\n\n // Set up in this.init()\n parentRoute!: TParentRoute\n id!: TId\n // customId!: TCustomId\n path!: TPath\n fullPath!: TFullPath\n to!: TrimPathRight<TFullPath>\n\n // Optional\n children?: TChildren\n originalIndex?: number\n router?: AnyRouter\n rank!: number\n\n constructor(\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TRouteContext,\n TAllContext,\n TLoaderData\n >,\n ) {\n this.options = (options as any) || {}\n this.isRoot = !options?.getParentRoute as any\n Route.__onInit(this)\n }\n\n types!: {\n parentRoute: TParentRoute\n path: TPath\n to: TrimPathRight<TFullPath>\n fullPath: TFullPath\n customId: TCustomId\n id: TId\n searchSchema: TSearchSchema\n fullSearchSchema: TFullSearchSchema\n params: TParams\n allParams: TAllParams\n routeContext: TRouteContext\n allContext: TAllContext\n children: TChildren\n routeTree: TRouteTree\n routerContext: TRouterContext\n loaderData: TLoaderData\n }\n\n init = (opts: { originalIndex: number }) => {\n this.originalIndex = opts.originalIndex\n\n const options = this.options as RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TRouteContext,\n TAllContext,\n TLoaderData\n > &\n RoutePathOptionsIntersection<TCustomId, TPath>\n\n const isRoot = !options?.path && !options?.id\n\n this.parentRoute = this.options?.getParentRoute?.()\n\n if (isRoot) {\n this.path = rootRouteId as TPath\n } else {\n invariant(\n this.parentRoute,\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPath(path)\n }\n\n const customId = options?.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n (this.parentRoute.id as any) === rootRouteId\n ? ''\n : this.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path])\n\n this.path = path as TPath\n this.id = id as TId\n // this.customId = customId as TCustomId\n this.fullPath = fullPath as TFullPath\n this.to = fullPath as TrimPathRight<TFullPath>\n }\n\n addChildren = <TNewChildren extends AnyRoute[]>(\n children: TNewChildren,\n ): Route<\n TParentRoute,\n TPath,\n TFullPath,\n TCustomId,\n TId,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TRouteContext,\n TAllContext,\n TRouterContext,\n TNewChildren,\n TRouteTree\n > => {\n this.children = children as any\n return this as any\n }\n\n update = (\n options: UpdatableRouteOptions<\n TFullSearchSchema,\n TAllParams,\n Expand<\n Assign<IsAny<TParentRoute['types']['allContext'], {}>, TRouteContext>\n >,\n TLoaderData\n >,\n ) => {\n Object.assign(this.options, options)\n return this\n }\n\n static __onInit = (route: any) => {\n // This is a dummy static method that should get\n // replaced by a framework specific implementation if necessary\n }\n\n useMatch = <TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }): TSelected => {\n return useMatch({ ...opts, from: this.id }) as any\n }\n useRouteContext = <TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }): TSelected => {\n return useMatch({\n ...opts,\n from: this.id,\n select: (d: any) => (opts?.select ? opts.select(d.context) : d.context),\n } as any)\n }\n useSearch = <TSelected = TFullSearchSchema>(opts?: {\n select?: (search: TFullSearchSchema) => TSelected\n }): TSelected => {\n return useSearch({ ...opts, from: this.id } as any)\n }\n useParams = <TSelected = TAllParams>(opts?: {\n select?: (search: TAllParams) => TSelected\n }): TSelected => {\n return useParams({ ...opts, from: this.id } as any)\n }\n useLoaderData = <TSelected = TLoaderData>(opts?: {\n select?: (search: TLoaderData) => TSelected\n }): TSelected => {\n return useLoaderData({ ...opts, from: this.id } as any) as any\n }\n}\n\nexport type AnyRootRoute = RootRoute<any, any, any>\n\nexport function rootRouteWithContext<TRouterContext extends {}>() {\n return <\n TSearchSchema extends Record<string, any> = {},\n TRouteContext extends RouteContext = RouteContext,\n TLoaderData extends any = unknown,\n >(\n options?: Omit<\n RouteOptions<\n AnyRoute, // TParentRoute\n RootRouteId, // TCustomId\n '', // TPath\n TSearchSchema, // TSearchSchema\n TSearchSchema, // TFullSearchSchema\n {}, // TParams\n {}, // TAllParams\n TRouteContext, // TRouteContext\n Assign<TRouterContext, TRouteContext>, // TAllContext\n TLoaderData // TLoaderData\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ): RootRoute<TSearchSchema, TRouteContext, TRouterContext> => {\n return new RootRoute(options) as any\n }\n}\n\nexport class RootRoute<\n TSearchSchema extends Record<string, any> = {},\n TRouteContext extends RouteContext = RouteContext,\n TRouterContext extends {} = {},\n TLoaderData extends any = unknown,\n> extends Route<\n any, // TParentRoute\n '/', // TPath\n '/', // TFullPath\n string, // TCustomId\n RootRouteId, // TId\n TSearchSchema, // TSearchSchema\n TSearchSchema, // TFullSearchSchema\n {}, // TParams\n {}, // TAllParams\n TRouteContext, // TRouteContext\n Expand<Assign<TRouterContext, TRouteContext>>, // TAllContext\n TRouterContext, // TRouterContext\n TLoaderData,\n any, // TChildren\n any // TRouteTree\n> {\n constructor(\n options?: Omit<\n RouteOptions<\n AnyRoute, // TParentRoute\n RootRouteId, // TCustomId\n '', // TPath\n TSearchSchema, // TSearchSchema\n TSearchSchema, // TFullSearchSchema\n {}, // TParams\n {}, // TAllParams\n TRouteContext, // TRouteContext\n Assign<TRouterContext, TRouteContext>, // TAllContext\n TLoaderData\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ) {\n super(options as any)\n }\n}\n\nexport type ResolveFullPath<\n TParentRoute extends AnyRoute,\n TPath extends string,\n TPrefixed = RoutePrefix<TParentRoute['fullPath'], TPath>,\n> = TPrefixed extends RootRouteId ? '/' : TPrefixed\n\ntype RoutePrefix<\n TPrefix extends string,\n TPath extends string,\n> = string extends TPath\n ? RootRouteId\n : TPath extends string\n ? TPrefix extends RootRouteId\n ? TPath extends '/'\n ? '/'\n : `/${TrimPath<TPath>}`\n : `${TPrefix}/${TPath}` extends '/'\n ? '/'\n : `/${TrimPathLeft<`${TrimPathRight<TPrefix>}/${TrimPath<TPath>}`>}`\n : never\n\nexport type TrimPath<T extends string> = '' extends T\n ? ''\n : TrimPathRight<TrimPathLeft<T>>\n\nexport type TrimPathLeft<T extends string> =\n T extends `${RootRouteId}/${infer U}`\n ? TrimPathLeft<U>\n : T extends `/${infer U}`\n ? TrimPathLeft<U>\n : T\nexport type TrimPathRight<T extends string> = T extends '/'\n ? '/'\n : T extends `${infer U}/`\n ? TrimPathRight<U>\n : T\n\nexport type RouteMask<TRouteTree extends AnyRoute> = {\n routeTree: TRouteTree\n from: RoutePaths<TRouteTree>\n to?: any\n params?: any\n search?: any\n hash?: any\n state?: any\n unmaskOnReload?: boolean\n}\n\nexport function createRouteMask<\n TRouteTree extends AnyRoute,\n TFrom extends RoutePaths<TRouteTree>,\n TTo extends string,\n>(\n opts: {\n routeTree: TRouteTree\n } & ToSubOptions<TRouteTree, TFrom, TTo>,\n): RouteMask<TRouteTree> {\n return opts as any\n}\n\nexport type RouteProps<\n TFullSearchSchema extends Record<string, any> = AnySearchSchema,\n TAllParams extends AnyPathParams = AnyPathParams,\n TAllContext extends Record<string, any> = AnyContext,\n TLoaderData extends any = unknown,\n> = {\n useMatch: <TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }) => TSelected\n useRouteContext: <TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }) => TSelected\n useSearch: <TSelected = TFullSearchSchema>(opts?: {\n select?: (search: TFullSearchSchema) => TSelected\n }) => TSelected\n useParams: <TSelected = TAllParams>(opts?: {\n select?: (search: TAllParams) => TSelected\n }) => TSelected\n useLoaderData: <TSelected = TLoaderData>(opts?: {\n select?: (search: TLoaderData) => TSelected\n }) => TSelected\n}\n\nexport type ErrorRouteProps<\n TFullSearchSchema extends Record<string, any> = AnySearchSchema,\n TAllParams extends AnyPathParams = AnyPathParams,\n TAllContext extends Record<string, any> = AnyContext,\n> = {\n error: unknown\n info: { componentStack: string }\n} & RouteProps<TFullSearchSchema, TAllParams, TAllContext>\n\nexport type PendingRouteProps<\n TFullSearchSchema extends Record<string, any> = AnySearchSchema,\n TAllParams extends AnyPathParams = AnyPathParams,\n TAllContext extends Record<string, any> = AnyContext,\n> = RouteProps<TFullSearchSchema, TAllParams, TAllContext>\n//\n\nexport type ReactNode = any\n\nexport type SyncRouteComponent<TProps> =\n | ((props: TProps) => ReactNode)\n | React.LazyExoticComponent<(props: TProps) => ReactNode>\n\nexport type AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {\n preload?: () => Promise<void>\n}\n\nexport type RouteComponent<\n TFullSearchSchema extends Record<string, any>,\n TAllParams extends AnyPathParams,\n TAllContext extends Record<string, any>,\n TLoaderData extends any = unknown,\n> = AsyncRouteComponent<\n RouteProps<TFullSearchSchema, TAllParams, TAllContext, TLoaderData>\n>\n\nexport type ErrorRouteComponent<\n TFullSearchSchema extends Record<string, any>,\n TAllParams extends AnyPathParams,\n TAllContext extends Record<string, any>,\n> = AsyncRouteComponent<\n ErrorRouteProps<TFullSearchSchema, TAllParams, TAllContext>\n>\n\nexport type PendingRouteComponent<\n TFullSearchSchema extends Record<string, any>,\n TAllParams extends AnyPathParams,\n TAllContext extends Record<string, any>,\n> = AsyncRouteComponent<\n PendingRouteProps<TFullSearchSchema, TAllParams, TAllContext>\n>\n\nexport type AnyRouteComponent = RouteComponent<any, any, any, any>\n"],"names":["rootRouteId","Route","constructor","options","isRoot","getParentRoute","__onInit","init","opts","originalIndex","path","id","parentRoute","invariant","trimPath","customId","joinPaths","fullPath","to","addChildren","children","update","Object","assign","route","useMatch","from","useRouteContext","select","d","context","useSearch","useParams","useLoaderData","rootRouteWithContext","RootRoute","createRouteMask"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBO,MAAMA,WAAW,GAAG,WAAmB;;AAgO9C;;AAkIO,MAAMC,KAAK,CAmChB;AAmBA;;AAGA;;AAKA;;EAMAC,WAAWA,CACTC,OAWC,EACD;AACA,IAAA,IAAI,CAACA,OAAO,GAAIA,OAAO,IAAY,EAAE,CAAA;AACrC,IAAA,IAAI,CAACC,MAAM,GAAG,CAACD,OAAO,EAAEE,cAAqB,CAAA;AAC7CJ,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B;AACf,IAAA,OAAOuB,mBAAS,CAAC;AAAE,MAAA,GAAGvB,IAAI;MAAEkB,IAAI,EAAE,IAAI,CAACf,EAAAA;AAAG,KAAQ,CAAC,CAAA;GACpD,CAAA;EACDqB,SAAS,GAA4BxB,IAEpC,IAAgB;AACf,IAAA,OAAOwB,mBAAS,CAAC;AAAE,MAAA,GAAGxB,IAAI;MAAEkB,IAAI,EAAE,IAAI,CAACf,EAAAA;AAAG,KAAQ,CAAC,CAAA;GACpD,CAAA;EACDsB,aAAa,GAA6BzB,IAEzC,IAAgB;AACf,IAAA,OAAOyB,qBAAa,CAAC;AAAE,MAAA,GAAGzB,IAAI;MAAEkB,IAAI,EAAE,IAAI,CAACf,EAAAA;AAAG,KAAQ,CAAC,CAAA;GACxD,CAAA;AACH,CAAA;AAIO,SAASuB,oBAAoBA,GAA8B;AAChE,EAAA,OAKE/B,OAmBC,IAC2D;AAC5D,IAAA,OAAO,IAAIgC,SAAS,CAAChC,OAAO,CAAC,CAAA;GAC9B,CAAA;AACH,CAAA;AAEO,MAAMgC,SAAS,SAKZlC,KAAK,CAgBb;EACAC,WAAWA,CACTC,OAmBC,EACD;IACA,KAAK,CAACA,OAAc,CAAC,CAAA;AACvB,GAAA;AACF,CAAA;AAkDO,SAASiC,eAAeA,CAK7B5B,IAEwC,EACjB;AACvB,EAAA,OAAOA,IAAI,CAAA;AACb,CAAA;;AAuCA;;;;;;;;"}
@@ -1,203 +0,0 @@
1
- /**
2
- * @tanstack/react-router/src/index.tsx
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var searchParams = require('./searchParams.js');
16
-
17
- //
18
-
19
- //
20
-
21
- const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
22
- class Router {
23
- // dehydratedData?: TDehydrated
24
- // resetNextScroll = false
25
- // tempLocationKey = `${Math.round(Math.random() * 10000000)}`
26
- constructor(options) {
27
- this.options = {
28
- defaultPreloadDelay: 50,
29
- context: undefined,
30
- ...options,
31
- stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
32
- parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch
33
- };
34
- this.routeTree = this.options.routeTree;
35
- }
36
- subscribers = new Set();
37
- subscribe = (eventType, fn) => {
38
- const listener = {
39
- eventType,
40
- fn
41
- };
42
- this.subscribers.add(listener);
43
- return () => {
44
- this.subscribers.delete(listener);
45
- };
46
- };
47
- emit = routerEvent => {
48
- this.subscribers.forEach(listener => {
49
- if (listener.eventType === routerEvent.type) {
50
- listener.fn(routerEvent);
51
- }
52
- });
53
- };
54
-
55
- // dehydrate = (): DehydratedRouter => {
56
- // return {
57
- // state: {
58
- // dehydratedMatches: state.matches.map((d) =>
59
- // pick(d, ['fetchedAt', 'invalid', 'id', 'status', 'updatedAt']),
60
- // ),
61
- // },
62
- // }
63
- // }
64
-
65
- // hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
66
- // let _ctx = __do_not_use_server_ctx
67
- // // Client hydrates from window
68
- // if (typeof document !== 'undefined') {
69
- // _ctx = window.__TSR_DEHYDRATED__
70
- // }
71
-
72
- // invariant(
73
- // _ctx,
74
- // 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
75
- // )
76
-
77
- // const ctx = _ctx
78
- // this.dehydratedData = ctx.payload as any
79
- // this.options.hydrate?.(ctx.payload as any)
80
- // const dehydratedState = ctx.router.state
81
-
82
- // let matches = this.matchRoutes(
83
- // state.location.pathname,
84
- // state.location.search,
85
- // ).map((match) => {
86
- // const dehydratedMatch = dehydratedState.dehydratedMatches.find(
87
- // (d) => d.id === match.id,
88
- // )
89
-
90
- // invariant(
91
- // dehydratedMatch,
92
- // `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
93
- // )
94
-
95
- // if (dehydratedMatch) {
96
- // return {
97
- // ...match,
98
- // ...dehydratedMatch,
99
- // }
100
- // }
101
- // return match
102
- // })
103
-
104
- // this.setState((s) => {
105
- // return {
106
- // ...s,
107
- // matches: dehydratedState.dehydratedMatches as any,
108
- // }
109
- // })
110
- // }
111
-
112
- // TODO:
113
- // injectedHtml: (string | (() => Promise<string> | string))[] = []
114
-
115
- // TODO:
116
- // injectHtml = async (html: string | (() => Promise<string> | string)) => {
117
- // this.injectedHtml.push(html)
118
- // }
119
-
120
- // TODO:
121
- // dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
122
- // if (typeof document === 'undefined') {
123
- // const strKey = typeof key === 'string' ? key : JSON.stringify(key)
124
-
125
- // this.injectHtml(async () => {
126
- // const id = `__TSR_DEHYDRATED__${strKey}`
127
- // const data =
128
- // typeof getData === 'function' ? await (getData as any)() : getData
129
- // return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
130
- // strKey,
131
- // )}"] = ${JSON.stringify(data)}
132
- // ;(() => {
133
- // var el = document.getElementById('${id}')
134
- // el.parentElement.removeChild(el)
135
- // })()
136
- // </script>`
137
- // })
138
-
139
- // return () => this.hydrateData<T>(key)
140
- // }
141
-
142
- // return () => undefined
143
- // }
144
-
145
- // hydrateData = <T = unknown>(key: any) => {
146
- // if (typeof document !== 'undefined') {
147
- // const strKey = typeof key === 'string' ? key : JSON.stringify(key)
148
-
149
- // return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
150
- // }
151
-
152
- // return undefined
153
- // }
154
-
155
- // resolveMatchPromise = (matchId: string, key: string, value: any) => {
156
- // state.matches
157
- // .find((d) => d.id === matchId)
158
- // ?.__promisesByKey[key]?.resolve(value)
159
- // }
160
-
161
- // setRouteMatch = (
162
- // id: string,
163
- // pending: boolean,
164
- // updater: NonNullableUpdater<RouteMatch<TRouteTree>>,
165
- // ) => {
166
- // const key = pending ? 'pendingMatches' : 'matches'
167
-
168
- // this.setState((prev) => {
169
- // return {
170
- // ...prev,
171
- // [key]: prev[key].map((d) => {
172
- // if (d.id === id) {
173
- // return functionalUpdate(updater, d)
174
- // }
175
-
176
- // return d
177
- // }),
178
- // }
179
- // })
180
- // }
181
-
182
- // setPendingRouteMatch = (
183
- // id: string,
184
- // updater: NonNullableUpdater<RouteMatch<TRouteTree>>,
185
- // ) => {
186
- // this.setRouteMatch(id, true, updater)
187
- // }
188
- }
189
-
190
- // A function that takes an import() argument which is a function and returns a new function that will
191
- // proxy arguments from the caller to the imported function, retaining all type
192
- // information along the way
193
- function lazyFn(fn, key) {
194
- return async (...args) => {
195
- const imported = await fn();
196
- return imported[key || 'default'](...args);
197
- };
198
- }
199
-
200
- exports.Router = Router;
201
- exports.componentTypes = componentTypes;
202
- exports.lazyFn = lazyFn;
203
- //# sourceMappingURL=router.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"router.js","sources":["../../../src/router.ts"],"sourcesContent":["import { RouterHistory } from '@tanstack/history'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n} from './route'\nimport { FullSearchSchema } from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport { PickAsRequired, Updater, NonNullableUpdater } from './utils'\nimport {\n ErrorRouteComponent,\n PendingRouteComponent,\n RouteComponent,\n} from './route'\nimport { RouteMatch } from './RouterProvider'\nimport { ParsedLocation } from './location'\nimport { LocationState } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport { RouterContext } from './RouterProvider'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: HydrationCtx\n __TSR_ROUTER_CONTEXT__?: React.Context<RouterContext<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent<AnySearchSchema, AnyPathParams, AnyContext>\n defaultErrorComponent?: ErrorRouteComponent<\n AnySearchSchema,\n AnyPathParams,\n AnyContext\n >\n defaultPendingComponent?: PendingRouteComponent<\n AnySearchSchema,\n AnyPathParams,\n AnyContext\n >\n defaultMaxAge?: number\n defaultGcMaxAge?: number\n defaultPreloadMaxAge?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n createRoute?: (opts: { route: AnyRoute; router: AnyRouter }) => void\n context?: TRouteTree['types']['routerContext']\n // dehydrate?: () => TDehydrated\n // hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n matches: RouteMatch<TRouteTree>[]\n pendingMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<LocationState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<LocationState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'fetchedAt' | 'invalid' | 'id' | 'status' | 'updatedAt'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n> {\n options: PickAsRequired<\n RouterOptions<TRouteTree, TDehydrated>,\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n routeTree: TRouteTree\n // dehydratedData?: TDehydrated\n // resetNextScroll = false\n // tempLocationKey = `${Math.round(Math.random() * 10000000)}`\n\n constructor(options: RouterConstructorOptions<TRouteTree, TDehydrated>) {\n this.options = {\n defaultPreloadDelay: 50,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n }\n\n this.routeTree = this.options.routeTree as TRouteTree\n }\n\n subscribers = new Set<RouterListener<RouterEvent>>()\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n // dehydrate = (): DehydratedRouter => {\n // return {\n // state: {\n // dehydratedMatches: state.matches.map((d) =>\n // pick(d, ['fetchedAt', 'invalid', 'id', 'status', 'updatedAt']),\n // ),\n // },\n // }\n // }\n\n // hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {\n // let _ctx = __do_not_use_server_ctx\n // // Client hydrates from window\n // if (typeof document !== 'undefined') {\n // _ctx = window.__TSR_DEHYDRATED__\n // }\n\n // invariant(\n // _ctx,\n // 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n // )\n\n // const ctx = _ctx\n // this.dehydratedData = ctx.payload as any\n // this.options.hydrate?.(ctx.payload as any)\n // const dehydratedState = ctx.router.state\n\n // let matches = this.matchRoutes(\n // state.location.pathname,\n // state.location.search,\n // ).map((match) => {\n // const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n // (d) => d.id === match.id,\n // )\n\n // invariant(\n // dehydratedMatch,\n // `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n // )\n\n // if (dehydratedMatch) {\n // return {\n // ...match,\n // ...dehydratedMatch,\n // }\n // }\n // return match\n // })\n\n // this.setState((s) => {\n // return {\n // ...s,\n // matches: dehydratedState.dehydratedMatches as any,\n // }\n // })\n // }\n\n // TODO:\n // injectedHtml: (string | (() => Promise<string> | string))[] = []\n\n // TODO:\n // injectHtml = async (html: string | (() => Promise<string> | string)) => {\n // this.injectedHtml.push(html)\n // }\n\n // TODO:\n // dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n // if (typeof document === 'undefined') {\n // const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n // this.injectHtml(async () => {\n // const id = `__TSR_DEHYDRATED__${strKey}`\n // const data =\n // typeof getData === 'function' ? await (getData as any)() : getData\n // return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n // strKey,\n // )}\"] = ${JSON.stringify(data)}\n // ;(() => {\n // var el = document.getElementById('${id}')\n // el.parentElement.removeChild(el)\n // })()\n // </script>`\n // })\n\n // return () => this.hydrateData<T>(key)\n // }\n\n // return () => undefined\n // }\n\n // hydrateData = <T = unknown>(key: any) => {\n // if (typeof document !== 'undefined') {\n // const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n // return window[`__TSR_DEHYDRATED__${strKey}` as any] as T\n // }\n\n // return undefined\n // }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n\n // setRouteMatch = (\n // id: string,\n // pending: boolean,\n // updater: NonNullableUpdater<RouteMatch<TRouteTree>>,\n // ) => {\n // const key = pending ? 'pendingMatches' : 'matches'\n\n // this.setState((prev) => {\n // return {\n // ...prev,\n // [key]: prev[key].map((d) => {\n // if (d.id === id) {\n // return functionalUpdate(updater, d)\n // }\n\n // return d\n // }),\n // }\n // })\n // }\n\n // setPendingRouteMatch = (\n // id: string,\n // updater: NonNullableUpdater<RouteMatch<TRouteTree>>,\n // ) => {\n // this.setRouteMatch(id, true, updater)\n // }\n}\n\nfunction escapeJSON(jsonString: string) {\n return jsonString\n .replace(/\\\\/g, '\\\\\\\\') // Escape backslashes\n .replace(/'/g, \"\\\\'\") // Escape single quotes\n .replace(/\"/g, '\\\\\"') // Escape double quotes\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n"],"names":["componentTypes","Router","constructor","options","defaultPreloadDelay","context","undefined","stringifySearch","defaultStringifySearch","parseSearch","defaultParseSearch","routeTree","subscribers","Set","subscribe","eventType","fn","listener","add","delete","emit","routerEvent","forEach","type","lazyFn","key","args","imported"],"mappings":";;;;;;;;;;;;;;;;AAEA;;AAuBA;;AAoHO,MAAMA,cAAc,GAAG,CAC5B,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EACV;AA8BH,MAAMC,MAAM,CAGjB;AAMA;AACA;AACA;EAEAC,WAAWA,CAACC,OAA0D,EAAE;IACtE,IAAI,CAACA,OAAO,GAAG;AACbC,MAAAA,mBAAmB,EAAE,EAAE;AACvBC,MAAAA,OAAO,EAAEC,SAAU;AACnB,MAAA,GAAGH,OAAO;AACVI,MAAAA,eAAe,EAAEJ,OAAO,EAAEI,eAAe,IAAIC,mCAAsB;AACnEC,MAAAA,WAAW,EAAEN,OAAO,EAAEM,WAAW,IAAIC,+BAAAA;KACtC,CAAA;AAED,IAAA,IAAI,CAACC,SAAS,GAAG,IAAI,CAACR,OAAO,CAACQ,SAAuB,CAAA;AACvD,GAAA;AAEAC,EAAAA,WAAW,GAAG,IAAIC,GAAG,EAA+B,CAAA;AAEpDC,EAAAA,SAAS,GAAGA,CACVC,SAAgB,EAChBC,EAAmC,KAChC;AACH,IAAA,MAAMC,QAA6B,GAAG;MACpCF,SAAS;AACTC,MAAAA,EAAAA;KACD,CAAA;AAED,IAAA,IAAI,CAACJ,WAAW,CAACM,GAAG,CAACD,QAAQ,CAAC,CAAA;AAE9B,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,CAACL,WAAW,CAACO,MAAM,CAACF,QAAQ,CAAC,CAAA;KAClC,CAAA;GACF,CAAA;EAEDG,IAAI,GAAIC,WAAwB,IAAK;AACnC,IAAA,IAAI,CAACT,WAAW,CAACU,OAAO,CAAEL,QAAQ,IAAK;AACrC,MAAA,IAAIA,QAAQ,CAACF,SAAS,KAAKM,WAAW,CAACE,IAAI,EAAE;AAC3CN,QAAAA,QAAQ,CAACD,EAAE,CAACK,WAAW,CAAC,CAAA;AAC1B,OAAA;AACF,KAAC,CAAC,CAAA;GACH,CAAA;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACF,CAAA;;AASA;AACA;AACA;AACO,SAASG,MAAMA,CAGpBR,EAAoB,EAAES,GAAU,EAAE;EAClC,OAAO,OAAO,GAAGC,IAAyB,KAAmC;AAC3E,IAAA,MAAMC,QAAQ,GAAG,MAAMX,EAAE,EAAE,CAAA;IAC3B,OAAOW,QAAQ,CAACF,GAAG,IAAI,SAAS,CAAC,CAAC,GAAGC,IAAI,CAAC,CAAA;GAC3C,CAAA;AACH;;;;;;"}
@@ -1,186 +0,0 @@
1
- /**
2
- * @tanstack/react-router/src/index.tsx
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var React = require('react');
16
- var RouterProvider = require('./RouterProvider.js');
17
- var utils = require('./utils.js');
18
-
19
- function _interopNamespace(e) {
20
- if (e && e.__esModule) return e;
21
- var n = Object.create(null);
22
- if (e) {
23
- Object.keys(e).forEach(function (k) {
24
- if (k !== 'default') {
25
- var d = Object.getOwnPropertyDescriptor(e, k);
26
- Object.defineProperty(n, k, d.get ? d : {
27
- enumerable: true,
28
- get: function () { return e[k]; }
29
- });
30
- }
31
- });
32
- }
33
- n["default"] = e;
34
- return Object.freeze(n);
35
- }
36
-
37
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
38
-
39
- const useLayoutEffect = typeof window !== 'undefined' ? React__namespace.useLayoutEffect : React__namespace.useEffect;
40
- const windowKey = 'window';
41
- const delimiter = '___';
42
- let weakScrolledElements = new WeakSet();
43
- let cache;
44
- const sessionsStorage = typeof window !== 'undefined' && window.sessionStorage;
45
- const defaultGetKey = location => location.state.key;
46
- function useScrollRestoration(options) {
47
- const {
48
- state,
49
- subscribe,
50
- resetNextScrollRef
51
- } = RouterProvider.useRouter();
52
- useLayoutEffect(() => {
53
- const getKey = options?.getKey || defaultGetKey;
54
- if (sessionsStorage) {
55
- if (!cache) {
56
- cache = (() => {
57
- const storageKey = 'tsr-scroll-restoration-v2';
58
- const state = JSON.parse(window.sessionStorage.getItem(storageKey) || 'null') || {
59
- cached: {},
60
- next: {}
61
- };
62
- return {
63
- state,
64
- set: updater => {
65
- cache.state = utils.functionalUpdate(updater, cache.state);
66
- window.sessionStorage.setItem(storageKey, JSON.stringify(cache.state));
67
- }
68
- };
69
- })();
70
- }
71
- }
72
- const {
73
- history
74
- } = window;
75
- if (history.scrollRestoration) {
76
- history.scrollRestoration = 'manual';
77
- }
78
- const onScroll = event => {
79
- if (weakScrolledElements.has(event.target)) return;
80
- weakScrolledElements.add(event.target);
81
- const elementSelector = event.target === document || event.target === window ? windowKey : getCssSelector(event.target);
82
- if (!cache.state.next[elementSelector]) {
83
- cache.set(c => ({
84
- ...c,
85
- next: {
86
- ...c.next,
87
- [elementSelector]: {
88
- scrollX: NaN,
89
- scrollY: NaN
90
- }
91
- }
92
- }));
93
- }
94
- };
95
- const getCssSelector = el => {
96
- let path = [],
97
- parent;
98
- while (parent = el.parentNode) {
99
- path.unshift(`${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`);
100
- el = parent;
101
- }
102
- return `${path.join(' > ')}`.toLowerCase();
103
- };
104
- if (typeof document !== 'undefined') {
105
- document.addEventListener('scroll', onScroll, true);
106
- }
107
- const unsubOnBeforeLoad = subscribe('onBeforeLoad', event => {
108
- if (event.pathChanged) {
109
- const restoreKey = getKey(event.fromLocation);
110
- for (const elementSelector in cache.state.next) {
111
- const entry = cache.state.next[elementSelector];
112
- if (elementSelector === windowKey) {
113
- entry.scrollX = window.scrollX || 0;
114
- entry.scrollY = window.scrollY || 0;
115
- } else if (elementSelector) {
116
- const element = document.querySelector(elementSelector);
117
- entry.scrollX = element?.scrollLeft || 0;
118
- entry.scrollY = element?.scrollTop || 0;
119
- }
120
- cache.set(c => {
121
- const next = {
122
- ...c.next
123
- };
124
- delete next[elementSelector];
125
- return {
126
- ...c,
127
- next,
128
- cached: {
129
- ...c.cached,
130
- [[restoreKey, elementSelector].join(delimiter)]: entry
131
- }
132
- };
133
- });
134
- }
135
- }
136
- });
137
- const unsubOnResolved = subscribe('onResolved', event => {
138
- if (event.pathChanged) {
139
- if (!resetNextScrollRef.current) {
140
- return;
141
- }
142
- resetNextScrollRef.current = true;
143
- const getKey = options?.getKey || defaultGetKey;
144
- const restoreKey = getKey(event.toLocation);
145
- let windowRestored = false;
146
- for (const cacheKey in cache.state.cached) {
147
- const entry = cache.state.cached[cacheKey];
148
- const [key, elementSelector] = cacheKey.split(delimiter);
149
- if (key === restoreKey) {
150
- if (elementSelector === windowKey) {
151
- windowRestored = true;
152
- window.scrollTo(entry.scrollX, entry.scrollY);
153
- } else if (elementSelector) {
154
- const element = document.querySelector(elementSelector);
155
- if (element) {
156
- element.scrollLeft = entry.scrollX;
157
- element.scrollTop = entry.scrollY;
158
- }
159
- }
160
- }
161
- }
162
- if (!windowRestored) {
163
- window.scrollTo(0, 0);
164
- }
165
- cache.set(c => ({
166
- ...c,
167
- next: {}
168
- }));
169
- weakScrolledElements = new WeakSet();
170
- }
171
- });
172
- return () => {
173
- document.removeEventListener('scroll', onScroll);
174
- unsubOnBeforeLoad();
175
- unsubOnResolved();
176
- };
177
- }, []);
178
- }
179
- function ScrollRestoration(props) {
180
- useScrollRestoration(props);
181
- return null;
182
- }
183
-
184
- exports.ScrollRestoration = ScrollRestoration;
185
- exports.useScrollRestoration = useScrollRestoration;
186
- //# sourceMappingURL=scroll-restoration.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"scroll-restoration.js","sources":["../../../src/scroll-restoration.tsx"],"sourcesContent":["import * as React from 'react'\n\nconst useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\nimport { ParsedLocation } from './location'\nimport { useRouter } from './RouterProvider'\nimport { NonNullableUpdater, functionalUpdate } from './utils'\n\nconst windowKey = 'window'\nconst delimiter = '___'\n\nlet weakScrolledElements = new WeakSet<any>()\n\ntype CacheValue = Record<string, { scrollX: number; scrollY: number }>\ntype CacheState = {\n cached: CacheValue\n next: CacheValue\n}\n\ntype Cache = {\n state: CacheState\n set: (updater: NonNullableUpdater<CacheState>) => void\n}\n\nlet cache: Cache\n\nconst sessionsStorage = typeof window !== 'undefined' && window.sessionStorage\n\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n}\n\nconst defaultGetKey = (location: ParsedLocation) => location.state.key!\n\nexport function useScrollRestoration(options?: ScrollRestorationOptions) {\n const { state, subscribe, resetNextScrollRef } = useRouter()\n\n useLayoutEffect(() => {\n const getKey = options?.getKey || defaultGetKey\n\n if (sessionsStorage) {\n if (!cache) {\n cache = (() => {\n const storageKey = 'tsr-scroll-restoration-v2'\n\n const state: CacheState = JSON.parse(\n window.sessionStorage.getItem(storageKey) || 'null',\n ) || { cached: {}, next: {} }\n\n return {\n state,\n set: (updater) => {\n cache.state = functionalUpdate(updater, cache.state)\n window.sessionStorage.setItem(\n storageKey,\n JSON.stringify(cache.state),\n )\n },\n }\n })()\n }\n }\n\n const { history } = window\n if (history.scrollRestoration) {\n history.scrollRestoration = 'manual'\n }\n\n const onScroll = (event: Event) => {\n if (weakScrolledElements.has(event.target)) return\n weakScrolledElements.add(event.target)\n\n const elementSelector =\n event.target === document || event.target === window\n ? windowKey\n : getCssSelector(event.target)\n\n if (!cache.state.next[elementSelector]) {\n cache.set((c) => ({\n ...c,\n next: {\n ...c.next,\n [elementSelector]: {\n scrollX: NaN,\n scrollY: NaN,\n },\n },\n }))\n }\n }\n\n const getCssSelector = (el: any): string => {\n let path = [],\n parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${\n ([].indexOf as any).call(parent.children, el) + 1\n })`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n }\n\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', onScroll, true)\n }\n\n const unsubOnBeforeLoad = subscribe('onBeforeLoad', (event) => {\n if (event.pathChanged) {\n const restoreKey = getKey(event.fromLocation)\n for (const elementSelector in cache.state.next) {\n const entry = cache.state.next[elementSelector]!\n if (elementSelector === windowKey) {\n entry.scrollX = window.scrollX || 0\n entry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n entry.scrollX = element?.scrollLeft || 0\n entry.scrollY = element?.scrollTop || 0\n }\n\n cache.set((c) => {\n const next = { ...c.next }\n delete next[elementSelector]\n\n return {\n ...c,\n next,\n cached: {\n ...c.cached,\n [[restoreKey, elementSelector].join(delimiter)]: entry,\n },\n }\n })\n }\n }\n })\n\n const unsubOnResolved = subscribe('onResolved', (event) => {\n if (event.pathChanged) {\n if (!resetNextScrollRef.current) {\n return\n }\n\n resetNextScrollRef.current = true\n\n const getKey = options?.getKey || defaultGetKey\n\n const restoreKey = getKey(event.toLocation)\n let windowRestored = false\n\n for (const cacheKey in cache.state.cached) {\n const entry = cache.state.cached[cacheKey]!\n const [key, elementSelector] = cacheKey.split(delimiter)\n if (key === restoreKey) {\n if (elementSelector === windowKey) {\n windowRestored = true\n window.scrollTo(entry.scrollX, entry.scrollY)\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\n if (!windowRestored) {\n window.scrollTo(0, 0)\n }\n\n cache.set((c) => ({ ...c, next: {} }))\n weakScrolledElements = new WeakSet<any>()\n }\n })\n\n return () => {\n document.removeEventListener('scroll', onScroll)\n unsubOnBeforeLoad()\n unsubOnResolved()\n }\n }, [])\n}\n\nexport function ScrollRestoration(props: ScrollRestorationOptions) {\n useScrollRestoration(props)\n return null\n}\n"],"names":["useLayoutEffect","window","React","useEffect","windowKey","delimiter","weakScrolledElements","WeakSet","cache","sessionsStorage","sessionStorage","defaultGetKey","location","state","key","useScrollRestoration","options","subscribe","resetNextScrollRef","useRouter","getKey","storageKey","JSON","parse","getItem","cached","next","set","updater","functionalUpdate","setItem","stringify","history","scrollRestoration","onScroll","event","has","target","add","elementSelector","document","getCssSelector","c","scrollX","NaN","scrollY","el","path","parent","parentNode","unshift","tagName","indexOf","call","children","join","toLowerCase","addEventListener","unsubOnBeforeLoad","pathChanged","restoreKey","fromLocation","entry","element","querySelector","scrollLeft","scrollTop","unsubOnResolved","current","toLocation","windowRestored","cacheKey","split","scrollTo","removeEventListener","ScrollRestoration","props"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAMA,eAAe,GACnB,OAAOC,MAAM,KAAK,WAAW,GAAGC,gBAAK,CAACF,eAAe,GAAGE,gBAAK,CAACC,SAAS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