feat: allow layout and _app overrides (#1611)

This commit is contained in:
Marvin Hagemeister
2023-08-09 16:35:53 +00:00
committed by GitHub
parent 81ae7b8427
commit 7ebaf0404d
13 changed files with 277 additions and 20 deletions
+62
View File
@@ -7,6 +7,18 @@ 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.
```sh
routes/
_app.tsx
_layout.tsx # will be applied to all routes
/sub
index.tsx
page.tsx
/other
_layout.tsx # will be applied on top of `routes/_layout.tsx`
page.tsx
```
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
@@ -26,3 +38,53 @@ export default function Layout({ Component, state }: LayoutProps) {
);
}
```
## Opting out of layout inheritance
Sometimes you want to opt out of the layout inheritance mechanism for a
particular route. This can be done via route configuration. Picture a directory
structure like this:
```sh
routes/
_layout.tsx
/sub
_layout.tsx
index.tsx
special.tsx # should not inherit layouts
```
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
`rootLayout: true`.
```tsx
// routes/sub/special.tsx
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
rootLayout: true, // Mark this route as the root layout
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
Note that you can also mark layouts as root layouts.
## Disabling the root `_app` template
In very rare cases you might want to disable the root `_app` template for a
particular route. This can be done by setting `appTemplate: false`.
```tsx
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
appTemplate: false, // Disable the `_app` template
};
export default function MyPage() {
return <p>Hello world</p>;
}
```
+10
View File
@@ -253,6 +253,8 @@ export class ServerContext {
component,
handler,
csp: Boolean(config?.csp ?? false),
appLayout: Boolean(config?.appTemplate ?? true),
rootLayout: Boolean(config?.rootLayout ?? false),
};
routes.push(route);
} else if (isMiddleware) {
@@ -288,6 +290,8 @@ export class ServerContext {
component,
handler: handler ?? ((req) => router.defaultOtherHandler(req)),
csp: Boolean(config?.csp ?? false),
appLayout: Boolean(config?.appTemplate ?? true),
rootLayout: Boolean(config?.rootLayout ?? false),
};
} else if (
path === "/_500.tsx" || path === "/_500.ts" ||
@@ -308,6 +312,8 @@ export class ServerContext {
handler: handler ??
((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)),
csp: Boolean(config?.csp ?? false),
appLayout: Boolean(config?.appTemplate ?? true),
rootLayout: Boolean(config?.rootLayout ?? false),
};
}
}
@@ -971,6 +977,8 @@ const DEFAULT_NOT_FOUND: UnknownPage = {
name: "_404",
handler: (req) => router.defaultOtherHandler(req),
csp: false,
appLayout: true,
rootLayout: false,
};
const DEFAULT_ERROR: ErrorPage = {
@@ -981,6 +989,8 @@ const DEFAULT_ERROR: ErrorPage = {
component: DefaultErrorHandler,
handler: (_req, ctx) => ctx.render(),
csp: false,
appLayout: true,
rootLayout: false,
};
export function selectSharedRoutes<T>(
+35 -13
View File
@@ -154,7 +154,24 @@ export async function render<Data>(
opts: RenderOptions<Data>,
): Promise<[string, ContentSecurityPolicy | undefined] | Response> {
const component = opts.route.component;
const layouts = opts.layouts;
// Only inherit layouts up to the nearest root layout.
// Note that the route itself can act as the root layout.
let layouts = opts.layouts;
if (!opts.route.rootLayout) {
let rootIdx = 0;
let layoutIdx = opts.layouts.length;
while (layoutIdx--) {
if (opts.layouts[layoutIdx].config?.rootLayout) {
rootIdx = layoutIdx;
break;
}
}
layouts = opts.layouts.slice(rootIdx);
} else {
layouts = [];
}
const isAsyncComponent = checkAsyncComponent(component);
const props: Record<string, unknown> = {
@@ -204,20 +221,25 @@ export async function render<Data>(
const syncPlugins = opts.plugins.filter((p) => p.render);
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!,
Component() {
return appComponent;
},
})
: appComponent;
return h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(opts.app.default, {
params: opts.params as Record<string, string>,
url: opts.url,
route: opts.route.pattern,
data: opts.data,
state: opts.state!,
Component() {
return appComponent;
},
}),
children: child,
}),
});
}
@@ -226,7 +248,7 @@ export async function render<Data>(
// deno-lint-ignore no-explicit-any
let finalAppComp: VNode<any> = vnode as any;
let i = opts.layouts.length;
let i = layouts.length;
while (i--) {
const layout = layouts[i];
const curComp = finalAppComp;
@@ -309,7 +331,7 @@ export async function render<Data>(
} else {
if (
isAsyncComponent ||
opts.layouts.some((layout) => checkAsyncComponent(layout.default))
layouts.some((layout) => checkAsyncComponent(layout.default))
) {
if (opts.renderFn !== DEFAULT_RENDER_FN) {
throw new Error(
+19
View File
@@ -79,6 +79,18 @@ export interface RouteConfig {
* using the `useCSP` hook.
*/
csp?: boolean;
/**
* Mark this route as the root layout and ignore previously
* inherited layouts. Default: `false`
*/
rootLayout?: boolean;
/**
* Whether to use the `routes/_app` template if available or not.
* Default: `true`
*/
appTemplate?: boolean;
}
// deno-lint-ignore no-empty-interface
@@ -153,6 +165,8 @@ export interface Route<Data = any> {
component?: PageComponent<Data>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
appLayout: boolean;
rootLayout: boolean;
}
export interface RouterState {
@@ -185,6 +199,7 @@ export type AsyncLayout<T = any, S = Record<string, unknown>> = (
export interface LayoutModule {
default: ComponentType<LayoutProps> | AsyncLayout;
config?: Pick<RouteConfig, "appTemplate" | "rootLayout">;
}
export interface LayoutRoute {
@@ -236,6 +251,8 @@ export interface UnknownPage {
component?: PageComponent<UnknownPageProps>;
handler: UnknownHandler;
csp: boolean;
appLayout: boolean;
rootLayout: boolean;
}
// --- ERROR PAGE ---
@@ -281,6 +298,8 @@ export interface ErrorPage {
component?: PageComponent<ErrorPageProps>;
handler: ErrorHandler;
csp: boolean;
appLayout: boolean;
rootLayout: boolean;
}
// --- MIDDLEWARES ---
+18 -6
View File
@@ -23,9 +23,15 @@ import * as $17 from "./routes/foo/_layout.tsx";
import * as $18 from "./routes/foo/bar.tsx";
import * as $19 from "./routes/foo/index.tsx";
import * as $20 from "./routes/index.tsx";
import * as $21 from "./routes/other.tsx";
import * as $22 from "./routes/skip/sub/_layout.tsx";
import * as $23 from "./routes/skip/sub/index.tsx";
import * as $21 from "./routes/no_app.tsx";
import * as $22 from "./routes/other.tsx";
import * as $23 from "./routes/override/_layout.tsx";
import * as $24 from "./routes/override/index.tsx";
import * as $25 from "./routes/override/no_app.tsx";
import * as $26 from "./routes/override/no_layout.tsx";
import * as $27 from "./routes/override/no_layout_no_app.tsx";
import * as $28 from "./routes/skip/sub/_layout.tsx";
import * as $29 from "./routes/skip/sub/index.tsx";
const manifest = {
routes: {
@@ -50,9 +56,15 @@ const manifest = {
"./routes/foo/bar.tsx": $18,
"./routes/foo/index.tsx": $19,
"./routes/index.tsx": $20,
"./routes/other.tsx": $21,
"./routes/skip/sub/_layout.tsx": $22,
"./routes/skip/sub/index.tsx": $23,
"./routes/no_app.tsx": $21,
"./routes/other.tsx": $22,
"./routes/override/_layout.tsx": $23,
"./routes/override/index.tsx": $24,
"./routes/override/no_app.tsx": $25,
"./routes/override/no_layout.tsx": $26,
"./routes/override/no_layout_no_app.tsx": $27,
"./routes/skip/sub/_layout.tsx": $28,
"./routes/skip/sub/index.tsx": $29,
},
islands: {},
baseUrl: import.meta.url,
+17
View File
@@ -0,0 +1,17 @@
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
appTemplate: false,
};
export default function OverridePage() {
return (
<html>
<body>
<p class="no-app">
no <pre>_app.tsx</pre> template
</p>
</body>
</html>
);
}
@@ -0,0 +1,13 @@
import { LayoutProps, RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
rootLayout: true,
};
export default function OverrideLayout({ Component }: LayoutProps) {
return (
<div class="override-layout">
<Component />
</div>
);
}
@@ -0,0 +1,7 @@
export default function OverridePage() {
return (
<div class="override-page">
/override index page
</div>
);
}
@@ -0,0 +1,13 @@
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
appTemplate: false,
};
export default function OverridePage() {
return (
<p class="no-app">
no <code>_app.tsx</code> template
</p>
);
}
@@ -0,0 +1,13 @@
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
rootLayout: true,
};
export default function OverridePage() {
return (
<p class="no-layouts">
no layouts
</p>
);
}
@@ -0,0 +1,14 @@
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
appTemplate: false,
rootLayout: true,
};
export default function OverridePage() {
return (
<p class="no-app-no-layouts">
no <code>_app.tsx</code> template and no layouts
</p>
);
}
+47 -1
View File
@@ -1,5 +1,10 @@
import { assert } from "./deps.ts";
import { assertSelector, fetchHtml, withFresh } from "./test_utils.ts";
import {
assertNotSelector,
assertSelector,
fetchHtml,
withFresh,
} from "./test_utils.ts";
Deno.test("apply root _layout and _app", async () => {
await withFresh(
@@ -103,3 +108,44 @@ Deno.test({
);
},
});
Deno.test("disable _app layout", async () => {
await withFresh(
"./tests/fixture_layouts/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/override/no_app`);
assertNotSelector(doc, "body body");
assertSelector(doc, "body > .override-layout >.no-app");
},
);
});
Deno.test("override layouts", async () => {
await withFresh(
"./tests/fixture_layouts/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/override`);
assertSelector(doc, "body > .app > .override-layout > .override-page");
},
);
});
Deno.test("route overrides layout", async () => {
await withFresh(
"./tests/fixture_layouts/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/override/no_layout`);
assertSelector(doc, "body > .app > .no-layouts");
},
);
});
Deno.test("route overrides layout", async () => {
await withFresh(
"./tests/fixture_layouts/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/override/no_layout_no_app`);
assertSelector(doc, "body > .no-app-no-layouts");
},
);
});
+9
View File
@@ -40,6 +40,15 @@ export function assertSelector(doc: Document, selector: string) {
}
}
export function assertNotSelector(doc: Document, selector: string) {
if (doc.querySelector(selector) !== null) {
const html = prettyDom(doc);
throw new Error(
`Selector "${selector}" found in document.\n\n${html}`,
);
}
}
export function assertTextMany(
doc: Document,
selector: string,