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

fileRoute.ts

295 lines8.9 KB

1import { createRoute } from './route'
2​
3import { useMatch } from './useMatch'
4import { useLoaderDeps } from './useLoaderDeps'
5import { useLoaderData } from './useLoaderData'
6import { useSearch } from './useSearch'
7import { useParams } from './useParams'
8import { useNavigate } from './useNavigate'
9import { useRouter } from './useRouter'
10import { useRouteContext } from './useRouteContext'
11import type { UseParamsRoute } from './useParams'
12import type { UseMatchRoute } from './useMatch'
13import type { UseSearchRoute } from './useSearch'
14import type {
15 AnyContext,
16 AnyRoute,
17 AnyRouter,
18 Constrain,
19 ConstrainLiteral,
20 FileBaseRouteOptions,
21 FileRoutesByPath,
22 LazyRouteOptions,
23 Register,
24 RegisteredRouter,
25 ResolveParams,
26 Route,
27 RouteById,
28 RouteConstraints,
29 RouteIds,
30 RouteLoaderEntry,
31 UpdatableRouteOptions,
32 UseNavigateResult,
33} from '@tanstack/router-core'
34import type { UseLoaderDepsRoute } from './useLoaderDeps'
35import type { UseLoaderDataRoute } from './useLoaderData'
36import type { UseRouteContextRoute } from './useRouteContext'
37​
38/**
39 * Creates a file-based Route factory for a given path.
40 *
41 * Used by TanStack Router's file-based routing to associate a file with a
42 * route. The returned function accepts standard route options. In normal usage
43 * the `path` string is inserted and maintained by the `tsr` generator.
44 *
45 * @param path File path literal for the route (usually auto-generated).
46 * @returns A function that accepts Route options and returns a Route instance.
47 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
48 */
49export function createFileRoute<
50 TFilePath extends keyof FileRoutesByPath,
51 TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
52 TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
53 TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
54 TFullPath extends RouteConstraints['TFullPath'] =
55 FileRoutesByPath[TFilePath]['fullPath'],
56>(
57 // eslint-disable-next-line unused-imports/no-unused-vars
58 path?: TFilePath,
59): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'] {
60 return (options) => {
61 const route = createRoute(options as any)
62 ;(route as any).isRoot = false
63 return route as any
64 }
66​
67/**
68 @deprecated It's no longer recommended to use the `FileRoute` class directly.
69 Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
70*/
71export class FileRoute<
72 TFilePath extends keyof FileRoutesByPath,
73 TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
74 TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
75 TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
76 TFullPath extends RouteConstraints['TFullPath'] =
77 FileRoutesByPath[TFilePath]['fullPath'],
78> {
79 silent?: boolean
80​
81 constructor(
82 public path?: TFilePath,
83 _opts?: { silent: boolean },
84 ) {
85 this.silent = _opts?.silent
86 }
87​
88 createRoute = <
89 TRegister = Register,
90 TSearchValidator = undefined,
91 TParams = ResolveParams<TPath>,
92 TRouteContextFn = AnyContext,
93 TBeforeLoadFn = AnyContext,
94 TLoaderDeps extends Record<string, any> = {},
95 TLoaderFn = undefined,
96 TChildren = unknown,
97 TSSR = unknown,
98 const TMiddlewares = unknown,
99 THandlers = undefined,
100 >(
101 options?: FileBaseRouteOptions<
102 TRegister,
103 TParentRoute,
104 TId,
105 TPath,
106 TSearchValidator,
107 TParams,
108 TLoaderDeps,
109 TLoaderFn,
110 AnyContext,
111 TRouteContextFn,
112 TBeforeLoadFn,
113 AnyContext,
114 TSSR,
115 TMiddlewares,
116 THandlers
117 > &
118 UpdatableRouteOptions<
119 TParentRoute,
120 TId,
121 TFullPath,
122 TParams,
123 TSearchValidator,
124 TLoaderFn,
125 TLoaderDeps,
126 AnyContext,
127 TRouteContextFn,
128 TBeforeLoadFn
129 >,
130 ): Route<
131 TRegister,
132 TParentRoute,
133 TPath,
134 TFullPath,
135 TFilePath,
136 TId,
137 TSearchValidator,
138 TParams,
139 AnyContext,
140 TRouteContextFn,
141 TBeforeLoadFn,
142 TLoaderDeps,
143 TLoaderFn,
144 TChildren,
145 unknown,
146 TSSR,
147 TMiddlewares,
148 THandlers
149 > => {
150 if (process.env.NODE_ENV !== 'production') {
151 if (!this.silent) {
152 console.warn(
153 'Warning: FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.',
154 )
155 }
156 }
157 const route = createRoute(options as any)
158 ;(route as any).isRoot = false
159 return route as any
160 }
162​
163/**
164 @deprecated It's recommended not to split loaders into separate files.
165 Instead, place the loader function in the main route file via `createFileRoute`.
166*/
167export function FileRouteLoader<
168 TFilePath extends keyof FileRoutesByPath,
169 TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
170>(
171 _path: TFilePath,
172): <TLoaderFn>(
173 loaderFn: Constrain<
174 TLoaderFn,
175 RouteLoaderEntry<
176 Register,
177 TRoute['parentRoute'],
178 TRoute['types']['id'],
179 TRoute['types']['params'],
180 TRoute['types']['loaderDeps'],
181 TRoute['types']['routerContext'],
182 TRoute['types']['routeContextFn'],
183 TRoute['types']['beforeLoadFn']
184 >
185 >,
186) => TLoaderFn {
187 if (process.env.NODE_ENV !== 'production') {
188 console.warn(
189 `Warning: FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`,
190 )
191 }
192 return (loaderFn) => loaderFn as any
194​
195declare module '@tanstack/router-core' {
196 export interface LazyRoute<in out TRoute extends AnyRoute> {
197 useMatch: UseMatchRoute<TRoute['id']>
198 useRouteContext: UseRouteContextRoute<TRoute['id']>
199 useSearch: UseSearchRoute<TRoute['id']>
200 useParams: UseParamsRoute<TRoute['id']>
201 useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>
202 useLoaderData: UseLoaderDataRoute<TRoute['id']>
203 useNavigate: () => UseNavigateResult<TRoute['fullPath']>
204 }
206​
207export class LazyRoute<TRoute extends AnyRoute> {
208 options: {
209 id: string
210 } & LazyRouteOptions
211​
212 constructor(
213 opts: {
214 id: string
215 } & LazyRouteOptions,
216 ) {
217 this.options = opts
218 }
219​
220 useMatch: UseMatchRoute<TRoute['id']> = (opts) => {
221 return useMatch({ ...opts, from: this.options.id } as any) as any
222 }
223​
224 useRouteContext: UseRouteContextRoute<TRoute['id']> = (opts) => {
225 return useRouteContext({ ...(opts as any), from: this.options.id })
226 }
227​
228 useSearch: UseSearchRoute<TRoute['id']> = (opts) => {
229 return useSearch({ ...opts, from: this.options.id } as any)
230 }
231​
232 useParams: UseParamsRoute<TRoute['id']> = (opts) => {
233 return useParams({ ...opts, from: this.options.id } as any)
234 }
235​
236 useLoaderDeps: UseLoaderDepsRoute<TRoute['id']> = (opts) => {
237 return useLoaderDeps({ ...opts, from: this.options.id } as any)
238 }
239​
240 useLoaderData: UseLoaderDataRoute<TRoute['id']> = (opts) => {
241 return useLoaderData({ ...opts, from: this.options.id } as any)
242 }
243​
244 useNavigate = (): UseNavigateResult<TRoute['fullPath']> => {
245 const router = useRouter()
246 return useNavigate({ from: router.routesById[this.options.id].fullPath })
247 }
249​
250/**
251 * Creates a lazily-configurable code-based route stub by ID.
252 *
253 * Use this for code-splitting with code-based routes. The returned function
254 * accepts only non-critical route options like `component`, `pendingComponent`,
255 * `errorComponent`, and `notFoundComponent` which are applied when the route
256 * is matched.
257 *
258 * @param id Route ID string literal to associate with the lazy route.
259 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
260 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
261 */
262export function createLazyRoute<
263 TRouter extends AnyRouter = RegisteredRouter,
264 TId extends string = string,
265 TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>,
266>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>) {
267 return (opts: LazyRouteOptions) => {
268 return new LazyRoute<TRoute>({
269 id: id,
270 ...opts,
271 })
272 }
274​
275/**
276 * Creates a lazily-configurable file-based route stub by file path.
277 *
278 * Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
279 * The returned function accepts only non-critical route options like
280 * `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
281 *
282 * @param id File path literal for the route file.
283 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
284 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
285 */
286export function createLazyFileRoute<
287 TFilePath extends keyof FileRoutesByPath,
288 TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
289>(id: TFilePath): (opts: LazyRouteOptions) => LazyRoute<TRoute> {
290 if (typeof id === 'object') {
291 return new LazyRoute<TRoute>(id) as any
292 }
293​
294 return (opts: LazyRouteOptions) => new LazyRoute<TRoute>({ id, ...opts })