docs: update canary docs for Fresh 2 (#3108)
There are still some rough edges here and there, but it's in a much better shape than what we have today.
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
---
|
||||
description: |
|
||||
Add a global app wrapper to provide common meta tags or context for application routes.
|
||||
---
|
||||
|
||||
The app wrapper component is a Preact component that represents the outer
|
||||
structure of the HTML document, typically up until the `<body>`-tag. It is only
|
||||
rendered on the server and never on the client. The passed `Component` value
|
||||
represents the children of this component.
|
||||
|
||||
```tsx
|
||||
function AppWrapper({ Component }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>My App</title>
|
||||
</head>
|
||||
<body>
|
||||
<Component />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
app.appWrapper(AppWrapper);
|
||||
```
|
||||
|
||||
Every `ctx.render()` call will include the app wrapper component by default,
|
||||
unless opted out.
|
||||
|
||||
Note that only one app wrapper component is supported per
|
||||
[`App`](/docs/canary/concepts/app) instance.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
description: |
|
||||
Error pages can be used to customize the page that is shown when an error occurs in the application.
|
||||
---
|
||||
|
||||
Fresh supports customizing the `404 Not Found`, and the
|
||||
`500 Internal Server Error` pages. These are shown when a request is made but no
|
||||
matching route exists, and when a middleware, route handler, or page component
|
||||
throws an error respectively.
|
||||
|
||||
### 404: Not Found
|
||||
|
||||
The 404 page can be customized by creating a `_404.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `PageProps` is passed in as an argument.
|
||||
|
||||
```tsx routes/_404.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function NotFoundPage({ url }: PageProps) {
|
||||
return <p>404 not found: {url.pathname}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
#### Manually render 404 pages
|
||||
|
||||
The `_404.tsx` file will be invoked automatically when no route matches the URL.
|
||||
In some cases, one needs to manually trigger the rendering of the 404 page, for
|
||||
example when the route did match, but the requested resource does not exist.
|
||||
This can be achieved with `ctx.renderNotFound`.
|
||||
|
||||
```tsx routes/blog/[slug].tsx
|
||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
const blogpost = await fetchBlogpost(ctx.params.slug);
|
||||
if (!blogpost) {
|
||||
return ctx.renderNotFound({
|
||||
custom: "prop",
|
||||
});
|
||||
}
|
||||
return ctx.render({ blogpost });
|
||||
},
|
||||
};
|
||||
|
||||
export default function BlogpostPage({ data }) {
|
||||
return (
|
||||
<article>
|
||||
<h1>{data.blogpost.title}</h1>
|
||||
{/* rest of your page */}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
This can also be achieved by throwing an error, if you're uninterested in
|
||||
passing specific data to your 404 page:
|
||||
|
||||
```tsx
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
GET(_req, _ctx) {
|
||||
throw new Deno.errors.NotFound();
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 500: Internal Server Error
|
||||
|
||||
The 500 page can be customized by creating a `_500.tsx` file in the `routes/`
|
||||
folder. The file must have a default export that is a regular Preact component.
|
||||
A props object of type `PageProps` is passed in as an argument.
|
||||
|
||||
```tsx routes/_500.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
|
||||
export default function Error500Page({ error }: PageProps) {
|
||||
return <p>500 internal error: {(error as Error).message}</p>;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
description: |
|
||||
Robustly handle user inputs using HTML `<form>` elements client side, and form
|
||||
submission handlers server side.
|
||||
---
|
||||
|
||||
For stronger resiliency and user experience, Fresh relies on native browser
|
||||
support for form submissions with the HTML `<form>` element.
|
||||
|
||||
In the browser, a `<form>` submit will send an HTML action (usually `GET` or
|
||||
`POST`) to the server, which responds with a new page to render.
|
||||
|
||||
## POST request with `application/x-www-form-urlencoded`
|
||||
|
||||
Forms typically submit as a `GET` request with data encoded in the URL's search
|
||||
parameters, or as a `POST` request with either an
|
||||
`application/x-www-form-urlencoded` or `multipart/form-data` body.
|
||||
|
||||
This example demonstrates how to handle `application/x-www-form-urlencoded`
|
||||
`<form>` submissions:
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET(req, ctx) {
|
||||
return await ctx.render();
|
||||
},
|
||||
async POST(req, ctx) {
|
||||
const form = await req.formData();
|
||||
const email = form.get("email")?.toString();
|
||||
|
||||
// Add email to list.
|
||||
|
||||
// Redirect user to thank you page.
|
||||
const headers = new Headers();
|
||||
headers.set("location", "/thanks-for-subscribing");
|
||||
return new Response(null, {
|
||||
status: 303, // See Other
|
||||
headers,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function Subscribe() {
|
||||
return (
|
||||
<>
|
||||
<form method="post">
|
||||
<input type="email" name="email" value="" />
|
||||
<button type="submit">Subscribe</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
When the user submits the form, Deno will retrieve the `email` value using the
|
||||
request's `formData()` method, add the email to a list, and redirect the user to
|
||||
a thank you page.
|
||||
|
||||
## Handling file uploads
|
||||
|
||||
File uploads can be handled in a very similar manner to the example above. Note
|
||||
that this time, we have to explicitly declare the form's encoding to be
|
||||
`multipart/form-data`.
|
||||
|
||||
```tsx routes/subscribe.tsx
|
||||
import { Handlers, type PageProps } from "$fresh/server.ts";
|
||||
|
||||
interface Props {
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Props> = {
|
||||
async GET(req, ctx) {
|
||||
return await ctx.render({
|
||||
message: null,
|
||||
});
|
||||
},
|
||||
async POST(req, ctx) {
|
||||
const form = await req.formData();
|
||||
const file = form.get("my-file") as File;
|
||||
|
||||
if (!file) {
|
||||
return ctx.render({
|
||||
message: `Please try again`,
|
||||
});
|
||||
}
|
||||
|
||||
const name = file.name;
|
||||
const contents = await file.text();
|
||||
|
||||
console.log(contents);
|
||||
|
||||
return ctx.render({
|
||||
message: `${name} uploaded!`,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function Upload(props: PageProps<Props>) {
|
||||
const { message } = props.data;
|
||||
return (
|
||||
<>
|
||||
<form method="post" encType="multipart/form-data">
|
||||
<input type="file" name="my-file" />
|
||||
<button type="submit">Upload</button>
|
||||
</form>
|
||||
{message ? <p>{message}</p> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## A note of caution
|
||||
|
||||
These examples are simplified to demonstrate how Deno and Fresh handle HTTP
|
||||
requests. In the Real World™, you'll want to validate your data (_especially the
|
||||
file type_) and protect against cross-site request forgery. Consider yourself
|
||||
warned.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
description: "Create re-usable layouts across routes"
|
||||
---
|
||||
|
||||
Layouts are plain Preact components that are inherited based on the matching
|
||||
pattern. When you have a section on your site where all pages share the same
|
||||
HTML structure and only the content changes, a layout is a neat way to abstract
|
||||
this. Layouts only ever render on the server. The passed `Component` value
|
||||
represents the children of this component.
|
||||
|
||||
```tsx
|
||||
function PageLayout({ Component }) {
|
||||
return (
|
||||
<div>
|
||||
<Component />
|
||||
<aside>Here is some sidebar content</aside>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const app = new App()
|
||||
.layout("*", PageLayout)
|
||||
.get("/", (ctx) => ctx.render(<h1>hello</h1>));
|
||||
```
|
||||
|
||||
If you browse to the `/` route, Fresh will render the following HTML
|
||||
|
||||
```html
|
||||
<div>
|
||||
<h1>hello world</h1>
|
||||
<aside>Here is some sidebar content</aside>
|
||||
</div>
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
Add a layout and ignore all previously inherited ones.
|
||||
|
||||
```ts
|
||||
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
||||
```
|
||||
|
||||
Ignore the app wrapper component:
|
||||
|
||||
```ts
|
||||
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
description: |
|
||||
Partials allow areas of a page to be updated without causing the browser to reload the page. They enable optimized fine grained UI updates and can be used to do client-side navigation.
|
||||
---
|
||||
|
||||
Partials allow areas of the page to be updated with new content by the server
|
||||
without causing the browser to reload the page. They make your website feel more
|
||||
app-like because only the parts of the page that need to be updated will be
|
||||
updated.
|
||||
|
||||
## Enabling partials
|
||||
|
||||
Partials are enabled by adding a `f-client-nav` attribute to an HTML element and
|
||||
wrapping one or more areas in the page with a
|
||||
`<Partial name="my-partial">`-component.
|
||||
|
||||
The quickest way to get started is to enable partials for every page in
|
||||
`routes/_app.tsx` by making the following changes.
|
||||
|
||||
```diff routes/_app.tsx
|
||||
import { PageProps } from "$fresh/server.ts";
|
||||
+ import { Partial } from "$fresh/runtime.ts";
|
||||
|
||||
export default function App({ Component }: PageProps) {
|
||||
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>
|
||||
+ <body f-client-nav>
|
||||
+ <Partial name="body">
|
||||
<Component />
|
||||
+ </Partial>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
By adding the `f-client-nav` attribute, we enable partials for every element
|
||||
beneath the `<body>`-tag. To mark an area of the page as a partial we wrap it
|
||||
with a `<Partial>`-component with a unique name.
|
||||
|
||||
Behind the scenes, when the user clicks an `<a>`-tag, Fresh fetches the new page
|
||||
and only pulls out the relevant content out of the HTML response. When it finds
|
||||
a matching partial area it will update the content inside the partial.
|
||||
|
||||
> [info]: The `name` prop of the `<Partial>` component is expected to be unique
|
||||
> among Partials. That's how Fresh knows which parts of the response need to go
|
||||
> on the current page.
|
||||
|
||||
> [info]: Passing `f-client-nav={false}` disables client side navigation for all
|
||||
> elements below the current node.
|
||||
|
||||
### Optimizing partial requests
|
||||
|
||||
By default, with `f-client-nav` set, Fresh fetches the full next page and only
|
||||
picks out the relevant parts of the response. We can optimize this pattern
|
||||
further by only rendering the parts we need, instead of always rendering the
|
||||
full page. This is done by adding the `f-partial` attribute to a link.
|
||||
|
||||
```diff
|
||||
- <a href="/docs/routes">Routes</a>
|
||||
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
||||
```
|
||||
|
||||
When the `f-partial` attribute is present, Fresh will navigate to the page URL
|
||||
defined in the `href` attribute, but fetch the updated UI from the URL specified
|
||||
in `f-partial` instead. This can be a highly optimized route that only delivers
|
||||
the content you care about.
|
||||
|
||||
Let's use a typical documentation page layout as an example. It often features a
|
||||
main content area and a sidebar of links to switch between pages of the
|
||||
documentation (marked green here).
|
||||
|
||||

|
||||
|
||||
The code for such a page (excluding styling) might look like this:
|
||||
|
||||
```tsx routes/docs/[id].tsx
|
||||
export default defineRoute(async (req, ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<aside>
|
||||
<a href="/docs/page1">Page 1</a>
|
||||
<a href="/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
An optimal route that only renders the content instead of the outer layout with
|
||||
the sidebar might look like this respectively.
|
||||
|
||||
```tsx routes/partials/docs/[id].tsx
|
||||
import { defineRoute, RouteConfig } from "$fresh/server.ts";
|
||||
import { Partial } from "$fresh/runtime.ts";
|
||||
|
||||
// We only want to render the content, so disable
|
||||
// the `_app.tsx` template as well as any potentially
|
||||
// inherited layouts
|
||||
export const config: RouteConfig = {
|
||||
skipAppWrapper: true,
|
||||
skipInheritedLayouts: true,
|
||||
};
|
||||
|
||||
export default defineRoute(async (req, ctx) => {
|
||||
const content = await loadContent(ctx.params.id);
|
||||
|
||||
// Only render the new content
|
||||
return (
|
||||
<Partial name="docs-content">
|
||||
{content}
|
||||
</Partial>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
By adding the `f-partial` attribute we tell Fresh to fetch the content from our
|
||||
newly added `/partials/docs/[id].tsx` route.
|
||||
|
||||
```diff routes/docs/[id].tsx
|
||||
<aside>
|
||||
- <a href="/docs/page1">Page 1</a>
|
||||
- <a href="/docs/page2">Page 2</a>
|
||||
+ <a href="/docs/page1" f-partial="/partials/docs/page1">Page 1</a>
|
||||
+ <a href="/docs/page2" f-partial="/partials/docs/page2">Page 2</a>
|
||||
</aside>
|
||||
```
|
||||
|
||||
With this in place, Fresh will navigate to the new page when clicking any of the
|
||||
two links and _only_ load the content rendered by our optimized partial route.
|
||||
|
||||
> Currently, `f-partial` is scoped to `<a>`, `<button>` and `<form>` elements.
|
||||
> This might be extended to more elements in the future.
|
||||
|
||||
## Sending multiple Partials at the same time
|
||||
|
||||
A neat aspect of partials in Fresh is that a response can return as many
|
||||
partials as desired. That way you can update multiple unrelated areas on your
|
||||
page in one single HTTP response. A scenario where this is useful are online
|
||||
shops for example.
|
||||
|
||||
```tsx routes/partials/cart.tsx
|
||||
export default function AddToCartPartial() {
|
||||
return (
|
||||
<>
|
||||
<Partial name="cart-items" mode="append">
|
||||
{/* Render the new cart item here */}
|
||||
</Partial>
|
||||
<Partial name="total-price">
|
||||
<p>Total: {totalPrice} €</p>
|
||||
</Partial>
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Both partials will be applied to the current page.
|
||||
|
||||
## Replacement mode
|
||||
|
||||
By default the whole content inside a partial will be replaced, but there are
|
||||
scenarios where you want to prepend or append new content instead. This can be
|
||||
achieved by adding the `mode` prop to a `Partial` component.
|
||||
|
||||
- `replace` - Swap out the content of the existing partial (default)
|
||||
- `prepend` - Insert the new content before the existing content
|
||||
- `append` - Insert the new content after the existing content
|
||||
|
||||
Personally, we’ve found that the `append` mode is really useful when you have an
|
||||
UI which displays log messages or similar list-like data.
|
||||
|
||||
```tsx
|
||||
export default function LogView() {
|
||||
const lines = getNewLogLines();
|
||||
|
||||
return (
|
||||
<Partial name="logs-list" mode="append">
|
||||
{lines.map((line) => {
|
||||
return <li key={line}>{line}</li>;
|
||||
})}
|
||||
</Partial>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
> [info]: When picking the `prepend` or `append` mode, make sure to add keys to
|
||||
> the elements.
|
||||
|
||||
## Bypassing or disabling Partials
|
||||
|
||||
If you want to exempt a particular element from triggering a partial request
|
||||
like on a particular link, form or button, you can opt out of it by setting
|
||||
`f-client-nav={false}` on the element or one of the ancestor elements.
|
||||
|
||||
```tsx
|
||||
<body f-client-nav>
|
||||
{/* This will cause a partial navigation */}
|
||||
<a href="/docs/page1">With partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation */}
|
||||
<a href="/docs/page1" f-client-nav={false}>No partials</a>
|
||||
|
||||
{/* This WONT cause a partial navigation on any elements below */}
|
||||
<div f-client-nav={false}>
|
||||
<div>
|
||||
<a href="/docs/page1">No partials</a>
|
||||
</div>
|
||||
</div>
|
||||
</body>;
|
||||
```
|
||||
|
||||
Whenever an element is clicked Fresh checks if it has the `f-client-nav`
|
||||
attribute and if it is set to `true`. If the element itself doesn't have such an
|
||||
attribute, it will check if any of the ancestor elements has it. If an element
|
||||
was found with a truthy `f-client-nav` attribute a partial request will be
|
||||
triggered. If there is no such attribute or if it's set to `false`, no partial
|
||||
request will occur.
|
||||
Reference in New Issue
Block a user