diff --git a/examples/react/large-file-based/src/createRoutes.mjs b/examples/react/large-file-based/src/createRoutes.mjs index c86294b699..816bd79686 100644 --- a/examples/react/large-file-based/src/createRoutes.mjs +++ b/examples/react/large-file-based/src/createRoutes.mjs @@ -2,6 +2,7 @@ import { readFile, writeFile, mkdir } from 'fs/promises' import { existsSync } from 'fs' const length = 100 +const nestedDepth = 3 const main = async () => { const absolute = (await readFile('./src/routes/absolute.tsx')).toString() @@ -34,6 +35,34 @@ const main = async () => { await writeFile('./src/routes/(gen)/search/route.tsx', searchRoute) await writeFile('./src/routes/(gen)/params/route.tsx', paramsRoute) + const nestedRouteTemplate = (path, label, depthIndex) => { + const depthAccess = Array.from({ length: depthIndex + 1 }, (_, index) => + index === 0 ? 'matches[0].routeId' : `matches[${index}]?.routeId`, + ).join(' && ') + + return `import { createFileRoute } from '@tanstack/react-router' +import * as React from 'react' + +export const Route = createFileRoute('${path}')({ + component: ${label}Component, + head: ({ matches }) => { + if (${depthAccess}) { + // ... + } + return {} + }, +}) + +function ${label}Component() { + return ( +
+

${label}

+
+ ) +} +` + } + for (let y = 0; y < length; y = y + 1) { const replacedAbsolute = absolute.replaceAll('/absolute', `/absolute${y}`) const replacedRelative = relative.replaceAll('/relative', `/relative${y}`) @@ -43,6 +72,41 @@ const main = async () => { await writeFile(`./src/routes/(gen)/relative${y}.tsx`, replacedRelative) await writeFile(`./src/routes/(gen)/search/search${y}.tsx`, replacedSearch) await writeFile(`./src/routes/(gen)/params/$param${y}.tsx`, replacedParams) + + const nestedBasePath = `./src/routes/(gen)/nested${y}` + if (!existsSync(nestedBasePath)) { + await mkdir(nestedBasePath) + } + + let currentPath = `/nested${y}` + let currentDir = nestedBasePath + + for (let depth = 0; depth < nestedDepth; depth = depth + 1) { + const label = `Nested${y}Level${depth + 1}` + const segment = `level${depth + 1}` + const routePath = currentPath + + await writeFile( + `${currentDir}/route.tsx`, + nestedRouteTemplate(routePath, label, depth + 1), + ) + + currentPath = `${currentPath}/${segment}` + currentDir = `${currentDir}/${segment}` + + if (!existsSync(currentDir)) { + await mkdir(currentDir) + } + } + + await writeFile( + `${currentDir}/leaf.tsx`, + nestedRouteTemplate( + `${currentPath}/leaf`, + `Nested${y}Leaf`, + nestedDepth + 1, + ), + ) } } diff --git a/examples/react/large-file-based/src/routes/absolute.tsx b/examples/react/large-file-based/src/routes/absolute.tsx index 0dc5578842..00c111af46 100644 --- a/examples/react/large-file-based/src/routes/absolute.tsx +++ b/examples/react/large-file-based/src/routes/absolute.tsx @@ -4,6 +4,12 @@ import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/absolute')({ component: AbsoluteComponent, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function AbsoluteComponent() { diff --git a/examples/react/large-file-based/src/routes/index.tsx b/examples/react/large-file-based/src/routes/index.tsx index 0a5b7572ba..b9ecb0fc52 100644 --- a/examples/react/large-file-based/src/routes/index.tsx +++ b/examples/react/large-file-based/src/routes/index.tsx @@ -3,6 +3,12 @@ import * as React from 'react' export const Route = createFileRoute('/')({ component: Home, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function Home() { diff --git a/examples/react/large-file-based/src/routes/linkProps.tsx b/examples/react/large-file-based/src/routes/linkProps.tsx index d520cf0f96..abfa7f6c7b 100644 --- a/examples/react/large-file-based/src/routes/linkProps.tsx +++ b/examples/react/large-file-based/src/routes/linkProps.tsx @@ -4,6 +4,12 @@ import { Link, linkOptions } from '@tanstack/react-router' export const Route = createFileRoute('/linkProps')({ component: LinkPropsPage, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function LinkPropsPage() { diff --git a/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx b/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx index 1442464a1c..5983539137 100644 --- a/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx +++ b/examples/react/large-file-based/src/routes/params/$paramsPlaceholder.tsx @@ -25,6 +25,12 @@ export const Route = createFileRoute('/params/$paramsPlaceholder')({ component: ParamsComponent, loader: (opts) => opts.context.queryClient.ensureQueryData(paramsQueryOptions), + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + } }) function ParamsComponent() { diff --git a/examples/react/large-file-based/src/routes/params/route.tsx b/examples/react/large-file-based/src/routes/params/route.tsx index 0e29ec1e1e..2ad81c977a 100644 --- a/examples/react/large-file-based/src/routes/params/route.tsx +++ b/examples/react/large-file-based/src/routes/params/route.tsx @@ -3,4 +3,10 @@ import * as React from 'react' export const Route = createFileRoute('/params')({ component: () =>
Hello /params!
, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) diff --git a/examples/react/large-file-based/src/routes/relative.tsx b/examples/react/large-file-based/src/routes/relative.tsx index b2e8c7a10a..341c5a96b4 100644 --- a/examples/react/large-file-based/src/routes/relative.tsx +++ b/examples/react/large-file-based/src/routes/relative.tsx @@ -4,6 +4,12 @@ import { Link } from '@tanstack/react-router' export const Route = createFileRoute('/relative')({ component: RelativeComponent, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function RelativeComponent() { diff --git a/examples/react/large-file-based/src/routes/search/route.tsx b/examples/react/large-file-based/src/routes/search/route.tsx index 33447e4c80..04d790a439 100644 --- a/examples/react/large-file-based/src/routes/search/route.tsx +++ b/examples/react/large-file-based/src/routes/search/route.tsx @@ -10,4 +10,10 @@ const search = z.object({ export const Route = createFileRoute('/search')({ component: () =>
Hello /search!
, validateSearch: search, + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) diff --git a/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx b/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx index 8938899d13..430b7e5543 100644 --- a/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx +++ b/examples/react/large-file-based/src/routes/search/searchPlaceholder.tsx @@ -32,6 +32,12 @@ export const Route = createFileRoute('/search/searchPlaceholder')({ validateSearch: search, loader: (opts) => opts.context.queryClient.ensureQueryData(searchQueryOptions), + head: ({ matches }) => { + if (matches[0].routeId) { + // ... + } + return {} + }, }) function SearchComponent() { diff --git a/packages/router-core/src/fileRoute.ts b/packages/router-core/src/fileRoute.ts index 90b47ab643..d49884d205 100644 --- a/packages/router-core/src/fileRoute.ts +++ b/packages/router-core/src/fileRoute.ts @@ -78,7 +78,8 @@ export interface FileRouteOptions< TLoaderDeps, AnyContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister > {} export type CreateFileRoute< @@ -148,7 +149,8 @@ export type LazyRouteOptions = Pick< AnyContext, AnyContext, AnyContext, - AnyContext + AnyContext, + Register >, 'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent' > diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts index 838d77e9d3..16a94176b5 100644 --- a/packages/router-core/src/load-matches.ts +++ b/packages/router-core/src/load-matches.ts @@ -584,9 +584,9 @@ const executeHead = ( } return Promise.all([ - route.options.head?.(assetContext), - route.options.scripts?.(assetContext), - route.options.headers?.(assetContext), + route.options.head?.(assetContext as any), + route.options.scripts?.(assetContext as any), + route.options.headers?.(assetContext as any), ]).then(([headFnContent, scripts, headers]) => { const meta = headFnContent?.meta const links = headFnContent?.links diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 243e93c989..dd78cea381 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -16,7 +16,13 @@ import type { RouteMatch, } from './Matches' import type { RootRouteId } from './root' -import type { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo' +import type { + ParseRoute, + RouteById, + RouteIds, + RoutePaths, + RoutesById, +} from './routeInfo' import type { AnyRouter, Register, RegisteredRouter, SSROption } from './router' import type { BuildLocationFn, NavigateFn } from './RouterProvider' import type { @@ -693,7 +699,8 @@ export interface Route< TLoaderDeps, TRouterContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister >, ) => this lazy: RouteLazyFn< @@ -854,7 +861,8 @@ export type RouteOptions< NoInfer, NoInfer, NoInfer, - NoInfer + NoInfer, + NoInfer > export type RouteContextFn< @@ -1140,6 +1148,7 @@ export interface BeforeLoadContextOptions< } type AssetFnContextOptions< + in out TRegister, in out TRouteId, in out TFullPath, in out TParentRoute extends AnyRoute, @@ -1154,22 +1163,7 @@ type AssetFnContextOptions< ssr?: { nonce?: string } - matches: Array< - RouteMatch< - TRouteId, - TFullPath, - ResolveAllParamsFromParent, - ResolveFullSearchSchema, - ResolveLoaderData, - ResolveAllContext< - TParentRoute, - TRouterContext, - TRouteContextFn, - TBeforeLoadFn - >, - TLoaderDeps - > - > + matches: InferAssetFnMatches match: RouteMatch< TRouteId, TFullPath, @@ -1188,6 +1182,144 @@ type AssetFnContextOptions< loaderData?: ResolveLoaderData } +type RegisteredRouterRouteTree = + RegisteredRouter extends { + routeTree: infer TRouteTree + } + ? TRouteTree extends AnyRoute + ? TRouteTree + : AnyRoute + : AnyRoute + +/** + * Extract the ancestor ID tuple from a route ID string by splitting on '/'. + * + * For '/foo/bar/baz' → ['__root__', '/foo', '/foo/bar', '/foo/bar/baz'] + * For '__root__' → ['__root__'] + * + * This is O(D) string-only manipulation — no union operations. + */ +type AncestorIdTuple = TRouteId extends RootRouteId + ? [RootRouteId] + : [RootRouteId, ...BuildIdTupleFromSegments>] + +type StripLeadingSlash = T extends `/${infer R}` ? R : T + +/** + * Given 'foo/bar/baz' and prefix '', build ['/foo', '/foo/bar', '/foo/bar/baz']. + * Recursion depth = number of path segments (typically ≤ 8). + */ +type BuildIdTupleFromSegments< + TSegments extends string, + TPrefix extends string = '', +> = TSegments extends `${infer THead}/${infer TRest}` + ? [ + `${TPrefix}/${THead}`, + ...BuildIdTupleFromSegments, + ] + : TSegments extends '' + ? [] + : [`${TPrefix}/${TSegments}`] + +type RoutesByIdFor = RoutesById + +type RouteIdsFor = RouteIds + +type RouteByIdFrom = Extract< + TRoutesById[TId & keyof TRoutesById], + AnyRoute +> + +type RouteMatchByIdFor = { + [K in keyof TRoutesById]: MakeRouteMatchFromRoute< + RouteByIdFrom + > +} + +/** + * Map a tuple of route IDs to a tuple of route matches. + * Uses RoutesById for O(1) cached lookups per ID. + */ +type MapIdTupleToMatches< + TRouteMatchById, + TIds extends Array, +> = TIds extends [ + infer TFirst extends string, + ...infer TRest extends Array, +] + ? [ + TRouteMatchById[TFirst & keyof TRouteMatchById], + ...MapIdTupleToMatches, + ] + : [] + +/** + * Compute descendant route IDs from the route ID union. + * + * This distributes over a string union (RouteIds) instead of a route-object union, + * which is typically cheaper for the type checker. + */ +type DescendantRouteIds< + TAllRouteIds, + TRouteId extends string, +> = TRouteId extends RootRouteId + ? Exclude + : Extract + +type DescendantMatchesById = TIds extends string + ? RouteMatchByIdFor[TIds & keyof RouteMatchByIdFor] + : never + +type DescendantIdsByRouteId = { + [K in RouteIdsFor]: DescendantRouteIds +} + +type AncestorIdTupleByRouteId = { + [K in RouteIdsFor]: AncestorIdTuple +} + +/** + * Infer the concrete matches tuple for a route's head/scripts/headers callbacks. + * + * Produces: [...AncestorMatches, SelfMatch, ...DescendantMatch[]] + * + * Performance: Ancestor tuple is built by string-splitting the route ID (O(D)) + * then looking up each ancestor via RouteById (O(1) cached mapped-type access). + * Descendants distribute over RouteIds (string union) and map IDs to matches via + * RouteById (cached mapped-type access). + * Total cost per route: O(D + Nd), where D = nesting depth, Nd = number of + * descendant IDs in the route tree. + * + * Note on lazy evaluation: UpdatableRouteOptions uses `in out` variance on + * TRegister, which forces TypeScript to fully evaluate InferAssetFnMatches + * for every route — even those without head/scripts/headers. True lazy + * evaluation would require removing TRegister from the variance contract + * or restructuring the API, which is out of scope for this change. + */ +export type InferAssetFnMatches = + RegisteredRouterRouteTree extends infer TTree extends AnyRoute + ? TRouteId extends string + ? RoutesByIdFor extends infer TRoutesById + ? RouteIdsFor extends infer TAllRouteIds + ? [ + ...MapIdTupleToMatches< + RouteMatchByIdFor, + AncestorIdTupleByRouteId[TRouteId & + keyof AncestorIdTupleByRouteId] + >, + ...Array< + DescendantMatchesById< + TRoutesById, + DescendantIdsByRouteId[TRouteId & + keyof DescendantIdsByRouteId] + > + >, + ] + : never + : never + : never + : never + export interface DefaultUpdatableRouteOptionsExtensions { component?: unknown errorComponent?: unknown @@ -1208,6 +1340,7 @@ export interface UpdatableRouteOptions< in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, + in out TRegister = Register, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { /** @@ -1333,6 +1466,7 @@ export interface UpdatableRouteOptions< ) => void headers?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1347,6 +1481,7 @@ export interface UpdatableRouteOptions< ) => Awaitable | undefined> head?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1366,6 +1501,7 @@ export interface UpdatableRouteOptions< }> scripts?: ( ctx: AssetFnContextOptions< + TRegister, TRouteId, TFullPath, TParentRoute, @@ -1894,7 +2030,8 @@ export class BaseRoute< TLoaderDeps, TRouterContext, TRouteContextFn, - TBeforeLoadFn + TBeforeLoadFn, + TRegister >, ): this => { Object.assign(this.options, options) diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index ce314c85f7..42bae1def2 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -195,9 +195,9 @@ export async function hydrate(router: AnyRouter): Promise { params: match.params, loaderData: match.loaderData, } - const headFnContent = await route.options.head?.(assetContext) + const headFnContent = await route.options.head?.(assetContext as any) - const scripts = await route.options.scripts?.(assetContext) + const scripts = await route.options.scripts?.(assetContext as any) match.meta = headFnContent?.meta match.links = headFnContent?.links diff --git a/packages/router-core/tests/head-matches-typing.test-d.ts b/packages/router-core/tests/head-matches-typing.test-d.ts new file mode 100644 index 0000000000..c6ad21f43d --- /dev/null +++ b/packages/router-core/tests/head-matches-typing.test-d.ts @@ -0,0 +1,230 @@ +import { describe, expectTypeOf, test } from 'vitest' + +import type { + AnyRoute, + AnyRouter, + MakeRouteMatchFromRoute, + UpdatableRouteOptions, + RouteMatch, +} from '../src' +import type { InferAssetFnMatches } from '../src/route' +import { BaseRootRoute, BaseRoute, rootRouteId } from '../src' + +type TestRegister = { + router: { routeTree: TRouteTree } +} + +type HeadCtxFor = Parameters< + NonNullable< + UpdatableRouteOptions< + TRoute['types']['parentRoute'], + TRoute['types']['id'], + TRoute['types']['fullPath'], + TRoute['types']['params'], + TRoute['types']['searchValidator'], + NonNullable, + TRoute['types']['loaderDeps'], + TRoute['types']['routerContext'], + TRoute['types']['routeContextFn'], + TRoute['types']['beforeLoadFn'], + TRegister + >['head'] + > +>[0] + +const rootRoute = new BaseRootRoute({ + loader: () => ({ + root: 'root', + }), +}) + +const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => ({ + foo: 123, + }), + head: () => ({}), +}) + +const barRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/bar', + loader: () => ({ + bar: true, + }), + head: () => ({}), +}) + +const bazRoute = new BaseRoute({ + getParentRoute: () => fooRoute, + path: '/baz', + loader: () => ({ + baz: true, + }), + head: () => ({}), +}) + +const helloRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hello', + loader: () => ({ + hello: 'hello', + }), + head: () => ({}), +}) + +const worldRoute = new BaseRoute({ + getParentRoute: () => helloRoute, + path: '/world', + loader: () => ({ + world: 1, + }), + head: () => ({}), +}) + +const xyzRoute = new BaseRoute({ + getParentRoute: () => helloRoute, + path: '/xyz', + loader: () => ({ + xyz: 1, + }), + head: () => ({}), +}) + +const routeTree = rootRoute.addChildren([ + fooRoute.addChildren({ + barRoute, + bazRoute, + }), + helloRoute.addChildren([worldRoute, xyzRoute]), +]) + +type RegisterWithTestRouteTree = TestRegister + +type IsAny = 0 extends 1 & T ? true : false + +describe('Route head matches typing', () => { + test('InferAssetFnMatches resolves concrete route types, not any', () => { + type Matches = InferAssetFnMatches + + // With tuple typing, matches[0] should be the root match specifically + type FirstElement = Matches[0] + type RouteIdOfFirst = FirstElement['routeId'] + + // routeId should not be any + expectTypeOf>().toEqualTypeOf() + + // routeId of first element should be exactly the root route ID + expectTypeOf().toEqualTypeOf() + }) + + test('foo head matches: positional tuple [root, foo, ...descendants[]]', () => { + type FooHeadCtx = HeadCtxFor + type FooMatches = FooHeadCtx['matches'] + + // matches should not be any or unknown + expectTypeOf().not.toBeAny() + expectTypeOf().not.toBeUnknown() + + // Position 0: root match + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf<'/'>() + // loaderData is optional on RouteMatch, so it's TLoaderData | undefined + expectTypeOf>().toEqualTypeOf<{ + root: string + }>() + + // Position 1: foo match (self) + expectTypeOf().toEqualTypeOf<'/foo'>() + expectTypeOf().toEqualTypeOf<'/foo'>() + expectTypeOf>().toEqualTypeOf<{ + foo: number + }>() + + // Position 2+: descendants (bar | baz union) + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/foo/bar'>().toMatchTypeOf() + expectTypeOf<'/foo/baz'>().toMatchTypeOf() + + // Descendants should NOT include unrelated routes + type HelloExtendsDescendants = '/hello' extends DescendantRouteIds + ? true + : false + expectTypeOf().toEqualTypeOf() + }) + + test('hello head matches: positional tuple [root, hello, ...descendants[]]', () => { + type HelloHeadCtx = HeadCtxFor + type HelloMatches = HelloHeadCtx['matches'] + + // Not any or unknown + expectTypeOf().not.toBeAny() + expectTypeOf().not.toBeUnknown() + + // Position 0: root match + expectTypeOf().toEqualTypeOf< + typeof rootRouteId + >() + expectTypeOf().toEqualTypeOf<'/'>() + + // Position 1: hello match (self) + expectTypeOf().toEqualTypeOf<'/hello'>() + expectTypeOf().toEqualTypeOf<'/hello'>() + expectTypeOf>().toEqualTypeOf<{ + hello: string + }>() + + // Position 2+: descendants (world | xyz union) + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/hello/world'>().toMatchTypeOf() + expectTypeOf<'/hello/xyz'>().toMatchTypeOf() + + // Descendants should NOT include unrelated routes + type FooExtendsDescendants = '/foo' extends DescendantRouteIds + ? true + : false + expectTypeOf().toEqualTypeOf() + }) + + test('bar head matches: positional tuple [root, foo, bar] with no descendants', () => { + type BarHeadCtx = HeadCtxFor + type BarMatches = BarHeadCtx['matches'] + + expectTypeOf().not.toBeAny() + + // Position 0: root + expectTypeOf().toEqualTypeOf() + + // Position 1: foo (parent) + expectTypeOf().toEqualTypeOf<'/foo'>() + + // Position 2: bar (self) + expectTypeOf().toEqualTypeOf<'/foo/bar'>() + expectTypeOf>().toEqualTypeOf<{ + bar: boolean + }>() + }) + + test('root head matches: positional tuple [root, ...all descendants[]]', () => { + type RootHeadCtx = HeadCtxFor + type RootMatches = RootHeadCtx['matches'] + + expectTypeOf().not.toBeAny() + + // Position 0: root (self) + expectTypeOf().toEqualTypeOf< + typeof rootRouteId + >() + expectTypeOf>().toEqualTypeOf<{ + root: string + }>() + + // Position 1+: all other routes as descendants + type DescendantRouteIds = NonNullable['routeId'] + expectTypeOf<'/foo'>().toMatchTypeOf() + expectTypeOf<'/foo/bar'>().toMatchTypeOf() + expectTypeOf<'/hello'>().toMatchTypeOf() + expectTypeOf<'/hello/world'>().toMatchTypeOf() + }) +})