From 4b352f4251bd77b0815e008e45bbe93b21c2459b Mon Sep 17 00:00:00 2001 From: Manuel Schiller Date: Tue, 20 May 2025 22:14:11 +0200 Subject: [PATCH] fix: allow head to be async (#4213) --- packages/router-core/src/route.ts | 9 +- packages/router-core/src/router.ts | 82 +++++++++---------- packages/router-core/src/utils.ts | 1 + packages/solid-router/tests/route.test.tsx | 32 ++++++-- packages/start-client-core/src/ssr-client.tsx | 78 +++++++++--------- 5 files changed, 110 insertions(+), 92 deletions(-) diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 2c876e2149..0e057efab9 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -17,6 +17,7 @@ import type { AnyRouter, RegisteredRouter } from './router' import type { BuildLocationFn, NavigateFn } from './RouterProvider' import type { Assign, + Awaitable, Constrain, Expand, IntersectAssign, @@ -1083,7 +1084,7 @@ export interface UpdatableRouteOptions< TBeforeLoadFn, TLoaderDeps >, - ) => Record + ) => Awaitable> head?: ( ctx: AssetFnContextOptions< TRouteId, @@ -1097,11 +1098,11 @@ export interface UpdatableRouteOptions< TBeforeLoadFn, TLoaderDeps >, - ) => { + ) => Awaitable<{ links?: AnyRouteMatch['links'] scripts?: AnyRouteMatch['headScripts'] meta?: AnyRouteMatch['meta'] - } + }> scripts?: ( ctx: AssetFnContextOptions< TRouteId, @@ -1115,7 +1116,7 @@ export interface UpdatableRouteOptions< TBeforeLoadFn, TLoaderDeps >, - ) => AnyRouteMatch['scripts'] + ) => Awaitable ssr?: boolean codeSplitGroupings?: Array< Array< diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 3899ce384c..f61a7284e8 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -2589,7 +2589,7 @@ export class RouterCore< !this.state.matches.find((d) => d.id === matchId), })) - const executeHead = () => { + const executeHead = async () => { const match = this.getMatch(matchId) // in case of a redirecting match during preload, the match does not exist if (!match) { @@ -2601,21 +2601,17 @@ export class RouterCore< params: match.params, loaderData: match.loaderData, } - const headFnContent = route.options.head?.(assetContext) + const headFnContent = + await route.options.head?.(assetContext) const meta = headFnContent?.meta const links = headFnContent?.links const headScripts = headFnContent?.scripts - const scripts = route.options.scripts?.(assetContext) - const headers = route.options.headers?.(assetContext) - updateMatch(matchId, (prev) => ({ - ...prev, - meta, - links, - headScripts, - headers, - scripts, - })) + const scripts = + await route.options.scripts?.(assetContext) + const headers = + await route.options.headers?.(assetContext) + return { meta, links, headScripts, headers, scripts } } const runLoader = async () => { @@ -2662,17 +2658,19 @@ export class RouterCore< // to be preloaded before we resolve the match await route._componentsPromise - batch(() => { - updateMatch(matchId, (prev) => ({ - ...prev, - error: undefined, - status: 'success', - isFetching: false, - updatedAt: Date.now(), - loaderData, - })) - executeHead() - }) + updateMatch(matchId, (prev) => ({ + ...prev, + error: undefined, + status: 'success', + isFetching: false, + updatedAt: Date.now(), + loaderData, + })) + const head = await executeHead() + updateMatch(matchId, (prev) => ({ + ...prev, + ...head, + })) } catch (e) { let error = e @@ -2689,16 +2687,14 @@ export class RouterCore< onErrorError, ) } - - batch(() => { - updateMatch(matchId, (prev) => ({ - ...prev, - error, - status: 'error', - isFetching: false, - })) - executeHead() - }) + const head = await executeHead() + updateMatch(matchId, (prev) => ({ + ...prev, + error, + status: 'error', + isFetching: false, + ...head, + })) } this.serverSsr?.onMatchSettled({ @@ -2706,13 +2702,13 @@ export class RouterCore< match: this.getMatch(matchId)!, }) } catch (err) { - batch(() => { - updateMatch(matchId, (prev) => ({ - ...prev, - loaderPromise: undefined, - })) - executeHead() - }) + const head = await executeHead() + + updateMatch(matchId, (prev) => ({ + ...prev, + loaderPromise: undefined, + ...head, + })) handleRedirectAndNotFound(this.getMatch(matchId)!, err) } } @@ -2752,7 +2748,11 @@ export class RouterCore< // if the loader did not run, still update head. // reason: parent's beforeLoad may have changed the route context // and only now do we know the route context (and that the loader would not run) - executeHead() + const head = await executeHead() + updateMatch(matchId, (prev) => ({ + ...prev, + ...head, + })) } } if (!loaderIsRunningAsync) { diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 1df674e8b9..8d7207a693 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -1,6 +1,7 @@ import type { RouteIds } from './routeInfo' import type { AnyRouter } from './router' +export type Awaitable = T | Promise export type NoInfer = [T][T extends any ? 0 : never] export type IsAny = 1 extends 0 & TValue ? TYesResult diff --git a/packages/solid-router/tests/route.test.tsx b/packages/solid-router/tests/route.test.tsx index 7a8f776a61..f0a2a8e591 100644 --- a/packages/solid-router/tests/route.test.tsx +++ b/packages/solid-router/tests/route.test.tsx @@ -1,15 +1,26 @@ -import { afterEach, describe, expect, it, test, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest' import { cleanup, render, screen } from '@solidjs/testing-library' import { RouterProvider, + createBrowserHistory, createRootRoute, createRoute, createRouter, getRouteApi, } from '../src' +import type { RouterHistory } from '../src' + +let history: RouterHistory + +beforeEach(() => { + history = createBrowserHistory() + expect(window.location.pathname).toBe('/') +}) + afterEach(() => { + history.destroy() vi.resetAllMocks() window.history.replaceState(null, 'root', '/') cleanup() @@ -161,7 +172,7 @@ describe('onEnter event', () => { }, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree, context: { foo: 'bar' } }) + const router = createRouter({ routeTree, history, context: { foo: 'bar' } }) await router.load() @@ -182,7 +193,7 @@ describe('onEnter event', () => { }, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree, context: { foo: 'bar' } }) + const router = createRouter({ routeTree, history, context: { foo: 'bar' } }) render(() => ) @@ -214,8 +225,9 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) + await router.load() const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() @@ -254,7 +266,7 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() @@ -286,8 +298,9 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) + await router.load() const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() @@ -316,7 +329,7 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() @@ -343,8 +356,9 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) + await router.load() const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() @@ -373,7 +387,7 @@ describe('route.head', () => { component: () =>
Index
, }) const routeTree = rootRoute.addChildren([indexRoute]) - const router = createRouter({ routeTree }) + const router = createRouter({ routeTree, history }) render(() => ) const indexElem = await screen.findByText('Index') expect(indexElem).toBeInTheDocument() diff --git a/packages/start-client-core/src/ssr-client.tsx b/packages/start-client-core/src/ssr-client.tsx index 9eddf971db..0ef6036fb1 100644 --- a/packages/start-client-core/src/ssr-client.tsx +++ b/packages/start-client-core/src/ssr-client.tsx @@ -179,50 +179,52 @@ export function hydrate(router: AnyRouter) { // now that all necessary data is hydrated: // 1) fully reconstruct the route context // 2) execute `head()` and `scripts()` for each match - router.state.matches.forEach((match) => { - const route = router.looseRoutesById[match.routeId]! + await Promise.all( + router.state.matches.map(async (match) => { + const route = router.looseRoutesById[match.routeId]! - const parentMatch = router.state.matches[match.index - 1] - const parentContext = parentMatch?.context ?? router.options.context ?? {} + const parentMatch = router.state.matches[match.index - 1] + const parentContext = parentMatch?.context ?? router.options.context ?? {} - // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed - // so run it again and merge route context - const contextFnContext: RouteContextOptions = { - deps: match.loaderDeps, - params: match.params, - context: parentContext, - location: router.state.location, - navigate: (opts: any) => - router.navigate({ ...opts, _fromLocation: router.state.location }), - buildLocation: router.buildLocation, - cause: match.cause, - abortController: match.abortController, - preload: false, - matches, - } - match.__routeContext = route.options.context?.(contextFnContext) ?? {} + // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed + // so run it again and merge route context + const contextFnContext: RouteContextOptions = { + deps: match.loaderDeps, + params: match.params, + context: parentContext, + location: router.state.location, + navigate: (opts: any) => + router.navigate({ ...opts, _fromLocation: router.state.location }), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: match.abortController, + preload: false, + matches, + } + match.__routeContext = route.options.context?.(contextFnContext) ?? {} - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, - } + match.context = { + ...parentContext, + ...match.__routeContext, + ...match.__beforeLoadContext, + } - const assetContext = { - matches: router.state.matches, - match, - params: match.params, - loaderData: match.loaderData, - } - const headFnContent = route.options.head?.(assetContext) + const assetContext = { + matches: router.state.matches, + match, + params: match.params, + loaderData: match.loaderData, + } + const headFnContent = await route.options.head?.(assetContext) - const scripts = route.options.scripts?.(assetContext) + const scripts = await route.options.scripts?.(assetContext) - match.meta = headFnContent?.meta - match.links = headFnContent?.links - match.headScripts = headFnContent?.scripts - match.scripts = scripts - }) + match.meta = headFnContent?.meta + match.links = headFnContent?.links + match.headScripts = headFnContent?.scripts + match.scripts = scripts + }), + ) return routeChunkPromise }