www: Various documentation improvements (#1635)

Co-authored-by: Reed von Redwitz <reed+github@vonredwitz.com>
This commit is contained in:
Marvin Hagemeister
2023-08-16 16:24:53 +02:00
committed by GitHub
co-authored by Reed von Redwitz
parent 794c8ac10c
commit b2362da281
14 changed files with 275 additions and 137 deletions
+104
View File
@@ -0,0 +1,104 @@
---
description: |
Add a global app wrapper to provide common meta tags or context for application routes.
---
An app wrapper is defined in an `_app.tsx` file in `routes/` folder and is
typically used to create the outer structure of an HTML document. It must
contain a default export that is a regular Preact component. Only one such
wrapper is allowed per application.
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/_app.tsx
import { AppProps } from "$fresh/server.ts";
export default function App({ Component, state }: AppProps) {
// do something with state here
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Fresh app</title>
</head>
<body>
<Component />
</body>
</html>
);
}
```
## Async app wrapper
Similar to routes and layouts, the app wrapper can be made asynchronous. This
changes the function signature so that the first argument is the `Request`
instsance and the second one is the `AppContext`.
```tsx routes/_app.tsx
import { AppContext } from "$fresh/server.ts";
export default async function App(req: Request, ctx: AppContext) {
const data = await loadData();
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Fresh app</title>
</head>
<body>
<h1>Hello {data.name}</h1>
<ctx.Component />
</body>
</html>
);
}
```
### Define helper
To make it quicker to type the async app wrapper, Fresh includes a `defineApp`
helper which already infers the correct types for you.
```tsx routes/_app.tsx
import { defineApp } from "$fresh/server.ts";
export default defineApp(async (req, ctx) => {
const data = await loadData();
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Fresh app</title>
</head>
<body>
<h1>Hello {data.name}</h1>
<ctx.Component />
</body>
</html>
);
});
```
## Disabling the app wrapper
Rendering the app wrapper can be skipped on a route or layout basis. To do that,
set `skipAppWrapper: true` to the layout or route config.
```tsx routes/my-special-route.tsx
export const config: RouteConfig {
skipAppWrapper: true; // Skip the app wrapper during rendering
}
export default function Page() {
// ...
}
```
@@ -1,11 +1,11 @@
--- ---
description: | description: |
Add a route layout to provide common meta tags, context for application sub routes, and common layout. Add a 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 An layout is defined in a `_layout.tsx` file in any sub directory (at any level)
level) under the `routes/` folder. It must contain a default export that is a under the `routes/` folder. It must contain a default export that is a regular
regular Preact component. Only one such layout is allowed per sub directory. Preact component. Only one such layout is allowed per sub directory.
```txt Project structure ```txt Project structure
└── routes └── routes
@@ -28,7 +28,7 @@ set by middleware is available via `props.state`.
import { LayoutProps } from "$fresh/server.ts"; import { LayoutProps } from "$fresh/server.ts";
export default function Layout({ Component, state }: LayoutProps) { export default function Layout({ Component, state }: LayoutProps) {
//do something with state here // do something with state here
return ( return (
<div class="layout"> <div class="layout">
<Component /> <Component />
@@ -37,6 +37,48 @@ export default function Layout({ Component, state }: LayoutProps) {
} }
``` ```
## Async layouts
In case you need to fetch data asynchronously before rendering the layout, you
can use an async layout to do so.
```tsx routes/sub/_layout.tsx
import { LayoutProps } from "$fresh/server.ts";
export default async function Layout(req: Request, ctx: LayoutContext) {
// do something with state here
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
}
```
### Define helper
To make it a little quicker to write async layouts, Fresh ships with a
`defineLayout` helper which automatically infers the correct types for the
function arguments.
```tsx
import { defineLayout } from "$fresh/server.ts";
export default defineLayout(async (req, ctx) => {
const data = await loadData();
return (
<div class="layout">
<p>{data.greeting}</p>
<ctx.Component />
</div>
);
});
```
## Opting out of layout inheritance ## Opting out of layout inheritance
Sometimes you want to opt out of the layout inheritance mechanism for a Sometimes you want to opt out of the layout inheritance mechanism for a
@@ -53,13 +95,13 @@ structure like this:
``` ```
To make `routes/sub/special.tsx` opt out of rendering layouts we can set To make `routes/sub/special.tsx` opt out of rendering layouts we can set
`rootLayout: true`. `skipInheritedLayouts: true`.
```tsx routes/sub/special.tsx ```tsx routes/sub/special.tsx
import { RouteConfig } from "$fresh/server.ts"; import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = { export const config: RouteConfig = {
rootLayout: true, // Mark this route as the root layout skipInheritedLayouts: true, // Skip already inherited layouts
}; };
export default function MyPage() { export default function MyPage() {
@@ -67,18 +109,13 @@ export default function MyPage() {
} }
``` ```
Note that you can also mark layouts as root layouts. You can skip already inherited layouts inside a layout file:
## Disabling the root `_app` template ```tsx routes/special/_layout.sx
import { LayoutConfig } from "$fresh/server.ts";
In very rare cases you might want to disable the root `_app` template for a export const config: LayoutConfig = {
particular route. This can be done by setting `appTemplate: false`. skipInheritedLayouts: true, // Skip already inherited layouts
```tsx
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
appTemplate: false, // Disable the `_app` template
}; };
export default function MyPage() { export default function MyPage() {
-58
View File
@@ -1,58 +0,0 @@
---
description: |
Route groups allow you to organize your route segments into groups and share layout or middleware code without affecting the URL structure.
---
When working with [route layouts](/docs/canary/concepts/route-layout) or
[route middlewares](/docs/canary/concepts/middleware) you'll sometimes come
across a situation where you want your routes to inherit from a different layout
than another route that's in the same URL segment.
Let's illustrate that with an example:
```txt
/about -> layout A
/career -> layout A
/archive -> layout B
/contact -> layout B
```
Without any way to group routes this is a problem because every route segment
can only have one `_layout` file.
```txt Project structure
└── routes
   ├── _layout.tsx # applies to all routes here :(
   ├── about.tsx
   ├── career.tsx
   ├── archive.tsx
   └── contact.tsx
```
We can solve this problem with route groups. A route group is a folder which has
a name that is wrapped in braces. For example `(pages)` would be considered a
route and so would be `(marketing)`. This enables us to group related routes in
a folder and use a different `_layout` file for each group.
```txt Project structure
└── routes
   ├── (marketing)
   │ ├── _layout.tsx # only applies to about.tsx and career.tsx
   │ ├── about.tsx
   │ └── career.tsx
   └── (info)
   ├── _layout.tsx # only applies to archive.tsx and contact.tsx
   ├── archive.tsx
   └── contact.tsx
```
> ℹ️ Be careful about routes in different groups which match to the same URL.
> Such scenarios will lead to ambiguity as to which route file should be picked.
>
> ```txt Project structure
> └── routes
>    ├── (group-1)
>    │ └── about.tsx # Bad: Maps to same `/about` url
>    └── (group-2)
>    └── about.tsx # Bad: Maps to same `/about` url
> ```
+20
View File
@@ -165,3 +165,23 @@ export default async function MyPage(req: Request, ctx: RouteContext) {
return <p>foo is: {value}</p>; return <p>foo is: {value}</p>;
} }
``` ```
### Define helper
To make it a little quicker to write async routes, Fresh ships with a
`defineRoute` helper which automatically infers the correct types for the
function arguments.
```tsx
import { defineRoute } from "$fresh/server.ts";
export default defineRoute(async (req, ctx) => {
const data = await loadData();
return (
<div class="page">
<h1>Hello {data.name}</h1>
</div>
);
});
```
+56
View File
@@ -51,4 +51,60 @@ export const config: RouteConfig = {
// ... // ...
``` ```
## Route Groups
When working with [route layouts](/docs/canary/concepts/route-layout) or
[route middlewares](/docs/canary/concepts/middleware), you'll sometimes come
across a situation where you want your routes to inherit from a layout other
than what's suggested by the URL segment.
Let's illustrate that with an example:
```txt
/about -> layout A
/career -> layout A
/archive -> layout B
/contact -> layout B
```
Without any way to group routes this is a problem because every route segment
can only have one `_layout` file.
```txt Project structure
└── routes
   ├── _layout.tsx # applies to all routes here :(
   ├── about.tsx
   ├── career.tsx
   ├── archive.tsx
   └── contact.tsx
```
We can solve this problem with route groups. A route group is a folder which has
a name that is wrapped in braces. For example `(pages)` would be considered a
route and so would be `(marketing)`. This enables us to group related routes in
a folder and use a different `_layout` file for each group.
```txt Project structure
└── routes
   ├── (marketing)
   │ ├── _layout.tsx # only applies to about.tsx and career.tsx
   │ ├── about.tsx
   │ └── career.tsx
   └── (info)
   ├── _layout.tsx # only applies to archive.tsx and contact.tsx
   ├── archive.tsx
   └── contact.tsx
```
> ℹ️ Be careful about routes in different groups which match to the same URL.
> Such scenarios will lead to ambiguity as to which route file should be picked.
>
> ```txt Project structure
> └── routes
>    ├── (group-1)
>    │ └── about.tsx # Bad: Maps to same `/about` url
>    └── (group-2)
>    └── about.tsx # Bad: Maps to same `/about` url
> ```
[urlpattern]: https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API [urlpattern]: https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
+4 -6
View File
@@ -46,20 +46,19 @@ const toc: RawTableOfContents = {
pages: [ pages: [
["architecture", "Architecture", "link:latest"], ["architecture", "Architecture", "link:latest"],
["server-components", "Server Components", "link:latest"], ["server-components", "Server Components", "link:latest"],
["routing", "Routing", "link:latest"],
["routes", "Routes", "link:latest"], ["routes", "Routes", "link:latest"],
["app-wrapper", "App wrapper", "link:canary"],
["layouts", "Layouts", "link:canary"],
["forms", "Forms", "link:latest"], ["forms", "Forms", "link:latest"],
["islands", "Interactive islands", "link:latest"], ["islands", "Interactive islands", "link:latest"],
["static-files", "Static files", "link:latest"], ["static-files", "Static files", "link:latest"],
["middleware", "Route middleware", "link:canary"], ["middleware", "Middlewares", "link:canary"],
["error-pages", "Error pages", "link:latest"], ["error-pages", "Error pages", "link:latest"],
["routing", "Routing", "link:latest"],
["data-fetching", "Data fetching", "link:latest"], ["data-fetching", "Data fetching", "link:latest"],
["deployment", "Deployment", "link:latest"], ["deployment", "Deployment", "link:latest"],
["plugins", "Plugins", "link:latest"], ["plugins", "Plugins", "link:latest"],
["updating", "Updating Fresh", "link:latest"], ["updating", "Updating Fresh", "link:latest"],
["app-wrapper", "Application wrapper", "link:latest"],
["route-layout", "Route layouts", "link:canary"],
["route-groups", "Route groups", "link:canary"],
["server-configuration", "Server configuration", "link:latest"], ["server-configuration", "Server configuration", "link:latest"],
], ],
}, },
@@ -72,7 +71,6 @@ const toc: RawTableOfContents = {
link: "latest", link: "latest",
pages: [ pages: [
["modifying-the-head", "Modifying the <head>", "link:latest"], ["modifying-the-head", "Modifying the <head>", "link:latest"],
["setting-the-language", "Setting the language", "link:latest"],
["writing-tests", "Writing tests", "link:latest"], ["writing-tests", "Writing tests", "link:latest"],
[ [
"changing-the-src-dir", "changing-the-src-dir",
+6 -6
View File
@@ -253,7 +253,7 @@ export class ServerContext {
component, component,
handler, handler,
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
appTemplate: !config?.skipAppTemplate, appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts, inheritLayouts: !config?.skipInheritedLayouts,
}; };
routes.push(route); routes.push(route);
@@ -274,7 +274,7 @@ export class ServerContext {
baseRoute: toBaseRoute(baseRoute), baseRoute: toBaseRoute(baseRoute),
handler: mod.handler, handler: mod.handler,
component: mod.default, component: mod.default,
appTemplate: !config?.skipAppTemplate, appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts, inheritLayouts: !config?.skipInheritedLayouts,
}); });
} else if ( } else if (
@@ -295,7 +295,7 @@ export class ServerContext {
component, component,
handler: handler ?? ((req) => router.defaultOtherHandler(req)), handler: handler ?? ((req) => router.defaultOtherHandler(req)),
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
appTemplate: !config?.skipAppTemplate, appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts, inheritLayouts: !config?.skipInheritedLayouts,
}; };
} else if ( } else if (
@@ -317,7 +317,7 @@ export class ServerContext {
handler: handler ?? handler: handler ??
((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)), ((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)),
csp: Boolean(config?.csp ?? false), csp: Boolean(config?.csp ?? false),
appTemplate: !config?.skipAppTemplate, appWrapper: !config?.skipAppWrapper,
inheritLayouts: !config?.skipInheritedLayouts, inheritLayouts: !config?.skipInheritedLayouts,
}; };
} }
@@ -982,7 +982,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = {
name: "_404", name: "_404",
handler: (req) => router.defaultOtherHandler(req), handler: (req) => router.defaultOtherHandler(req),
csp: false, csp: false,
appTemplate: true, appWrapper: true,
inheritLayouts: true, inheritLayouts: true,
}; };
@@ -994,7 +994,7 @@ const DEFAULT_ERROR: ErrorPage = {
component: DefaultErrorHandler, component: DefaultErrorHandler,
handler: (_req, ctx) => ctx.render(), handler: (_req, ctx) => ctx.render(),
csp: false, csp: false,
appTemplate: true, appWrapper: true,
inheritLayouts: true, inheritLayouts: true,
}; };
+2 -2
View File
@@ -265,8 +265,8 @@ export async function render<Data>(
const renderStack: any[] = []; const renderStack: any[] = [];
// Check if appLayout is enabled // Check if appLayout is enabled
if ( if (
opts.route.appTemplate && opts.route.appWrapper &&
layouts.every((layout) => layout.appTemplate) layouts.every((layout) => layout.appWrapper)
) { ) {
renderStack.push(opts.app.default); renderStack.push(opts.app.default);
} }
+6 -6
View File
@@ -98,7 +98,7 @@ export interface RouteConfig {
* Skip rendering the `routes/_app` template * Skip rendering the `routes/_app` template
* Default: `false` * Default: `false`
*/ */
skipAppTemplate?: boolean; skipAppWrapper?: boolean;
} }
// deno-lint-ignore no-empty-interface // deno-lint-ignore no-empty-interface
@@ -173,7 +173,7 @@ export interface Route<Data = any> {
component?: PageComponent<Data> | AsyncLayout<Data> | AsyncRoute<Data>; component?: PageComponent<Data> | AsyncLayout<Data> | AsyncRoute<Data>;
handler: Handler<Data> | Handlers<Data>; handler: Handler<Data> | Handlers<Data>;
csp: boolean; csp: boolean;
appTemplate: boolean; appWrapper: boolean;
inheritLayouts: boolean; inheritLayouts: boolean;
} }
@@ -218,7 +218,7 @@ export interface LayoutConfig {
* Skip already inherited layouts * Skip already inherited layouts
* Default: `false` * Default: `false`
*/ */
skipAppTemplate?: boolean; skipAppWrapper?: boolean;
/** /**
* Skip rendering the `routes/_app`. * Skip rendering the `routes/_app`.
* Default: `false` * Default: `false`
@@ -238,7 +238,7 @@ export interface LayoutRoute {
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>; handler?: Handler<any, any> | Handlers<any, any>;
component: LayoutModule["default"]; component: LayoutModule["default"];
appTemplate: boolean; appWrapper: boolean;
inheritLayouts: boolean; inheritLayouts: boolean;
} }
@@ -286,7 +286,7 @@ export interface UnknownPage {
component?: PageComponent<UnknownPageProps>; component?: PageComponent<UnknownPageProps>;
handler: UnknownHandler; handler: UnknownHandler;
csp: boolean; csp: boolean;
appTemplate: boolean; appWrapper: boolean;
inheritLayouts: boolean; inheritLayouts: boolean;
} }
@@ -333,7 +333,7 @@ export interface ErrorPage {
component?: PageComponent<ErrorPageProps>; component?: PageComponent<ErrorPageProps>;
handler: ErrorHandler; handler: ErrorHandler;
csp: boolean; csp: boolean;
appTemplate: boolean; appWrapper: boolean;
inheritLayouts: boolean; inheritLayouts: boolean;
} }
+20 -22
View File
@@ -23,17 +23,16 @@ import * as $17 from "./routes/foo/_layout.tsx";
import * as $18 from "./routes/foo/bar.tsx"; import * as $18 from "./routes/foo/bar.tsx";
import * as $19 from "./routes/foo/index.tsx"; import * as $19 from "./routes/foo/index.tsx";
import * as $20 from "./routes/index.tsx"; import * as $20 from "./routes/index.tsx";
import * as $21 from "./routes/no_app.tsx"; import * as $21 from "./routes/other.tsx";
import * as $22 from "./routes/other.tsx"; import * as $22 from "./routes/override/_layout.tsx";
import * as $23 from "./routes/override/_layout.tsx"; import * as $23 from "./routes/override/index.tsx";
import * as $24 from "./routes/override/index.tsx"; import * as $24 from "./routes/override/layout_no_app/_layout.tsx";
import * as $25 from "./routes/override/layout_no_app/_layout.tsx"; import * as $25 from "./routes/override/layout_no_app/index.tsx";
import * as $26 from "./routes/override/layout_no_app/index.tsx"; import * as $26 from "./routes/override/no_app.tsx";
import * as $27 from "./routes/override/no_app.tsx"; import * as $27 from "./routes/override/no_layout.tsx";
import * as $28 from "./routes/override/no_layout.tsx"; import * as $28 from "./routes/override/no_layout_no_app.tsx";
import * as $29 from "./routes/override/no_layout_no_app.tsx"; import * as $29 from "./routes/skip/sub/_layout.tsx";
import * as $30 from "./routes/skip/sub/_layout.tsx"; import * as $30 from "./routes/skip/sub/index.tsx";
import * as $31 from "./routes/skip/sub/index.tsx";
const manifest = { const manifest = {
routes: { routes: {
@@ -58,17 +57,16 @@ const manifest = {
"./routes/foo/bar.tsx": $18, "./routes/foo/bar.tsx": $18,
"./routes/foo/index.tsx": $19, "./routes/foo/index.tsx": $19,
"./routes/index.tsx": $20, "./routes/index.tsx": $20,
"./routes/no_app.tsx": $21, "./routes/other.tsx": $21,
"./routes/other.tsx": $22, "./routes/override/_layout.tsx": $22,
"./routes/override/_layout.tsx": $23, "./routes/override/index.tsx": $23,
"./routes/override/index.tsx": $24, "./routes/override/layout_no_app/_layout.tsx": $24,
"./routes/override/layout_no_app/_layout.tsx": $25, "./routes/override/layout_no_app/index.tsx": $25,
"./routes/override/layout_no_app/index.tsx": $26, "./routes/override/no_app.tsx": $26,
"./routes/override/no_app.tsx": $27, "./routes/override/no_layout.tsx": $27,
"./routes/override/no_layout.tsx": $28, "./routes/override/no_layout_no_app.tsx": $28,
"./routes/override/no_layout_no_app.tsx": $29, "./routes/skip/sub/_layout.tsx": $29,
"./routes/skip/sub/_layout.tsx": $30, "./routes/skip/sub/index.tsx": $30,
"./routes/skip/sub/index.tsx": $31,
}, },
islands: {}, islands: {},
baseUrl: import.meta.url, baseUrl: import.meta.url,
-17
View File
@@ -1,17 +0,0 @@
import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = {
skipAppTemplate: false,
};
export default function OverridePage() {
return (
<html>
<body>
<p class="no-app">
no <pre>_app.tsx</pre> template
</p>
</body>
</html>
);
}
@@ -1,7 +1,7 @@
import { LayoutConfig, LayoutProps } from "$fresh/server.ts"; import { LayoutConfig, LayoutProps } from "$fresh/server.ts";
export const config: LayoutConfig = { export const config: LayoutConfig = {
skipAppTemplate: true, skipAppWrapper: true,
}; };
export default function OverrideLayout({ Component }: LayoutProps) { export default function OverrideLayout({ Component }: LayoutProps) {
@@ -1,7 +1,7 @@
import { RouteConfig } from "$fresh/server.ts"; import { RouteConfig } from "$fresh/server.ts";
export const config: RouteConfig = { export const config: RouteConfig = {
skipAppTemplate: true, skipAppWrapper: true,
}; };
export default function OverridePage() { export default function OverridePage() {
@@ -1,7 +1,7 @@
import { LayoutConfig } from "$fresh/server.ts"; import { LayoutConfig } from "$fresh/server.ts";
export const config: LayoutConfig = { export const config: LayoutConfig = {
skipAppTemplate: true, skipAppWrapper: true,
skipInheritedLayouts: true, skipInheritedLayouts: true,
}; };