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

fileRoute.ts

378 lines12.4 KB

1import warning from 'tiny-warning'
2import { createRoute } from './route'
3​
4import { useMatch } from './useMatch'
5import { useLoaderDeps } from './useLoaderDeps'
6import { useLoaderData } from './useLoaderData'
7import { useSearch } from './useSearch'
8import { useParams } from './useParams'
9import { useNavigate } from './useNavigate'
10import { useRouter } from './useRouter'
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 RouteLoaderFn,
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 */
49/**
50 * Creates a file-based Route factory for a given path.
51 *
52 * Used by TanStack Router's file-based routing to associate a file with a
53 * route. The returned function accepts standard route options. In normal usage
54 * the `path` string is inserted and maintained by the `tsr` generator.
55 *
56 * @param path File path literal for the route (usually auto-generated).
57 * @returns A function that accepts Route options and returns a Route instance.
58 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
59 */
60/**
61 * Creates a file-based Route factory for a given path.
62 * Used by file-based routing to associate a file with a route. The returned
63 * function accepts standard route options; the path is typically auto-managed
64 * by the generator.
65 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createFileRouteFunction
66 */
67export function createFileRoute<
68 TFilePath extends keyof FileRoutesByPath,
69 TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
70 TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
71 TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
72 TFullPath extends
73 RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],
74>(
75 path?: TFilePath,
76): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'] {
77 if (typeof path === 'object') {
78 return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, {
79 silent: true,
80 }).createRoute(path) as any
81 }
82 return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, {
83 silent: true,
84 }).createRoute
86​
87/**
88 @deprecated It's no longer recommended to use the `FileRoute` class directly.
89 Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
90*/
91/**
92 @deprecated It's no longer recommended to use the `FileRoute` class directly.
93 Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
94*/
95/**
96 @deprecated It's no longer recommended to use the `FileRoute` class directly.
97 Instead, use `createFileRoute('/path')(options)` to create a file route.
98*/
99export class FileRoute<
100 TFilePath extends keyof FileRoutesByPath,
101 TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
102 TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
103 TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
104 TFullPath extends
105 RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],
106> {
107 silent?: boolean
108​
109 constructor(
110 public path?: TFilePath,
111 _opts?: { silent: boolean },
112 ) {
113 this.silent = _opts?.silent
114 }
115​
116 createRoute = <
117 TRegister = Register,
118 TSearchValidator = undefined,
119 TParams = ResolveParams<TPath>,
120 TRouteContextFn = AnyContext,
121 TBeforeLoadFn = AnyContext,
122 TLoaderDeps extends Record<string, any> = {},
123 TLoaderFn = undefined,
124 TChildren = unknown,
125 TSSR = unknown,
126 const TMiddlewares = unknown,
127 THandlers = undefined,
128 >(
129 options?: FileBaseRouteOptions<
130 TRegister,
131 TParentRoute,
132 TId,
133 TPath,
134 TSearchValidator,
135 TParams,
136 TLoaderDeps,
137 TLoaderFn,
138 AnyContext,
139 TRouteContextFn,
140 TBeforeLoadFn,
141 AnyContext,
142 TSSR,
143 TMiddlewares,
144 THandlers
145 > &
146 UpdatableRouteOptions<
147 TParentRoute,
148 TId,
149 TFullPath,
150 TParams,
151 TSearchValidator,
152 TLoaderFn,
153 TLoaderDeps,
154 AnyContext,
155 TRouteContextFn,
156 TBeforeLoadFn
157 >,
158 ): Route<
159 TRegister,
160 TParentRoute,
161 TPath,
162 TFullPath,
163 TFilePath,
164 TId,
165 TSearchValidator,
166 TParams,
167 AnyContext,
168 TRouteContextFn,
169 TBeforeLoadFn,
170 TLoaderDeps,
171 TLoaderFn,
172 TChildren,
173 unknown,
174 TSSR,
175 TMiddlewares,
176 THandlers
177 > => {
178 warning(
179 this.silent,
180 'FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.',
181 )
182 const route = createRoute(options as any)
183 ;(route as any).isRoot = false
184 return route as any
185 }
187​
188/**
189 @deprecated It's recommended not to split loaders into separate files.
190 Instead, place the loader function in the the main route file, inside the
191 `createFileRoute('/path/to/file)(options)` options.
192*/
193/**
194 @deprecated It's recommended not to split loaders into separate files.
195 Instead, place the loader function in the the main route file, inside the
196 `createFileRoute('/path/to/file)(options)` options.
197*/
198/**
199 @deprecated It's recommended not to split loaders into separate files.
200 Instead, place the loader function in the main route file via `createFileRoute`.
201*/
202export function FileRouteLoader<
203 TFilePath extends keyof FileRoutesByPath,
204 TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
205>(
206 _path: TFilePath,
207): <TLoaderFn>(
208 loaderFn: Constrain<
209 TLoaderFn,
210 RouteLoaderFn<
211 Register,
212 TRoute['parentRoute'],
213 TRoute['types']['id'],
214 TRoute['types']['params'],
215 TRoute['types']['loaderDeps'],
216 TRoute['types']['routerContext'],
217 TRoute['types']['routeContextFn'],
218 TRoute['types']['beforeLoadFn']
219 >
220 >,
221) => TLoaderFn {
222 warning(
223 false,
224 `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`,
225 )
226 return (loaderFn) => loaderFn as any
228​
229declare module '@tanstack/router-core' {
230 export interface LazyRoute<in out TRoute extends AnyRoute> {
231 useMatch: UseMatchRoute<TRoute['id']>
232 useRouteContext: UseRouteContextRoute<TRoute['id']>
233 useSearch: UseSearchRoute<TRoute['id']>
234 useParams: UseParamsRoute<TRoute['id']>
235 useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>
236 useLoaderData: UseLoaderDataRoute<TRoute['id']>
237 useNavigate: () => UseNavigateResult<TRoute['fullPath']>
238 }
240​
241export class LazyRoute<TRoute extends AnyRoute> {
242 options: {
243 id: string
244 } & LazyRouteOptions
245​
246 constructor(
247 opts: {
248 id: string
249 } & LazyRouteOptions,
250 ) {
251 this.options = opts
252 ;(this as any).$$typeof = Symbol.for('react.memo')
253 }
254​
255 useMatch: UseMatchRoute<TRoute['id']> = (opts) => {
256 return useMatch({
257 select: opts?.select,
258 from: this.options.id,
259 structuralSharing: opts?.structuralSharing,
260 } as any) as any
261 }
262​
263 useRouteContext: UseRouteContextRoute<TRoute['id']> = (opts) => {
264 return useMatch({
265 from: this.options.id,
266 select: (d: any) => (opts?.select ? opts.select(d.context) : d.context),
267 }) as any
268 }
269​
270 useSearch: UseSearchRoute<TRoute['id']> = (opts) => {
271 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
272 return useSearch({
273 select: opts?.select,
274 structuralSharing: opts?.structuralSharing,
275 from: this.options.id,
276 } as any) as any
277 }
278​
279 useParams: UseParamsRoute<TRoute['id']> = (opts) => {
280 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
281 return useParams({
282 select: opts?.select,
283 structuralSharing: opts?.structuralSharing,
284 from: this.options.id,
285 } as any) as any
286 }
287​
288 useLoaderDeps: UseLoaderDepsRoute<TRoute['id']> = (opts) => {
289 return useLoaderDeps({ ...opts, from: this.options.id } as any)
290 }
291​
292 useLoaderData: UseLoaderDataRoute<TRoute['id']> = (opts) => {
293 return useLoaderData({ ...opts, from: this.options.id } as any)
294 }
295​
296 useNavigate = (): UseNavigateResult<TRoute['fullPath']> => {
297 const router = useRouter()
298 return useNavigate({ from: router.routesById[this.options.id].fullPath })
299 }
301​
302/**
303 * Creates a lazily-configurable code-based route stub by ID.
304 *
305 * Use this for code-splitting with code-based routes. The returned function
306 * accepts only non-critical route options like `component`, `pendingComponent`,
307 * `errorComponent`, and `notFoundComponent` which are applied when the route
308 * is matched.
309 *
310 * @param id Route ID string literal to associate with the lazy route.
311 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
312 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
313 */
314/**
315 * Creates a lazily-configurable code-based route stub by ID.
316 *
317 * Use this for code-splitting with code-based routes. The returned function
318 * accepts only non-critical route options like `component`, `pendingComponent`,
319 * `errorComponent`, and `notFoundComponent` which are applied when the route
320 * is matched.
321 *
322 * @param id Route ID string literal to associate with the lazy route.
323 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
324 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
325 */
326/**
327 * Create a lazily-configurable code-based route stub by ID.
328 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyRouteFunction
329 */
330export function createLazyRoute<
331 TRouter extends AnyRouter = RegisteredRouter,
332 TId extends string = string,
333 TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>,
334>(id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>) {
335 return (opts: LazyRouteOptions) => {
336 return new LazyRoute<TRoute>({
337 id: id,
338 ...opts,
339 })
340 }
342​
343/**
344 * Creates a lazily-configurable file-based route stub by file path.
345 *
346 * Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
347 * The returned function accepts only non-critical route options like
348 * `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
349 *
350 * @param id File path literal for the route file.
351 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
352 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
353 */
354/**
355 * Creates a lazily-configurable file-based route stub by file path.
356 *
357 * Use this for code-splitting with file-based routes (eg. `.lazy.tsx` files).
358 * The returned function accepts only non-critical route options like
359 * `component`, `pendingComponent`, `errorComponent`, and `notFoundComponent`.
360 *
361 * @param id File path literal for the route file.
362 * @returns A function that accepts lazy route options and returns a `LazyRoute`.
363 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
364 */
365/**
366 * Create a lazily-configurable file-based route stub by file path.
367 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createLazyFileRouteFunction
368 */
369export function createLazyFileRoute<
370 TFilePath extends keyof FileRoutesByPath,
371 TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
372>(id: TFilePath): (opts: LazyRouteOptions) => LazyRoute<TRoute> {
373 if (typeof id === 'object') {
374 return new LazyRoute<TRoute>(id) as any
375 }
376​
377 return (opts: LazyRouteOptions) => new LazyRoute<TRoute>({ id, ...opts })