feat: support async app template (#1626)

Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
Marvin Hagemeister
2023-08-14 14:52:48 +02:00
committed by GitHub
co-authored by Asher Gomez
parent 563b61d849
commit ba67d895ce
14 changed files with 217 additions and 158 deletions
+2 -2
View File
@@ -9,7 +9,7 @@ import {
typeByExtension, typeByExtension,
walk, walk,
} from "./deps.ts"; } from "./deps.ts";
import { h } from "preact"; import { ComponentType, h } from "preact";
import * as router from "./router.ts"; import * as router from "./router.ts";
import { DenoConfig, Manifest } from "./mod.ts"; import { DenoConfig, Manifest } from "./mod.ts";
import { ALIVE_URL, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts"; import { ALIVE_URL, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
@@ -967,7 +967,7 @@ const DEFAULT_ROUTER_OPTIONS: RouterOptions = {
}; };
const DEFAULT_APP: AppModule = { const DEFAULT_APP: AppModule = {
default: ({ Component }) => h(Component, {}), default: ({ Component }: { Component: ComponentType }) => h(Component, {}),
}; };
const DEFAULT_NOT_FOUND: UnknownPage = { const DEFAULT_NOT_FOUND: UnknownPage = {
+2
View File
@@ -14,6 +14,7 @@ import {
UnknownPageModule, UnknownPageModule,
} from "./types.ts"; } from "./types.ts";
export type { export type {
AppContext,
AppProps, AppProps,
ErrorHandler, ErrorHandler,
ErrorHandlerContext, ErrorHandlerContext,
@@ -22,6 +23,7 @@ export type {
Handler, Handler,
HandlerContext, HandlerContext,
Handlers, Handlers,
LayoutContext,
LayoutProps, LayoutProps,
MiddlewareHandler, MiddlewareHandler,
MiddlewareHandlerContext, MiddlewareHandlerContext,
+79 -133
View File
@@ -16,13 +16,13 @@ import {
ErrorPage, ErrorPage,
Island, Island,
LayoutModule, LayoutModule,
LayoutProps,
Plugin, Plugin,
PluginRenderFunctionResult, PluginRenderFunctionResult,
PluginRenderResult, PluginRenderResult,
PluginRenderStyleTag, PluginRenderStyleTag,
RenderFunction, RenderFunction,
Route, Route,
RouteContext,
UnknownPage, UnknownPage,
} from "./types.ts"; } from "./types.ts";
import { HEAD_CONTEXT } from "../runtime/head.ts"; import { HEAD_CONTEXT } from "../runtime/head.ts";
@@ -196,8 +196,6 @@ export async function render<Data>(
layouts = []; layouts = [];
} }
const isAsyncComponent = checkAsyncComponent(component);
const props: Record<string, unknown> = { const props: Record<string, unknown> = {
params: opts.params, params: opts.params,
url: opts.url, url: opts.url,
@@ -251,44 +249,77 @@ export async function render<Data>(
opts.lang ?? "en", opts.lang ?? "en",
); );
let bodyHtml: string | null = null; const context: RouteContext = {
localAddr: opts.context.localAddr,
remoteAddr: opts.context.remoteAddr,
renderNotFound: opts.context.renderNotFound,
url: opts.url,
route: opts.route.pattern,
params: opts.params as Record<string, string>,
state: opts.state ?? {},
data: opts.data,
};
const syncPlugins = opts.plugins.filter((p) => p.render); // Prepare render order
// deno-lint-ignore no-explicit-any
const renderStack: any[] = [];
// Check if appLayout is enabled
if (
opts.route.appLayout &&
layouts.every((layout) => layout.config?.appTemplate !== false)
) {
renderStack.push(opts.app.default);
}
for (let i = 0; i < layouts.length; i++) {
renderStack.push(layouts[i].default);
}
renderStack.push(component);
function buildRoot(appComponent: VNode) { // Build the final stack of component functions
// Only use the _app layout if not explicitly disabled const componentStack = new Array(renderStack.length).fill(null);
const child = opts.route.appLayout for (let i = 0; i < renderStack.length; i++) {
? h(opts.app.default, { const fn = renderStack[i];
params: opts.params as Record<string, string>, if (!fn) continue;
url: opts.url,
route: opts.route.pattern, if (checkAsyncComponent(fn)) {
data: opts.data, // Don't pass <Component /> when it's the route component
state: opts.state!, const isRouteComponent = fn === component;
const componentCtx = isRouteComponent ? context : {
...context,
Component() { Component() {
return appComponent; return h(componentStack[i + 1], props);
}, },
}) };
: appComponent; // deno-lint-ignore no-explicit-any
const res = await fn(opts.request, componentCtx as any);
return h(CSP_CONTEXT.Provider, { // Bail out of rendering if we returned a response
value: csp, if (res instanceof Response) {
children: h(HEAD_CONTEXT.Provider, { return res;
value: headComponents, }
children: child,
}), const componentFn = () => res;
}); // Set displayName to make debugging easier
// deno-lint-ignore no-explicit-any
componentFn.displayName = (fn as any).displayName || fn.name;
componentStack[i] = componentFn;
} else {
componentStack[i] = fn;
}
} }
function renderInnerSync(vnode: ComponentChildren): string { function render() {
// deno-lint-ignore no-explicit-any const routeComponent = componentStack[componentStack.length - 1];
let finalAppComp: VNode<any> = vnode as any; let finalComp = h(routeComponent, props);
let i = layouts.length; // Skip page component
let i = componentStack.length - 1;
while (i--) { while (i--) {
const layout = layouts[i]; const component = componentStack[i];
const curComp = finalAppComp; const curComp = finalComp;
finalAppComp = h(layout.default as ComponentType<LayoutProps>, { finalComp = h(component, {
// @ts-ignore weird jsx types
params: opts.params as Record<string, string>, params: opts.params as Record<string, string>,
url: opts.url, url: opts.url,
route: opts.route.pattern, route: opts.route.pattern,
@@ -300,26 +331,30 @@ export async function render<Data>(
}); });
} }
const root = buildRoot(finalAppComp); const app = h(CSP_CONTEXT.Provider, {
bodyHtml = renderToString(root); value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: finalComp,
}),
});
let html = renderToString(app);
for (const [id, children] of SLOTS_TRACKER.entries()) { for (const [id, children] of SLOTS_TRACKER.entries()) {
const slotHtml = renderToString(h(Fragment, null, children)); const slotHtml = renderToString(h(Fragment, null, children));
const templateId = id.replace(/:/g, "-"); const templateId = id.replace(/:/g, "-");
bodyHtml += `<template id="${templateId}">${slotHtml}</template>`; html += `<template id="${templateId}">${slotHtml}</template>`;
} }
return bodyHtml; return html;
} }
let bodyHtml: string | null = null;
const syncPlugins = opts.plugins.filter((p) => p.render);
const renderResults: [Plugin, PluginRenderResult][] = []; const renderResults: [Plugin, PluginRenderResult][] = [];
if (isAsyncComponent && syncPlugins.length > 0) {
throw new Error(
`Async server components cannot be rendered synchronously. The following plugins use a synchronous render method: "${
syncPlugins.map((plugin) => plugin.name).join('", "')
}"`,
);
}
function renderSync(): PluginRenderFunctionResult { function renderSync(): PluginRenderFunctionResult {
const plugin = syncPlugins.shift(); const plugin = syncPlugins.shift();
@@ -332,7 +367,7 @@ export async function render<Data>(
} }
renderResults.push([plugin, res]); renderResults.push([plugin, res]);
} else { } else {
renderInnerSync(h(component as ComponentType, props)); bodyHtml = render();
} }
if (bodyHtml === null) { if (bodyHtml === null) {
throw new Error( throw new Error(
@@ -364,96 +399,7 @@ export async function render<Data>(
); );
} }
} else { } else {
if ( await opts.renderFn(ctx, () => renderSync().htmlText);
isAsyncComponent ||
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.`,
);
}
const context = {
localAddr: opts.context.localAddr,
remoteAddr: opts.context.remoteAddr,
renderNotFound: opts.context.renderNotFound,
url: opts.url,
route: opts.route.pattern,
params: opts.params as Record<string, string>,
state: opts.state ?? {},
};
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<any>[] = [];
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<string, string>,
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<string, string>,
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);
}
if (bodyHtml === null) { if (bodyHtml === null) {
throw new Error( throw new Error(
+27 -11
View File
@@ -59,9 +59,17 @@ export interface PageProps<T = any, S = Record<string, unknown>> {
* Context passed to async route components. * Context passed to async route components.
*/ */
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export type RouteContext<T = any, S = Record<string, unknown>> = export type RouteContext<T = any, S = Record<string, unknown>> = {
& Omit<HandlerContext<T, S>, "render"> /** @types deprecated */
& Omit<PageProps<unknown, S>, "data">; localAddr?: Deno.NetAddr;
remoteAddr: Deno.NetAddr;
renderNotFound: (data?: T) => Response | Promise<Response>;
url: URL;
route: string;
params: Record<string, string>;
state: S;
data: T;
};
export interface RouteConfig { export interface RouteConfig {
/** /**
@@ -162,7 +170,7 @@ export interface Route<Data = any> {
pattern: string; pattern: string;
url: string; url: string;
name: string; name: string;
component?: PageComponent<Data>; component?: PageComponent<Data> | AsyncLayout<Data> | AsyncRoute<Data>;
handler: Handler<Data> | Handlers<Data>; handler: Handler<Data> | Handlers<Data>;
csp: boolean; csp: boolean;
appLayout: boolean; appLayout: boolean;
@@ -176,15 +184,24 @@ export interface RouterState {
// --- APP --- // --- APP ---
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export interface AppProps<T = any, S = Record<string, unknown>> export type AppProps<T = any, S = Record<string, unknown>> = LayoutProps<T, S>;
extends PageProps<T, S> {
Component: ComponentType<Record<never, never>>;
}
export interface AppModule { export interface AppModule {
default: ComponentType<AppProps>; default: ComponentType<AppProps> | AsyncLayout;
} }
// deno-lint-ignore no-explicit-any
export type AppContext<T = any, S = Record<string, unknown>> =
& RouteContext<T, S>
& {
Component: () => VNode;
};
// deno-lint-ignore no-explicit-any
export type LayoutContext<T = any, S = Record<string, unknown>> = AppContext<
T,
S
>;
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export interface LayoutProps<T = any, S = Record<string, unknown>> export interface LayoutProps<T = any, S = Record<string, unknown>>
extends PageProps<T, S> { extends PageProps<T, S> {
@@ -193,8 +210,7 @@ export interface LayoutProps<T = any, S = Record<string, unknown>>
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export type AsyncLayout<T = any, S = Record<string, unknown>> = ( export type AsyncLayout<T = any, S = Record<string, unknown>> = (
req: Request, req: Request,
ctx: RouteContext<T, S>, ctx: LayoutContext<T, S>,
props: LayoutProps,
) => Promise<ComponentChildren | Response>; ) => Promise<ComponentChildren | Response>;
export interface LayoutModule { export interface LayoutModule {
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+19
View File
@@ -0,0 +1,19 @@
// DO NOT EDIT. This file is generated by Fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/_app.tsx";
import * as $1 from "./routes/_layout.tsx";
import * as $2 from "./routes/index.tsx";
const manifest = {
routes: {
"./routes/_app.tsx": $0,
"./routes/_layout.tsx": $1,
"./routes/index.tsx": $2,
},
islands: {},
baseUrl: import.meta.url,
};
export default manifest;
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
+25
View File
@@ -0,0 +1,25 @@
import { delay } from "$std/async/delay.ts";
import { AppContext } from "$fresh/src/server/types.ts";
export default async function App(req: Request, ctx: AppContext) {
await delay(100);
return (
<html lang="fr">
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>fresh title</title>
</head>
<body>
<div class="app">
App template
<ctx.Component />
</div>
</body>
</html>
);
}
@@ -0,0 +1,15 @@
import { LayoutContext } from "$fresh/server.ts";
import { delay } from "$std/async/delay.ts";
export default async function AsyncLayout(
req: Request,
ctx: LayoutContext,
) {
await delay(10);
return (
<div class="layout">
<p>Async layout</p>
<ctx.Component />
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
// deno-lint-ignore require-await
export default async function Home() {
return (
<div class="page">
Home
</div>
);
}
@@ -1,15 +1,15 @@
import { LayoutProps, RouteContext } from "$fresh/server.ts"; import { LayoutContext } from "$fresh/server.ts";
import { delay } from "$fresh/tests/deps.ts";
export default async function AsyncLayout( export default async function AsyncLayout(
req: Request, req: Request,
ctx: RouteContext, ctx: LayoutContext,
{ Component }: LayoutProps,
) { ) {
await new Promise((r) => setTimeout(r, 10)); await delay(10);
return ( return (
<div class="async-layout"> <div class="async-layout">
<p>Async layout</p> <p>Async layout</p>
<Component /> <ctx.Component />
</div> </div>
); );
} }
@@ -1,10 +1,9 @@
import { LayoutProps, RouteContext } from "$fresh/server.ts"; import { LayoutContext } from "$fresh/server.ts";
import { delay } from "$std/async/mod.ts"; import { delay } from "$std/async/mod.ts";
export default async function AsyncSubLayout( export default async function AsyncSubLayout(
req: Request, req: Request,
ctx: RouteContext, ctx: LayoutContext,
{ Component }: LayoutProps,
) { ) {
await delay(10); await delay(10);
return new Response(null, { return new Response(null, {
@@ -1,15 +1,14 @@
import { LayoutProps, RouteContext } from "$fresh/server.ts"; import { LayoutContext } from "$fresh/server.ts";
export default async function AsyncSubLayout( export default async function AsyncSubLayout(
req: Request, req: Request,
ctx: RouteContext, ctx: LayoutContext,
{ Component }: LayoutProps,
) { ) {
await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 10));
return ( return (
<div class="async-sub-layout"> <div class="async-sub-layout">
<p>Async Sub layout</p> <p>Async Sub layout</p>
<Component /> <ctx.Component />
</div> </div>
); );
} }
+15
View File
@@ -1,5 +1,6 @@
import { assertEquals } from "./deps.ts"; import { assertEquals } from "./deps.ts";
import { import {
assertSelector,
assertTextMany, assertTextMany,
fetchHtml, fetchHtml,
withFresh, withFresh,
@@ -156,3 +157,17 @@ Deno.test({
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,
}); });
Deno.test({
name: "renders async app template",
async fn() {
await withFresh(
"./tests/fixture_async_app/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}`);
assertSelector(doc, "html > body > .app > .layout > .page");
},
);
},
});