feat: support route layouts via _layout.tsx (#1506)
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
co-authored by
Marvin Hagemeister
parent
18857ea052
commit
1ed93cec88
+43
-2
@@ -14,6 +14,8 @@ import {
|
||||
AsyncRoute,
|
||||
ErrorPage,
|
||||
Island,
|
||||
LayoutModule,
|
||||
LayoutRoute,
|
||||
Plugin,
|
||||
PluginRenderFunctionResult,
|
||||
PluginRenderResult,
|
||||
@@ -56,6 +58,7 @@ export interface RenderOptions<Data> {
|
||||
islands: Island[];
|
||||
plugins: Plugin[];
|
||||
app: AppModule;
|
||||
layouts: LayoutRoute[];
|
||||
imports: string[];
|
||||
dependenciesFn: (path: string) => string[];
|
||||
url: URL;
|
||||
@@ -135,6 +138,25 @@ function defaultCsp() {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a list of layouts that needs to be applied for request url
|
||||
* @param url the request url
|
||||
* @param layouts Array of layouts handlers and their routes as path-to-regexp style
|
||||
*/
|
||||
export function selectLayouts(url: string, layouts: LayoutRoute[]) {
|
||||
const selectedLayouts: LayoutModule[] = [];
|
||||
const reqURL = new URL(url);
|
||||
|
||||
for (const layout of layouts) {
|
||||
const res = layout.compiledPattern.exec(reqURL);
|
||||
if (res) {
|
||||
selectedLayouts.push(layout);
|
||||
}
|
||||
}
|
||||
|
||||
return selectedLayouts;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function renders out a page. Rendering is synchronous and non streaming.
|
||||
* Suspense boundaries are not supported.
|
||||
@@ -189,6 +211,26 @@ export async function render<Data>(
|
||||
let bodyHtml: string | null = null;
|
||||
|
||||
function renderInner(vnode: ComponentChildren): string {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
let finalAppComp: VNode<any> = vnode as any;
|
||||
|
||||
const layouts = selectLayouts(opts.url.toString(), opts.layouts);
|
||||
|
||||
layouts.forEach((layout) => {
|
||||
const curComp = { ...finalAppComp };
|
||||
|
||||
finalAppComp = h(layout.default, {
|
||||
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 = h(CSP_CONTEXT.Provider, {
|
||||
value: csp,
|
||||
children: h(HEAD_CONTEXT.Provider, {
|
||||
@@ -200,8 +242,7 @@ export async function render<Data>(
|
||||
data: opts.data,
|
||||
state: opts.state!,
|
||||
Component() {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return vnode as any;
|
||||
return finalAppComp;
|
||||
},
|
||||
}),
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user