feat: support async app template (#1626)
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
co-authored by
Asher Gomez
parent
563b61d849
commit
ba67d895ce
@@ -9,7 +9,7 @@ import {
|
||||
typeByExtension,
|
||||
walk,
|
||||
} from "./deps.ts";
|
||||
import { h } from "preact";
|
||||
import { ComponentType, h } from "preact";
|
||||
import * as router from "./router.ts";
|
||||
import { DenoConfig, Manifest } from "./mod.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 = {
|
||||
default: ({ Component }) => h(Component, {}),
|
||||
default: ({ Component }: { Component: ComponentType }) => h(Component, {}),
|
||||
};
|
||||
|
||||
const DEFAULT_NOT_FOUND: UnknownPage = {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
UnknownPageModule,
|
||||
} from "./types.ts";
|
||||
export type {
|
||||
AppContext,
|
||||
AppProps,
|
||||
ErrorHandler,
|
||||
ErrorHandlerContext,
|
||||
@@ -22,6 +23,7 @@ export type {
|
||||
Handler,
|
||||
HandlerContext,
|
||||
Handlers,
|
||||
LayoutContext,
|
||||
LayoutProps,
|
||||
MiddlewareHandler,
|
||||
MiddlewareHandlerContext,
|
||||
|
||||
+79
-133
@@ -16,13 +16,13 @@ import {
|
||||
ErrorPage,
|
||||
Island,
|
||||
LayoutModule,
|
||||
LayoutProps,
|
||||
Plugin,
|
||||
PluginRenderFunctionResult,
|
||||
PluginRenderResult,
|
||||
PluginRenderStyleTag,
|
||||
RenderFunction,
|
||||
Route,
|
||||
RouteContext,
|
||||
UnknownPage,
|
||||
} from "./types.ts";
|
||||
import { HEAD_CONTEXT } from "../runtime/head.ts";
|
||||
@@ -196,8 +196,6 @@ export async function render<Data>(
|
||||
layouts = [];
|
||||
}
|
||||
|
||||
const isAsyncComponent = checkAsyncComponent(component);
|
||||
|
||||
const props: Record<string, unknown> = {
|
||||
params: opts.params,
|
||||
url: opts.url,
|
||||
@@ -251,44 +249,77 @@ export async function render<Data>(
|
||||
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) {
|
||||
// Only use the _app layout if not explicitly disabled
|
||||
const child = opts.route.appLayout
|
||||
? h(opts.app.default, {
|
||||
params: opts.params as Record<string, string>,
|
||||
url: opts.url,
|
||||
route: opts.route.pattern,
|
||||
data: opts.data,
|
||||
state: opts.state!,
|
||||
// Build the final stack of component functions
|
||||
const componentStack = new Array(renderStack.length).fill(null);
|
||||
for (let i = 0; i < renderStack.length; i++) {
|
||||
const fn = renderStack[i];
|
||||
if (!fn) continue;
|
||||
|
||||
if (checkAsyncComponent(fn)) {
|
||||
// Don't pass <Component /> when it's the route component
|
||||
const isRouteComponent = fn === component;
|
||||
const componentCtx = isRouteComponent ? context : {
|
||||
...context,
|
||||
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, {
|
||||
value: csp,
|
||||
children: h(HEAD_CONTEXT.Provider, {
|
||||
value: headComponents,
|
||||
children: child,
|
||||
}),
|
||||
});
|
||||
// Bail out of rendering if we returned a response
|
||||
if (res instanceof Response) {
|
||||
return res;
|
||||
}
|
||||
|
||||
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 {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
let finalAppComp: VNode<any> = vnode as any;
|
||||
function render() {
|
||||
const routeComponent = componentStack[componentStack.length - 1];
|
||||
let finalComp = h(routeComponent, props);
|
||||
|
||||
let i = layouts.length;
|
||||
// Skip page component
|
||||
let i = componentStack.length - 1;
|
||||
while (i--) {
|
||||
const layout = layouts[i];
|
||||
const curComp = finalAppComp;
|
||||
const component = componentStack[i];
|
||||
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>,
|
||||
url: opts.url,
|
||||
route: opts.route.pattern,
|
||||
@@ -300,26 +331,30 @@ export async function render<Data>(
|
||||
});
|
||||
}
|
||||
|
||||
const root = buildRoot(finalAppComp);
|
||||
bodyHtml = renderToString(root);
|
||||
const app = h(CSP_CONTEXT.Provider, {
|
||||
value: csp,
|
||||
children: h(HEAD_CONTEXT.Provider, {
|
||||
value: headComponents,
|
||||
children: finalComp,
|
||||
}),
|
||||
});
|
||||
|
||||
let html = renderToString(app);
|
||||
|
||||
for (const [id, children] of SLOTS_TRACKER.entries()) {
|
||||
const slotHtml = renderToString(h(Fragment, null, children));
|
||||
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][] = [];
|
||||
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 {
|
||||
const plugin = syncPlugins.shift();
|
||||
@@ -332,7 +367,7 @@ export async function render<Data>(
|
||||
}
|
||||
renderResults.push([plugin, res]);
|
||||
} else {
|
||||
renderInnerSync(h(component as ComponentType, props));
|
||||
bodyHtml = render();
|
||||
}
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
@@ -364,96 +399,7 @@ export async function render<Data>(
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
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);
|
||||
}
|
||||
await opts.renderFn(ctx, () => renderSync().htmlText);
|
||||
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
|
||||
+27
-11
@@ -59,9 +59,17 @@ export interface PageProps<T = any, S = Record<string, unknown>> {
|
||||
* Context passed to async route components.
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type RouteContext<T = any, S = Record<string, unknown>> =
|
||||
& Omit<HandlerContext<T, S>, "render">
|
||||
& Omit<PageProps<unknown, S>, "data">;
|
||||
export type RouteContext<T = any, S = Record<string, unknown>> = {
|
||||
/** @types deprecated */
|
||||
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 {
|
||||
/**
|
||||
@@ -162,7 +170,7 @@ export interface Route<Data = any> {
|
||||
pattern: string;
|
||||
url: string;
|
||||
name: string;
|
||||
component?: PageComponent<Data>;
|
||||
component?: PageComponent<Data> | AsyncLayout<Data> | AsyncRoute<Data>;
|
||||
handler: Handler<Data> | Handlers<Data>;
|
||||
csp: boolean;
|
||||
appLayout: boolean;
|
||||
@@ -176,15 +184,24 @@ export interface RouterState {
|
||||
// --- APP ---
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface AppProps<T = any, S = Record<string, unknown>>
|
||||
extends PageProps<T, S> {
|
||||
Component: ComponentType<Record<never, never>>;
|
||||
}
|
||||
export type AppProps<T = any, S = Record<string, unknown>> = LayoutProps<T, S>;
|
||||
|
||||
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
|
||||
export interface LayoutProps<T = any, S = Record<string, unknown>>
|
||||
extends PageProps<T, S> {
|
||||
@@ -193,8 +210,7 @@ export interface LayoutProps<T = any, S = Record<string, unknown>>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: RouteContext<T, S>,
|
||||
props: LayoutProps,
|
||||
ctx: LayoutContext<T, S>,
|
||||
) => Promise<ComponentChildren | Response>;
|
||||
|
||||
export interface LayoutModule {
|
||||
|
||||
Reference in New Issue
Block a user