diff --git a/docs/canary/concepts/route-layout.md b/docs/canary/concepts/route-layout.md new file mode 100644 index 00000000..4b7481a8 --- /dev/null +++ b/docs/canary/concepts/route-layout.md @@ -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 ( +
+ +
+ ); +} +``` diff --git a/docs/toc.ts b/docs/toc.ts index dc76fb07..ab7676ba 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -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"], ], }, diff --git a/src/server/context.ts b/src/server/context.ts index 514a88c2..40c8c9f7 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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( + 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); diff --git a/src/server/mod.ts b/src/server/mod.ts index 108614c0..aeff3578 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -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 >; diff --git a/src/server/render.ts b/src/server/render.ts index 9a2ad8da..888885bc 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -14,6 +14,8 @@ import { AsyncRoute, ErrorPage, Island, + LayoutModule, + LayoutRoute, Plugin, PluginRenderFunctionResult, PluginRenderResult, @@ -56,6 +58,7 @@ export interface RenderOptions { 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( let bodyHtml: string | null = null; function renderInner(vnode: ComponentChildren): string { + // deno-lint-ignore no-explicit-any + let finalAppComp: VNode = 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, + 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: opts.data, state: opts.state!, Component() { - // deno-lint-ignore no-explicit-any - return vnode as any; + return finalAppComp; }, }), }), diff --git a/src/server/types.ts b/src/server/types.ts index 557490a6..a69ca0b8 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -171,6 +171,25 @@ export interface AppModule { default: ComponentType; } +export interface LayoutProps extends PageProps { + Component: ComponentType>; +} + +export interface LayoutModule { + default: ComponentType; +} + +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 diff --git a/tests/fixture_layouts/dev.ts b/tests/fixture_layouts/dev.ts new file mode 100644 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_layouts/dev.ts @@ -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"); diff --git a/tests/fixture_layouts/fresh.gen.ts b/tests/fixture_layouts/fresh.gen.ts new file mode 100644 index 00000000..5f23fbba --- /dev/null +++ b/tests/fixture_layouts/fresh.gen.ts @@ -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; diff --git a/tests/fixture_layouts/main.ts b/tests/fixture_layouts/main.ts new file mode 100644 index 00000000..0f15e8de --- /dev/null +++ b/tests/fixture_layouts/main.ts @@ -0,0 +1,10 @@ +/// +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +await start(manifest); diff --git a/tests/fixture_layouts/routes/_app.tsx b/tests/fixture_layouts/routes/_app.tsx new file mode 100644 index 00000000..14b8496f --- /dev/null +++ b/tests/fixture_layouts/routes/_app.tsx @@ -0,0 +1,9 @@ +import { AppProps } from "$fresh/server.ts"; + +export default function App({ Component }: AppProps) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/_layout.tsx b/tests/fixture_layouts/routes/_layout.tsx new file mode 100644 index 00000000..0820eb80 --- /dev/null +++ b/tests/fixture_layouts/routes/_layout.tsx @@ -0,0 +1,9 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function RootLayout({ Component }: LayoutProps) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/files/js/_layout.js b/tests/fixture_layouts/routes/files/js/_layout.js new file mode 100644 index 00000000..57fb09c0 --- /dev/null +++ b/tests/fixture_layouts/routes/files/js/_layout.js @@ -0,0 +1,5 @@ +import { h } from "preact"; + +export default function JsLayout({ Component }) { + return h("div", { class: "js-layout" }, h(Component, null)); +} diff --git a/tests/fixture_layouts/routes/files/js/index.js b/tests/fixture_layouts/routes/files/js/index.js new file mode 100644 index 00000000..4980f6ed --- /dev/null +++ b/tests/fixture_layouts/routes/files/js/index.js @@ -0,0 +1,5 @@ +import { h } from "preact"; + +export default function JsPage() { + return h("div", { class: "js-page" }, "/files/js"); +} diff --git a/tests/fixture_layouts/routes/files/jsx/_layout.jsx b/tests/fixture_layouts/routes/files/jsx/_layout.jsx new file mode 100644 index 00000000..a35d3879 --- /dev/null +++ b/tests/fixture_layouts/routes/files/jsx/_layout.jsx @@ -0,0 +1,9 @@ +import { h } from "preact"; + +export default function JsxLayout({ Component }) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/files/jsx/index.jsx b/tests/fixture_layouts/routes/files/jsx/index.jsx new file mode 100644 index 00000000..e44ea6df --- /dev/null +++ b/tests/fixture_layouts/routes/files/jsx/index.jsx @@ -0,0 +1,3 @@ +export default function JsxPage() { + return
/files/jsx page
; +} diff --git a/tests/fixture_layouts/routes/files/ts/_layout.ts b/tests/fixture_layouts/routes/files/ts/_layout.ts new file mode 100644 index 00000000..33617a71 --- /dev/null +++ b/tests/fixture_layouts/routes/files/ts/_layout.ts @@ -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)); +} diff --git a/tests/fixture_layouts/routes/files/ts/index.ts b/tests/fixture_layouts/routes/files/ts/index.ts new file mode 100644 index 00000000..930cdc41 --- /dev/null +++ b/tests/fixture_layouts/routes/files/ts/index.ts @@ -0,0 +1,5 @@ +import { h } from "preact"; + +export default function TsPage() { + return h("div", { class: "ts-page" }, "/files/ts"); +} diff --git a/tests/fixture_layouts/routes/files/tsx/_layout.tsx b/tests/fixture_layouts/routes/files/tsx/_layout.tsx new file mode 100644 index 00000000..c8600dbb --- /dev/null +++ b/tests/fixture_layouts/routes/files/tsx/_layout.tsx @@ -0,0 +1,10 @@ +import { h } from "preact"; +import { LayoutProps } from "$fresh/server.ts"; + +export default function TsxLayout({ Component }: LayoutProps) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/files/tsx/index.tsx b/tests/fixture_layouts/routes/files/tsx/index.tsx new file mode 100644 index 00000000..b61a2b66 --- /dev/null +++ b/tests/fixture_layouts/routes/files/tsx/index.tsx @@ -0,0 +1,3 @@ +export default function TsxPage() { + return
/files/tsx page
; +} diff --git a/tests/fixture_layouts/routes/foo/_layout.tsx b/tests/fixture_layouts/routes/foo/_layout.tsx new file mode 100644 index 00000000..da0f7c8f --- /dev/null +++ b/tests/fixture_layouts/routes/foo/_layout.tsx @@ -0,0 +1,9 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function FooLayout({ Component }: LayoutProps) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/foo/bar.tsx b/tests/fixture_layouts/routes/foo/bar.tsx new file mode 100644 index 00000000..c5cc588e --- /dev/null +++ b/tests/fixture_layouts/routes/foo/bar.tsx @@ -0,0 +1,7 @@ +export default function BarPage() { + return ( +
+ /foo/bar page +
+ ); +} diff --git a/tests/fixture_layouts/routes/foo/index.tsx b/tests/fixture_layouts/routes/foo/index.tsx new file mode 100644 index 00000000..b2db53f7 --- /dev/null +++ b/tests/fixture_layouts/routes/foo/index.tsx @@ -0,0 +1,7 @@ +export default function FooPage() { + return ( +
+ /foo index page +
+ ); +} diff --git a/tests/fixture_layouts/routes/index.tsx b/tests/fixture_layouts/routes/index.tsx new file mode 100644 index 00000000..13e0de19 --- /dev/null +++ b/tests/fixture_layouts/routes/index.tsx @@ -0,0 +1,7 @@ +export default function Home() { + return ( +
+ Home +
+ ); +} diff --git a/tests/fixture_layouts/routes/other.tsx b/tests/fixture_layouts/routes/other.tsx new file mode 100644 index 00000000..47d7befe --- /dev/null +++ b/tests/fixture_layouts/routes/other.tsx @@ -0,0 +1,7 @@ +export default function OtherPage() { + return ( +
+ /other +
+ ); +} diff --git a/tests/fixture_layouts/routes/skip/sub/_layout.tsx b/tests/fixture_layouts/routes/skip/sub/_layout.tsx new file mode 100644 index 00000000..f237534b --- /dev/null +++ b/tests/fixture_layouts/routes/skip/sub/_layout.tsx @@ -0,0 +1,9 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function SubLayout({ Component }: LayoutProps) { + return ( +
+ +
+ ); +} diff --git a/tests/fixture_layouts/routes/skip/sub/index.tsx b/tests/fixture_layouts/routes/skip/sub/index.tsx new file mode 100644 index 00000000..7c22ad9e --- /dev/null +++ b/tests/fixture_layouts/routes/skip/sub/index.tsx @@ -0,0 +1,7 @@ +export default function SubPage() { + return ( +
+ /skip/sub page +
+ ); +} diff --git a/tests/layouts_test.ts b/tests/layouts_test.ts new file mode 100644 index 00000000..c2f66dfc --- /dev/null +++ b/tests/layouts_test.ts @@ -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"); + }); + }, + ); +});