From 8325225a0dc91a81c8e3cb38a2262e4261d0e4af Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Tue, 8 Aug 2023 14:15:02 +0200 Subject: [PATCH] feat: support async layout functions (#1597) Co-authored-by: Asher Gomez --- src/server/render.ts | 144 ++++++++++++++---- src/server/types.ts | 8 +- tests/fixture_layouts/fresh.gen.ts | 72 +++++---- tests/fixture_layouts/routes/_app.tsx | 2 +- .../fixture_layouts/routes/async/_layout.tsx | 15 ++ tests/fixture_layouts/routes/async/index.tsx | 10 ++ .../routes/async/redirect/_layout.tsx | 14 ++ .../routes/async/redirect/index.tsx | 13 ++ .../routes/async/sub/_layout.tsx | 15 ++ .../routes/async/sub/index.tsx | 10 ++ tests/layouts_test.ts | 39 +++++ 11 files changed, 277 insertions(+), 65 deletions(-) create mode 100644 tests/fixture_layouts/routes/async/_layout.tsx create mode 100644 tests/fixture_layouts/routes/async/index.tsx create mode 100644 tests/fixture_layouts/routes/async/redirect/_layout.tsx create mode 100644 tests/fixture_layouts/routes/async/redirect/index.tsx create mode 100644 tests/fixture_layouts/routes/async/sub/_layout.tsx create mode 100644 tests/fixture_layouts/routes/async/sub/index.tsx diff --git a/src/server/render.ts b/src/server/render.ts index f270977f..d6c23c9d 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -11,10 +11,12 @@ import { } from "preact"; import { AppModule, + AsyncLayout, AsyncRoute, ErrorPage, Island, LayoutModule, + LayoutProps, Plugin, PluginRenderFunctionResult, PluginRenderResult, @@ -137,6 +139,13 @@ function defaultCsp() { }; } +function checkAsyncComponent( + component: unknown, +): component is AsyncRoute | AsyncLayout { + return typeof component === "function" && + component.constructor.name === "AsyncFunction"; +} + /** * This function renders out a page. Rendering is synchronous and non streaming. * Suspense boundaries are not supported. @@ -145,8 +154,8 @@ export async function render( opts: RenderOptions, ): Promise<[string, ContentSecurityPolicy | undefined] | Response> { const component = opts.route.component; - const isAsyncComponent = typeof component === "function" && - component.constructor.name === "AsyncFunction"; + const layouts = opts.layouts; + const isAsyncComponent = checkAsyncComponent(component); const props: Record = { params: opts.params, @@ -192,16 +201,37 @@ export async function render( let bodyHtml: string | null = null; - function renderInner(vnode: ComponentChildren): string { + const syncPlugins = opts.plugins.filter((p) => p.render); + + function buildRoot(appComponent: VNode) { + return h(CSP_CONTEXT.Provider, { + value: csp, + children: h(HEAD_CONTEXT.Provider, { + value: headComponents, + children: h(opts.app.default, { + params: opts.params as Record, + url: opts.url, + route: opts.route.pattern, + data: opts.data, + state: opts.state!, + Component() { + return appComponent; + }, + }), + }), + }); + } + + function renderInnerSync(vnode: ComponentChildren): string { // deno-lint-ignore no-explicit-any let finalAppComp: VNode = vnode as any; let i = opts.layouts.length; while (i--) { - const layout = opts.layouts[i]; - + const layout = layouts[i]; const curComp = finalAppComp; - finalAppComp = h(layout.default, { + + finalAppComp = h(layout.default as ComponentType, { params: opts.params as Record, url: opts.url, route: opts.route.pattern, @@ -213,22 +243,7 @@ export async function render( }); } - const root = h(CSP_CONTEXT.Provider, { - value: csp, - children: h(HEAD_CONTEXT.Provider, { - value: headComponents, - children: h(opts.app.default, { - params: opts.params as Record, - url: opts.url, - route: opts.route.pattern, - data: opts.data, - state: opts.state!, - Component() { - return finalAppComp; - }, - }), - }), - }); + const root = buildRoot(finalAppComp); bodyHtml = renderToString(root); for (const [id, children] of SLOTS_TRACKER.entries()) { @@ -241,7 +256,6 @@ export async function render( } const renderResults: [Plugin, PluginRenderResult][] = []; - const syncPlugins = opts.plugins.filter((p) => p.render); if (isAsyncComponent && syncPlugins.length > 0) { throw new Error( `Async server components cannot be rendered synchronously. The following plugins use a synchronous render method: "${ @@ -261,7 +275,7 @@ export async function render( } renderResults.push([plugin, res]); } else { - renderInner(h(component as ComponentType, props)); + renderInnerSync(h(component as ComponentType, props)); } if (bodyHtml === null) { throw new Error( @@ -293,15 +307,17 @@ export async function render( ); } } else { - if (isAsyncComponent) { + if ( + isAsyncComponent || + opts.layouts.some((layout) => checkAsyncComponent(layout.default)) + ) { if (opts.renderFn !== DEFAULT_RENDER_FN) { throw new Error( `Async server components are not supported with custom render functions.`, ); } - // deno-lint-ignore no-explicit-any - const res = await (component as AsyncRoute)(opts.request, { + const context = { localAddr: opts.context.localAddr, remoteAddr: opts.context.remoteAddr, renderNotFound: opts.context.renderNotFound, @@ -309,12 +325,74 @@ export async function render( route: opts.route.pattern, params: opts.params as Record, state: opts.state ?? {}, - }); - if (res instanceof Response) { - asyncRenderResponse = res; - bodyHtml = ""; - } else { - renderInner(res); + }; + + const renderStack = [ + ...layouts.map((layout) => layout.default), + component, + ]; + + const componentStack: (VNode | null)[] = new Array(renderStack.length) + .fill(null); + + // deno-lint-ignore no-explicit-any + const preparedLayouts: ComponentType[] = []; + for (let i = 0; i < renderStack.length; i++) { + const layout = renderStack[i]; + if (!layout) continue; + + if (checkAsyncComponent(layout)) { + const res = await layout(opts.request, context, { + params: opts.params as Record, + url: opts.url, + route: opts.route.pattern, + data: opts.data, + state: opts.state!, + Component() { + return componentStack[i + 1]; + }, + }); + if (res instanceof Response) { + asyncRenderResponse = res; + bodyHtml = ""; + break; + } + // deno-lint-ignore no-explicit-any + preparedLayouts.push(() => res as any); + } else { + // deno-lint-ignore no-explicit-any + preparedLayouts.push(layout as any); + } + } + + // Only continue rendering layouts if we didn't abort + // earlier by returning a response object. + if (!asyncRenderResponse) { + const routeComponent = preparedLayouts[preparedLayouts.length - 1]; + let finalAppComp = h(routeComponent, props); + componentStack.push(finalAppComp); + + // Skip page component + let i = preparedLayouts.length - 1; + while (i--) { + const layout = preparedLayouts[i]; + const curComp = finalAppComp; + componentStack[i + 1] = curComp; + + finalAppComp = h(layout, { + params: opts.params as Record, + url: opts.url, + route: opts.route.pattern, + data: opts.data, + state: opts.state!, + Component() { + return curComp; + }, + }); + } + + const root = buildRoot(finalAppComp); + bodyHtml = renderToString(root); } } else { await opts.renderFn(ctx, () => renderSync().htmlText); diff --git a/src/server/types.ts b/src/server/types.ts index 0cf7d4e7..1d4b7c8b 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -176,9 +176,15 @@ export interface LayoutProps> extends PageProps { Component: ComponentType>; } +// deno-lint-ignore no-explicit-any +export type AsyncLayout> = ( + req: Request, + ctx: RouteContext, + props: LayoutProps, +) => Promise; export interface LayoutModule { - default: ComponentType; + default: ComponentType | AsyncLayout; } export interface LayoutRoute { diff --git a/tests/fixture_layouts/fresh.gen.ts b/tests/fixture_layouts/fresh.gen.ts index c8f9f9f2..a1a8a110 100644 --- a/tests/fixture_layouts/fresh.gen.ts +++ b/tests/fixture_layouts/fresh.gen.ts @@ -5,42 +5,54 @@ import * as $0 from "./routes/_app.tsx"; import * as $1 from "./routes/_layout.tsx"; import * as $2 from "./routes/_middleware.ts"; -import * as $3 from "./routes/files/js/_layout.js"; -import * as $4 from "./routes/files/js/index.js"; -import * as $5 from "./routes/files/jsx/_layout.jsx"; -import * as $6 from "./routes/files/jsx/index.jsx"; -import * as $7 from "./routes/files/ts/_layout.ts"; -import * as $8 from "./routes/files/ts/index.ts"; -import * as $9 from "./routes/files/tsx/_layout.tsx"; -import * as $10 from "./routes/files/tsx/index.tsx"; -import * as $11 from "./routes/foo/_layout.tsx"; -import * as $12 from "./routes/foo/bar.tsx"; -import * as $13 from "./routes/foo/index.tsx"; -import * as $14 from "./routes/index.tsx"; -import * as $15 from "./routes/other.tsx"; -import * as $16 from "./routes/skip/sub/_layout.tsx"; -import * as $17 from "./routes/skip/sub/index.tsx"; +import * as $3 from "./routes/async/_layout.tsx"; +import * as $4 from "./routes/async/index.tsx"; +import * as $5 from "./routes/async/redirect/_layout.tsx"; +import * as $6 from "./routes/async/redirect/index.tsx"; +import * as $7 from "./routes/async/sub/_layout.tsx"; +import * as $8 from "./routes/async/sub/index.tsx"; +import * as $9 from "./routes/files/js/_layout.js"; +import * as $10 from "./routes/files/js/index.js"; +import * as $11 from "./routes/files/jsx/_layout.jsx"; +import * as $12 from "./routes/files/jsx/index.jsx"; +import * as $13 from "./routes/files/ts/_layout.ts"; +import * as $14 from "./routes/files/ts/index.ts"; +import * as $15 from "./routes/files/tsx/_layout.tsx"; +import * as $16 from "./routes/files/tsx/index.tsx"; +import * as $17 from "./routes/foo/_layout.tsx"; +import * as $18 from "./routes/foo/bar.tsx"; +import * as $19 from "./routes/foo/index.tsx"; +import * as $20 from "./routes/index.tsx"; +import * as $21 from "./routes/other.tsx"; +import * as $22 from "./routes/skip/sub/_layout.tsx"; +import * as $23 from "./routes/skip/sub/index.tsx"; const manifest = { routes: { "./routes/_app.tsx": $0, "./routes/_layout.tsx": $1, "./routes/_middleware.ts": $2, - "./routes/files/js/_layout.js": $3, - "./routes/files/js/index.js": $4, - "./routes/files/jsx/_layout.jsx": $5, - "./routes/files/jsx/index.jsx": $6, - "./routes/files/ts/_layout.ts": $7, - "./routes/files/ts/index.ts": $8, - "./routes/files/tsx/_layout.tsx": $9, - "./routes/files/tsx/index.tsx": $10, - "./routes/foo/_layout.tsx": $11, - "./routes/foo/bar.tsx": $12, - "./routes/foo/index.tsx": $13, - "./routes/index.tsx": $14, - "./routes/other.tsx": $15, - "./routes/skip/sub/_layout.tsx": $16, - "./routes/skip/sub/index.tsx": $17, + "./routes/async/_layout.tsx": $3, + "./routes/async/index.tsx": $4, + "./routes/async/redirect/_layout.tsx": $5, + "./routes/async/redirect/index.tsx": $6, + "./routes/async/sub/_layout.tsx": $7, + "./routes/async/sub/index.tsx": $8, + "./routes/files/js/_layout.js": $9, + "./routes/files/js/index.js": $10, + "./routes/files/jsx/_layout.jsx": $11, + "./routes/files/jsx/index.jsx": $12, + "./routes/files/ts/_layout.ts": $13, + "./routes/files/ts/index.ts": $14, + "./routes/files/tsx/_layout.tsx": $15, + "./routes/files/tsx/index.tsx": $16, + "./routes/foo/_layout.tsx": $17, + "./routes/foo/bar.tsx": $18, + "./routes/foo/index.tsx": $19, + "./routes/index.tsx": $20, + "./routes/other.tsx": $21, + "./routes/skip/sub/_layout.tsx": $22, + "./routes/skip/sub/index.tsx": $23, }, islands: {}, baseUrl: import.meta.url, diff --git a/tests/fixture_layouts/routes/_app.tsx b/tests/fixture_layouts/routes/_app.tsx index 14b8496f..ba763d1d 100644 --- a/tests/fixture_layouts/routes/_app.tsx +++ b/tests/fixture_layouts/routes/_app.tsx @@ -1,6 +1,6 @@ import { AppProps } from "$fresh/server.ts"; -export default function App({ Component }: AppProps) { +export default function App({ Component, state }: AppProps) { return (
diff --git a/tests/fixture_layouts/routes/async/_layout.tsx b/tests/fixture_layouts/routes/async/_layout.tsx new file mode 100644 index 00000000..cb604e32 --- /dev/null +++ b/tests/fixture_layouts/routes/async/_layout.tsx @@ -0,0 +1,15 @@ +import { LayoutProps, RouteContext } from "$fresh/server.ts"; + +export default async function AsyncLayout( + req: Request, + ctx: RouteContext, + { Component }: LayoutProps, +) { + await new Promise((r) => setTimeout(r, 10)); + return ( +
+

Async layout

+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/async/index.tsx b/tests/fixture_layouts/routes/async/index.tsx new file mode 100644 index 00000000..648f6222 --- /dev/null +++ b/tests/fixture_layouts/routes/async/index.tsx @@ -0,0 +1,10 @@ +import { RouteContext } from "$fresh/server.ts"; + +export default async function AsyncPage(req: Request, ctx: RouteContext) { + await new Promise((r) => setTimeout(r, 10)); + return ( +
+

Async page

+
+ ); +} diff --git a/tests/fixture_layouts/routes/async/redirect/_layout.tsx b/tests/fixture_layouts/routes/async/redirect/_layout.tsx new file mode 100644 index 00000000..96d1bd39 --- /dev/null +++ b/tests/fixture_layouts/routes/async/redirect/_layout.tsx @@ -0,0 +1,14 @@ +import { LayoutProps, RouteContext } from "$fresh/server.ts"; +import { delay } from "$std/async/mod.ts"; + +export default async function AsyncSubLayout( + req: Request, + ctx: RouteContext, + { Component }: LayoutProps, +) { + await delay(10); + return new Response(null, { + status: 307, + headers: { Location: "/async/sub" }, + }); +} diff --git a/tests/fixture_layouts/routes/async/redirect/index.tsx b/tests/fixture_layouts/routes/async/redirect/index.tsx new file mode 100644 index 00000000..f3380619 --- /dev/null +++ b/tests/fixture_layouts/routes/async/redirect/index.tsx @@ -0,0 +1,13 @@ +import { RouteContext } from "$fresh/server.ts"; + +export default async function AsyncRedirectPage( + req: Request, + ctx: RouteContext, +) { + await new Promise((r) => setTimeout(r, 10)); + return ( +
+

Async Redirect page

+
+ ); +} diff --git a/tests/fixture_layouts/routes/async/sub/_layout.tsx b/tests/fixture_layouts/routes/async/sub/_layout.tsx new file mode 100644 index 00000000..540170d0 --- /dev/null +++ b/tests/fixture_layouts/routes/async/sub/_layout.tsx @@ -0,0 +1,15 @@ +import { LayoutProps, RouteContext } from "$fresh/server.ts"; + +export default async function AsyncSubLayout( + req: Request, + ctx: RouteContext, + { Component }: LayoutProps, +) { + await new Promise((r) => setTimeout(r, 10)); + return ( +
+

Async Sub layout

+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/async/sub/index.tsx b/tests/fixture_layouts/routes/async/sub/index.tsx new file mode 100644 index 00000000..c63bd184 --- /dev/null +++ b/tests/fixture_layouts/routes/async/sub/index.tsx @@ -0,0 +1,10 @@ +import { RouteContext } from "$fresh/server.ts"; + +export default async function AsyncSubPage(req: Request, ctx: RouteContext) { + await new Promise((r) => setTimeout(r, 10)); + return ( +
+

Async Sub page

+
+ ); +} diff --git a/tests/layouts_test.ts b/tests/layouts_test.ts index c735e7d0..e2973c53 100644 --- a/tests/layouts_test.ts +++ b/tests/layouts_test.ts @@ -64,3 +64,42 @@ Deno.test("check file types", async (t) => { }, ); }); + +Deno.test("render async layout", async () => { + await withFresh( + "./tests/fixture_layouts/main.ts", + async (address) => { + const doc = await fetchHtml(`${address}/async`); + assertSelector(doc, ".app .root-layout .async-layout .async-page"); + }, + ); +}); + +Deno.test("render nested async layout", async () => { + await withFresh( + "./tests/fixture_layouts/main.ts", + async (address) => { + const doc = await fetchHtml(`${address}/async/sub`); + assertSelector( + doc, + ".app .root-layout .async-layout .async-sub-layout .async-sub-page", + ); + }, + ); +}); + +Deno.test({ + name: "can return Response from async layout", + fn: async () => { + await withFresh( + "./tests/fixture_layouts/main.ts", + async (address) => { + const doc = await fetchHtml(`${address}/async/redirect`); + assertSelector( + doc, + ".app .root-layout .async-layout .async-sub-layout .async-sub-page", + ); + }, + ); + }, +});