@tanstack/react-router 1.48.1 → 1.49.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/Matches.cjs +3 -1
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/Matches.d.cts +5 -4
- package/dist/cjs/Transitioner.cjs +2 -2
- package/dist/cjs/Transitioner.cjs.map +1 -1
- package/dist/cjs/fileRoute.cjs.map +1 -1
- package/dist/cjs/fileRoute.d.cts +4 -4
- package/dist/cjs/index.cjs +2 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +3 -1
- package/dist/cjs/route.cjs +1 -1
- package/dist/cjs/route.cjs.map +1 -1
- package/dist/cjs/route.d.cts +73 -59
- package/dist/cjs/router.cjs +90 -57
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +22 -9
- package/dist/cjs/transformer.cjs +39 -0
- package/dist/cjs/transformer.cjs.map +1 -0
- package/dist/cjs/transformer.d.cts +5 -0
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/cjs/utils.d.cts +1 -0
- package/dist/esm/Matches.d.ts +5 -4
- package/dist/esm/Matches.js +3 -1
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/Transitioner.js +2 -2
- package/dist/esm/Transitioner.js.map +1 -1
- package/dist/esm/fileRoute.d.ts +4 -4
- package/dist/esm/fileRoute.js.map +1 -1
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/route.d.ts +73 -59
- package/dist/esm/route.js +1 -1
- package/dist/esm/route.js.map +1 -1
- package/dist/esm/router.d.ts +22 -9
- package/dist/esm/router.js +91 -58
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/transformer.d.ts +5 -0
- package/dist/esm/transformer.js +39 -0
- package/dist/esm/transformer.js.map +1 -0
- package/dist/esm/utils.d.ts +1 -0
- package/dist/esm/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/Matches.tsx +11 -7
- package/src/Transitioner.tsx +2 -2
- package/src/fileRoute.ts +26 -21
- package/src/index.tsx +5 -1
- package/src/route.ts +356 -186
- package/src/router.ts +144 -75
- package/src/transformer.ts +49 -0
- package/src/utils.ts +5 -0
package/dist/cjs/router.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Store, NoInfer } from '@tanstack/react-store';
|
|
2
2
|
import { HistoryState, RouterHistory } from '@tanstack/history';
|
|
3
3
|
import { Manifest } from './manifest.cjs';
|
|
4
|
-
import { AnyContext, AnyRoute, AnyRouteWithContext,
|
|
4
|
+
import { AnyContext, AnyRoute, AnyRouteWithContext, ErrorRouteComponent, NotFoundRouteComponent, RootRoute, RouteComponent, RouteMask } from './route.cjs';
|
|
5
5
|
import { FullSearchSchema, RouteById, RoutePaths, RoutesById, RoutesByPath } from './routeInfo.cjs';
|
|
6
6
|
import { ControlledPromise, NonNullableUpdater, PickAsRequired, Updater } from './utils.cjs';
|
|
7
7
|
import { AnyRouteMatch, MakeRouteMatch, MatchRouteOptions } from './Matches.cjs';
|
|
@@ -11,12 +11,17 @@ import { BuildLocationFn, CommitLocationOptions, NavigateFn } from './RouterProv
|
|
|
11
11
|
import { AnyRedirect, ResolvedRedirect } from './redirects.cjs';
|
|
12
12
|
import { NotFoundError } from './not-found.cjs';
|
|
13
13
|
import { NavigateOptions, ResolveRelativePath, ToOptions } from './link.cjs';
|
|
14
|
+
import { RouterTransformer } from './transformer.cjs';
|
|
14
15
|
|
|
15
16
|
import type * as React from 'react';
|
|
16
17
|
declare global {
|
|
17
18
|
interface Window {
|
|
18
19
|
__TSR__?: {
|
|
19
|
-
matches: Array<
|
|
20
|
+
matches: Array<{
|
|
21
|
+
__beforeLoadContext?: string;
|
|
22
|
+
loaderData?: string;
|
|
23
|
+
extracted?: Array<ExtractedEntry>;
|
|
24
|
+
}>;
|
|
20
25
|
streamedValues: Record<string, {
|
|
21
26
|
value: any;
|
|
22
27
|
parsed: any;
|
|
@@ -38,7 +43,19 @@ export type HydrationCtx = {
|
|
|
38
43
|
router: DehydratedRouter;
|
|
39
44
|
payload: Record<string, any>;
|
|
40
45
|
};
|
|
41
|
-
export type InferRouterContext<TRouteTree extends AnyRoute> = TRouteTree extends RootRoute<any,
|
|
46
|
+
export type InferRouterContext<TRouteTree extends AnyRoute> = TRouteTree extends RootRoute<any, infer TRouterContext extends AnyContext, any, any, any, any, any, any> ? TRouterContext : AnyContext;
|
|
47
|
+
export type ExtractedEntry = {
|
|
48
|
+
dataType: '__beforeLoadContext' | 'loaderData';
|
|
49
|
+
type: 'promise' | 'stream';
|
|
50
|
+
path: Array<string>;
|
|
51
|
+
value: any;
|
|
52
|
+
id: number;
|
|
53
|
+
streamState?: StreamState;
|
|
54
|
+
matchIndex: number;
|
|
55
|
+
};
|
|
56
|
+
export type StreamState = {
|
|
57
|
+
promises: Array<ControlledPromise<string | null>>;
|
|
58
|
+
};
|
|
42
59
|
export type RouterContextOptions<TRouteTree extends AnyRoute> = AnyContext extends InferRouterContext<TRouteTree> ? {
|
|
43
60
|
context?: InferRouterContext<TRouteTree>;
|
|
44
61
|
} : {
|
|
@@ -328,10 +345,6 @@ export interface RouterOptions<TRouteTree extends AnyRoute, TTrailingSlashOption
|
|
|
328
345
|
*/
|
|
329
346
|
isServer?: boolean;
|
|
330
347
|
}
|
|
331
|
-
export interface RouterTransformer {
|
|
332
|
-
stringify: (obj: unknown) => string;
|
|
333
|
-
parse: (str: string) => unknown;
|
|
334
|
-
}
|
|
335
348
|
export interface RouterErrorSerializer<TSerializedError> {
|
|
336
349
|
serialize: (err: unknown) => TSerializedError;
|
|
337
350
|
deserialize: (err: TSerializedError) => unknown;
|
|
@@ -422,7 +435,7 @@ export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailing
|
|
|
422
435
|
match: Pick<AnyRouteMatch, 'id' | 'status' | 'error' | 'loadPromise' | 'minPendingPromise'>;
|
|
423
436
|
matchIndex: number;
|
|
424
437
|
}) => any;
|
|
425
|
-
serializeLoaderData?: (
|
|
438
|
+
serializeLoaderData?: (type: '__beforeLoadContext' | 'loaderData', loaderData: any, ctx: {
|
|
426
439
|
router: AnyRouter;
|
|
427
440
|
match: AnyRouteMatch;
|
|
428
441
|
}) => any;
|
|
@@ -452,7 +465,7 @@ export declare class Router<in out TRouteTree extends AnyRoute, in out TTrailing
|
|
|
452
465
|
parseLocation: (previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>) => ParsedLocation<FullSearchSchema<TRouteTree>>;
|
|
453
466
|
resolvePathWithBase: (from: string, path: string) => string;
|
|
454
467
|
get looseRoutesById(): Record<string, AnyRoute>;
|
|
455
|
-
matchRoutes: (
|
|
468
|
+
matchRoutes: (next: ParsedLocation, opts?: {
|
|
456
469
|
preload?: boolean;
|
|
457
470
|
throwOnError?: boolean;
|
|
458
471
|
}) => Array<AnyRouteMatch>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const utils = require("./utils.cjs");
|
|
4
|
+
const defaultTransformer = {
|
|
5
|
+
stringify: (value) => JSON.stringify(value, function replacer(key, value2) {
|
|
6
|
+
const keyVal = this[key];
|
|
7
|
+
const transformer = transformers.find((t) => t.stringifyCondition(keyVal));
|
|
8
|
+
if (transformer) {
|
|
9
|
+
return transformer.stringify(keyVal);
|
|
10
|
+
}
|
|
11
|
+
return value2;
|
|
12
|
+
}),
|
|
13
|
+
parse: (value) => JSON.parse(value, function parser(key, value2) {
|
|
14
|
+
const keyVal = this[key];
|
|
15
|
+
const transformer = transformers.find((t) => t.parseCondition(keyVal));
|
|
16
|
+
if (transformer) {
|
|
17
|
+
return transformer.parse(keyVal);
|
|
18
|
+
}
|
|
19
|
+
return value2;
|
|
20
|
+
})
|
|
21
|
+
};
|
|
22
|
+
const transformers = [
|
|
23
|
+
{
|
|
24
|
+
// Dates
|
|
25
|
+
stringifyCondition: (value) => value instanceof Date,
|
|
26
|
+
stringify: (value) => ({ $date: value.toISOString() }),
|
|
27
|
+
parseCondition: (value) => utils.isPlainObject(value) && value.$date,
|
|
28
|
+
parse: (value) => new Date(value.$date)
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
// undefined
|
|
32
|
+
stringifyCondition: (value) => value === void 0,
|
|
33
|
+
stringify: () => ({ $undefined: "" }),
|
|
34
|
+
parseCondition: (value) => utils.isPlainObject(value) && value.$undefined === "",
|
|
35
|
+
parse: () => void 0
|
|
36
|
+
}
|
|
37
|
+
];
|
|
38
|
+
exports.defaultTransformer = defaultTransformer;
|
|
39
|
+
//# sourceMappingURL=transformer.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformer.cjs","sources":["../../src/transformer.ts"],"sourcesContent":["import { isPlainObject } from './utils'\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\n\nexport const defaultTransformer: RouterTransformer = {\n stringify: (value: any) =>\n JSON.stringify(value, function replacer(key, value) {\n const keyVal = this[key]\n const transformer = transformers.find((t) => t.stringifyCondition(keyVal))\n\n if (transformer) {\n return transformer.stringify(keyVal)\n }\n\n return value\n }),\n parse: (value: string) =>\n JSON.parse(value, function parser(key, value) {\n const keyVal = this[key]\n const transformer = transformers.find((t) => t.parseCondition(keyVal))\n\n if (transformer) {\n return transformer.parse(keyVal)\n }\n\n return value\n }),\n}\n\nconst transformers = [\n {\n // Dates\n stringifyCondition: (value: any) => value instanceof Date,\n stringify: (value: any) => ({ $date: value.toISOString() }),\n parseCondition: (value: any) => isPlainObject(value) && value.$date,\n parse: (value: any) => new Date(value.$date),\n },\n {\n // undefined\n stringifyCondition: (value: any) => value === undefined,\n stringify: () => ({ $undefined: '' }),\n parseCondition: (value: any) =>\n isPlainObject(value) && value.$undefined === '',\n parse: () => undefined,\n },\n] as const\n"],"names":["value","isPlainObject"],"mappings":";;;AAOO,MAAM,qBAAwC;AAAA,EACnD,WAAW,CAAC,UACV,KAAK,UAAU,OAAO,SAAS,SAAS,KAAKA,QAAO;AAC5C,UAAA,SAAS,KAAK,GAAG;AACjB,UAAA,cAAc,aAAa,KAAK,CAAC,MAAM,EAAE,mBAAmB,MAAM,CAAC;AAEzE,QAAI,aAAa;AACR,aAAA,YAAY,UAAU,MAAM;AAAA,IACrC;AAEOA,WAAAA;AAAAA,EAAA,CACR;AAAA,EACH,OAAO,CAAC,UACN,KAAK,MAAM,OAAO,SAAS,OAAO,KAAKA,QAAO;AACtC,UAAA,SAAS,KAAK,GAAG;AACjB,UAAA,cAAc,aAAa,KAAK,CAAC,MAAM,EAAE,eAAe,MAAM,CAAC;AAErE,QAAI,aAAa;AACR,aAAA,YAAY,MAAM,MAAM;AAAA,IACjC;AAEOA,WAAAA;AAAAA,EAAA,CACR;AACL;AAEA,MAAM,eAAe;AAAA,EACnB;AAAA;AAAA,IAEE,oBAAoB,CAAC,UAAe,iBAAiB;AAAA,IACrD,WAAW,CAAC,WAAgB,EAAE,OAAO,MAAM;IAC3C,gBAAgB,CAAC,UAAeC,MAAAA,cAAc,KAAK,KAAK,MAAM;AAAA,IAC9D,OAAO,CAAC,UAAe,IAAI,KAAK,MAAM,KAAK;AAAA,EAC7C;AAAA,EACA;AAAA;AAAA,IAEE,oBAAoB,CAAC,UAAe,UAAU;AAAA,IAC9C,WAAW,OAAO,EAAE,YAAY;IAChC,gBAAgB,CAAC,UACfA,oBAAc,KAAK,KAAK,MAAM,eAAe;AAAA,IAC/C,OAAO,MAAM;AAAA,EACf;AACF;;"}
|
package/dist/cjs/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import * as React from 'react'\n\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\n// export type Expand<T> = T\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = Omit<\n TRight,\n keyof TLeft\n> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n}\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type Assign<TLeft, TRight> = keyof TLeft extends never\n ? TRight\n : keyof TRight extends never\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type MergeUnionObjects<TUnion> = TUnion extends MergeUnionPrimitive\n ? never\n : TUnion\n\nexport type MergeUnionObject<TUnion> =\n MergeUnionObjects<TUnion> extends infer TObj\n ? {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeUnionPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n\nexport type MergeUnionPrimitives<TUnion> = TUnion extends MergeUnionPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type MergeUnion<TUnion> =\n | MergeUnionPrimitives<TUnion>\n | MergeUnionObject<TUnion>\n\nexport function last<T>(arr: Array<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\nexport function functionalUpdate<TResult>(\n updater: Updater<TResult> | NonNullableUpdater<TResult>,\n previous: TResult,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nexport function pick<TValue, TKey extends keyof TValue>(\n parent: TValue,\n keys: Array<TKey>,\n): Pick<TValue, TKey> {\n return keys.reduce((obj: any, key: TKey) => {\n obj[key] = parent[key]\n return obj\n }, {} as any)\n}\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(prev: any, _next: T): T {\n if (prev === _next) {\n return prev\n }\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (array || (isPlainObject(prev) && isPlainObject(next))) {\n const prevItems = array ? prev : Object.keys(prev)\n const prevSize = prevItems.length\n const nextItems = array ? next : Object.keys(next)\n const nextSize = nextItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n if (\n ((!array && prevItems.includes(key)) || array) &&\n prev[key] === undefined &&\n next[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(prev[key], next[key])\n if (copy[key] === prev[key] && prev[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n }\n\n return next\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\nexport function deepEqual(a: any, b: any, partial: boolean = false): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a).filter((key) => a[key] !== undefined)\n const bKeys = Object.keys(b).filter((key) => b[key] !== undefined)\n\n if (!partial && aKeys.length !== bKeys.length) {\n return false\n }\n\n return !bKeys.some(\n (key) => !(key in a) || !deepEqual(a[key], b[key], partial),\n )\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return false\n }\n return !a.some((item, index) => !deepEqual(item, b[index], partial))\n }\n\n return false\n}\n\nexport function useStableCallback<T extends (...args: Array<any>) => any>(\n fn: T,\n): T {\n const fnRef = React.useRef(fn)\n fnRef.current = fn\n\n const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))\n return ref.current as T\n}\n\nexport function shallow<T>(objA: T, objB: T) {\n if (Object.is(objA, objB)) {\n return true\n }\n\n if (\n typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null\n ) {\n return false\n }\n\n const keysA = Object.keys(objA)\n if (keysA.length !== Object.keys(objB).length) {\n return false\n }\n\n for (const item of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(objB, item) ||\n !Object.is(objA[item as keyof T], objB[item as keyof T])\n ) {\n return false\n }\n }\n return true\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type StrictOrFrom<\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: StringLiteral<TFrom> | TFrom\n strict?: TStrict\n }\n\nexport const useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\n/**\n *\n * @deprecated use `jsesc` instead\n */\nexport function 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\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\n/**\n * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3\n */\nexport function usePrevious<T>(value: T): T | null {\n // initialise the ref with previous and current values\n const ref = React.useRef<{ value: T; prev: T | null }>({\n value: value,\n prev: null,\n })\n\n const current = ref.current.value\n\n // if the value passed into hook doesn't match what we store as \"current\"\n // move the \"current\" to the \"previous\"\n // and store the passed value as \"current\"\n if (value !== current) {\n ref.current = {\n value: value,\n prev: current,\n }\n }\n\n // return the previous value only\n return ref.current.prev\n}\n\n/**\n * React hook to wrap `IntersectionObserver`.\n *\n * This hook will create an `IntersectionObserver` and observe the ref passed to it.\n *\n * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.\n *\n * @param ref - The ref to observe\n * @param intersectionObserverOptions - The options to pass to the IntersectionObserver\n * @param options - The options to pass to the hook\n * @param callback - The callback to call when the intersection changes\n * @returns The IntersectionObserver instance\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const ref = React.useRef<HTMLDivElement>(null)\n * useIntersectionObserver(\n * ref,\n * (entry) => { doSomething(entry) },\n * { rootMargin: '10px' },\n * { disabled: false }\n * )\n * return <div ref={ref} />\n * ```\n */\nexport function useIntersectionObserver<T extends Element>(\n ref: React.RefObject<T>,\n callback: (entry: IntersectionObserverEntry | undefined) => void,\n intersectionObserverOptions: IntersectionObserverInit = {},\n options: { disabled?: boolean } = {},\n): IntersectionObserver | null {\n const isIntersectionObserverAvailable = React.useRef(\n typeof IntersectionObserver === 'function',\n )\n\n const observerRef = React.useRef<IntersectionObserver | null>(null)\n\n React.useEffect(() => {\n if (\n !ref.current ||\n !isIntersectionObserverAvailable.current ||\n options.disabled\n ) {\n return\n }\n\n observerRef.current = new IntersectionObserver(([entry]) => {\n callback(entry)\n }, intersectionObserverOptions)\n\n observerRef.current.observe(ref.current)\n\n return () => {\n observerRef.current?.disconnect()\n }\n }, [callback, intersectionObserverOptions, options.disabled, ref])\n\n return observerRef.current\n}\n\n/**\n * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element.\n *\n * @param ref - The forwarded ref\n * @returns The inner ref returned by `useRef`\n * @example\n * ```tsx\n * const MyComponent = React.forwardRef((props, ref) => {\n * const innerRef = useForwardedRef(ref)\n * return <div ref={innerRef} />\n * })\n * ```\n */\nexport function useForwardedRef<T>(ref?: React.ForwardedRef<T>) {\n const innerRef = React.useRef<T>(null)\n\n React.useEffect(() => {\n if (!ref) return\n if (typeof ref === 'function') {\n ref(innerRef.current)\n } else {\n ref.current = innerRef.current\n }\n })\n\n return innerRef\n}\n"],"names":["React"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoGO,SAAS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,EAAA,CACD;AAEM,SAAA;AACT;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../src/utils.ts"],"sourcesContent":["import * as React from 'react'\n\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\nexport type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue\n ? TYesResult\n : TNoResult\n\nexport type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<\n TValue,\n TKey\n> &\n Required<Pick<TValue, TKey>>\n\nexport type PickRequired<T> = {\n [K in keyof T as undefined extends T[K] ? never : K]: T[K]\n}\n\n// from https://stackoverflow.com/a/76458160\nexport type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never\n\n// export type Expand<T> = T\nexport type Expand<T> = T extends object\n ? T extends infer O\n ? O extends Function\n ? O\n : { [K in keyof O]: O[K] }\n : never\n : T\n\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>\n }\n : T\n\nexport type MakeDifferenceOptional<TLeft, TRight> = Omit<\n TRight,\n keyof TLeft\n> & {\n [K in keyof TLeft & keyof TRight]?: TRight[K]\n}\n\n// from https://stackoverflow.com/a/53955431\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type IsUnion<T, U extends T = T> = (\n T extends any ? (U extends T ? false : true) : never\n) extends false\n ? false\n : true\n\nexport type Assign<TLeft, TRight> = keyof TLeft extends never\n ? TRight\n : keyof TRight extends never\n ? TLeft\n : keyof TLeft & keyof TRight extends never\n ? TLeft & TRight\n : Omit<TLeft, keyof TRight> & TRight\n\nexport type Timeout = ReturnType<typeof setTimeout>\n\nexport type Updater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev?: TPrevious) => TResult)\n\nexport type NonNullableUpdater<TPrevious, TResult = TPrevious> =\n | TResult\n | ((prev: TPrevious) => TResult)\n\nexport type MergeUnionObjects<TUnion> = TUnion extends MergeUnionPrimitive\n ? never\n : TUnion\n\nexport type MergeUnionObject<TUnion> =\n MergeUnionObjects<TUnion> extends infer TObj\n ? {\n [TKey in TObj extends any ? keyof TObj : never]?: TObj extends any\n ? TKey extends keyof TObj\n ? TObj[TKey]\n : never\n : never\n }\n : never\n\nexport type MergeUnionPrimitive =\n | ReadonlyArray<any>\n | number\n | string\n | bigint\n | boolean\n | symbol\n\nexport type MergeUnionPrimitives<TUnion> = TUnion extends MergeUnionPrimitive\n ? TUnion\n : TUnion extends object\n ? never\n : TUnion\n\nexport type MergeUnion<TUnion> =\n | MergeUnionPrimitives<TUnion>\n | MergeUnionObject<TUnion>\n\nexport type Constrain<T, TConstaint> =\n | (T extends TConstaint ? T : never)\n | TConstaint\n\nexport function last<T>(arr: Array<T>) {\n return arr[arr.length - 1]\n}\n\nfunction isFunction(d: any): d is Function {\n return typeof d === 'function'\n}\n\nexport function functionalUpdate<TResult>(\n updater: Updater<TResult> | NonNullableUpdater<TResult>,\n previous: TResult,\n): TResult {\n if (isFunction(updater)) {\n return updater(previous)\n }\n\n return updater\n}\n\nexport function pick<TValue, TKey extends keyof TValue>(\n parent: TValue,\n keys: Array<TKey>,\n): Pick<TValue, TKey> {\n return keys.reduce((obj: any, key: TKey) => {\n obj[key] = parent[key]\n return obj\n }, {} as any)\n}\n\n/**\n * This function returns `prev` if `_next` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between immutable JSON values for example.\n * Do not use this with signals\n */\nexport function replaceEqualDeep<T>(prev: any, _next: T): T {\n if (prev === _next) {\n return prev\n }\n\n const next = _next as any\n\n const array = isPlainArray(prev) && isPlainArray(next)\n\n if (array || (isPlainObject(prev) && isPlainObject(next))) {\n const prevItems = array ? prev : Object.keys(prev)\n const prevSize = prevItems.length\n const nextItems = array ? next : Object.keys(next)\n const nextSize = nextItems.length\n const copy: any = array ? [] : {}\n\n let equalItems = 0\n\n for (let i = 0; i < nextSize; i++) {\n const key = array ? i : (nextItems[i] as any)\n if (\n ((!array && prevItems.includes(key)) || array) &&\n prev[key] === undefined &&\n next[key] === undefined\n ) {\n copy[key] = undefined\n equalItems++\n } else {\n copy[key] = replaceEqualDeep(prev[key], next[key])\n if (copy[key] === prev[key] && prev[key] !== undefined) {\n equalItems++\n }\n }\n }\n\n return prevSize === nextSize && equalItems === prevSize ? prev : copy\n }\n\n return next\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\nexport function isPlainObject(o: any) {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has modified constructor\n const ctor = o.constructor\n if (typeof ctor === 'undefined') {\n return true\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\nfunction hasObjectPrototype(o: any) {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\nexport function deepEqual(a: any, b: any, partial: boolean = false): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a).filter((key) => a[key] !== undefined)\n const bKeys = Object.keys(b).filter((key) => b[key] !== undefined)\n\n if (!partial && aKeys.length !== bKeys.length) {\n return false\n }\n\n return !bKeys.some(\n (key) => !(key in a) || !deepEqual(a[key], b[key], partial),\n )\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return false\n }\n return !a.some((item, index) => !deepEqual(item, b[index], partial))\n }\n\n return false\n}\n\nexport function useStableCallback<T extends (...args: Array<any>) => any>(\n fn: T,\n): T {\n const fnRef = React.useRef(fn)\n fnRef.current = fn\n\n const ref = React.useRef((...args: Array<any>) => fnRef.current(...args))\n return ref.current as T\n}\n\nexport function shallow<T>(objA: T, objB: T) {\n if (Object.is(objA, objB)) {\n return true\n }\n\n if (\n typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null\n ) {\n return false\n }\n\n const keysA = Object.keys(objA)\n if (keysA.length !== Object.keys(objB).length) {\n return false\n }\n\n for (const item of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(objB, item) ||\n !Object.is(objA[item as keyof T], objB[item as keyof T])\n ) {\n return false\n }\n }\n return true\n}\n\nexport type StringLiteral<T> = T extends string\n ? string extends T\n ? string\n : T\n : never\n\nexport type StrictOrFrom<\n TFrom,\n TStrict extends boolean = true,\n> = TStrict extends false\n ? {\n from?: never\n strict: TStrict\n }\n : {\n from: StringLiteral<TFrom> | TFrom\n strict?: TStrict\n }\n\nexport const useLayoutEffect =\n typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect\n\n/**\n *\n * @deprecated use `jsesc` instead\n */\nexport function 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\nexport type ControlledPromise<T> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value: any) => void\n status: 'pending' | 'resolved' | 'rejected'\n value?: T\n}\n\nexport function createControlledPromise<T>(onResolve?: (value: T) => void) {\n let resolveLoadPromise!: (value: T) => void\n let rejectLoadPromise!: (value: any) => void\n\n const controlledPromise = new Promise<T>((resolve, reject) => {\n resolveLoadPromise = resolve\n rejectLoadPromise = reject\n }) as ControlledPromise<T>\n\n controlledPromise.status = 'pending'\n\n controlledPromise.resolve = (value: T) => {\n controlledPromise.status = 'resolved'\n controlledPromise.value = value\n resolveLoadPromise(value)\n onResolve?.(value)\n }\n\n controlledPromise.reject = (e) => {\n controlledPromise.status = 'rejected'\n rejectLoadPromise(e)\n }\n\n return controlledPromise\n}\n\n/**\n * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3\n */\nexport function usePrevious<T>(value: T): T | null {\n // initialise the ref with previous and current values\n const ref = React.useRef<{ value: T; prev: T | null }>({\n value: value,\n prev: null,\n })\n\n const current = ref.current.value\n\n // if the value passed into hook doesn't match what we store as \"current\"\n // move the \"current\" to the \"previous\"\n // and store the passed value as \"current\"\n if (value !== current) {\n ref.current = {\n value: value,\n prev: current,\n }\n }\n\n // return the previous value only\n return ref.current.prev\n}\n\n/**\n * React hook to wrap `IntersectionObserver`.\n *\n * This hook will create an `IntersectionObserver` and observe the ref passed to it.\n *\n * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`.\n *\n * @param ref - The ref to observe\n * @param intersectionObserverOptions - The options to pass to the IntersectionObserver\n * @param options - The options to pass to the hook\n * @param callback - The callback to call when the intersection changes\n * @returns The IntersectionObserver instance\n * @example\n * ```tsx\n * const MyComponent = () => {\n * const ref = React.useRef<HTMLDivElement>(null)\n * useIntersectionObserver(\n * ref,\n * (entry) => { doSomething(entry) },\n * { rootMargin: '10px' },\n * { disabled: false }\n * )\n * return <div ref={ref} />\n * ```\n */\nexport function useIntersectionObserver<T extends Element>(\n ref: React.RefObject<T>,\n callback: (entry: IntersectionObserverEntry | undefined) => void,\n intersectionObserverOptions: IntersectionObserverInit = {},\n options: { disabled?: boolean } = {},\n): IntersectionObserver | null {\n const isIntersectionObserverAvailable = React.useRef(\n typeof IntersectionObserver === 'function',\n )\n\n const observerRef = React.useRef<IntersectionObserver | null>(null)\n\n React.useEffect(() => {\n if (\n !ref.current ||\n !isIntersectionObserverAvailable.current ||\n options.disabled\n ) {\n return\n }\n\n observerRef.current = new IntersectionObserver(([entry]) => {\n callback(entry)\n }, intersectionObserverOptions)\n\n observerRef.current.observe(ref.current)\n\n return () => {\n observerRef.current?.disconnect()\n }\n }, [callback, intersectionObserverOptions, options.disabled, ref])\n\n return observerRef.current\n}\n\n/**\n * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element.\n *\n * @param ref - The forwarded ref\n * @returns The inner ref returned by `useRef`\n * @example\n * ```tsx\n * const MyComponent = React.forwardRef((props, ref) => {\n * const innerRef = useForwardedRef(ref)\n * return <div ref={innerRef} />\n * })\n * ```\n */\nexport function useForwardedRef<T>(ref?: React.ForwardedRef<T>) {\n const innerRef = React.useRef<T>(null)\n\n React.useEffect(() => {\n if (!ref) return\n if (typeof ref === 'function') {\n ref(innerRef.current)\n } else {\n ref.current = innerRef.current\n }\n })\n\n return innerRef\n}\n"],"names":["React"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyGO,SAAS,KAAQ,KAAe;AAC9B,SAAA,IAAI,IAAI,SAAS,CAAC;AAC3B;AAEA,SAAS,WAAW,GAAuB;AACzC,SAAO,OAAO,MAAM;AACtB;AAEgB,SAAA,iBACd,SACA,UACS;AACL,MAAA,WAAW,OAAO,GAAG;AACvB,WAAO,QAAQ,QAAQ;AAAA,EACzB;AAEO,SAAA;AACT;AAEgB,SAAA,KACd,QACA,MACoB;AACpB,SAAO,KAAK,OAAO,CAAC,KAAU,QAAc;AACtC,QAAA,GAAG,IAAI,OAAO,GAAG;AACd,WAAA;AAAA,EACT,GAAG,CAAS,CAAA;AACd;AAQgB,SAAA,iBAAoB,MAAW,OAAa;AAC1D,MAAI,SAAS,OAAO;AACX,WAAA;AAAA,EACT;AAEA,QAAM,OAAO;AAEb,QAAM,QAAQ,aAAa,IAAI,KAAK,aAAa,IAAI;AAErD,MAAI,SAAU,cAAc,IAAI,KAAK,cAAc,IAAI,GAAI;AACzD,UAAM,YAAY,QAAQ,OAAO,OAAO,KAAK,IAAI;AACjD,UAAM,WAAW,UAAU;AAC3B,UAAM,YAAY,QAAQ,OAAO,OAAO,KAAK,IAAI;AACjD,UAAM,WAAW,UAAU;AAC3B,UAAM,OAAY,QAAQ,CAAC,IAAI;AAE/B,QAAI,aAAa;AAEjB,aAAS,IAAI,GAAG,IAAI,UAAU,KAAK;AACjC,YAAM,MAAM,QAAQ,IAAK,UAAU,CAAC;AACpC,WACI,CAAC,SAAS,UAAU,SAAS,GAAG,KAAM,UACxC,KAAK,GAAG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,UAAU,6BAA6B,QAAQ,UAAU,GAAG,CAAC;AAEjE,SAAO,YAAY;AACrB;AAeO,SAAS,gBAAmB,KAA6B;AACxD,QAAA,WAAWA,iBAAM,OAAU,IAAI;AAErCA,mBAAM,UAAU,MAAM;AACpB,QAAI,CAAC,IAAK;AACN,QAAA,OAAO,QAAQ,YAAY;AAC7B,UAAI,SAAS,OAAO;AAAA,IAAA,OACf;AACL,UAAI,UAAU,SAAS;AAAA,IACzB;AAAA,EAAA,CACD;AAEM,SAAA;AACT;;;;;;;;;;;;;;;;"}
|
package/dist/cjs/utils.d.cts
CHANGED
|
@@ -27,6 +27,7 @@ export type MergeUnionObject<TUnion> = MergeUnionObjects<TUnion> extends infer T
|
|
|
27
27
|
export type MergeUnionPrimitive = ReadonlyArray<any> | number | string | bigint | boolean | symbol;
|
|
28
28
|
export type MergeUnionPrimitives<TUnion> = TUnion extends MergeUnionPrimitive ? TUnion : TUnion extends object ? never : TUnion;
|
|
29
29
|
export type MergeUnion<TUnion> = MergeUnionPrimitives<TUnion> | MergeUnionObject<TUnion>;
|
|
30
|
+
export type Constrain<T, TConstaint> = (T extends TConstaint ? T : never) | TConstaint;
|
|
30
31
|
export declare function last<T>(arr: Array<T>): T | undefined;
|
|
31
32
|
export declare function functionalUpdate<TResult>(updater: Updater<TResult> | NonNullableUpdater<TResult>, previous: TResult): TResult;
|
|
32
33
|
export declare function pick<TValue, TKey extends keyof TValue>(parent: TValue, keys: Array<TKey>): Pick<TValue, TKey>;
|
package/dist/esm/Matches.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { ResolveRelativePath, ToOptions } from './link.js';
|
|
|
4
4
|
import { AllContext, AllLoaderData, AllParams, FullSearchSchema, ParseRoute, RouteById, RouteByPath, RouteIds, RoutePaths } from './routeInfo.js';
|
|
5
5
|
import { ControlledPromise, DeepPartial, NoInfer } from './utils.js';
|
|
6
6
|
import * as React from 'react';
|
|
7
|
-
export interface RouteMatch<TRouteId, TAllParams, TFullSearchSchema, TLoaderData, TAllContext,
|
|
7
|
+
export interface RouteMatch<TRouteId, TAllParams, TFullSearchSchema, TLoaderData, TAllContext, TLoaderDeps> {
|
|
8
8
|
id: string;
|
|
9
9
|
routeId: TRouteId;
|
|
10
10
|
index: number;
|
|
@@ -21,7 +21,8 @@ export interface RouteMatch<TRouteId, TAllParams, TFullSearchSchema, TLoaderData
|
|
|
21
21
|
beforeLoadPromise?: ControlledPromise<void>;
|
|
22
22
|
loaderPromise?: ControlledPromise<void>;
|
|
23
23
|
loaderData?: TLoaderData;
|
|
24
|
-
|
|
24
|
+
__routeContext: Record<string, unknown>;
|
|
25
|
+
__beforeLoadContext: Record<string, unknown>;
|
|
25
26
|
context: TAllContext;
|
|
26
27
|
search: TFullSearchSchema;
|
|
27
28
|
fetchCount: number;
|
|
@@ -39,8 +40,8 @@ export interface RouteMatch<TRouteId, TAllParams, TFullSearchSchema, TLoaderData
|
|
|
39
40
|
minPendingPromise?: ControlledPromise<void>;
|
|
40
41
|
pendingTimeout?: ReturnType<typeof setTimeout>;
|
|
41
42
|
}
|
|
42
|
-
export type MakeRouteMatch<TRouteTree extends AnyRoute = RegisteredRouter['routeTree'], TRouteId = ParseRoute<TRouteTree>['id'], TStrict extends boolean = true, TTypes extends AnyRoute['types'] = RouteById<TRouteTree, TRouteId>['types'], TAllParams = TStrict extends false ? AllParams<TRouteTree> : TTypes['allParams'], TFullSearchSchema = TStrict extends false ? FullSearchSchema<TRouteTree> : TTypes['fullSearchSchema'], TLoaderData = TStrict extends false ? AllLoaderData<TRouteTree> : TTypes['loaderData'], TAllContext = TStrict extends false ? AllContext<TRouteTree> : TTypes['allContext'],
|
|
43
|
-
export type AnyRouteMatch = RouteMatch<any, any, any, any, any, any
|
|
43
|
+
export type MakeRouteMatch<TRouteTree extends AnyRoute = RegisteredRouter['routeTree'], TRouteId = ParseRoute<TRouteTree>['id'], TStrict extends boolean = true, TTypes extends AnyRoute['types'] = RouteById<TRouteTree, TRouteId>['types'], TAllParams = TStrict extends false ? AllParams<TRouteTree> : TTypes['allParams'], TFullSearchSchema = TStrict extends false ? FullSearchSchema<TRouteTree> : TTypes['fullSearchSchema'], TLoaderData = TStrict extends false ? AllLoaderData<TRouteTree> : TTypes['loaderData'], TAllContext = TStrict extends false ? AllContext<TRouteTree> : TTypes['allContext'], TLoaderDeps = TTypes['loaderDeps']> = RouteMatch<TRouteId, TAllParams, TFullSearchSchema, TLoaderData, TAllContext, TLoaderDeps>;
|
|
44
|
+
export type AnyRouteMatch = RouteMatch<any, any, any, any, any, any>;
|
|
44
45
|
export declare function Matches(): import("react/jsx-runtime").JSX.Element;
|
|
45
46
|
export interface MatchRouteOptions {
|
|
46
47
|
pending?: boolean;
|
package/dist/esm/Matches.js
CHANGED
|
@@ -7,10 +7,12 @@ import { useRouter } from "./useRouter.js";
|
|
|
7
7
|
import { Transitioner } from "./Transitioner.js";
|
|
8
8
|
import { matchContext } from "./matchContext.js";
|
|
9
9
|
import { Match } from "./Match.js";
|
|
10
|
+
import { SafeFragment } from "./SafeFragment.js";
|
|
10
11
|
function Matches() {
|
|
11
12
|
const router = useRouter();
|
|
12
13
|
const pendingElement = router.options.defaultPendingComponent ? /* @__PURE__ */ jsx(router.options.defaultPendingComponent, {}) : null;
|
|
13
|
-
const
|
|
14
|
+
const ResolvedSuspense = router.isServer || typeof document !== "undefined" && window.__TSR__ ? SafeFragment : React.Suspense;
|
|
15
|
+
const inner = /* @__PURE__ */ jsxs(ResolvedSuspense, { fallback: pendingElement, children: [
|
|
14
16
|
/* @__PURE__ */ jsx(Transitioner, {}),
|
|
15
17
|
/* @__PURE__ */ jsx(MatchesInner, {})
|
|
16
18
|
] });
|
package/dist/esm/Matches.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Matches.js","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport {\n type AnyRoute,\n type ReactNode,\n type StaticDataRouteOption,\n} from './route'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type { AnyRouter, RegisteredRouter } from './router'\nimport type { ResolveRelativePath, ToOptions } from './link'\nimport type {\n AllContext,\n AllLoaderData,\n AllParams,\n FullSearchSchema,\n ParseRoute,\n RouteById,\n RouteByPath,\n RouteIds,\n RoutePaths,\n} from './routeInfo'\nimport type { ControlledPromise, DeepPartial, NoInfer } from './utils'\n\nexport interface RouteMatch<\n TRouteId,\n TAllParams,\n TFullSearchSchema,\n TLoaderData,\n TAllContext,\n TRouteContext,\n TLoaderDeps,\n> {\n id: string\n routeId: TRouteId\n index: number\n pathname: string\n params: TAllParams\n status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'\n isFetching: false | 'beforeLoad' | 'loader'\n error: unknown\n paramsError: unknown\n searchError: unknown\n updatedAt: number\n componentsPromise?: Promise<Array<void>>\n loadPromise?: ControlledPromise<void>\n beforeLoadPromise?: ControlledPromise<void>\n loaderPromise?: ControlledPromise<void>\n loaderData?: TLoaderData\n routeContext: TRouteContext\n context: TAllContext\n search: TFullSearchSchema\n fetchCount: number\n abortController: AbortController\n cause: 'preload' | 'enter' | 'stay'\n loaderDeps: TLoaderDeps\n preload: boolean\n invalid: boolean\n meta?: Array<React.JSX.IntrinsicElements['meta']>\n links?: Array<React.JSX.IntrinsicElements['link']>\n scripts?: Array<React.JSX.IntrinsicElements['script']>\n headers?: Record<string, string>\n globalNotFound?: boolean\n staticData: StaticDataRouteOption\n minPendingPromise?: ControlledPromise<void>\n pendingTimeout?: ReturnType<typeof setTimeout>\n}\n\nexport type MakeRouteMatch<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId = ParseRoute<TRouteTree>['id'],\n TStrict extends boolean = true,\n TTypes extends AnyRoute['types'] = RouteById<TRouteTree, TRouteId>['types'],\n TAllParams = TStrict extends false\n ? AllParams<TRouteTree>\n : TTypes['allParams'],\n TFullSearchSchema = TStrict extends false\n ? FullSearchSchema<TRouteTree>\n : TTypes['fullSearchSchema'],\n TLoaderData = TStrict extends false\n ? AllLoaderData<TRouteTree>\n : TTypes['loaderData'],\n TAllContext = TStrict extends false\n ? AllContext<TRouteTree>\n : TTypes['allContext'],\n TRouteContext = TTypes['routeContext'],\n TLoaderDeps = TTypes['loaderDeps'],\n> = RouteMatch<\n TRouteId,\n TAllParams,\n TFullSearchSchema,\n TLoaderData,\n TAllContext,\n TRouteContext,\n TLoaderDeps\n>\n\nexport type AnyRouteMatch = RouteMatch<any, any, any, any, any, any, any>\n\nexport function Matches() {\n const router = useRouter()\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n const inner = (\n <React.Suspense fallback={pendingElement}>\n <Transitioner />\n <MatchesInner />\n </React.Suspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n return (\n <matchContext.Provider value={matchId}>\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchId ? <Match matchId={matchId} /> : null}\n </CatchBoundary>\n </matchContext.Provider>\n )\n}\n\nexport interface MatchRouteOptions {\n pending?: boolean\n caseSensitive?: boolean\n includeSearch?: boolean\n fuzzy?: boolean\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n TOptions extends ToOptions<\n TRouter,\n TFrom,\n TTo,\n TMaskFrom,\n TMaskTo\n > = ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n TRelaxedOptions = Omit<TOptions, 'search' | 'params'> &\n DeepPartial<Pick<TOptions, 'search' | 'params'>>,\n> = TRelaxedOptions & MatchRouteOptions\n\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation.href, s.status],\n })\n\n return React.useCallback(\n <\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '',\n TResolved extends string = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | RouteByPath<TRouter['routeTree'], TResolved>['types']['allParams'] => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => ReactNode)\n | React.ReactNode\n}\n\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any)\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport function useMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n return useRouterState({\n select: (state) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n\nexport function useParentMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n\nexport function useChildMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n"],"names":[],"mappings":";;;;;;;;;AAwGO,SAAS,UAAU;AACxB,QAAM,SAAS;AAET,QAAA,iBAAiB,OAAO,QAAQ,8CACnC,OAAO,QAAQ,yBAAf,CAAuC,CAAA,IACtC;AAEJ,QAAM,QACH,qBAAA,MAAM,UAAN,EAAe,UAAU,gBACxB,UAAA;AAAA,IAAA,oBAAC,cAAa,EAAA;AAAA,wBACb,cAAa,EAAA;AAAA,EAChB,EAAA,CAAA;AAGK,SAAA,OAAO,QAAQ,YACpB,oBAAC,OAAO,QAAQ,WAAf,EAA0B,UAAA,MAAM,CAAA,IAEjC;AAEJ;AAEA,SAAS,eAAe;AACtB,QAAM,UAAU,eAAe;AAAA,IAC7B,QAAQ,CAAC,MAAM;;AACN,cAAA,OAAE,QAAQ,CAAC,MAAX,mBAAc;AAAA,IACvB;AAAA,EAAA,CACD;AAED,QAAM,WAAW,eAAe;AAAA,IAC9B,QAAQ,CAAC,MAAM,EAAE;AAAA,EAAA,CAClB;AAED,SACG,oBAAA,aAAa,UAAb,EAAsB,OAAO,SAC5B,UAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,aAAa,MAAM;AAAA,MACnB,gBAAgB;AAAA,MAChB,SAAS,CAAC,UAAU;AAClB;AAAA,UACE;AAAA,UACA;AAAA,QAAA;AAEF,gBAAQ,OAAO,MAAM,WAAW,MAAM,UAAU;AAAA,MAClD;AAAA,MAEC,UAAU,UAAA,oBAAC,OAAM,EAAA,QAAkB,CAAA,IAAK;AAAA,IAAA;AAAA,EAE7C,EAAA,CAAA;AAEJ;AA4BO,SAAS,gBAA8D;AAC5E,QAAM,SAAS;AAEA,iBAAA;AAAA,IACb,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,iBAAiB,MAAM,EAAE,MAAM;AAAA,EAAA,CAC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"file":"Matches.js","sources":["../../src/Matches.tsx"],"sourcesContent":["import * as React from 'react'\nimport warning from 'tiny-warning'\nimport { CatchBoundary, ErrorComponent } from './CatchBoundary'\nimport { useRouterState } from './useRouterState'\nimport { useRouter } from './useRouter'\nimport { Transitioner } from './Transitioner'\nimport {\n type AnyRoute,\n type ReactNode,\n type StaticDataRouteOption,\n} from './route'\nimport { matchContext } from './matchContext'\nimport { Match } from './Match'\nimport { SafeFragment } from './SafeFragment'\nimport type { AnyRouter, RegisteredRouter } from './router'\nimport type { ResolveRelativePath, ToOptions } from './link'\nimport type {\n AllContext,\n AllLoaderData,\n AllParams,\n FullSearchSchema,\n ParseRoute,\n RouteById,\n RouteByPath,\n RouteIds,\n RoutePaths,\n} from './routeInfo'\nimport type { ControlledPromise, DeepPartial, NoInfer } from './utils'\n\nexport interface RouteMatch<\n TRouteId,\n TAllParams,\n TFullSearchSchema,\n TLoaderData,\n TAllContext,\n TLoaderDeps,\n> {\n id: string\n routeId: TRouteId\n index: number\n pathname: string\n params: TAllParams\n status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'\n isFetching: false | 'beforeLoad' | 'loader'\n error: unknown\n paramsError: unknown\n searchError: unknown\n updatedAt: number\n componentsPromise?: Promise<Array<void>>\n loadPromise?: ControlledPromise<void>\n beforeLoadPromise?: ControlledPromise<void>\n loaderPromise?: ControlledPromise<void>\n loaderData?: TLoaderData\n __routeContext: Record<string, unknown>\n __beforeLoadContext: Record<string, unknown>\n context: TAllContext\n search: TFullSearchSchema\n fetchCount: number\n abortController: AbortController\n cause: 'preload' | 'enter' | 'stay'\n loaderDeps: TLoaderDeps\n preload: boolean\n invalid: boolean\n meta?: Array<React.JSX.IntrinsicElements['meta']>\n links?: Array<React.JSX.IntrinsicElements['link']>\n scripts?: Array<React.JSX.IntrinsicElements['script']>\n headers?: Record<string, string>\n globalNotFound?: boolean\n staticData: StaticDataRouteOption\n minPendingPromise?: ControlledPromise<void>\n pendingTimeout?: ReturnType<typeof setTimeout>\n}\n\nexport type MakeRouteMatch<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId = ParseRoute<TRouteTree>['id'],\n TStrict extends boolean = true,\n TTypes extends AnyRoute['types'] = RouteById<TRouteTree, TRouteId>['types'],\n TAllParams = TStrict extends false\n ? AllParams<TRouteTree>\n : TTypes['allParams'],\n TFullSearchSchema = TStrict extends false\n ? FullSearchSchema<TRouteTree>\n : TTypes['fullSearchSchema'],\n TLoaderData = TStrict extends false\n ? AllLoaderData<TRouteTree>\n : TTypes['loaderData'],\n TAllContext = TStrict extends false\n ? AllContext<TRouteTree>\n : TTypes['allContext'],\n TLoaderDeps = TTypes['loaderDeps'],\n> = RouteMatch<\n TRouteId,\n TAllParams,\n TFullSearchSchema,\n TLoaderData,\n TAllContext,\n TLoaderDeps\n>\n\nexport type AnyRouteMatch = RouteMatch<any, any, any, any, any, any>\n\nexport function Matches() {\n const router = useRouter()\n\n const pendingElement = router.options.defaultPendingComponent ? (\n <router.options.defaultPendingComponent />\n ) : null\n\n // Do not render a root Suspense during SSR or hydrating from SSR\n const ResolvedSuspense =\n router.isServer || (typeof document !== 'undefined' && window.__TSR__)\n ? SafeFragment\n : React.Suspense\n\n const inner = (\n <ResolvedSuspense fallback={pendingElement}>\n <Transitioner />\n <MatchesInner />\n </ResolvedSuspense>\n )\n\n return router.options.InnerWrap ? (\n <router.options.InnerWrap>{inner}</router.options.InnerWrap>\n ) : (\n inner\n )\n}\n\nfunction MatchesInner() {\n const matchId = useRouterState({\n select: (s) => {\n return s.matches[0]?.id\n },\n })\n\n const resetKey = useRouterState({\n select: (s) => s.loadedAt,\n })\n\n return (\n <matchContext.Provider value={matchId}>\n <CatchBoundary\n getResetKey={() => resetKey}\n errorComponent={ErrorComponent}\n onCatch={(error) => {\n warning(\n false,\n `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`,\n )\n warning(false, error.message || error.toString())\n }}\n >\n {matchId ? <Match matchId={matchId} /> : null}\n </CatchBoundary>\n </matchContext.Provider>\n )\n}\n\nexport interface MatchRouteOptions {\n pending?: boolean\n caseSensitive?: boolean\n includeSearch?: boolean\n fuzzy?: boolean\n}\n\nexport type UseMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n TOptions extends ToOptions<\n TRouter,\n TFrom,\n TTo,\n TMaskFrom,\n TMaskTo\n > = ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n TRelaxedOptions = Omit<TOptions, 'search' | 'params'> &\n DeepPartial<Pick<TOptions, 'search' | 'params'>>,\n> = TRelaxedOptions & MatchRouteOptions\n\nexport function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() {\n const router = useRouter()\n\n useRouterState({\n select: (s) => [s.location.href, s.resolvedLocation.href, s.status],\n })\n\n return React.useCallback(\n <\n TFrom extends RoutePaths<TRouter['routeTree']> | string = string,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,\n TMaskTo extends string = '',\n TResolved extends string = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n ):\n | false\n | RouteByPath<TRouter['routeTree'], TResolved>['types']['allParams'] => {\n const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts\n\n return router.matchRoute(rest as any, {\n pending,\n caseSensitive,\n fuzzy,\n includeSearch,\n })\n },\n [router],\n )\n}\n\nexport type MakeMatchRouteOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n> = UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {\n // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns\n children?:\n | ((\n params?: RouteByPath<\n TRouter['routeTree'],\n ResolveRelativePath<TFrom, NoInfer<TTo>>\n >['types']['allParams'],\n ) => ReactNode)\n | React.ReactNode\n}\n\nexport function MatchRoute<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends RoutePaths<TRouter['routeTree']> = RoutePaths<\n TRouter['routeTree']\n >,\n TTo extends string = '',\n TMaskFrom extends RoutePaths<TRouter['routeTree']> = TFrom,\n TMaskTo extends string = '',\n>(props: MakeMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>): any {\n const matchRoute = useMatchRoute()\n const params = matchRoute(props as any)\n\n if (typeof props.children === 'function') {\n return (props.children as any)(params)\n }\n\n return params ? props.children : null\n}\n\nexport function useMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n return useRouterState({\n select: (state) => {\n const matches = state.matches\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n\nexport function useParentMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches) => {\n matches = matches.slice(\n 0,\n matches.findIndex((d) => d.id === contextMatchId),\n )\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n\nexport function useChildMatches<\n TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],\n TRouteId extends RouteIds<TRouteTree> = ParseRoute<TRouteTree>['id'],\n TRouteMatch = MakeRouteMatch<TRouteTree, TRouteId>,\n T = Array<TRouteMatch>,\n>(opts?: { select?: (matches: Array<TRouteMatch>) => T }): T {\n const contextMatchId = React.useContext(matchContext)\n\n return useMatches({\n select: (matches) => {\n matches = matches.slice(\n matches.findIndex((d) => d.id === contextMatchId) + 1,\n )\n return opts?.select\n ? opts.select(matches as Array<TRouteMatch>)\n : (matches as T)\n },\n })\n}\n"],"names":[],"mappings":";;;;;;;;;;AAsGO,SAAS,UAAU;AACxB,QAAM,SAAS;AAET,QAAA,iBAAiB,OAAO,QAAQ,8CACnC,OAAO,QAAQ,yBAAf,CAAuC,CAAA,IACtC;AAGE,QAAA,mBACJ,OAAO,YAAa,OAAO,aAAa,eAAe,OAAO,UAC1D,eACA,MAAM;AAEZ,QAAM,QACJ,qBAAC,kBAAiB,EAAA,UAAU,gBAC1B,UAAA;AAAA,IAAA,oBAAC,cAAa,EAAA;AAAA,wBACb,cAAa,EAAA;AAAA,EAChB,EAAA,CAAA;AAGK,SAAA,OAAO,QAAQ,YACpB,oBAAC,OAAO,QAAQ,WAAf,EAA0B,UAAA,MAAM,CAAA,IAEjC;AAEJ;AAEA,SAAS,eAAe;AACtB,QAAM,UAAU,eAAe;AAAA,IAC7B,QAAQ,CAAC,MAAM;;AACN,cAAA,OAAE,QAAQ,CAAC,MAAX,mBAAc;AAAA,IACvB;AAAA,EAAA,CACD;AAED,QAAM,WAAW,eAAe;AAAA,IAC9B,QAAQ,CAAC,MAAM,EAAE;AAAA,EAAA,CAClB;AAED,SACG,oBAAA,aAAa,UAAb,EAAsB,OAAO,SAC5B,UAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,aAAa,MAAM;AAAA,MACnB,gBAAgB;AAAA,MAChB,SAAS,CAAC,UAAU;AAClB;AAAA,UACE;AAAA,UACA;AAAA,QAAA;AAEF,gBA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SAAS,gBAKd,MAA2D;AACrD,QAAA,iBAAiB,MAAM,WAAW,YAAY;AAEpD,SAAO,WAAW;AAAA,IAChB,QAAQ,CAAC,YAAY;AACnB,gBAAU,QAAQ;AAAA,QAChB,QAAQ,UAAU,CAAC,MAAM,EAAE,OAAO,cAAc,IAAI;AAAA,MAAA;AAEtD,cAAO,6BAAM,UACT,KAAK,OAAO,OAA6B,IACxC;AAAA,IACP;AAAA,EAAA,CACD;AACH;"}
|
package/dist/esm/Transitioner.js
CHANGED
|
@@ -37,7 +37,7 @@ function Transitioner() {
|
|
|
37
37
|
}, [router, router.history]);
|
|
38
38
|
useLayoutEffect(() => {
|
|
39
39
|
var _a;
|
|
40
|
-
if (((_a = window.__TSR__) == null ? void 0 : _a.dehydrated) || mountLoadForRouter.current.router === router && mountLoadForRouter.current.mounted) {
|
|
40
|
+
if (typeof window !== "undefined" && ((_a = window.__TSR__) == null ? void 0 : _a.dehydrated) || mountLoadForRouter.current.router === router && mountLoadForRouter.current.mounted) {
|
|
41
41
|
return;
|
|
42
42
|
}
|
|
43
43
|
mountLoadForRouter.current = { router, mounted: true };
|
|
@@ -80,7 +80,7 @@ function Transitioner() {
|
|
|
80
80
|
status: "idle",
|
|
81
81
|
resolvedLocation: s.location
|
|
82
82
|
}));
|
|
83
|
-
if (document.querySelector) {
|
|
83
|
+
if (typeof document !== "undefined" && document.querySelector) {
|
|
84
84
|
if (router.state.location.hash !== "") {
|
|
85
85
|
const el = document.getElementById(router.state.location.hash);
|
|
86
86
|
if (el) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Transitioner.js","sources":["../../src/Transitioner.tsx"],"sourcesContent":["import * as React from 'react'\nimport { pick, useLayoutEffect, usePrevious } from './utils'\nimport { useRouter } from './useRouter'\nimport { useRouterState } from './useRouterState'\nimport { trimPathRight } from './path'\n\nexport function Transitioner() {\n const router = useRouter()\n const mountLoadForRouter = React.useRef({ router, mounted: false })\n const routerState = useRouterState({\n select: (s) =>\n pick(s, ['isLoading', 'location', 'resolvedLocation', 'isTransitioning']),\n })\n\n const [isTransitioning, startReactTransition_] = React.useTransition()\n // Track pending state changes\n const hasPendingMatches = useRouterState({\n select: (s) => s.matches.some((d) => d.status === 'pending'),\n })\n\n const previousIsLoading = usePrevious(routerState.isLoading)\n\n const isAnyPending =\n routerState.isLoading || isTransitioning || hasPendingMatches\n const previousIsAnyPending = usePrevious(isAnyPending)\n\n if (!router.isServer) {\n router.startReactTransition = startReactTransition_\n }\n\n // Subscribe to location changes\n // and try to load the new location\n React.useEffect(() => {\n const unsub = router.history.subscribe(router.load)\n\n const nextLocation = router.buildLocation({\n to: router.latestLocation.pathname,\n search: true,\n params: true,\n hash: true,\n state: true,\n })\n\n if (\n trimPathRight(router.latestLocation.href) !==\n trimPathRight(nextLocation.href)\n ) {\n router.commitLocation({ ...nextLocation, replace: true })\n }\n\n return () => {\n unsub()\n }\n }, [router, router.history])\n\n // Try to load the initial location\n useLayoutEffect(() => {\n if (\n window.__TSR__?.dehydrated ||\n (mountLoadForRouter.current.router === router &&\n mountLoadForRouter.current.mounted)\n ) {\n return\n }\n mountLoadForRouter.current = { router, mounted: true }\n\n const tryLoad = async () => {\n try {\n await router.load()\n } catch (err) {\n console.error(err)\n }\n }\n\n tryLoad()\n }, [router])\n\n useLayoutEffect(() => {\n // The router was loading and now it's not\n if (previousIsLoading && !routerState.isLoading) {\n const toLocation = router.state.location\n const fromLocation = router.state.resolvedLocation\n const pathChanged = fromLocation.href !== toLocation.href\n\n router.emit({\n type: 'onLoad', // When the new URL has committed, when the new matches have been loaded into state.matches\n fromLocation,\n toLocation,\n pathChanged,\n })\n }\n }, [previousIsLoading, router, routerState.isLoading])\n\n useLayoutEffect(() => {\n // The router was pending and now it's not\n if (previousIsAnyPending && !isAnyPending) {\n const toLocation = router.state.location\n const fromLocation = router.state.resolvedLocation\n const pathChanged = fromLocation.href !== toLocation.href\n\n router.emit({\n type: 'onResolved',\n fromLocation,\n toLocation,\n pathChanged,\n })\n\n router.__store.setState((s) => ({\n ...s,\n status: 'idle',\n resolvedLocation: s.location,\n }))\n\n if ((document as any).querySelector) {\n if (router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView()\n }\n }\n }\n }\n }, [isAnyPending, previousIsAnyPending, router])\n\n return null\n}\n"],"names":[],"mappings":";;;;;AAMO,SAAS,eAAe;AAC7B,QAAM,SAAS;AACf,QAAM,qBAAqB,MAAM,OAAO,EAAE,QAAQ,SAAS,OAAO;AAClE,QAAM,cAAc,eAAe;AAAA,IACjC,QAAQ,CAAC,MACP,KAAK,GAAG,CAAC,aAAa,YAAY,oBAAoB,iBAAiB,CAAC;AAAA,EAAA,CAC3E;AAED,QAAM,CAAC,iBAAiB,qBAAqB,IAAI,MAAM,cAAc;AAErE,QAAM,oBAAoB,eAAe;AAAA,IACvC,QAAQ,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,WAAW,SAAS;AAAA,EAAA,CAC5D;AAEK,QAAA,oBAAoB,YAAY,YAAY,SAAS;AAErD,QAAA,eACJ,YAAY,aAAa,mBAAmB;AACxC,QAAA,uBAAuB,YAAY,YAAY;AAEjD,MAAA,CAAC,OAAO,UAAU;AACpB,WAAO,uBAAuB;AAAA,EAChC;AAIA,QAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,OAAO,QAAQ,UAAU,OAAO,IAAI;AAE5C,UAAA,eAAe,OAAO,cAAc;AAAA,MACxC,IAAI,OAAO,eAAe;AAAA,MAC1B,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,OAAO;AAAA,IAAA,CACR;AAGC,QAAA,cAAc,OAAO,eAAe,IAAI,MACxC,cAAc,aAAa,IAAI,GAC/B;AACA,aAAO,eAAe,EAAE,GAAG,cAAc,SAAS,MAAM;AAAA,IAC1D;AAEA,WAAO,MAAM;AACL;IAAA;AAAA,EAEP,GAAA,CAAC,QAAQ,OAAO,OAAO,CAAC;AAG3B,kBAAgB,MAAM;;
|
|
1
|
+
{"version":3,"file":"Transitioner.js","sources":["../../src/Transitioner.tsx"],"sourcesContent":["import * as React from 'react'\nimport { pick, useLayoutEffect, usePrevious } from './utils'\nimport { useRouter } from './useRouter'\nimport { useRouterState } from './useRouterState'\nimport { trimPathRight } from './path'\n\nexport function Transitioner() {\n const router = useRouter()\n const mountLoadForRouter = React.useRef({ router, mounted: false })\n const routerState = useRouterState({\n select: (s) =>\n pick(s, ['isLoading', 'location', 'resolvedLocation', 'isTransitioning']),\n })\n\n const [isTransitioning, startReactTransition_] = React.useTransition()\n // Track pending state changes\n const hasPendingMatches = useRouterState({\n select: (s) => s.matches.some((d) => d.status === 'pending'),\n })\n\n const previousIsLoading = usePrevious(routerState.isLoading)\n\n const isAnyPending =\n routerState.isLoading || isTransitioning || hasPendingMatches\n const previousIsAnyPending = usePrevious(isAnyPending)\n\n if (!router.isServer) {\n router.startReactTransition = startReactTransition_\n }\n\n // Subscribe to location changes\n // and try to load the new location\n React.useEffect(() => {\n const unsub = router.history.subscribe(router.load)\n\n const nextLocation = router.buildLocation({\n to: router.latestLocation.pathname,\n search: true,\n params: true,\n hash: true,\n state: true,\n })\n\n if (\n trimPathRight(router.latestLocation.href) !==\n trimPathRight(nextLocation.href)\n ) {\n router.commitLocation({ ...nextLocation, replace: true })\n }\n\n return () => {\n unsub()\n }\n }, [router, router.history])\n\n // Try to load the initial location\n useLayoutEffect(() => {\n if (\n (typeof window !== 'undefined' && window.__TSR__?.dehydrated) ||\n (mountLoadForRouter.current.router === router &&\n mountLoadForRouter.current.mounted)\n ) {\n return\n }\n mountLoadForRouter.current = { router, mounted: true }\n\n const tryLoad = async () => {\n try {\n await router.load()\n } catch (err) {\n console.error(err)\n }\n }\n\n tryLoad()\n }, [router])\n\n useLayoutEffect(() => {\n // The router was loading and now it's not\n if (previousIsLoading && !routerState.isLoading) {\n const toLocation = router.state.location\n const fromLocation = router.state.resolvedLocation\n const pathChanged = fromLocation.href !== toLocation.href\n\n router.emit({\n type: 'onLoad', // When the new URL has committed, when the new matches have been loaded into state.matches\n fromLocation,\n toLocation,\n pathChanged,\n })\n }\n }, [previousIsLoading, router, routerState.isLoading])\n\n useLayoutEffect(() => {\n // The router was pending and now it's not\n if (previousIsAnyPending && !isAnyPending) {\n const toLocation = router.state.location\n const fromLocation = router.state.resolvedLocation\n const pathChanged = fromLocation.href !== toLocation.href\n\n router.emit({\n type: 'onResolved',\n fromLocation,\n toLocation,\n pathChanged,\n })\n\n router.__store.setState((s) => ({\n ...s,\n status: 'idle',\n resolvedLocation: s.location,\n }))\n\n if (typeof document !== 'undefined' && (document as any).querySelector) {\n if (router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView()\n }\n }\n }\n }\n }, [isAnyPending, previousIsAnyPending, router])\n\n return null\n}\n"],"names":[],"mappings":";;;;;AAMO,SAAS,eAAe;AAC7B,QAAM,SAAS;AACf,QAAM,qBAAqB,MAAM,OAAO,EAAE,QAAQ,SAAS,OAAO;AAClE,QAAM,cAAc,eAAe;AAAA,IACjC,QAAQ,CAAC,MACP,KAAK,GAAG,CAAC,aAAa,YAAY,oBAAoB,iBAAiB,CAAC;AAAA,EAAA,CAC3E;AAED,QAAM,CAAC,iBAAiB,qBAAqB,IAAI,MAAM,cAAc;AAErE,QAAM,oBAAoB,eAAe;AAAA,IACvC,QAAQ,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,EAAE,WAAW,SAAS;AAAA,EAAA,CAC5D;AAEK,QAAA,oBAAoB,YAAY,YAAY,SAAS;AAErD,QAAA,eACJ,YAAY,aAAa,mBAAmB;AACxC,QAAA,uBAAuB,YAAY,YAAY;AAEjD,MAAA,CAAC,OAAO,UAAU;AACpB,WAAO,uBAAuB;AAAA,EAChC;AAIA,QAAM,UAAU,MAAM;AACpB,UAAM,QAAQ,OAAO,QAAQ,UAAU,OAAO,IAAI;AAE5C,UAAA,eAAe,OAAO,cAAc;AA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S,CAAC,OAAO;AAAA,QAC9B,GAAG;AAAA,QACH,QAAQ;AAAA,QACR,kBAAkB,EAAE;AAAA,MACpB,EAAA;AAEF,UAAI,OAAO,aAAa,eAAgB,SAAiB,eAAe;AACtE,YAAI,OAAO,MAAM,SAAS,SAAS,IAAI;AACrC,gBAAM,KAAK,SAAS,eAAe,OAAO,MAAM,SAAS,IAAI;AAC7D,cAAI,IAAI;AACN,eAAG,eAAe;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACC,GAAA,CAAC,cAAc,sBAAsB,MAAM,CAAC;AAExC,SAAA;AACT;"}
|
package/dist/esm/fileRoute.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NoInfer } from '@tanstack/react-store';
|
|
2
2
|
import { ParsePathParams } from './link.js';
|
|
3
|
-
import { AnyContext, AnyPathParams, AnyRoute, AnySearchValidator, DefaultSearchValidator, FileBaseRouteOptions,
|
|
3
|
+
import { AnyContext, AnyPathParams, AnyRoute, AnySearchValidator, DefaultSearchValidator, FileBaseRouteOptions, ResolveAllParamsFromParent, ResolveLoaderData, Route, RouteConstraints, RouteLoaderFn, UpdatableRouteOptions } from './route.js';
|
|
4
4
|
import { MakeRouteMatch } from './Matches.js';
|
|
5
5
|
import { RegisteredRouter } from './router.js';
|
|
6
6
|
import { RouteById, RouteIds } from './routeInfo.js';
|
|
@@ -18,15 +18,15 @@ export declare class FileRoute<TFilePath extends keyof FileRoutesByPath, TParent
|
|
|
18
18
|
constructor(path: TFilePath, _opts?: {
|
|
19
19
|
silent: boolean;
|
|
20
20
|
});
|
|
21
|
-
createRoute: <TSearchValidator extends AnySearchValidator = DefaultSearchValidator, TParams = Record<ParsePathParams<TPath>, string>, TAllParams = ResolveAllParamsFromParent<TParentRoute, TParams>,
|
|
21
|
+
createRoute: <TSearchValidator extends AnySearchValidator = DefaultSearchValidator, TParams = Record<ParsePathParams<TPath>, string>, TAllParams = ResolveAllParamsFromParent<TParentRoute, TParams>, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderDataReturn = {}, TLoaderData = ResolveLoaderData<TLoaderDataReturn>, TChildren = unknown>(options?: FileBaseRouteOptions<TParentRoute, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderDataReturn, AnyContext, TRouteContextFn, TBeforeLoadFn> & UpdatableRouteOptions<TParentRoute, TId, TAllParams, TSearchValidator, TLoaderData, TLoaderDeps, AnyContext, TRouteContextFn, TBeforeLoadFn>) => Route<TParentRoute, TPath, TFullPath, TFilePath, TId, TSearchValidator, TParams, TAllParams, AnyContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderDataReturn, TLoaderData, TChildren>;
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
@deprecated It's recommended not to split loaders into separate files.
|
|
25
25
|
Instead, place the loader function in the the main route file, inside the
|
|
26
26
|
`createFileRoute('/path/to/file)(options)` options.
|
|
27
27
|
*/
|
|
28
|
-
export declare function FileRouteLoader<TFilePath extends keyof FileRoutesByPath, TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute']>(_path: TFilePath): <TLoaderData>(loaderFn: RouteLoaderFn<TRoute['types']['
|
|
29
|
-
export type LazyRouteOptions = Pick<UpdatableRouteOptions<AnyRoute, string, AnyPathParams, AnySearchValidator, {}, AnyContext, AnyContext,
|
|
28
|
+
export declare function FileRouteLoader<TFilePath extends keyof FileRoutesByPath, TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute']>(_path: TFilePath): <TLoaderData>(loaderFn: RouteLoaderFn<TRoute['parentRoute'], TRoute['types']['params'], TRoute['types']['loaderDeps'], TRoute['types']['routerContext'], TRoute['types']['routeContextFn'], TRoute['types']['beforeLoadFn'], TLoaderData>) => RouteLoaderFn<TRoute['parentRoute'], TRoute['types']['params'], TRoute['types']['loaderDeps'], TRoute['types']['routerContext'], TRoute['types']['routeContextFn'], TRoute['types']['beforeLoadFn'], NoInfer<TLoaderData>>;
|
|
29
|
+
export type LazyRouteOptions = Pick<UpdatableRouteOptions<AnyRoute, string, AnyPathParams, AnySearchValidator, {}, AnyContext, AnyContext, AnyContext, AnyContext>, 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent'>;
|
|
30
30
|
export declare class LazyRoute<TRoute extends AnyRoute> {
|
|
31
31
|
options: {
|
|
32
32
|
id: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileRoute.js","sources":["../../src/fileRoute.ts"],"sourcesContent":["import warning from 'tiny-warning'\nimport { createRoute } from './route'\nimport { useMatch } from './useMatch'\nimport { useLoaderDeps } from './useLoaderDeps'\nimport { useLoaderData } from './useLoaderData'\nimport { useSearch } from './useSearch'\nimport { useParams } from './useParams'\nimport { useNavigate } from './useNavigate'\nimport type { NoInfer } from '@tanstack/react-store'\nimport type { ParsePathParams } from './link'\nimport type {\n AnyContext,\n AnyPathParams,\n AnyRoute,\n AnySearchValidator,\n DefaultSearchValidator,\n FileBaseRouteOptions,\n
|
|
1
|
+
{"version":3,"file":"fileRoute.js","sources":["../../src/fileRoute.ts"],"sourcesContent":["import warning from 'tiny-warning'\nimport { createRoute } from './route'\nimport { useMatch } from './useMatch'\nimport { useLoaderDeps } from './useLoaderDeps'\nimport { useLoaderData } from './useLoaderData'\nimport { useSearch } from './useSearch'\nimport { useParams } from './useParams'\nimport { useNavigate } from './useNavigate'\nimport type { NoInfer } from '@tanstack/react-store'\nimport type { ParsePathParams } from './link'\nimport type {\n AnyContext,\n AnyPathParams,\n AnyRoute,\n AnySearchValidator,\n DefaultSearchValidator,\n FileBaseRouteOptions,\n ResolveAllParamsFromParent,\n ResolveLoaderData,\n ResolveRouteContext,\n Route,\n RouteConstraints,\n RouteContext,\n RouteContextFn,\n RouteLoaderFn,\n UpdatableRouteOptions,\n} from './route'\nimport type { MakeRouteMatch } from './Matches'\nimport type { RegisteredRouter } from './router'\nimport type { RouteById, RouteIds } from './routeInfo'\n\nexport interface FileRoutesByPath {\n // '/': {\n // parentRoute: typeof rootRoute\n // }\n}\n\nexport function createFileRoute<\n TFilePath extends keyof FileRoutesByPath,\n TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],\n TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],\n>(\n path: TFilePath,\n): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'] {\n return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, {\n silent: true,\n }).createRoute\n}\n\n/** \n @deprecated It's no longer recommended to use the `FileRoute` class directly.\n Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.\n*/\nexport class FileRoute<\n TFilePath extends keyof FileRoutesByPath,\n TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],\n TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],\n> {\n silent?: boolean\n\n constructor(\n public path: TFilePath,\n _opts?: { silent: boolean },\n ) {\n this.silent = _opts?.silent\n }\n\n createRoute = <\n TSearchValidator extends AnySearchValidator = DefaultSearchValidator,\n TParams = Record<ParsePathParams<TPath>, string>,\n TAllParams = ResolveAllParamsFromParent<TParentRoute, TParams>,\n TRouteContextFn = AnyContext,\n TBeforeLoadFn = AnyContext,\n TLoaderDeps extends Record<string, any> = {},\n TLoaderDataReturn = {},\n TLoaderData = ResolveLoaderData<TLoaderDataReturn>,\n TChildren = unknown,\n >(\n options?: FileBaseRouteOptions<\n TParentRoute,\n TPath,\n TSearchValidator,\n TParams,\n TLoaderDeps,\n TLoaderDataReturn,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn\n > &\n UpdatableRouteOptions<\n TParentRoute,\n TId,\n TAllParams,\n TSearchValidator,\n TLoaderData,\n TLoaderDeps,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn\n >,\n ): Route<\n TParentRoute,\n TPath,\n TFullPath,\n TFilePath,\n TId,\n TSearchValidator,\n TParams,\n TAllParams,\n AnyContext,\n TRouteContextFn,\n TBeforeLoadFn,\n TLoaderDeps,\n TLoaderDataReturn,\n TLoaderData,\n TChildren\n > => {\n warning(\n this.silent,\n 'FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.',\n )\n const route = createRoute(options as any)\n ;(route as any).isRoot = false\n return route as any\n }\n}\n\n/** \n @deprecated It's recommended not to split loaders into separate files.\n Instead, place the loader function in the the main route file, inside the\n `createFileRoute('/path/to/file)(options)` options.\n*/\nexport function FileRouteLoader<\n TFilePath extends keyof FileRoutesByPath,\n TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],\n>(\n _path: TFilePath,\n): <TLoaderData>(\n loaderFn: RouteLoaderFn<\n TRoute['parentRoute'],\n TRoute['types']['params'],\n TRoute['types']['loaderDeps'],\n TRoute['types']['routerContext'],\n TRoute['types']['routeContextFn'],\n TRoute['types']['beforeLoadFn'],\n TLoaderData\n >,\n) => RouteLoaderFn<\n TRoute['parentRoute'],\n TRoute['types']['params'],\n TRoute['types']['loaderDeps'],\n TRoute['types']['routerContext'],\n TRoute['types']['routeContextFn'],\n TRoute['types']['beforeLoadFn'],\n NoInfer<TLoaderData>\n> {\n warning(\n false,\n `FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the the main route file, inside the \\`createFileRoute('/path/to/file')(options)\\` options`,\n )\n return (loaderFn) => loaderFn\n}\n\nexport type LazyRouteOptions = Pick<\n UpdatableRouteOptions<\n AnyRoute,\n string,\n AnyPathParams,\n AnySearchValidator,\n {},\n AnyContext,\n AnyContext,\n AnyContext,\n AnyContext\n >,\n 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent'\n>\n\nexport class LazyRoute<TRoute extends AnyRoute> {\n options: {\n id: string\n } & LazyRouteOptions\n\n constructor(\n opts: {\n id: string\n } & LazyRouteOptions,\n ) {\n this.options = opts\n ;(this as any).$$typeof = Symbol.for('react.memo')\n }\n\n useMatch = <\n TRouteMatch = MakeRouteMatch<\n RegisteredRouter['routeTree'],\n TRoute['types']['id']\n >,\n TSelected = TRouteMatch,\n >(opts?: {\n select?: (match: TRouteMatch) => TSelected\n }): TSelected => {\n return useMatch({ select: opts?.select, from: this.options.id })\n }\n\n useRouteContext = <TSelected = TRoute['types']['allContext']>(opts?: {\n select?: (s: TRoute['types']['allContext']) => TSelected\n }): TSelected => {\n return useMatch({\n from: this.options.id,\n select: (d: any) => (opts?.select ? opts.select(d.context) : d.context),\n })\n }\n\n useSearch = <TSelected = TRoute['types']['fullSearchSchema']>(opts?: {\n select?: (s: TRoute['types']['fullSearchSchema']) => TSelected\n }): TSelected => {\n return useSearch({ ...opts, from: this.options.id })\n }\n\n useParams = <TSelected = TRoute['types']['allParams']>(opts?: {\n select?: (s: TRoute['types']['allParams']) => TSelected\n }): TSelected => {\n return useParams({ ...opts, from: this.options.id })\n }\n\n useLoaderDeps = <TSelected = TRoute['types']['loaderDeps']>(opts?: {\n select?: (s: TRoute['types']['loaderDeps']) => TSelected\n }): TSelected => {\n return useLoaderDeps({ ...opts, from: this.options.id } as any)\n }\n\n useLoaderData = <TSelected = TRoute['types']['loaderData']>(opts?: {\n select?: (s: TRoute['types']['loaderData']) => TSelected\n }): TSelected => {\n return useLoaderData({ ...opts, from: this.options.id } as any)\n }\n\n useNavigate = () => {\n return useNavigate({ from: this.options.id })\n }\n}\n\nexport function createLazyRoute<\n TId extends RouteIds<RegisteredRouter['routeTree']>,\n TRoute extends AnyRoute = RouteById<RegisteredRouter['routeTree'], TId>,\n>(id: TId) {\n return (opts: LazyRouteOptions) => {\n return new LazyRoute<TRoute>({ id: id as any, ...opts })\n }\n}\n\nexport function createLazyFileRoute<\n TFilePath extends keyof FileRoutesByPath,\n TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],\n>(id: TFilePath) {\n return (opts: LazyRouteOptions) => new LazyRoute<TRoute>({ id, ...opts })\n}\n"],"names":["opts"],"mappings":";;;;;;;;AAqCO,SAAS,gBAQd,MAC0E;AACnE,SAAA,IAAI,UAA0D,MAAM;AAAA,IACzE,QAAQ;AAAA,EACT,CAAA,EAAE;AACL;AAMO,MAAM,UAOX;AAAA,EAGA,YACS,MACP,OACA;AAFO,SAAA,OAAA;AAMT,SAAA,cAAc,CAWZ,YAsCG;AACH;AAAA,QACE,KAAK;AAAA,QACL;AAAA,MAAA;AAEI,YAAA,QAAQ,YAAY,OAAc;AACtC,YAAc,SAAS;AAClB,aAAA;AAAA,IAAA;AA3DP,SAAK,SAAS,+BAAO;AAAA,EACvB;AA4DF;AAOO,SAAS,gBAId,OAmBA;AACA;AAAA,IACE;AAAA,IACA;AAAA,EAAA;AAEF,SAAO,CAAC,aAAa;AACvB;AAiBO,MAAM,UAAmC;AAAA,EAK9C,YACE,MAGA;AAKF,SAAA,WAAW,CAMTA,UAEe;AACR,aAAA,SAAS,EAAE,QAAQA,SAAA,gBAAAA,MAAM,QAAQ,MAAM,KAAK,QAAQ,GAAA,CAAI;AAAA,IAAA;AAGjE,SAAA,kBAAkB,CAA4CA,UAE7C;AACf,aAAO,SAAS;AAAA,QACd,MAAM,KAAK,QAAQ;AAAA,QACnB,QAAQ,CAAC,OAAYA,SAAA,gBAAAA,MAAM,UAASA,MAAK,OAAO,EAAE,OAAO,IAAI,EAAE;AAAA,MAAA,CAChE;AAAA,IAAA;AAGH,SAAA,YAAY,CAAkDA,UAE7C;AACR,aAAA,UAAU,EAAE,GAAGA,OAAM,MAAM,KAAK,QAAQ,IAAI;AAAA,IAAA;AAGrD,SAAA,YAAY,CAA2CA,UAEtC;AACR,aAAA,UAAU,EAAE,GAAGA,OAAM,MAAM,KAAK,QAAQ,IAAI;AAAA,IAAA;AAGrD,SAAA,gBAAgB,CAA4CA,UAE3C;AACR,aAAA,cAAc,EAAE,GAAGA,OAAM,MAAM,KAAK,QAAQ,IAAW;AAAA,IAAA;AAGhE,SAAA,gBAAgB,CAA4CA,UAE3C;AACR,aAAA,cAAc,EAAE,GAAGA,OAAM,MAAM,KAAK,QAAQ,IAAW;AAAA,IAAA;AAGhE,SAAA,cAAc,MAAM;AAClB,aAAO,YAAY,EAAE,MAAM,KAAK,QAAQ,IAAI;AAAA,IAAA;AAlD5C,SAAK,UAAU;AACb,SAAa,WAAW,OAAO,IAAI,YAAY;AAAA,EACnD;AAkDF;AAEO,SAAS,gBAGd,IAAS;AACT,SAAO,CAAC,SAA2B;AACjC,WAAO,IAAI,UAAkB,EAAE,IAAe,GAAG,KAAM,CAAA;AAAA,EAAA;AAE3D;AAEO,SAAS,oBAGd,IAAe;AACR,SAAA,CAAC,SAA2B,IAAI,UAAkB,EAAE,IAAI,GAAG,MAAM;AAC1E;"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -34,13 +34,15 @@ export { RouteApi, getRouteApi, Route, createRoute, RootRoute, rootRouteWithCont
|
|
|
34
34
|
export type { AnyPathParams, SearchSchemaInput, SearchValidatorAdapter, AnySearchSchema, AnyContext, RouteContext, PreloadableObj, RoutePathOptions, StaticDataRouteOption, RoutePathOptionsIntersection, RouteOptions, FileBaseRouteOptions, BaseRouteOptions, UpdatableRouteOptions, UpdatableStaticRouteOption, MetaDescriptor, RouteLinkEntry, ParseParamsFn, RouteLoaderFn, LoaderFnContext, SearchFilter, ResolveId, InferFullSearchSchema, InferFullSearchSchemaInput, ResolveFullSearchSchema, ResolveFullSearchSchemaInput, AnyRoute, RouteConstraints, AnyRootRoute, ResolveFullPath, RouteMask, ErrorRouteProps, ErrorComponentProps, NotFoundRouteProps, ReactNode, SyncRouteComponent, AsyncRouteComponent, RouteComponent, ErrorRouteComponent, NotFoundRouteComponent, TrimPath, TrimPathLeft, TrimPathRight, RootRouteOptions, AnyRouteWithContext, } from './route.js';
|
|
35
35
|
export type { ParseRoute, RoutesById, RouteById, RouteIds, RoutesByPath, RouteByPath, RoutePaths, FullSearchSchema, AllParams, } from './routeInfo.js';
|
|
36
36
|
export { componentTypes, createRouter, Router, lazyFn, SearchParamError, PathParamError, getInitialRouterState, defaultSerializeError, } from './router.js';
|
|
37
|
-
export type { Register, AnyRouter, RegisteredRouter, HydrationCtx, RouterContextOptions, TrailingSlashOption, RouterOptions,
|
|
37
|
+
export type { Register, AnyRouter, RegisteredRouter, HydrationCtx, RouterContextOptions, TrailingSlashOption, RouterOptions, RouterErrorSerializer, RouterState, ListenerFn, BuildNextOptions, DehydratedRouterState, DehydratedRouteMatch, DehydratedRouter, RouterConstructorOptions, RouterEvents, RouterEvent, RouterListener, AnyRouterWithContext, ExtractedEntry, StreamState, } from './router.js';
|
|
38
38
|
export { RouterProvider, RouterContextProvider } from './RouterProvider.js';
|
|
39
39
|
export type { RouterProps, CommitLocationOptions, MatchLocation, NavigateFn, BuildLocationFn, InjectedHtmlEntry, } from './RouterProvider.js';
|
|
40
40
|
export { useScrollRestoration, useElementScrollRestoration, ScrollRestoration, } from './scroll-restoration.js';
|
|
41
41
|
export type { ScrollRestorationOptions } from './scroll-restoration.js';
|
|
42
42
|
export { defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith, } from './searchParams.js';
|
|
43
43
|
export type { SearchSerializer, SearchParser } from './searchParams.js';
|
|
44
|
+
export { defaultTransformer } from './transformer.js';
|
|
45
|
+
export type { RouterTransformer } from './transformer.js';
|
|
44
46
|
export { useBlocker, Block } from './useBlocker.js';
|
|
45
47
|
export { useNavigate, Navigate } from './useNavigate.js';
|
|
46
48
|
export type { UseNavigateResult } from './useNavigate.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -24,6 +24,7 @@ import { PathParamError, Router, SearchParamError, componentTypes, createRouter,
|
|
|
24
24
|
import { RouterContextProvider, RouterProvider } from "./RouterProvider.js";
|
|
25
25
|
import { ScrollRestoration, useElementScrollRestoration, useScrollRestoration } from "./scroll-restoration.js";
|
|
26
26
|
import { defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith } from "./searchParams.js";
|
|
27
|
+
import { defaultTransformer } from "./transformer.js";
|
|
27
28
|
import { Block, useBlocker } from "./useBlocker.js";
|
|
28
29
|
import { Navigate, useNavigate } from "./useNavigate.js";
|
|
29
30
|
import { useParams } from "./useParams.js";
|
|
@@ -84,6 +85,7 @@ export {
|
|
|
84
85
|
defaultParseSearch,
|
|
85
86
|
defaultSerializeError,
|
|
86
87
|
defaultStringifySearch,
|
|
88
|
+
defaultTransformer,
|
|
87
89
|
defer,
|
|
88
90
|
encode,
|
|
89
91
|
escapeJSON,
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|