feat: support route layouts via _layout.tsx (#1506)

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Michael Gearhardt
2023-07-26 11:49:08 +02:00
committed by GitHub
co-authored by Marvin Hagemeister
parent 18857ea052
commit 1ed93cec88
27 changed files with 397 additions and 3 deletions
+28
View File
@@ -0,0 +1,28 @@
---
description: |
Add a route layout to provide common meta tags, context for application sub routes, and common layout.
---
An route layout is defined in a `_layout.tsx` file in any sub directory (at any
level) under the `routes/` folder. It must contain a default export that is a
regular Preact component. Only one such layout is allowed per sub directory.
The component to be wrapped is received via props, in addition to a few other
things. This allows for the introduction of a global container functioning as a
template which can be conditioned based on state and params. Note that any state
set by middleware is available via `props.state`.
```tsx
// routes/sub/_layout.tsx
import { LayoutProps } from "$fresh/server.ts";
export default function Layout({ Component, state }: LayoutProps) {
//do something with state here
return (
<div class="layout">
<Component />
</div>
);
}
```
+1
View File
@@ -58,6 +58,7 @@ const toc: RawTableOfContents = {
["plugins", "Plugins", "link:latest"],
["updating", "Updating Fresh", "link:canary"],
["app-wrapper", "Application wrapper", "link:latest"],
["route-layout", "Route layouts", "link:canary"],
["server-configuration", "Server configuration", "link:latest"],
],
},
+60 -1
View File
@@ -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);
+3
View File
@@ -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
View File
@@ -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;
},
}),
}),
+19
View File
@@ -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
+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");
+47
View File
@@ -0,0 +1,47 @@
// 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/files/js/_layout.js";
import * as $3 from "./routes/files/js/index.js";
import * as $4 from "./routes/files/jsx/_layout.jsx";
import * as $5 from "./routes/files/jsx/index.jsx";
import * as $6 from "./routes/files/ts/_layout.ts";
import * as $7 from "./routes/files/ts/index.ts";
import * as $8 from "./routes/files/tsx/_layout.tsx";
import * as $9 from "./routes/files/tsx/index.tsx";
import * as $10 from "./routes/foo/_layout.tsx";
import * as $11 from "./routes/foo/bar.tsx";
import * as $12 from "./routes/foo/index.tsx";
import * as $13 from "./routes/index.tsx";
import * as $14 from "./routes/other.tsx";
import * as $15 from "./routes/skip/sub/_layout.tsx";
import * as $16 from "./routes/skip/sub/index.tsx";
const manifest = {
routes: {
"./routes/_app.tsx": $0,
"./routes/_layout.tsx": $1,
"./routes/files/js/_layout.js": $2,
"./routes/files/js/index.js": $3,
"./routes/files/jsx/_layout.jsx": $4,
"./routes/files/jsx/index.jsx": $5,
"./routes/files/ts/_layout.ts": $6,
"./routes/files/ts/index.ts": $7,
"./routes/files/tsx/_layout.tsx": $8,
"./routes/files/tsx/index.tsx": $9,
"./routes/foo/_layout.tsx": $10,
"./routes/foo/bar.tsx": $11,
"./routes/foo/index.tsx": $12,
"./routes/index.tsx": $13,
"./routes/other.tsx": $14,
"./routes/skip/sub/_layout.tsx": $15,
"./routes/skip/sub/index.tsx": $16,
},
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);
+9
View File
@@ -0,0 +1,9 @@
import { AppProps } from "$fresh/server.ts";
export default function App({ Component }: AppProps) {
return (
<div class="app">
<Component />
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
import { LayoutProps } from "$fresh/server.ts";
export default function RootLayout({ Component }: LayoutProps) {
return (
<div class="root-layout">
<Component />
</div>
);
}
@@ -0,0 +1,5 @@
import { h } from "preact";
export default function JsLayout({ Component }) {
return h("div", { class: "js-layout" }, h(Component, null));
}
@@ -0,0 +1,5 @@
import { h } from "preact";
export default function JsPage() {
return h("div", { class: "js-page" }, "/files/js");
}
@@ -0,0 +1,9 @@
import { h } from "preact";
export default function JsxLayout({ Component }) {
return (
<div class="jsx-layout">
<Component />
</div>
);
}
@@ -0,0 +1,3 @@
export default function JsxPage() {
return <div class="jsx-page">/files/jsx page</div>;
}
@@ -0,0 +1,6 @@
import { h } from "preact";
import { LayoutProps } from "$fresh/server.ts";
export default function TsLayout({ Component }: LayoutProps) {
return h("div", { class: "ts-layout" }, h(Component, null));
}
@@ -0,0 +1,5 @@
import { h } from "preact";
export default function TsPage() {
return h("div", { class: "ts-page" }, "/files/ts");
}
@@ -0,0 +1,10 @@
import { h } from "preact";
import { LayoutProps } from "$fresh/server.ts";
export default function TsxLayout({ Component }: LayoutProps) {
return (
<div class="tsx-layout">
<Component />
</div>
);
}
@@ -0,0 +1,3 @@
export default function TsxPage() {
return <div class="tsx-page">/files/tsx page</div>;
}
@@ -0,0 +1,9 @@
import { LayoutProps } from "$fresh/server.ts";
export default function FooLayout({ Component }: LayoutProps) {
return (
<div class="foo-layout">
<Component />
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function BarPage() {
return (
<div class="bar-page">
/foo/bar page
</div>
);
}
@@ -0,0 +1,7 @@
export default function FooPage() {
return (
<div class="foo-page">
/foo index page
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function Home() {
return (
<div class="home-page">
Home
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function OtherPage() {
return (
<div class="other-page">
/other
</div>
);
}
@@ -0,0 +1,9 @@
import { LayoutProps } from "$fresh/server.ts";
export default function SubLayout({ Component }: LayoutProps) {
return (
<div class="sub-layout">
<Component />
</div>
);
}
@@ -0,0 +1,7 @@
export default function SubPage() {
return (
<div class="sub-page">
/skip/sub page
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { withPageName } from "./test_utils.ts";
Deno.test("apply root _layout and _app", async () => {
await withPageName(
"./tests/fixture_layouts/main.ts",
async (page, address) => {
await page.goto(address);
await page.waitForSelector(".app .root-layout .home-page");
await page.goto(`${address}/other`);
await page.waitForSelector(".app .root-layout .other-page");
},
);
});
Deno.test("apply sub layouts", async () => {
await withPageName(
"./tests/fixture_layouts/main.ts",
async (page, address) => {
await page.goto(`${address}/foo`);
await page.waitForSelector(".app .root-layout .foo-layout .foo-page");
await page.goto(`${address}/foo/bar`);
await page.waitForSelector(".app .root-layout .foo-layout .bar-page");
},
);
});
Deno.test("skip layouts if not present", async () => {
await withPageName(
"./tests/fixture_layouts/main.ts",
async (page, address) => {
await page.goto(`${address}/skip/sub`);
await page.waitForSelector(".app .root-layout .sub-layout .sub-page");
},
);
});
Deno.test("check file types", async (t) => {
await withPageName(
"./tests/fixture_layouts/main.ts",
async (page, address) => {
await t.step(".js", async () => {
await page.goto(`${address}/files/js`);
await page.waitForSelector(".app .root-layout .js-layout .js-page");
});
await t.step(".jsx", async () => {
await page.goto(`${address}/files/jsx`);
await page.waitForSelector(".app .root-layout .jsx-layout .jsx-page");
});
await t.step(".ts", async () => {
await page.goto(`${address}/files/ts`);
await page.waitForSelector(".app .root-layout .ts-layout .ts-page");
});
await t.step(".tsx", async () => {
await page.goto(`${address}/files/tsx`);
await page.waitForSelector(".app .root-layout .tsx-layout .tsx-page");
});
},
);
});