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
+60
-1
@@ -22,6 +22,8 @@ import {
|
||||
FreshOptions,
|
||||
Handler,
|
||||
Island,
|
||||
LayoutModule,
|
||||
LayoutRoute,
|
||||
Middleware,
|
||||
MiddlewareHandlerContext,
|
||||
MiddlewareModule,
|
||||
@@ -91,6 +93,7 @@ export class ServerContext {
|
||||
#renderFn: RenderFunction;
|
||||
#middlewares: MiddlewareRoute[];
|
||||
#app: AppModule;
|
||||
#layouts: LayoutRoute[];
|
||||
#notFound: UnknownPage;
|
||||
#error: ErrorPage;
|
||||
#plugins: Plugin[];
|
||||
@@ -104,6 +107,7 @@ export class ServerContext {
|
||||
renderfn: RenderFunction,
|
||||
middlewares: MiddlewareRoute[],
|
||||
app: AppModule,
|
||||
layouts: LayoutRoute[],
|
||||
notFound: UnknownPage,
|
||||
error: ErrorPage,
|
||||
plugins: Plugin[],
|
||||
@@ -118,6 +122,7 @@ export class ServerContext {
|
||||
this.#renderFn = renderfn;
|
||||
this.#middlewares = middlewares;
|
||||
this.#app = app;
|
||||
this.#layouts = layouts;
|
||||
this.#notFound = notFound;
|
||||
this.#error = error;
|
||||
this.#plugins = plugins;
|
||||
@@ -176,6 +181,7 @@ export class ServerContext {
|
||||
const islands: Island[] = [];
|
||||
const middlewares: MiddlewareRoute[] = [];
|
||||
let app: AppModule = DEFAULT_APP;
|
||||
const layouts: LayoutRoute[] = [];
|
||||
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
|
||||
let error: ErrorPage = DEFAULT_ERROR;
|
||||
const allRoutes = [
|
||||
@@ -193,10 +199,15 @@ export class ServerContext {
|
||||
const path = url.substring(baseUrl.length).substring("routes".length);
|
||||
const baseRoute = path.substring(1, path.length - extname(path).length);
|
||||
const name = baseRoute.replace("/", "-");
|
||||
const isLayout = path.endsWith("/_layout.tsx") ||
|
||||
path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") ||
|
||||
path.endsWith("/_layout.js");
|
||||
const isMiddleware = path.endsWith("/_middleware.tsx") ||
|
||||
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
|
||||
path.endsWith("/_middleware.js");
|
||||
if (!path.startsWith("/_") && !isMiddleware) {
|
||||
if (
|
||||
!path.startsWith("/_") && !isLayout && !isMiddleware
|
||||
) {
|
||||
const { default: component, config } = module as RouteModule;
|
||||
let pattern = pathToPattern(baseRoute);
|
||||
if (config?.routeOverride) {
|
||||
@@ -248,6 +259,11 @@ export class ServerContext {
|
||||
path === "/_app.jsx" || path === "/_app.js"
|
||||
) {
|
||||
app = module as AppModule;
|
||||
} else if (isLayout) {
|
||||
layouts.push({
|
||||
...layoutPathToPattern(baseRoute),
|
||||
...module as LayoutModule,
|
||||
});
|
||||
} else if (
|
||||
path === "/_404.tsx" || path === "/_404.ts" ||
|
||||
path === "/_404.jsx" || path === "/_404.js"
|
||||
@@ -289,6 +305,7 @@ export class ServerContext {
|
||||
}
|
||||
sortRoutes(routes);
|
||||
sortMiddleware(middlewares);
|
||||
sortLayouts(layouts);
|
||||
|
||||
for (const [self, module] of Object.entries(manifest.islands)) {
|
||||
const url = new URL(self, baseUrl).href;
|
||||
@@ -370,6 +387,7 @@ export class ServerContext {
|
||||
opts.render ?? DEFAULT_RENDER_FN,
|
||||
middlewares,
|
||||
app,
|
||||
layouts,
|
||||
notFound,
|
||||
error,
|
||||
opts.plugins ?? [],
|
||||
@@ -646,6 +664,7 @@ export class ServerContext {
|
||||
islands: this.#islands,
|
||||
plugins: this.#plugins,
|
||||
app: this.#app,
|
||||
layouts: this.#layouts,
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: this.#renderFn,
|
||||
@@ -698,6 +717,7 @@ export class ServerContext {
|
||||
islands: this.#islands,
|
||||
plugins: this.#plugins,
|
||||
app: this.#app,
|
||||
layouts: this.#layouts,
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: this.#renderFn,
|
||||
@@ -944,6 +964,35 @@ export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
|
||||
return selectedMws;
|
||||
}
|
||||
|
||||
export function sortLayouts<T extends { pattern: string }>(
|
||||
layouts: LayoutRoute[],
|
||||
) {
|
||||
layouts.sort((a, b) => {
|
||||
const partsA = a.pattern.split("/");
|
||||
const partsB = b.pattern.split("/");
|
||||
|
||||
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
|
||||
const partA = partsA[i];
|
||||
const partB = partsB[i];
|
||||
|
||||
if (partA === undefined && partB === undefined) return 0;
|
||||
if (partA === undefined) return 1;
|
||||
if (partB === undefined) return -1;
|
||||
|
||||
if (partA === partB) continue;
|
||||
|
||||
const priorityA = getPriority(partA);
|
||||
const priorityB = getPriority(partB);
|
||||
|
||||
if (priorityA !== priorityB) {
|
||||
return priorityB - priorityA; // Sort in ascending order of priority
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort pages by their relative routing priority, based on the parts in the
|
||||
* route matcher
|
||||
@@ -1095,6 +1144,16 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
export function layoutPathToPattern(baseRoute: string) {
|
||||
baseRoute = baseRoute.slice(0, -"_layout".length);
|
||||
let pattern = pathToPattern(baseRoute);
|
||||
if (pattern.endsWith("/")) {
|
||||
pattern = pattern.slice(0, -1) + "{/*}?";
|
||||
}
|
||||
const compiledPattern = new URLPattern({ pathname: pattern });
|
||||
return { pattern, compiledPattern };
|
||||
}
|
||||
|
||||
export function middlewarePathToPattern(baseRoute: string) {
|
||||
baseRoute = baseRoute.slice(0, -"_middleware".length);
|
||||
let pattern = pathToPattern(baseRoute);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
AppModule,
|
||||
ErrorPageModule,
|
||||
IslandModule,
|
||||
LayoutModule,
|
||||
MiddlewareModule,
|
||||
RouteModule,
|
||||
ServeHandler,
|
||||
@@ -21,6 +22,7 @@ export type {
|
||||
Handler,
|
||||
HandlerContext,
|
||||
Handlers,
|
||||
LayoutProps,
|
||||
MiddlewareHandler,
|
||||
MiddlewareHandlerContext,
|
||||
MultiHandler,
|
||||
@@ -52,6 +54,7 @@ export interface Manifest {
|
||||
| RouteModule
|
||||
| MiddlewareModule
|
||||
| AppModule
|
||||
| LayoutModule
|
||||
| ErrorPageModule
|
||||
| UnknownPageModule
|
||||
>;
|
||||
|
||||
+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;
|
||||
},
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -171,6 +171,25 @@ export interface AppModule {
|
||||
default: ComponentType<AppProps>;
|
||||
}
|
||||
|
||||
export interface LayoutProps extends PageProps {
|
||||
Component: ComponentType<Record<never, never>>;
|
||||
}
|
||||
|
||||
export interface LayoutModule {
|
||||
default: ComponentType<LayoutProps>;
|
||||
}
|
||||
|
||||
export interface LayoutRoute extends LayoutModule {
|
||||
/**
|
||||
* path-to-regexp style url path
|
||||
*/
|
||||
pattern: string;
|
||||
/**
|
||||
* URLPattern of the route
|
||||
*/
|
||||
compiledPattern: URLPattern;
|
||||
}
|
||||
|
||||
// --- UNKNOWN PAGE ---
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
|
||||
Reference in New Issue
Block a user