Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

route.tsx

750 lines18.2 KB

1import {
2 BaseRootRoute,
3 BaseRoute,
4 BaseRouteApi,
5 notFound,
6} from '@tanstack/router-core'
7import React from 'react'
8import { useLoaderData } from './useLoaderData'
9import { useLoaderDeps } from './useLoaderDeps'
10import { useParams } from './useParams'
11import { useSearch } from './useSearch'
12import { useNavigate } from './useNavigate'
13import { useMatch } from './useMatch'
14import { useRouter } from './useRouter'
15import { Link } from './link'
16import type {
17 AnyContext,
18 AnyRoute,
19 AnyRouter,
20 ConstrainLiteral,
21 ErrorComponentProps,
22 NotFoundError,
23 NotFoundRouteProps,
24 Register,
25 RegisteredRouter,
26 ResolveFullPath,
27 ResolveId,
28 ResolveParams,
29 RootRoute as RootRouteCore,
30 RootRouteId,
31 RootRouteOptions,
32 RouteConstraints,
33 Route as RouteCore,
34 RouteIds,
35 RouteMask,
36 RouteOptions,
37 RouteTypesById,
38 RouterCore,
39 ToMaskOptions,
40 UseNavigateResult,
41} from '@tanstack/router-core'
42import type { UseLoaderDataRoute } from './useLoaderData'
43import type { UseMatchRoute } from './useMatch'
44import type { UseLoaderDepsRoute } from './useLoaderDeps'
45import type { UseParamsRoute } from './useParams'
46import type { UseSearchRoute } from './useSearch'
47import type { UseRouteContextRoute } from './useRouteContext'
48import type { LinkComponentRoute } from './link'
49​
50declare module '@tanstack/router-core' {
51 export interface UpdatableRouteOptionsExtensions {
52 component?: RouteComponent
53 errorComponent?: false | null | undefined | ErrorRouteComponent
54 notFoundComponent?: NotFoundRouteComponent
55 pendingComponent?: RouteComponent
56 }
57​
58 export interface RootRouteOptionsExtensions {
59 shellComponent?: ({
60 children,
61 }: {
62 children: React.ReactNode
63 }) => React.ReactNode
64 }
65​
66 export interface RouteExtensions<
67 in out TId extends string,
68 in out TFullPath extends string,
69 > {
70 useMatch: UseMatchRoute<TId>
71 useRouteContext: UseRouteContextRoute<TId>
72 useSearch: UseSearchRoute<TId>
73 useParams: UseParamsRoute<TId>
74 useLoaderDeps: UseLoaderDepsRoute<TId>
75 useLoaderData: UseLoaderDataRoute<TId>
76 useNavigate: () => UseNavigateResult<TFullPath>
77 Link: LinkComponentRoute<TFullPath>
78 }
80​
81/**
82 * Returns a route-specific API that exposes type-safe hooks pre-bound
83 * to a single route ID. Useful for consuming a route's APIs from files
84 * where the route object isn't directly imported (e.g. code-split files).
85 *
86 * @param id Route ID string literal for the target route.
87 * @returns A `RouteApi` instance bound to the given route ID.
88 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/getRouteApiFunction
89 */
90export function getRouteApi<
91 const TId,
92 TRouter extends AnyRouter = RegisteredRouter,
93>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>) {
94 return new RouteApi<TId, TRouter>({ id })
96​
97export class RouteApi<
98 TId,
99 TRouter extends AnyRouter = RegisteredRouter,
100> extends BaseRouteApi<TId, TRouter> {
101 /**
102 * @deprecated Use the `getRouteApi` function instead.
103 */
104 constructor({ id }: { id: TId }) {
105 super({ id })
106 }
107​
108 useMatch: UseMatchRoute<TId> = (opts) => {
109 return useMatch({
110 select: opts?.select,
111 from: this.id,
112 structuralSharing: opts?.structuralSharing,
113 } as any) as any
114 }
115​
116 useRouteContext: UseRouteContextRoute<TId> = (opts) => {
117 return useMatch({
118 from: this.id as any,
119 select: (d) => (opts?.select ? opts.select(d.context) : d.context),
120 }) as any
121 }
122​
123 useSearch: UseSearchRoute<TId> = (opts) => {
124 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
125 return useSearch({
126 select: opts?.select,
127 structuralSharing: opts?.structuralSharing,
128 from: this.id,
129 } as any) as any
130 }
131​
132 useParams: UseParamsRoute<TId> = (opts) => {
133 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
134 return useParams({
135 select: opts?.select,
136 structuralSharing: opts?.structuralSharing,
137 from: this.id,
138 } as any) as any
139 }
140​
141 useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => {
142 return useLoaderDeps({ ...opts, from: this.id, strict: false } as any)
143 }
144​
145 useLoaderData: UseLoaderDataRoute<TId> = (opts) => {
146 return useLoaderData({ ...opts, from: this.id, strict: false } as any)
147 }
148​
149 useNavigate = (): UseNavigateResult<
150 RouteTypesById<TRouter, TId>['fullPath']
151 > => {
152 const router = useRouter()
153 return useNavigate({ from: router.routesById[this.id as string].fullPath })
154 }
155​
156 notFound = (opts?: NotFoundError) => {
157 return notFound({ routeId: this.id as string, ...opts })
158 }
159​
160 Link: LinkComponentRoute<RouteTypesById<TRouter, TId>['fullPath']> =
161 React.forwardRef((props, ref: React.ForwardedRef<HTMLAnchorElement>) => {
162 const router = useRouter()
163 const fullPath = router.routesById[this.id as string].fullPath
164 return <Link ref={ref} from={fullPath as never} {...props} />
165 }) as unknown as LinkComponentRoute<
166 RouteTypesById<TRouter, TId>['fullPath']
167 >
169​
170export class Route<
171 in out TRegister = unknown,
172 in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,
173 in out TPath extends RouteConstraints['TPath'] = '/',
174 in out TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<
175 TParentRoute,
176 TPath
177 >,
178 in out TCustomId extends RouteConstraints['TCustomId'] = string,
179 in out TId extends RouteConstraints['TId'] = ResolveId<
180 TParentRoute,
181 TCustomId,
182 TPath
183 >,
184 in out TSearchValidator = undefined,
185 in out TParams = ResolveParams<TPath>,
186 in out TRouterContext = AnyContext,
187 in out TRouteContextFn = AnyContext,
188 in out TBeforeLoadFn = AnyContext,
189 in out TLoaderDeps extends Record<string, any> = {},
190 in out TLoaderFn = undefined,
191 in out TChildren = unknown,
192 in out TFileRouteTypes = unknown,
193 in out TSSR = unknown,
194 in out TServerMiddlewares = unknown,
195 in out THandlers = undefined,
196 >
197 extends BaseRoute<
198 TRegister,
199 TParentRoute,
200 TPath,
201 TFullPath,
202 TCustomId,
203 TId,
204 TSearchValidator,
205 TParams,
206 TRouterContext,
207 TRouteContextFn,
208 TBeforeLoadFn,
209 TLoaderDeps,
210 TLoaderFn,
211 TChildren,
212 TFileRouteTypes,
213 TSSR,
214 TServerMiddlewares,
215 THandlers
216 >
217 implements
218 RouteCore<
219 TRegister,
220 TParentRoute,
221 TPath,
222 TFullPath,
223 TCustomId,
224 TId,
225 TSearchValidator,
226 TParams,
227 TRouterContext,
228 TRouteContextFn,
229 TBeforeLoadFn,
230 TLoaderDeps,
231 TLoaderFn,
232 TChildren,
233 TFileRouteTypes,
234 TSSR,
235 TServerMiddlewares,
236 THandlers
237 >
239 /**
240 * @deprecated Use the `createRoute` function instead.
241 */
242 constructor(
243 options?: RouteOptions<
244 TRegister,
245 TParentRoute,
246 TId,
247 TCustomId,
248 TFullPath,
249 TPath,
250 TSearchValidator,
251 TParams,
252 TLoaderDeps,
253 TLoaderFn,
254 TRouterContext,
255 TRouteContextFn,
256 TBeforeLoadFn,
257 TSSR,
258 TServerMiddlewares,
259 THandlers
260 >,
261 ) {
262 super(options)
263 ;(this as any).$$typeof = Symbol.for('react.memo')
264 }
265​
266 useMatch: UseMatchRoute<TId> = (opts) => {
267 return useMatch({
268 select: opts?.select,
269 from: this.id,
270 structuralSharing: opts?.structuralSharing,
271 } as any) as any
272 }
273​
274 useRouteContext: UseRouteContextRoute<TId> = (opts?) => {
275 return useMatch({
276 ...opts,
277 from: this.id,
278 select: (d) => (opts?.select ? opts.select(d.context) : d.context),
279 }) as any
280 }
281​
282 useSearch: UseSearchRoute<TId> = (opts) => {
283 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
284 return useSearch({
285 select: opts?.select,
286 structuralSharing: opts?.structuralSharing,
287 from: this.id,
288 } as any) as any
289 }
290​
291 useParams: UseParamsRoute<TId> = (opts) => {
292 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
293 return useParams({
294 select: opts?.select,
295 structuralSharing: opts?.structuralSharing,
296 from: this.id,
297 } as any) as any
298 }
299​
300 useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => {
301 return useLoaderDeps({ ...opts, from: this.id } as any)
302 }
303​
304 useLoaderData: UseLoaderDataRoute<TId> = (opts) => {
305 return useLoaderData({ ...opts, from: this.id } as any)
306 }
307​
308 useNavigate = (): UseNavigateResult<TFullPath> => {
309 return useNavigate({ from: this.fullPath })
310 }
311​
312 Link: LinkComponentRoute<TFullPath> = React.forwardRef(
313 (props, ref: React.ForwardedRef<HTMLAnchorElement>) => {
314 return <Link ref={ref} from={this.fullPath as never} {...props} />
315 },
316 ) as unknown as LinkComponentRoute<TFullPath>
318​
319/**
320 * Creates a non-root Route instance for code-based routing.
321 *
322 * Use this to define a route that will be composed into a route tree
323 * (typically via a parent route's `addChildren`). If you're using file-based
324 * routing, prefer `createFileRoute`.
325 *
326 * @param options Route options (path, component, loader, context, etc.).
327 * @returns A Route instance to be attached to the route tree.
328 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouteFunction
329 */
330export function createRoute<
331 TRegister = unknown,
332 TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,
333 TPath extends RouteConstraints['TPath'] = '/',
334 TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<
335 TParentRoute,
336 TPath
337 >,
338 TCustomId extends RouteConstraints['TCustomId'] = string,
339 TId extends RouteConstraints['TId'] = ResolveId<
340 TParentRoute,
341 TCustomId,
342 TPath
343 >,
344 TSearchValidator = undefined,
345 TParams = ResolveParams<TPath>,
346 TRouteContextFn = AnyContext,
347 TBeforeLoadFn = AnyContext,
348 TLoaderDeps extends Record<string, any> = {},
349 TLoaderFn = undefined,
350 TChildren = unknown,
351 TSSR = unknown,
352 const TServerMiddlewares = unknown,
353>(
354 options: RouteOptions<
355 TRegister,
356 TParentRoute,
357 TId,
358 TCustomId,
359 TFullPath,
360 TPath,
361 TSearchValidator,
362 TParams,
363 TLoaderDeps,
364 TLoaderFn,
365 AnyContext,
366 TRouteContextFn,
367 TBeforeLoadFn,
368 TSSR,
369 TServerMiddlewares
370 >,
371): Route<
372 TRegister,
373 TParentRoute,
374 TPath,
375 TFullPath,
376 TCustomId,
377 TId,
378 TSearchValidator,
379 TParams,
380 AnyContext,
381 TRouteContextFn,
382 TBeforeLoadFn,
383 TLoaderDeps,
384 TLoaderFn,
385 TChildren,
386 TSSR,
387 TServerMiddlewares
388> {
389 return new Route<
390 TRegister,
391 TParentRoute,
392 TPath,
393 TFullPath,
394 TCustomId,
395 TId,
396 TSearchValidator,
397 TParams,
398 AnyContext,
399 TRouteContextFn,
400 TBeforeLoadFn,
401 TLoaderDeps,
402 TLoaderFn,
403 TChildren,
404 TSSR,
405 TServerMiddlewares
406 >(
407 // TODO: Help us TypeChris, you're our only hope!
408 options as any,
409 )
411​
412export type AnyRootRoute = RootRoute<
413 any,
414 any,
415 any,
416 any,
417 any,
418 any,
419 any,
420 any,
421 any,
422 any,
423 any
425​
426/**
427 * Creates a root route factory that requires a router context type.
428 *
429 * Use when your root route expects `context` to be provided to `createRouter`.
430 * The returned function behaves like `createRootRoute` but enforces a context type.
431 *
432 * @returns A factory function to configure and return a root route.
433 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction
434 */
435export function createRootRouteWithContext<TRouterContext extends {}>() {
436 return <
437 TRegister = Register,
438 TRouteContextFn = AnyContext,
439 TBeforeLoadFn = AnyContext,
440 TSearchValidator = undefined,
441 TLoaderDeps extends Record<string, any> = {},
442 TLoaderFn = undefined,
443 TSSR = unknown,
444 TServerMiddlewares = unknown,
445 >(
446 options?: RootRouteOptions<
447 TRegister,
448 TSearchValidator,
449 TRouterContext,
450 TRouteContextFn,
451 TBeforeLoadFn,
452 TLoaderDeps,
453 TLoaderFn,
454 TSSR,
455 TServerMiddlewares
456 >,
457 ) => {
458 return createRootRoute<
459 TRegister,
460 TSearchValidator,
461 TRouterContext,
462 TRouteContextFn,
463 TBeforeLoadFn,
464 TLoaderDeps,
465 TLoaderFn,
466 TSSR,
467 TServerMiddlewares
468 >(options as any)
469 }
471​
472/**
473 * @deprecated Use the `createRootRouteWithContext` function instead.
474 */
475export const rootRouteWithContext = createRootRouteWithContext
476​
477export class RootRoute<
478 in out TRegister = unknown,
479 in out TSearchValidator = undefined,
480 in out TRouterContext = {},
481 in out TRouteContextFn = AnyContext,
482 in out TBeforeLoadFn = AnyContext,
483 in out TLoaderDeps extends Record<string, any> = {},
484 in out TLoaderFn = undefined,
485 in out TChildren = unknown,
486 in out TFileRouteTypes = unknown,
487 in out TSSR = unknown,
488 in out TServerMiddlewares = unknown,
489 in out THandlers = undefined,
490 >
491 extends BaseRootRoute<
492 TRegister,
493 TSearchValidator,
494 TRouterContext,
495 TRouteContextFn,
496 TBeforeLoadFn,
497 TLoaderDeps,
498 TLoaderFn,
499 TChildren,
500 TFileRouteTypes,
501 TSSR,
502 TServerMiddlewares,
503 THandlers
504 >
505 implements
506 RootRouteCore<
507 TRegister,
508 TSearchValidator,
509 TRouterContext,
510 TRouteContextFn,
511 TBeforeLoadFn,
512 TLoaderDeps,
513 TLoaderFn,
514 TChildren,
515 TFileRouteTypes,
516 TSSR,
517 TServerMiddlewares,
518 THandlers
519 >
521 /**
522 * @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
523 */
524 constructor(
525 options?: RootRouteOptions<
526 TRegister,
527 TSearchValidator,
528 TRouterContext,
529 TRouteContextFn,
530 TBeforeLoadFn,
531 TLoaderDeps,
532 TLoaderFn,
533 TSSR,
534 TServerMiddlewares,
535 THandlers
536 >,
537 ) {
538 super(options)
539 ;(this as any).$$typeof = Symbol.for('react.memo')
540 }
541​
542 useMatch: UseMatchRoute<RootRouteId> = (opts) => {
543 return useMatch({
544 select: opts?.select,
545 from: this.id,
546 structuralSharing: opts?.structuralSharing,
547 } as any) as any
548 }
549​
550 useRouteContext: UseRouteContextRoute<RootRouteId> = (opts) => {
551 return useMatch({
552 ...opts,
553 from: this.id,
554 select: (d) => (opts?.select ? opts.select(d.context) : d.context),
555 }) as any
556 }
557​
558 useSearch: UseSearchRoute<RootRouteId> = (opts) => {
559 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
560 return useSearch({
561 select: opts?.select,
562 structuralSharing: opts?.structuralSharing,
563 from: this.id,
564 } as any) as any
565 }
566​
567 useParams: UseParamsRoute<RootRouteId> = (opts) => {
568 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
569 return useParams({
570 select: opts?.select,
571 structuralSharing: opts?.structuralSharing,
572 from: this.id,
573 } as any) as any
574 }
575​
576 useLoaderDeps: UseLoaderDepsRoute<RootRouteId> = (opts) => {
577 return useLoaderDeps({ ...opts, from: this.id } as any)
578 }
579​
580 useLoaderData: UseLoaderDataRoute<RootRouteId> = (opts) => {
581 return useLoaderData({ ...opts, from: this.id } as any)
582 }
583​
584 useNavigate = (): UseNavigateResult<'/'> => {
585 return useNavigate({ from: this.fullPath })
586 }
587​
588 Link: LinkComponentRoute<'/'> = React.forwardRef(
589 (props, ref: React.ForwardedRef<HTMLAnchorElement>) => {
590 return <Link ref={ref} from={this.fullPath} {...props} />
591 },
592 ) as unknown as LinkComponentRoute<'/'>
594​
595/**
596 * Creates a root Route instance used to build your route tree.
597 *
598 * Typically paired with `createRouter({ routeTree })`. If you need to require
599 * a typed router context, use `createRootRouteWithContext` instead.
600 *
601 * @param options Root route options (component, error, pending, etc.).
602 * @returns A root route instance.
603 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteFunction
604 */
605export function createRootRoute<
606 TRegister = Register,
607 TSearchValidator = undefined,
608 TRouterContext = {},
609 TRouteContextFn = AnyContext,
610 TBeforeLoadFn = AnyContext,
611 TLoaderDeps extends Record<string, any> = {},
612 TLoaderFn = undefined,
613 TSSR = unknown,
614 const TServerMiddlewares = unknown,
615 THandlers = undefined,
616>(
617 options?: RootRouteOptions<
618 TRegister,
619 TSearchValidator,
620 TRouterContext,
621 TRouteContextFn,
622 TBeforeLoadFn,
623 TLoaderDeps,
624 TLoaderFn,
625 TSSR,
626 TServerMiddlewares,
627 THandlers
628 >,
629): RootRoute<
630 TRegister,
631 TSearchValidator,
632 TRouterContext,
633 TRouteContextFn,
634 TBeforeLoadFn,
635 TLoaderDeps,
636 TLoaderFn,
637 unknown,
638 unknown,
639 TSSR,
640 TServerMiddlewares,
641 THandlers
642> {
643 return new RootRoute<
644 TRegister,
645 TSearchValidator,
646 TRouterContext,
647 TRouteContextFn,
648 TBeforeLoadFn,
649 TLoaderDeps,
650 TLoaderFn,
651 unknown,
652 unknown,
653 TSSR,
654 TServerMiddlewares,
655 THandlers
656 >(options)
658​
659export function createRouteMask<
660 TRouteTree extends AnyRoute,
661 TFrom extends string,
662 TTo extends string,
663>(
664 opts: {
665 routeTree: TRouteTree
666 } & ToMaskOptions<RouterCore<TRouteTree, 'never', boolean>, TFrom, TTo>,
667): RouteMask<TRouteTree> {
668 return opts as any
670​
671export interface DefaultRouteTypes<TProps> {
672 component:
673 | ((props: TProps) => any)
674 | React.LazyExoticComponent<(props: TProps) => any>
676export interface RouteTypes<TProps> extends DefaultRouteTypes<TProps> {}
677​
678export type AsyncRouteComponent<TProps> = RouteTypes<TProps>['component'] & {
679 preload?: () => Promise<void>
681​
682export type RouteComponent = AsyncRouteComponent<{}>
683​
684export type ErrorRouteComponent = AsyncRouteComponent<ErrorComponentProps>
685​
686export type NotFoundRouteComponent = RouteTypes<NotFoundRouteProps>['component']
687​
688export class NotFoundRoute<
689 TRegister,
690 TParentRoute extends AnyRootRoute,
691 TRouterContext = AnyContext,
692 TRouteContextFn = AnyContext,
693 TBeforeLoadFn = AnyContext,
694 TSearchValidator = undefined,
695 TLoaderDeps extends Record<string, any> = {},
696 TLoaderFn = undefined,
697 TChildren = unknown,
698 TSSR = unknown,
699 TServerMiddlewares = unknown,
700> extends Route<
701 TRegister,
702 TParentRoute,
703 '/404',
704 '/404',
705 '404',
706 '404',
707 TSearchValidator,
708 {},
709 TRouterContext,
710 TRouteContextFn,
711 TBeforeLoadFn,
712 TLoaderDeps,
713 TLoaderFn,
714 TChildren,
715 TSSR,
716 TServerMiddlewares
717> {
718 constructor(
719 options: Omit<
720 RouteOptions<
721 TRegister,
722 TParentRoute,
723 string,
724 string,
725 string,
726 string,
727 TSearchValidator,
728 {},
729 TLoaderDeps,
730 TLoaderFn,
731 TRouterContext,
732 TRouteContextFn,
733 TBeforeLoadFn,
734 TSSR,
735 TServerMiddlewares
736 >,
737 | 'caseSensitive'
738 | 'parseParams'
739 | 'stringifyParams'
740 | 'path'
741 | 'id'
742 | 'params'
743 >,
744 ) {
745 super({
746 ...(options as any),
747 id: '404',
748 })
749 }