fix(docs): improve and increase consistency for code blocks (#3163)
Follow-up from #3162. This PR does various tweaks, mostly related to code blocks. - Adds missing titles to code blocks, and updates titles to be more consistent - Adds filenames to most ` ```tsx` blocks with e.g. `main.ts`, `dev.ts` or a suitable example (e.g. `routes/greeting.tsx`) based on the code - Adds filenames to ` ```diff` blocks if there's a relevant file, to make the icon e.g. TS over Diff icon - Code blocks with Fresh code (e.g. interfaces) uses ` ```tsx fresh 🍋` - Changes most ` ```sh` blocks with example terminal commands to ` ```sh Terminal` - Updates ` ```txt Project Structure` or ` ```diff Project Structure` blocks to be more consistent - Changes `sh` or `txt` to `txt-files` which improves highlighting and makes icon consistent - Renames `<project dir>` to `<project root>` to match builder `root` option terminology - Adds `<project root>` root folder to most/all overview folder overviews - Makes the structure blocks more consistently displayed - Tried to make some "bare" examples more complete ## Comparison Here's a small curated set of before/after changes. ### Deployment - `deno` highlighted in terminal commands - `.gitignore` syntax highlighting works without using `sh` as language <img width="1641" height="1009" alt="image" src="https://github.com/user-attachments/assets/170cf833-1f6a-4b0d-8d2d-a081bc28a967" /> ### File routing Updated icon, comments same as before, but root and hierarchy have new colors (`operator`/`function`). <img width="1647" height="588" alt="image" src="https://github.com/user-attachments/assets/f28db51b-4bee-45e4-be1c-e137a6d3ae3d" />
This commit is contained in:
@@ -8,7 +8,7 @@ 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
|
rendered on the server and never on the client. The passed `Component` value
|
||||||
represents the children of this component.
|
represents the children of this component.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
function AppWrapper({ Component }) {
|
function AppWrapper({ Component }) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
|||||||
@@ -9,32 +9,40 @@ expliciteness of types, other's like the convenience of `define.*` helpers.
|
|||||||
|
|
||||||
Without define helpers:
|
Without define helpers:
|
||||||
|
|
||||||
```ts
|
```ts util.ts
|
||||||
interface State {
|
export interface State {
|
||||||
foo: string;
|
foo: string;
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
async function myMiddleware(ctx: Context<State>): Promise<Response> {
|
```ts middleware.ts
|
||||||
|
import type { State } from "./util.ts";
|
||||||
|
|
||||||
|
export async function myMiddleware(ctx: Context<State>): Promise<Response> {
|
||||||
return new Response("hello " + ctx.state.foo);
|
return new Response("hello " + ctx.state.foo);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function otherMiddleware(ctx: Context<State>): Promise<Response> {
|
export async function otherMiddleware(ctx: Context<State>): Promise<Response> {
|
||||||
return new Response("other " + ctx.state.foo);
|
return new Response("other " + ctx.state.foo);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
With define helpers:
|
With define helpers:
|
||||||
|
|
||||||
```ts
|
```ts util.ts
|
||||||
// Setup, do this once in a file and import it everywhere else.
|
// Setup, do this once in a file and import it everywhere else.
|
||||||
const define = createDefine<{ foo: string }>();
|
export const define = createDefine<{ foo: string }>();
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts middleware.ts
|
||||||
|
import { define } from "./util.ts";
|
||||||
|
|
||||||
// Usage
|
// Usage
|
||||||
const myMiddleware = define.middleware((ctx) => {
|
export const myMiddleware = define.middleware((ctx) => {
|
||||||
return new Response("hello " + ctx.state.foo);
|
return new Response("hello " + ctx.state.foo);
|
||||||
});
|
});
|
||||||
|
|
||||||
const otherMiddleware = define.middleware((ctx) => {
|
export const otherMiddleware = define.middleware((ctx) => {
|
||||||
return new Response("other " + ctx.state.foo);
|
return new Response("other " + ctx.state.foo);
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ Fresh supports two kind of error pages:
|
|||||||
|
|
||||||
To add an error page use [`app.onError()`](/docs/canary/concepts/app#onerror).
|
To add an error page use [`app.onError()`](/docs/canary/concepts/app#onerror).
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
.onError("*", (ctx) => {
|
.onError("*", (ctx) => {
|
||||||
console.log(`Error: ${ctx.error}`);
|
console.log(`Error: ${ctx.error}`);
|
||||||
@@ -36,7 +36,7 @@ will be invoked.
|
|||||||
|
|
||||||
You can also nest error pages:
|
You can also nest error pages:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
// Top level error page
|
// Top level error page
|
||||||
.onError("*", (ctx) => {
|
.onError("*", (ctx) => {
|
||||||
@@ -56,7 +56,7 @@ Not found errors are often treated differently than generic errors. You can both
|
|||||||
treat them with the `.onError()` way, but by adding a specific `.notFound()`
|
treat them with the `.onError()` way, but by adding a specific `.notFound()`
|
||||||
handler, Fresh ensures that every 404 error will invoke this callback.
|
handler, Fresh ensures that every 404 error will invoke this callback.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
// Top level error page
|
// Top level error page
|
||||||
.notFound((ctx) => {
|
.notFound((ctx) => {
|
||||||
@@ -73,7 +73,7 @@ middleware. Contrary to generic error pages this handler cannot be nested.
|
|||||||
If you need to bail out of execution and need to respond with a particular HTTP
|
If you need to bail out of execution and need to respond with a particular HTTP
|
||||||
error code, you can use Fresh's `HttpError` class.
|
error code, you can use Fresh's `HttpError` class.
|
||||||
|
|
||||||
```ts
|
```ts middleware/auth.ts
|
||||||
import { HttpError } from "fresh";
|
import { HttpError } from "fresh";
|
||||||
|
|
||||||
async function authMiddleware(ctx) {
|
async function authMiddleware(ctx) {
|
||||||
@@ -90,7 +90,7 @@ async function authMiddleware(ctx) {
|
|||||||
|
|
||||||
You can check the status code of the thrown `HttpError` in your error handler:
|
You can check the status code of the thrown `HttpError` in your error handler:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
app.onError((ctx) => {
|
app.onError((ctx) => {
|
||||||
if (ctx.error instanceof HttpError) {
|
if (ctx.error instanceof HttpError) {
|
||||||
const status = ctx.error.status;
|
const status = ctx.error.status;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ 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
|
this. Layouts only ever render on the server. The passed `Component` value
|
||||||
represents the children of this component.
|
represents the children of this component.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
function PageLayout({ Component }) {
|
function PageLayout({ Component }) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -25,7 +25,7 @@ const app = new App()
|
|||||||
|
|
||||||
If you browse to the `/` route, Fresh will render the following HTML
|
If you browse to the `/` route, Fresh will render the following HTML
|
||||||
|
|
||||||
```html
|
```html Response body
|
||||||
<div>
|
<div>
|
||||||
<h1>hello world</h1>
|
<h1>hello world</h1>
|
||||||
<aside>Here is some sidebar content</aside>
|
<aside>Here is some sidebar content</aside>
|
||||||
@@ -36,12 +36,12 @@ If you browse to the `/` route, Fresh will render the following HTML
|
|||||||
|
|
||||||
Add a layout and ignore all previously inherited ones.
|
Add a layout and ignore all previously inherited ones.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
|
||||||
```
|
```
|
||||||
|
|
||||||
Ignore the app wrapper component:
|
Ignore the app wrapper component:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ 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
|
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.
|
full page. This is done by adding the `f-partial` attribute to a link.
|
||||||
|
|
||||||
```diff
|
```diff routes/_app.tsx
|
||||||
- <a href="/docs/routes">Routes</a>
|
- <a href="/docs/routes">Routes</a>
|
||||||
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
||||||
```
|
```
|
||||||
@@ -180,7 +180,7 @@ achieved by adding the `mode` prop to a `Partial` component.
|
|||||||
Personally, we’ve found that the `append` mode is really useful when you have an
|
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.
|
UI which displays log messages or similar list-like data.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/log.tsx
|
||||||
export default function LogView() {
|
export default function LogView() {
|
||||||
const lines = getNewLogLines();
|
const lines = getNewLogLines();
|
||||||
|
|
||||||
@@ -203,7 +203,7 @@ 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
|
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.
|
`f-client-nav={false}` on the element or one of the ancestor elements.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_app.tsx
|
||||||
<body f-client-nav>
|
<body f-client-nav>
|
||||||
{/* This will cause a partial navigation */}
|
{/* This will cause a partial navigation */}
|
||||||
<a href="/docs/page1">With partials</a>
|
<a href="/docs/page1">With partials</a>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ The `App` class is the heart of Fresh and routes incoming requests to the
|
|||||||
correct middlewares. This is where routes, middlewares, layouts and more are
|
correct middlewares. This is where routes, middlewares, layouts and more are
|
||||||
defined.
|
defined.
|
||||||
|
|
||||||
```tsx
|
```tsx main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
.use(staticFiles())
|
.use(staticFiles())
|
||||||
.get("/", () => new Response("hello"))
|
.get("/", () => new Response("hello"))
|
||||||
@@ -20,7 +20,7 @@ app.listen();
|
|||||||
All items are applied from top to bottom. This means that when you defined a
|
All items are applied from top to bottom. This means that when you defined a
|
||||||
middleware _after_ a `.get()` handler, it won't be included.
|
middleware _after_ a `.get()` handler, it won't be included.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
.use((ctx) => {
|
.use((ctx) => {
|
||||||
// Will be called for all middlewares
|
// Will be called for all middlewares
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ if (Deno.args.includes("build")) {
|
|||||||
|
|
||||||
You can customize the builder by passing options.
|
You can customize the builder by passing options.
|
||||||
|
|
||||||
```ts
|
```ts dev.ts
|
||||||
const builder = new Builder({
|
const builder = new Builder({
|
||||||
// Browser target for generated code. Maps to https://esbuild.github.io/api/#target
|
// Browser target for generated code. Maps to https://esbuild.github.io/api/#target
|
||||||
target?: string | string[];
|
target?: string | string[];
|
||||||
@@ -57,7 +57,7 @@ const builder = new Builder({
|
|||||||
The builder is where you'll register files that contain islands. This is the
|
The builder is where you'll register files that contain islands. This is the
|
||||||
same API that Fresh uses internally.
|
same API that Fresh uses internally.
|
||||||
|
|
||||||
```ts
|
```ts dev.ts
|
||||||
const builder = new Builder();
|
const builder = new Builder();
|
||||||
|
|
||||||
// Path to local island
|
// Path to local island
|
||||||
@@ -72,7 +72,7 @@ builder.registerIsland("jsr:@marvinh-test/fresh-island");
|
|||||||
|
|
||||||
The `Builder` has a very simple processing mechanism for static files.
|
The `Builder` has a very simple processing mechanism for static files.
|
||||||
|
|
||||||
```ts
|
```ts dev.ts
|
||||||
builder.onTransformStaticFile({
|
builder.onTransformStaticFile({
|
||||||
pluginName: "My cool plugin",
|
pluginName: "My cool plugin",
|
||||||
filter: /\.css$/,
|
filter: /\.css$/,
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ const app = new App({ root: import.meta.url })
|
|||||||
|
|
||||||
Example project structure:
|
Example project structure:
|
||||||
|
|
||||||
```sh Project structure
|
```txt-files Project structure
|
||||||
|
<project root>
|
||||||
├── deno.json
|
├── deno.json
|
||||||
├── main.ts
|
├── main.ts
|
||||||
├── dev.ts
|
├── dev.ts
|
||||||
@@ -104,7 +105,7 @@ suggested by the URL segment.
|
|||||||
|
|
||||||
Let's illustrate that with an example:
|
Let's illustrate that with an example:
|
||||||
|
|
||||||
```txt
|
```txt Example page layout
|
||||||
/about -> layout A
|
/about -> layout A
|
||||||
/career -> layout A
|
/career -> layout A
|
||||||
/archive -> layout B
|
/archive -> layout B
|
||||||
@@ -114,8 +115,8 @@ Let's illustrate that with an example:
|
|||||||
Without any way to group routes this is a problem because every route segment
|
Without any way to group routes this is a problem because every route segment
|
||||||
can only have one `_layout` file.
|
can only have one `_layout` file.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── _layout.tsx # applies to all routes here :(
|
├── _layout.tsx # applies to all routes here :(
|
||||||
├── about.tsx
|
├── about.tsx
|
||||||
├── career.tsx
|
├── career.tsx
|
||||||
@@ -128,8 +129,8 @@ a name that is wrapped in parentheses. For example `(info)` would be considered
|
|||||||
a route group and so would `(marketing)`. This enables us to group related
|
a route group and so would `(marketing)`. This enables us to group related
|
||||||
routes in a folder and use a different `_layout` file for each group.
|
routes in a folder and use a different `_layout` file for each group.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── (marketing)
|
├── (marketing)
|
||||||
│ ├── _layout.tsx # only applies to about.tsx and career.tsx
|
│ ├── _layout.tsx # only applies to about.tsx and career.tsx
|
||||||
│ ├── about.tsx
|
│ ├── about.tsx
|
||||||
@@ -144,8 +145,8 @@ routes in a folder and use a different `_layout` file for each group.
|
|||||||
> URL. Such scenarios will lead to ambiguity as to which route file should be
|
> URL. Such scenarios will lead to ambiguity as to which route file should be
|
||||||
> picked.
|
> picked.
|
||||||
>
|
>
|
||||||
> ```txt Project structure
|
> ```txt-files Project structure
|
||||||
> └── routes
|
> └── <root>/routes
|
||||||
> ├── (group-1)
|
> ├── (group-1)
|
||||||
> │ └── about.tsx # Bad: Maps to same `/about` url
|
> │ └── about.tsx # Bad: Maps to same `/about` url
|
||||||
> └── (group-2)
|
> └── (group-2)
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ export default function MyIsland() {
|
|||||||
An island can be used anywhere like a regular Preact component. Fresh will take
|
An island can be used anywhere like a regular Preact component. Fresh will take
|
||||||
care of making it interactive on the client.
|
care of making it interactive on the client.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
@@ -56,9 +56,11 @@ deserialization.
|
|||||||
|
|
||||||
> [warn]: Passing functions to an island is not supported.
|
> [warn]: Passing functions to an island is not supported.
|
||||||
>
|
>
|
||||||
> ```tsx
|
> ```tsx routes/example.tsx
|
||||||
> // WRONG
|
> export default function () {
|
||||||
> <MyIsland onClick={() => console.log("hey")} />;
|
> // WRONG
|
||||||
|
> return <MyIsland onClick={() => console.log("hey")} />;
|
||||||
|
> }
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
### Passing JSX
|
### Passing JSX
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ A 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
|
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.
|
Preact component. Only one such layout is allowed per sub directory.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
|
<project root>
|
||||||
└── routes
|
└── routes
|
||||||
├── sub
|
├── sub
|
||||||
│ ├── page.tsx
|
│ ├── page.tsx
|
||||||
@@ -85,8 +86,8 @@ 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
|
particular route. This can be done via route configuration. Picture a directory
|
||||||
structure like this:
|
structure like this:
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── sub
|
├── sub
|
||||||
│ ├── _layout_.tsx
|
│ ├── _layout_.tsx
|
||||||
│ ├── special.tsx # should not inherit layouts
|
│ ├── special.tsx # should not inherit layouts
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ returns a
|
|||||||
are typically used to set HTTP Headers, measure response times or fetch data and
|
are typically used to set HTTP Headers, measure response times or fetch data and
|
||||||
pass it to another middleware.
|
pass it to another middleware.
|
||||||
|
|
||||||
```tsx
|
```tsx main.ts
|
||||||
const app = new App<{ greeting: string }>()
|
const app = new App<{ greeting: string }>()
|
||||||
.use((ctx) => {
|
.use((ctx) => {
|
||||||
// Middleware to pass data
|
// Middleware to pass data
|
||||||
@@ -38,7 +38,7 @@ excellent way to make http-related logic reusable on the server.
|
|||||||
|
|
||||||
Use the `define.middleware()` helper to get typings out of the box:
|
Use the `define.middleware()` helper to get typings out of the box:
|
||||||
|
|
||||||
```ts
|
```ts middleware/my-middleware.ts
|
||||||
import { define } from "./utils.ts";
|
import { define } from "./utils.ts";
|
||||||
|
|
||||||
const middleware = define.middleware(async (ctx) => {
|
const middleware = define.middleware(async (ctx) => {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: |
|
|||||||
Routing defines which middlewares and routes should respond to a particular
|
Routing defines which middlewares and routes should respond to a particular
|
||||||
request.
|
request.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App()
|
const app = new App()
|
||||||
.get("/", () => new Response("hello")) // Responds to: GET /
|
.get("/", () => new Response("hello")) // Responds to: GET /
|
||||||
.get("/other", () => new Response("other")) // Responds to: GET /other
|
.get("/other", () => new Response("other")) // Responds to: GET /other
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ disk for optimal performance with
|
|||||||
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
|
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
|
||||||
headers.
|
headers.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
import { staticFiles } from "fresh";
|
import { staticFiles } from "fresh";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
@@ -30,17 +30,20 @@ const builder = new Builder({ staticDir: "path/to/staticDir" });
|
|||||||
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
By default, Fresh adds caching headers for the `src` and `srcset` attributes on
|
||||||
`<img>` and `<source>` tags.
|
`<img>` and `<source>` tags.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
// Caching headers will be automatically added
|
// Caching headers will be automatically added
|
||||||
<img src="/user.png" />;
|
app.get("/user", (ctx) => ctx.render(<img src="/user.png" />));
|
||||||
```
|
```
|
||||||
|
|
||||||
You can always opt out of this behaviour per tag, by adding the
|
You can always opt out of this behaviour per tag, by adding the
|
||||||
`data-fresh-disable-lock` attribute.
|
`data-fresh-disable-lock` attribute.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
// Opt-out of automatic caching headers
|
// Opt-out of automatic caching headers
|
||||||
<img src="/user.png" data-fresh-disable-lock />;
|
app.get(
|
||||||
|
"/user",
|
||||||
|
(ctx) => ctx.render(<img src="/user.png" data-fresh-disable-lock />),
|
||||||
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Adding caching headers manually
|
## Adding caching headers manually
|
||||||
@@ -48,9 +51,11 @@ You can always opt out of this behaviour per tag, by adding the
|
|||||||
Use the `asset()` function to add caching headers manually. It will be served
|
Use the `asset()` function to add caching headers manually. It will be served
|
||||||
with a cache lifetime of one year.
|
with a cache lifetime of one year.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/about.tsx
|
||||||
import { asset } from "fresh/runtime";
|
import { asset } from "fresh/runtime";
|
||||||
|
|
||||||
// Adding caching headers manually
|
export default function About() {
|
||||||
<a href={asset("/brochure.pdf")}>View brochure</a>;
|
// Adding caching headers manually
|
||||||
|
return <a href={asset("/brochure.pdf")}>View brochure</a>;
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ which contains the optimized assets.
|
|||||||
> [info]: The `_fresh` folder should not be committed to git. Exclude it via
|
> [info]: The `_fresh` folder should not be committed to git. Exclude it via
|
||||||
> `.gitignore`.
|
> `.gitignore`.
|
||||||
>
|
>
|
||||||
> ```sh .gitignore
|
> ```gitignore .gitignore
|
||||||
> # Ignore fresh build directory
|
> # Ignore fresh build directory
|
||||||
> _fresh/
|
> _fresh/
|
||||||
> ```
|
> ```
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ styling current links where applicable.
|
|||||||
The aria-current attribute is easily styled with CSS using attribute selectors,
|
The aria-current attribute is easily styled with CSS using attribute selectors,
|
||||||
providing a native way to visually differentiate the active link.
|
providing a native way to visually differentiate the active link.
|
||||||
|
|
||||||
```css
|
```css static/styles.css
|
||||||
/* Give links pointing to the current page a green color */
|
/* Give links pointing to the current page a green color */
|
||||||
a[aria-current="page"] {
|
a[aria-current="page"] {
|
||||||
color: green;
|
color: green;
|
||||||
@@ -37,7 +37,7 @@ In Tailwindcss or similar CSS frameworks, you can apply styles to elements with
|
|||||||
the `aria-current` attribute using bracket notation in your class definitions.
|
the `aria-current` attribute using bracket notation in your class definitions.
|
||||||
For Tailwindcss, use the syntax:
|
For Tailwindcss, use the syntax:
|
||||||
|
|
||||||
```tsx
|
```tsx components/Menu.tsx
|
||||||
function Menu() {
|
function Menu() {
|
||||||
return (
|
return (
|
||||||
<a href="/foo" class="aria-[current]:text-green-600">
|
<a href="/foo" class="aria-[current]:text-green-600">
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ To get started with daisyUI, make sure you have Tailwind CSS enabled in your
|
|||||||
Fresh project, then install daisyUI and update your configuration.
|
Fresh project, then install daisyUI and update your configuration.
|
||||||
|
|
||||||
1. Run `deno i -D npm:daisyui@latest` to install daisyUI
|
1. Run `deno i -D npm:daisyui@latest` to install daisyUI
|
||||||
2. add daisyui configuration in `./static/styles.css`:
|
2. Add daisyUI configuration in `./static/styles.css`:
|
||||||
|
|
||||||
```diff
|
```diff static/styles.css
|
||||||
@import "tailwindcss";
|
@import "tailwindcss";
|
||||||
+ @plugin "daisyui";
|
+ @plugin "daisyui";
|
||||||
```
|
```
|
||||||
|
|
||||||
Now you're ready to use daisyUI.
|
Now you're ready to use daisyUI.
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ can transform markdown to html.
|
|||||||
1. Run `deno install jsr:@deno/gfm`
|
1. Run `deno install jsr:@deno/gfm`
|
||||||
2. Create a markdown file like `content.md`:
|
2. Create a markdown file like `content.md`:
|
||||||
|
|
||||||
```md
|
```md path/to/content.md
|
||||||
## some heading
|
## some heading
|
||||||
|
|
||||||
and some interesting text here
|
and some interesting text here
|
||||||
@@ -24,7 +24,7 @@ and some interesting text here
|
|||||||
|
|
||||||
4. Add a route that renders that file
|
4. Add a route that renders that file
|
||||||
|
|
||||||
```tsx
|
```tsx main.ts
|
||||||
import { CSS, render as renderMarkdown } from "@deno/gfm";
|
import { CSS, render as renderMarkdown } from "@deno/gfm";
|
||||||
|
|
||||||
const CONTENT = `## some heading
|
const CONTENT = `## some heading
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ Use this guide to migrate a Fresh 1.x app to Fresh 2.
|
|||||||
Most changes can be applied automatically with the update script. Start the
|
Most changes can be applied automatically with the update script. Start the
|
||||||
update by running it in your project directory:
|
update by running it in your project directory:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
deno run -Ar jsr:@fresh/update
|
deno run -Ar jsr:@fresh/update
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -29,12 +29,13 @@ Configuring Fresh doesn't require a dedicated config file anymore. You can
|
|||||||
delete the `fresh.config.ts` file. The `fresh.gen.ts` manifest file isn't needed
|
delete the `fresh.config.ts` file. The `fresh.gen.ts` manifest file isn't needed
|
||||||
anymore either.
|
anymore either.
|
||||||
|
|
||||||
```diff
|
```diff Project structure
|
||||||
routes/
|
<project root>
|
||||||
dev.ts
|
├── routes/
|
||||||
- fresh.gen.ts
|
├── dev.ts
|
||||||
- fresh.config.ts
|
- ├── fresh.gen.ts
|
||||||
main.ts
|
- ├── fresh.config.ts
|
||||||
|
└── main.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
Fresh 2 takes great care in ensuring that code that's only needed during
|
Fresh 2 takes great care in ensuring that code that's only needed during
|
||||||
@@ -50,7 +51,7 @@ plugins like [tailwindcss](https://tailwindcss.com/).
|
|||||||
|
|
||||||
The full `dev.ts` file for newly generated Fresh 2 projects looks like this:
|
The full `dev.ts` file for newly generated Fresh 2 projects looks like this:
|
||||||
|
|
||||||
```ts
|
```ts dev.ts
|
||||||
import { Builder } from "fresh/dev";
|
import { Builder } from "fresh/dev";
|
||||||
import { tailwind } from "@fresh/plugin-tailwind";
|
import { tailwind } from "@fresh/plugin-tailwind";
|
||||||
|
|
||||||
@@ -93,12 +94,12 @@ export const app = new App()
|
|||||||
Both the `_500.tsx` and `_404.tsx` template have been unified into a single
|
Both the `_500.tsx` and `_404.tsx` template have been unified into a single
|
||||||
`_error.tsx` template.
|
`_error.tsx` template.
|
||||||
|
|
||||||
```diff
|
```diff Project structure
|
||||||
routes/
|
└── <root>/routes/
|
||||||
- ├── _404.tsx
|
- ├── _404.tsx
|
||||||
- ├── _500.tsx
|
- ├── _500.tsx
|
||||||
+ ├── _error.tsx
|
+ ├── _error.tsx
|
||||||
└── ...
|
└── ...
|
||||||
```
|
```
|
||||||
|
|
||||||
Inside the `_error.tsx` template you can show different content based on errors
|
Inside the `_error.tsx` template you can show different content based on errors
|
||||||
@@ -129,8 +130,7 @@ machinery in the background to work.
|
|||||||
|
|
||||||
Instead, passing head-related data is best done via `ctx.state`
|
Instead, passing head-related data is best done via `ctx.state`
|
||||||
|
|
||||||
```tsx
|
```tsx routes/about.tsx
|
||||||
// about.tsx
|
|
||||||
export const handler = {
|
export const handler = {
|
||||||
GET(ctx) {
|
GET(ctx) {
|
||||||
// Set a route specific data in a handler
|
// Set a route specific data in a handler
|
||||||
@@ -138,8 +138,9 @@ export const handler = {
|
|||||||
return page();
|
return page();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
```
|
||||||
|
|
||||||
// Render that in _app.tsx
|
```tsx routes/_app.tsx
|
||||||
export default function AppWrapper(ctx: Context) {
|
export default function AppWrapper(ctx: Context) {
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
@@ -169,7 +170,7 @@ The handling trailing slashes has been extracted to an optional middleware that
|
|||||||
you can add if needed. This middleware can be used to ensure that URLs always
|
you can add if needed. This middleware can be used to ensure that URLs always
|
||||||
have a trailing slash at the end or that they will never have one.
|
have a trailing slash at the end or that they will never have one.
|
||||||
|
|
||||||
```diff
|
```diff main.ts
|
||||||
- import { App, staticFiles } from "fresh";
|
- import { App, staticFiles } from "fresh";
|
||||||
+ import { App, staticFiles, trailingSlashes } from "fresh";
|
+ import { App, staticFiles, trailingSlashes } from "fresh";
|
||||||
|
|
||||||
@@ -190,14 +191,14 @@ Middleware, handler and route component signatures have been unified to all look
|
|||||||
the same. Instead of receiving two arguments, they receive one. The `Request`
|
the same. Instead of receiving two arguments, they receive one. The `Request`
|
||||||
object is stored on the context object as `ctx.req`.
|
object is stored on the context object as `ctx.req`.
|
||||||
|
|
||||||
```diff
|
```diff middleware.ts
|
||||||
- const middleware = (req, ctx) => new Response("ok");
|
- const middleware = (req, ctx) => new Response("ok");
|
||||||
+ const middleware = (ctx) => new Response("ok");
|
+ const middleware = (ctx) => new Response("ok");
|
||||||
```
|
```
|
||||||
|
|
||||||
Same is true for handlers:
|
Same is true for handlers:
|
||||||
|
|
||||||
```diff
|
```diff route/page.tsx
|
||||||
export const handler = {
|
export const handler = {
|
||||||
- GET(req, ctx) {
|
- GET(req, ctx) {
|
||||||
+ GET(ctx) {
|
+ GET(ctx) {
|
||||||
@@ -208,7 +209,7 @@ Same is true for handlers:
|
|||||||
|
|
||||||
...and async route components:
|
...and async route components:
|
||||||
|
|
||||||
```diff
|
```diff routes/my-page.tsx
|
||||||
- export default async function MyPage(req: Request, ctx: RouteContext) {
|
- export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||||
+ export default async function MyPage(props: PageProps) {
|
+ export default async function MyPage(props: PageProps) {
|
||||||
const value = await loadFooValue();
|
const value = await loadFooValue();
|
||||||
@@ -240,7 +241,7 @@ re-use existing objects internally as a minor performance optimization.
|
|||||||
The `createHandler` function was often used to launch Fresh for tests. This can
|
The `createHandler` function was often used to launch Fresh for tests. This can
|
||||||
be now done via the [`Builder`](/docs/canary/concepts/builder).
|
be now done via the [`Builder`](/docs/canary/concepts/builder).
|
||||||
|
|
||||||
```ts
|
```ts main.test.ts
|
||||||
// Best to do this once instead of for every test case for
|
// Best to do this once instead of for every test case for
|
||||||
// performance reasons.
|
// performance reasons.
|
||||||
const builder = new Builder();
|
const builder = new Builder();
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ situations.
|
|||||||
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
|
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
|
||||||
prop:
|
prop:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/dynamic-html.tsx
|
||||||
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
|
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
|
||||||
```
|
```
|
||||||
|
|
||||||
This will output:
|
This will output:
|
||||||
|
|
||||||
```html
|
```html Response body
|
||||||
<div>
|
<div>
|
||||||
<h1>This is raw HTML</h1>
|
<h1>This is raw HTML</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ This will span a short wizard that guides you through the setup, like the
|
|||||||
project name, if you want to use tailwindcss and if you're using vscode. Your
|
project name, if you want to use tailwindcss and if you're using vscode. Your
|
||||||
project folder should look like this:
|
project folder should look like this:
|
||||||
|
|
||||||
```sh Project structure
|
```txt-files Project structure
|
||||||
<project dir>
|
<project root>
|
||||||
├── islands/ # Components that need JS to run client-side
|
├── islands/ # Components that need JS to run client-side
|
||||||
│ └── Counter.tsx
|
│ └── Counter.tsx
|
||||||
├── routes/ # File system based routes
|
├── routes/ # File system based routes
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ Fresh is a small, fast and extensible full stack web framework built on Web
|
|||||||
Standards. It's designed for building high-quality, performant, and personalized
|
Standards. It's designed for building high-quality, performant, and personalized
|
||||||
web applications.
|
web applications.
|
||||||
|
|
||||||
```tsx
|
```tsx main.tsx
|
||||||
import { App } from "fresh";
|
import { App } from "fresh";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ The `cors()` middleware can be used to add
|
|||||||
to HTTP requests. These allow the server to indicate which origins (domains,
|
to HTTP requests. These allow the server to indicate which origins (domains,
|
||||||
scheme or port) other than its own is permitted to load resources from.
|
scheme or port) other than its own is permitted to load resources from.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
import { cors } from "fresh";
|
import { cors } from "fresh";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ header. to HTTP requests. These allow the server to indicate which origins
|
|||||||
(domains, scheme or port) other than its own is permitted to load resources
|
(domains, scheme or port) other than its own is permitted to load resources
|
||||||
from.
|
from.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
const app = new App();
|
const app = new App();
|
||||||
|
|
||||||
app.use(csrf());
|
app.use(csrf());
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ If you need to modify requests, add HTTP headers or pass additional data to
|
|||||||
other middlewares via `ctx.state`, then going with a middleware is the way to
|
other middlewares via `ctx.state`, then going with a middleware is the way to
|
||||||
go.
|
go.
|
||||||
|
|
||||||
```ts
|
```ts middleware/fresh.ts
|
||||||
const addXFreshHeader = define.middleware(async (ctx) => {
|
const addXFreshHeader = define.middleware(async (ctx) => {
|
||||||
const res = await ctx.next();
|
const res = await ctx.next();
|
||||||
res.headers.set("X-Fresh", "served by Fresh");
|
res.headers.set("X-Fresh", "served by Fresh");
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ For more information on how to use tailwindcss, check out
|
|||||||
|
|
||||||
You can customize the tailwind plugin via the following options:
|
You can customize the tailwind plugin via the following options:
|
||||||
|
|
||||||
```ts
|
```ts dev.ts
|
||||||
tailwind(builder, app, {
|
tailwind(builder, app, {
|
||||||
// Exclude certain files from processing
|
// Exclude certain files from processing
|
||||||
exclude: ["/admin/**", "*.temp.css"],
|
exclude: ["/admin/**", "*.temp.css"],
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ The `trailingSlashes()` middleware can be used to ensure URL pathnames always
|
|||||||
end with a slash character or will never end with one. It redirects the user's
|
end with a slash character or will never end with one. It redirects the user's
|
||||||
request respectively.
|
request respectively.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
import { trailingSlashes } from "fresh";
|
import { trailingSlashes } from "fresh";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
@@ -16,7 +16,7 @@ const app = new App()
|
|||||||
|
|
||||||
Always append a trailing slash:
|
Always append a trailing slash:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
import { trailingSlashes } from "fresh";
|
import { trailingSlashes } from "fresh";
|
||||||
|
|
||||||
const app = new App()
|
const app = new App()
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ write tests.
|
|||||||
To test [middlewares](/docs/canary/concepts/middleware) we're going to create a
|
To test [middlewares](/docs/canary/concepts/middleware) we're going to create a
|
||||||
dummy app and return the relevant info we want to check in a custom `/` handler.
|
dummy app and return the relevant info we want to check in a custom `/` handler.
|
||||||
|
|
||||||
```ts
|
```ts middleware.test.ts
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { App } from "fresh";
|
import { App } from "fresh";
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ that adds a header to the returned response, you can assert against that too.
|
|||||||
Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and
|
Both the [app wrapper](/docs/canary/advanced/app-wrapper) component and
|
||||||
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
|
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_app.test.tsx
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { App } from "fresh";
|
import { App } from "fresh";
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ Deno.test("App Wrapper - renders title and content", async () => {
|
|||||||
|
|
||||||
Same can be done for layouts.
|
Same can be done for layouts.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_layout.test.tsx
|
||||||
import { expect } from "@std/expect";
|
import { expect } from "@std/expect";
|
||||||
import { App } from "fresh";
|
import { App } from "fresh";
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ pre-process or generate CSS files, for example.
|
|||||||
|
|
||||||
To have Fresh optimize all the assets, run one of the following commands:
|
To have Fresh optimize all the assets, run one of the following commands:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
# As a task in newer Fresh projects
|
# As a task in newer Fresh projects
|
||||||
deno task build
|
deno task build
|
||||||
# or invoke it manually
|
# or invoke it manually
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ deployed to any system or platform that can run a Deno based web server.
|
|||||||
|
|
||||||
Here are instructions for specific providers / systems:
|
Here are instructions for specific providers / systems:
|
||||||
|
|
||||||
- [Deno Deploy](#deno-deploy)
|
- [Deno Deploy](#-deno-deploy)
|
||||||
- [Docker](#docker)
|
- [Docker](#-docker)
|
||||||
|
|
||||||
## Deno Deploy
|
## Deno Deploy
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export default function BlogpostPage({ data }) {
|
|||||||
This can also be achieved by throwing an error, if you're uninterested in
|
This can also be achieved by throwing an error, if you're uninterested in
|
||||||
passing specific data to your 404 page:
|
passing specific data to your 404 page:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/missing-page.tsx
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ enough information to put the islands where they are supposed to go without
|
|||||||
requiring hydration for the static children of interactive islands. No
|
requiring hydration for the static children of interactive islands. No
|
||||||
Javascript is sent to the client when no interactivity is needed.
|
Javascript is sent to the client when no interactivity is needed.
|
||||||
|
|
||||||
```html
|
```html Response body
|
||||||
<!--frsh-myisland_default:default:0-->
|
<!--frsh-myisland_default:default:0-->
|
||||||
<div>
|
<div>
|
||||||
Counter is at 0.
|
Counter is at 0.
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ A 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
|
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.
|
Preact component. Only one such layout is allowed per sub directory.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
|
<project root>
|
||||||
└── routes
|
└── routes
|
||||||
├── sub
|
├── sub
|
||||||
│ ├── page.tsx
|
│ ├── page.tsx
|
||||||
@@ -64,7 +65,7 @@ To make it a little quicker to write async layouts, Fresh ships with a
|
|||||||
`defineLayout` helper which automatically infers the correct types for the
|
`defineLayout` helper which automatically infers the correct types for the
|
||||||
function arguments.
|
function arguments.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/greet/_layout.tsx
|
||||||
import { defineLayout } from "$fresh/server.ts";
|
import { defineLayout } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default defineLayout(async (req, ctx) => {
|
export default defineLayout(async (req, ctx) => {
|
||||||
@@ -85,8 +86,8 @@ 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
|
particular route. This can be done via route configuration. Picture a directory
|
||||||
structure like this:
|
structure like this:
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── sub
|
├── sub
|
||||||
│ ├── _layout_.tsx
|
│ ├── _layout_.tsx
|
||||||
│ ├── special.tsx # should not inherit layouts
|
│ ├── special.tsx # should not inherit layouts
|
||||||
|
|||||||
@@ -50,8 +50,8 @@ specific first).
|
|||||||
|
|
||||||
For example, take a project with the following routes:
|
For example, take a project with the following routes:
|
||||||
|
|
||||||
```txt Project Structure
|
```txt-files Project Structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── _middleware.ts
|
├── _middleware.ts
|
||||||
├── index.ts
|
├── index.ts
|
||||||
└── admin
|
└── admin
|
||||||
@@ -118,7 +118,7 @@ the value of `acme` in your middleware.
|
|||||||
To set the stage for this section, let's focus on the part of `FreshContext`
|
To set the stage for this section, let's focus on the part of `FreshContext`
|
||||||
that looks like this:
|
that looks like this:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export interface FreshContext<State = Record<string, unknown>> {
|
export interface FreshContext<State = Record<string, unknown>> {
|
||||||
...
|
...
|
||||||
next: () => Promise<Response>;
|
next: () => Promise<Response>;
|
||||||
@@ -135,7 +135,7 @@ export interface FreshContext<State = Record<string, unknown>> {
|
|||||||
|
|
||||||
and `router.DestinationKind` is defined like this:
|
and `router.DestinationKind` is defined like this:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -203,7 +203,7 @@ is only supposed to deal with routes.
|
|||||||
|
|
||||||
If you want to redirect a request from a middleware, you can do so by returning:
|
If you want to redirect a request from a middleware, you can do so by returning:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
export function handler(req: Request): Response {
|
export function handler(req: Request): Response {
|
||||||
return Response.redirect("https://example.com", 307);
|
return Response.redirect("https://example.com", 307);
|
||||||
}
|
}
|
||||||
@@ -212,7 +212,7 @@ export function handler(req: Request): Response {
|
|||||||
`307` stands for temporary redirect. You can also use `301` for permanent
|
`307` stands for temporary redirect. You can also use `301` for permanent
|
||||||
redirect. You can also redirect to a relative path by doing:
|
redirect. You can also redirect to a relative path by doing:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
export function handler(req: Request): Response {
|
export function handler(req: Request): Response {
|
||||||
return new Response("", {
|
return new Response("", {
|
||||||
status: 307,
|
status: 307,
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ 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
|
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.
|
full page. This is done by adding the `f-partial` attribute to a link.
|
||||||
|
|
||||||
```diff
|
```diff routes/_app.tsx
|
||||||
- <a href="/docs/routes">Routes</a>
|
- <a href="/docs/routes">Routes</a>
|
||||||
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
+ <a href="/docs/routes" f-partial="/partials/docs/routes">Routes</a>
|
||||||
```
|
```
|
||||||
@@ -180,7 +180,7 @@ achieved by adding the `mode` prop to a `Partial` component.
|
|||||||
Personally, we’ve found that the `append` mode is really useful when you have an
|
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.
|
UI which displays log messages or similar list-like data.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/log.tsx
|
||||||
export default function LogView() {
|
export default function LogView() {
|
||||||
const lines = getNewLogLines();
|
const lines = getNewLogLines();
|
||||||
|
|
||||||
@@ -203,7 +203,7 @@ 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
|
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.
|
`f-client-nav={false}` on the element or one of the ancestor elements.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
<body f-client-nav>
|
<body f-client-nav>
|
||||||
{/* This will cause a partial navigation */}
|
{/* This will cause a partial navigation */}
|
||||||
<a href="/docs/page1">With partials</a>
|
<a href="/docs/page1">With partials</a>
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ A Fresh plugin is just a JavaScript object that conforms to the
|
|||||||
required property of a plugin is its name. Names must only contain the
|
required property of a plugin is its name. Names must only contain the
|
||||||
characters `a`-`z`, and `_`.
|
characters `a`-`z`, and `_`.
|
||||||
|
|
||||||
```ts
|
```ts my-plugin.ts
|
||||||
import { Plugin } from "$fresh/server.ts";
|
import { Plugin } from "$fresh/server.ts";
|
||||||
|
|
||||||
const plugin: Plugin = {
|
const plugin: Plugin = {
|
||||||
|
|||||||
@@ -172,7 +172,7 @@ To make it a little quicker to write async routes, Fresh ships with a
|
|||||||
`defineRoute` helper which automatically infers the correct types for the
|
`defineRoute` helper which automatically infers the correct types for the
|
||||||
function arguments.
|
function arguments.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/hello.tsx
|
||||||
import { defineRoute } from "$fresh/server.ts";
|
import { defineRoute } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default defineRoute(async (req, ctx) => {
|
export default defineRoute(async (req, ctx) => {
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ suggested by the URL segment.
|
|||||||
|
|
||||||
Let's illustrate that with an example:
|
Let's illustrate that with an example:
|
||||||
|
|
||||||
```txt
|
```txt Example page layout
|
||||||
/about -> layout A
|
/about -> layout A
|
||||||
/career -> layout A
|
/career -> layout A
|
||||||
/archive -> layout B
|
/archive -> layout B
|
||||||
@@ -71,7 +71,8 @@ Let's illustrate that with an example:
|
|||||||
Without any way to group routes this is a problem because every route segment
|
Without any way to group routes this is a problem because every route segment
|
||||||
can only have one `_layout` file.
|
can only have one `_layout` file.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
|
<project root>
|
||||||
└── routes
|
└── routes
|
||||||
├── _layout.tsx # applies to all routes here :(
|
├── _layout.tsx # applies to all routes here :(
|
||||||
├── about.tsx
|
├── about.tsx
|
||||||
@@ -85,8 +86,8 @@ a name that is wrapped in parentheses. For example `(info)` would be considered
|
|||||||
a route group and so would `(marketing)`. This enables us to group related
|
a route group and so would `(marketing)`. This enables us to group related
|
||||||
routes in a folder and use a different `_layout` file for each group.
|
routes in a folder and use a different `_layout` file for each group.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── (marketing)
|
├── (marketing)
|
||||||
│ ├── _layout.tsx # only applies to about.tsx and career.tsx
|
│ ├── _layout.tsx # only applies to about.tsx and career.tsx
|
||||||
│ ├── about.tsx
|
│ ├── about.tsx
|
||||||
@@ -101,8 +102,8 @@ routes in a folder and use a different `_layout` file for each group.
|
|||||||
> URL. Such scenarios will lead to ambiguity as to which route file should be
|
> URL. Such scenarios will lead to ambiguity as to which route file should be
|
||||||
> picked.
|
> picked.
|
||||||
>
|
>
|
||||||
> ```txt Project structure
|
> ```txt-files Project structure
|
||||||
> └── routes
|
> └── <root>/routes
|
||||||
> ├── (group-1)
|
> ├── (group-1)
|
||||||
> │ └── about.tsx # Bad: Maps to same `/about` url
|
> │ └── about.tsx # Bad: Maps to same `/about` url
|
||||||
> └── (group-2)
|
> └── (group-2)
|
||||||
@@ -128,8 +129,8 @@ to house these.
|
|||||||
The one special name is `(_islands)` which tells Fresh to treat all files in
|
The one special name is `(_islands)` which tells Fresh to treat all files in
|
||||||
that folder as an island.
|
that folder as an island.
|
||||||
|
|
||||||
```txt Project structure
|
```txt-files Project structure
|
||||||
└── routes
|
└── <root>/routes
|
||||||
├── (marketing)
|
├── (marketing)
|
||||||
│ ├── _layout.tsx
|
│ ├── _layout.tsx
|
||||||
│ ├── about.tsx
|
│ ├── about.tsx
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ things get interesting.
|
|||||||
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) looks like
|
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) looks like
|
||||||
this:
|
this:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export interface FreshConfig {
|
export interface FreshConfig {
|
||||||
build?: {
|
build?: {
|
||||||
/**
|
/**
|
||||||
@@ -44,7 +44,7 @@ export interface FreshConfig {
|
|||||||
|
|
||||||
And for completeness here are the remaining two types:
|
And for completeness here are the remaining two types:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export type RenderFunction = (
|
export type RenderFunction = (
|
||||||
ctx: RenderContext,
|
ctx: RenderContext,
|
||||||
render: InnerRenderFunction,
|
render: InnerRenderFunction,
|
||||||
@@ -81,7 +81,7 @@ export interface RouterOptions {
|
|||||||
As the comment suggests, this can be used to configure where generated files are
|
As the comment suggests, this can be used to configure where generated files are
|
||||||
written:
|
written:
|
||||||
|
|
||||||
```tsx
|
```tsx dev.ts
|
||||||
await dev(import.meta.url, "./main.ts", {
|
await dev(import.meta.url, "./main.ts", {
|
||||||
build: {
|
build: {
|
||||||
outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined,
|
outDir: Deno.env.get("FRESH_TEST_OUTDIR") ?? undefined,
|
||||||
@@ -93,7 +93,7 @@ await dev(import.meta.url, "./main.ts", {
|
|||||||
|
|
||||||
This should be a valid ES Build target.
|
This should be a valid ES Build target.
|
||||||
|
|
||||||
```tsx
|
```tsx dev.ts
|
||||||
await dev(import.meta.url, "./main.ts", {
|
await dev(import.meta.url, "./main.ts", {
|
||||||
build: {
|
build: {
|
||||||
target: "es2015",
|
target: "es2015",
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ and `<source>` HTML tags. These will automatically use "locked" paths if Fresh
|
|||||||
deems it safe to do so. You can always opt out of this behaviour per tag, by
|
deems it safe to do so. You can always opt out of this behaviour per tag, by
|
||||||
adding the `data-fresh-disable-lock` attribute.
|
adding the `data-fresh-disable-lock` attribute.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/user.tsx
|
||||||
|
{/* Locked URL source */}
|
||||||
<img src="/user.png" />;
|
<img src="/user.png" />;
|
||||||
|
|
||||||
|
{/* Preserve URL source and disable lock */}
|
||||||
|
<img src="/user.png" data-fresh-disable-lock />;
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ the recommended way to use JSX in Fresh projects. Instead, starting with version
|
|||||||
1.1.0, Fresh projects should use the automatic JSX transform that requires no
|
1.1.0, Fresh projects should use the automatic JSX transform that requires no
|
||||||
JSX pragma or preact import.
|
JSX pragma or preact import.
|
||||||
|
|
||||||
```diff
|
```diff routes/hello-world.tsx
|
||||||
- /** @jsx h */
|
- /** @jsx h */
|
||||||
- import { h } from "preact";
|
- import { h } from "preact";
|
||||||
|
|
||||||
|
|||||||
@@ -8,18 +8,18 @@ aria-current attribute when rendering links that match the current URL. This
|
|||||||
attribute is recognized by assistive technologies and clearly indicates the
|
attribute is recognized by assistive technologies and clearly indicates the
|
||||||
current page within a set of pages.
|
current page within a set of pages.
|
||||||
|
|
||||||
- aria-current="page" - Added to links with an exact path match, enhancing
|
- `aria-current="page"` - Added to links with an exact path match, enhancing
|
||||||
accessibility by indicating the current page to assistive technologies.
|
accessibility by indicating the current page to assistive technologies.
|
||||||
|
|
||||||
As we aim to improve accessibility, we encourage the use of aria-current for
|
As we aim to improve accessibility, we encourage the use of `aria-current` for
|
||||||
styling current links where applicable.
|
styling current links where applicable.
|
||||||
|
|
||||||
## Styling with CSS
|
## Styling with CSS
|
||||||
|
|
||||||
The aria-current attribute is easily styled with CSS using attribute selectors,
|
The `aria-current` attribute is easily styled with CSS using attribute
|
||||||
providing a native way to visually differentiate the active link.
|
selectors, providing a native way to visually differentiate the active link.
|
||||||
|
|
||||||
```css
|
```css static/styles.css
|
||||||
/* Give links pointing to the current page a green color */
|
/* Give links pointing to the current page a green color */
|
||||||
a[aria-current="page"] {
|
a[aria-current="page"] {
|
||||||
color: green;
|
color: green;
|
||||||
@@ -38,7 +38,7 @@ elements with the aria-current attribute using bracket notation in your class
|
|||||||
definitions. However, the specific syntax varies slightly between Tailwind and
|
definitions. However, the specific syntax varies slightly between Tailwind and
|
||||||
Twind. For Tailwind, use the syntax:
|
Twind. For Tailwind, use the syntax:
|
||||||
|
|
||||||
```tsx
|
```tsx component/Menu.tsx
|
||||||
function Menu() {
|
function Menu() {
|
||||||
return (
|
return (
|
||||||
<a href="/foo" class="aria-[current]:text-green-600">
|
<a href="/foo" class="aria-[current]:text-green-600">
|
||||||
@@ -50,7 +50,7 @@ function Menu() {
|
|||||||
|
|
||||||
For Twind, the syntax is:
|
For Twind, the syntax is:
|
||||||
|
|
||||||
```tsx
|
```tsx component/Menu.tsx
|
||||||
function Menu() {
|
function Menu() {
|
||||||
return (
|
return (
|
||||||
<a href="/foo" class="[aria-current]:text-green-600">
|
<a href="/foo" class="[aria-current]:text-green-600">
|
||||||
@@ -65,7 +65,7 @@ function Menu() {
|
|||||||
The original twind plugin (`import twindPlugin from "$fresh/plugins/twind.ts";`)
|
The original twind plugin (`import twindPlugin from "$fresh/plugins/twind.ts";`)
|
||||||
supports the above style:
|
supports the above style:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page.tsx
|
||||||
class="[aria-current='page']:text-green-600"
|
class="[aria-current='page']:text-green-600"
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -74,6 +74,6 @@ class="[aria-current='page']:text-green-600"
|
|||||||
The new twind plugin (`import twindPlugin from "$fresh/plugins/twindv1.ts";`)
|
The new twind plugin (`import twindPlugin from "$fresh/plugins/twindv1.ts";`)
|
||||||
requires a slightly different syntax (note the position of the left bracket):
|
requires a slightly different syntax (note the position of the left bracket):
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page.tsx
|
||||||
class="aria-[current='page']:text-green-600"
|
class="aria-[current='page']:text-green-600"
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ description: |
|
|||||||
When you initialize a project with `deno run -A -r https://fresh.deno.dev`,
|
When you initialize a project with `deno run -A -r https://fresh.deno.dev`,
|
||||||
you'll end up with a project like the following:
|
you'll end up with a project like the following:
|
||||||
|
|
||||||
```txt Project Structure
|
```txt-files Project Structure
|
||||||
.
|
<project root>
|
||||||
├── README.md
|
├── README.md
|
||||||
├── components
|
├── components
|
||||||
│ └── Button.tsx
|
│ └── Button.tsx
|
||||||
@@ -53,8 +53,8 @@ Here's what the diff of `deno.json` looks like:
|
|||||||
|
|
||||||
The resulting file structure looks like this:
|
The resulting file structure looks like this:
|
||||||
|
|
||||||
```txt Project Structure
|
```txt-files Project Structure
|
||||||
.
|
<project root>
|
||||||
├── README.md
|
├── README.md
|
||||||
├── deno.json
|
├── deno.json
|
||||||
└── src
|
└── src
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ rendering might not be feasible.
|
|||||||
> [warn]: Proper typing might not be easily available, so we might need to
|
> [warn]: Proper typing might not be easily available, so we might need to
|
||||||
> define our own types or not use types at all.
|
> define our own types or not use types at all.
|
||||||
|
|
||||||
```ts
|
```ts context.ts
|
||||||
export const leafletContext = createContext<typeof Leaflet | null>(null);
|
export const leafletContext = createContext<typeof Leaflet | null>(null);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ state, and this value will be handled/shared with our other components.
|
|||||||
> script and css may cause issues. Leaflet, for instance, will throw errors if
|
> script and css may cause issues. Leaflet, for instance, will throw errors if
|
||||||
> we try to load it again.
|
> we try to load it again.
|
||||||
|
|
||||||
```tsx
|
```tsx context.ts
|
||||||
function LeafletProvider(props: { children: ComponentChildren }) {
|
function LeafletProvider(props: { children: ComponentChildren }) {
|
||||||
if (!IS_BROWSER) {
|
if (!IS_BROWSER) {
|
||||||
return (
|
return (
|
||||||
@@ -85,7 +85,7 @@ cases where the context has not loaded values yet is a good practice as well, in
|
|||||||
this way we can have a smooth integration and manipulation of client-side data
|
this way we can have a smooth integration and manipulation of client-side data
|
||||||
and logic on our server-side code.
|
and logic on our server-side code.
|
||||||
|
|
||||||
```tsx
|
```tsx component/Map.tsx
|
||||||
function MapComponent() {
|
function MapComponent() {
|
||||||
const leaf = useContext(leafletContext);
|
const leaf = useContext(leafletContext);
|
||||||
if (!leaf) return <p>Context not ready. Component placeholder</p>;
|
if (!leaf) return <p>Context not ready. Component placeholder</p>;
|
||||||
@@ -105,7 +105,7 @@ to demonstrate a simple usage. In real cases, it's usually better to add the
|
|||||||
Provider directly to our Page and then use Components that depend on that
|
Provider directly to our Page and then use Components that depend on that
|
||||||
provider inside it.
|
provider inside it.
|
||||||
|
|
||||||
```tsx
|
```tsx islands/MapIsland.tsx
|
||||||
export default function MapIsland() {
|
export default function MapIsland() {
|
||||||
return (
|
return (
|
||||||
<LeafletProvider>
|
<LeafletProvider>
|
||||||
@@ -117,7 +117,7 @@ export default function MapIsland() {
|
|||||||
|
|
||||||
## Full code:
|
## Full code:
|
||||||
|
|
||||||
```tsx MapIsland.tsx
|
```tsx islands/MapIsland.tsx
|
||||||
import * as Leaflet from "https://esm.sh/v135/@types/leaflet@1.9.4/index.d.ts";
|
import * as Leaflet from "https://esm.sh/v135/@types/leaflet@1.9.4/index.d.ts";
|
||||||
import { IS_BROWSER } from "$fresh/runtime.ts";
|
import { IS_BROWSER } from "$fresh/runtime.ts";
|
||||||
import { useContext, useEffect } from "preact/hooks";
|
import { useContext, useEffect } from "preact/hooks";
|
||||||
|
|||||||
@@ -19,12 +19,13 @@ In this example we'll be creating a small API that uses
|
|||||||
Our project structure will look like this (in addition to the rest of the Fresh
|
Our project structure will look like this (in addition to the rest of the Fresh
|
||||||
code from a new project):
|
code from a new project):
|
||||||
|
|
||||||
```txt Project Structure
|
```txt-files Project Structure
|
||||||
routes
|
<project root>
|
||||||
└── api
|
└── routes
|
||||||
└── users
|
└── api
|
||||||
├── [id].ts
|
└── users
|
||||||
└── index.ts
|
├── [id].ts
|
||||||
|
└── index.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
In each section about a method, only the relevant handler will be shown. The
|
In each section about a method, only the relevant handler will be shown. The
|
||||||
@@ -50,7 +51,7 @@ Test this with Postman (or your favorite client) with a URL like
|
|||||||
`http://localhost:8000/api/users` and a method of `POST`. Make sure to have a
|
`http://localhost:8000/api/users` and a method of `POST`. Make sure to have a
|
||||||
payload like:
|
payload like:
|
||||||
|
|
||||||
```json
|
```json Request body
|
||||||
{
|
{
|
||||||
"id": "2",
|
"id": "2",
|
||||||
"name": "TestUserName"
|
"name": "TestUserName"
|
||||||
@@ -59,7 +60,7 @@ payload like:
|
|||||||
|
|
||||||
You should receive the same thing back:
|
You should receive the same thing back:
|
||||||
|
|
||||||
```json
|
```json Response body
|
||||||
{ "id": "2", "name": "TestUserName" }
|
{ "id": "2", "name": "TestUserName" }
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -82,7 +83,7 @@ export const handler: Handlers<User | null> = {
|
|||||||
Let's practice retrieving our user! A `GET` request to
|
Let's practice retrieving our user! A `GET` request to
|
||||||
`http://localhost:8000/api/users/2` should return:
|
`http://localhost:8000/api/users/2` should return:
|
||||||
|
|
||||||
```json
|
```json Response body
|
||||||
{ "id": "2", "name": "TestUserName" }
|
{ "id": "2", "name": "TestUserName" }
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -116,7 +117,7 @@ export const handler: Handlers<User | null> = {
|
|||||||
Time to change their name. We'll now `PUT` a request to
|
Time to change their name. We'll now `PUT` a request to
|
||||||
`http://localhost:8000/api/users/2` like:
|
`http://localhost:8000/api/users/2` like:
|
||||||
|
|
||||||
```json
|
```json Request body
|
||||||
{
|
{
|
||||||
"id": "2",
|
"id": "2",
|
||||||
"name": "New Name"
|
"name": "New Name"
|
||||||
@@ -125,14 +126,14 @@ Time to change their name. We'll now `PUT` a request to
|
|||||||
|
|
||||||
We should receive:
|
We should receive:
|
||||||
|
|
||||||
```json
|
```json Response body
|
||||||
{ "id": "2", "name": "New Name" }
|
{ "id": "2", "name": "New Name" }
|
||||||
```
|
```
|
||||||
|
|
||||||
If, on the other hand, we chose to implement this as a `PATCH` operation, the
|
If, on the other hand, we chose to implement this as a `PATCH` operation, the
|
||||||
request would just involve the changed property like this:
|
request would just involve the changed property like this:
|
||||||
|
|
||||||
```json
|
```json Response body
|
||||||
{
|
{
|
||||||
"name": "New Name"
|
"name": "New Name"
|
||||||
}
|
}
|
||||||
@@ -161,7 +162,7 @@ export const handler: Handlers<User | null> = {
|
|||||||
Try sending `DELETE` to `http://localhost:8000/api/users/2` without a body.
|
Try sending `DELETE` to `http://localhost:8000/api/users/2` without a body.
|
||||||
We'll get back:
|
We'll get back:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
user 2 deleted
|
user 2 deleted
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -174,9 +175,9 @@ request checks for complex CORS use cases. See more on the
|
|||||||
## Full File Reference
|
## Full File Reference
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>[id].ts</summary>
|
<summary><code>[id].ts</code></summary>
|
||||||
|
|
||||||
```ts
|
```ts routes/api/users/[id].ts
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
type User = {
|
type User = {
|
||||||
@@ -218,9 +219,9 @@ export const handler: Handlers<User | null> = {
|
|||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>index.ts</summary>
|
<summary><code>index.ts</code></summary>
|
||||||
|
|
||||||
```ts
|
```ts routes/api/users/index.ts
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
type User = {
|
type User = {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ Now if we hit the server with a request like
|
|||||||
`http://localhost:8000/x/bestModule@1.33.7/asdf`, then logging the params will
|
`http://localhost:8000/x/bestModule@1.33.7/asdf`, then logging the params will
|
||||||
show the following:
|
show the following:
|
||||||
|
|
||||||
```
|
```txt Console output
|
||||||
{
|
{
|
||||||
module: "bestModule",
|
module: "bestModule",
|
||||||
version: "1.33.7",
|
version: "1.33.7",
|
||||||
@@ -66,18 +66,18 @@ Values are available via `params.resource` and `params.id`.
|
|||||||
|
|
||||||
Here are some example URLs that match this:
|
Here are some example URLs that match this:
|
||||||
|
|
||||||
- /api/db/bar/1
|
- `/api/db/bar/1`
|
||||||
- /api/db/jobs/1
|
- `/api/db/jobs/1`
|
||||||
- /api/db/job/1
|
- `/api/db/job/1`
|
||||||
- /api/db/job
|
- `/api/db/job`
|
||||||
- /api/db/jobs
|
- `/api/db/jobs`
|
||||||
- /api/db/bar
|
- `/api/db/bar`
|
||||||
|
|
||||||
Here are some that don't:
|
Here are some that don't:
|
||||||
|
|
||||||
- /api/db/other/123
|
- `/api/db/other/123`
|
||||||
- /api/db/jobs/abc
|
- `/api/db/jobs/abc`
|
||||||
- /api/db
|
- `/api/db`
|
||||||
|
|
||||||
## Regex
|
## Regex
|
||||||
|
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ have access to the complicated initialization step by calling
|
|||||||
|
|
||||||
When you run `deno task start` you should see the following output:
|
When you run `deno task start` you should see the following output:
|
||||||
|
|
||||||
```
|
```txt Terminal output
|
||||||
Task start deno run -A --watch=static/,routes/ dev.ts
|
Task start deno run -A --watch=static/,routes/ dev.ts
|
||||||
Watcher Process started.
|
Watcher Process started.
|
||||||
i'm logged during initialization, and not during handling!
|
i'm logged during initialization, and not during handling!
|
||||||
@@ -98,7 +98,7 @@ The manifest has been generated for 6 routes and 1 islands.
|
|||||||
|
|
||||||
Going to `http://localhost:8000/` should produce:
|
Going to `http://localhost:8000/` should produce:
|
||||||
|
|
||||||
```
|
```txt Terminal output
|
||||||
i'm logged during a request!
|
i'm logged during a request!
|
||||||
Context { complicatedStartupValue: 42 }
|
Context { complicatedStartupValue: 42 }
|
||||||
```
|
```
|
||||||
@@ -107,7 +107,7 @@ Context { complicatedStartupValue: 42 }
|
|||||||
|
|
||||||
When you run `deno task build` you should see:
|
When you run `deno task build` you should see:
|
||||||
|
|
||||||
```
|
```txt Terminal output
|
||||||
Task build deno run -A dev.ts build
|
Task build deno run -A dev.ts build
|
||||||
i'm logged during initialization, and not during handling!
|
i'm logged during initialization, and not during handling!
|
||||||
The manifest has been generated for 6 routes and 1 islands.
|
The manifest has been generated for 6 routes and 1 islands.
|
||||||
@@ -121,7 +121,7 @@ initialization occurred.
|
|||||||
|
|
||||||
Finally when you run `deno task preview` you should see:
|
Finally when you run `deno task preview` you should see:
|
||||||
|
|
||||||
```
|
```txt Terminal output
|
||||||
Task preview deno run -A main.ts
|
Task preview deno run -A main.ts
|
||||||
i'm logged during initialization, and not during handling!
|
i'm logged during initialization, and not during handling!
|
||||||
Using snapshot found at /Users/reed/code/temp/1763/_fresh
|
Using snapshot found at /Users/reed/code/temp/1763/_fresh
|
||||||
@@ -132,7 +132,7 @@ Using snapshot found at /Users/reed/code/temp/1763/_fresh
|
|||||||
|
|
||||||
Going to `http://localhost:8000/` should produce:
|
Going to `http://localhost:8000/` should produce:
|
||||||
|
|
||||||
```
|
```txt Terminal output
|
||||||
i'm logged during a request!
|
i'm logged during a request!
|
||||||
Context { complicatedStartupValue: 42 }
|
Context { complicatedStartupValue: 42 }
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -121,9 +121,9 @@ That's it! Now you can use Tailwind CSS in your project.
|
|||||||
> apply. In other words, to use dynamic classes, you need to ensure that they
|
> apply. In other words, to use dynamic classes, you need to ensure that they
|
||||||
> are present in the final CSS file.
|
> are present in the final CSS file.
|
||||||
>
|
>
|
||||||
> | Twind | Tailwind CSS |
|
> | Twind | Tailwind CSS |
|
||||||
> | --------------------------------- | ------------------------------------------------------------ |
|
> | ----------------------------------- | -------------------------------------------------------------- |
|
||||||
> | `<a class={`link-${color}`}></a>` | `<a class={color === 'blue' ?`link-blue`:`link-green`}></a>` |
|
> | ``<a class={`link-${color}`}></a>`` | ``<a class={color === 'blue' ?`link-blue`:`link-green`}></a>`` |
|
||||||
|
|
||||||
## Frequently Asked Questions (FAQ)
|
## Frequently Asked Questions (FAQ)
|
||||||
|
|
||||||
|
|||||||
@@ -43,30 +43,30 @@ You might end up with duplicate tags, when multiple `<Head />` components are
|
|||||||
rendered on the same page. This can happen when you render `<Head />` in a route
|
rendered on the same page. This can happen when you render `<Head />` in a route
|
||||||
and another `<Head />` in another component for example.
|
and another `<Head />` in another component for example.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page-a.tsx
|
||||||
// routes/page-a.tsx
|
|
||||||
<Head>
|
<Head>
|
||||||
<meta name="og:title" content="This is a title" />
|
<meta name="og:title" content="This is a title" />
|
||||||
</Head>
|
</Head>;
|
||||||
|
```
|
||||||
|
|
||||||
// components/MyTitle.tsx
|
```tsx components/MyTitle.tsx
|
||||||
<Head>
|
<Head>
|
||||||
<meta name="og:title" content="Other title" />
|
<meta name="og:title" content="Other title" />
|
||||||
</Head>
|
</Head>;
|
||||||
```
|
```
|
||||||
|
|
||||||
To ensure that the tag is not duplicated, Fresh supports setting the `key` prop.
|
To ensure that the tag is not duplicated, Fresh supports setting the `key` prop.
|
||||||
By giving matching elements the same `key` prop, only the last one will be
|
By giving matching elements the same `key` prop, only the last one will be
|
||||||
rendered.
|
rendered.
|
||||||
|
|
||||||
```diff
|
```diff routes/page-a.tsx
|
||||||
// routes/page-a.tsx
|
|
||||||
<Head>
|
<Head>
|
||||||
- <meta name="og:title" content="This is a title" />
|
- <meta name="og:title" content="This is a title" />
|
||||||
+ <meta name="og:title" content="This is a title" key="title" />
|
+ <meta name="og:title" content="This is a title" key="title" />
|
||||||
</Head>
|
</Head>
|
||||||
|
```
|
||||||
|
|
||||||
// components/MyTitle.tsx
|
```diff components/MyTitle.tsx
|
||||||
<Head>
|
<Head>
|
||||||
- <meta name="og:title" content="Other title" />
|
- <meta name="og:title" content="Other title" />
|
||||||
+ <meta name="og:title" content="Other title" key="title" />
|
+ <meta name="og:title" content="Other title" key="title" />
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ description: testFromText
|
|||||||
|
|
||||||
You'll also need to import the `Github Flavored Markdown` module:
|
You'll also need to import the `Github Flavored Markdown` module:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
deno add jsr:@deno/gfm
|
deno add jsr:@deno/gfm
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ you trust.
|
|||||||
Suppose we need to add some microdata markup to a page. The following will
|
Suppose we need to add some microdata markup to a page. The following will
|
||||||
result in **escaped characters, and will not work**:
|
result in **escaped characters, and will not work**:
|
||||||
|
|
||||||
```tsx
|
```tsx components/json-ld.tsx
|
||||||
const json = `
|
const json = `
|
||||||
{
|
{
|
||||||
"@context": "http://schema.org",
|
"@context": "http://schema.org",
|
||||||
@@ -40,7 +40,7 @@ export default function JsonLd() {
|
|||||||
|
|
||||||
Instead, we can use `dangerouslySetInnerHTML`:
|
Instead, we can use `dangerouslySetInnerHTML`:
|
||||||
|
|
||||||
```tsx
|
```tsx components/json-ld.tsx
|
||||||
export default function JsonLd() {
|
export default function JsonLd() {
|
||||||
return (
|
return (
|
||||||
<script
|
<script
|
||||||
@@ -57,7 +57,7 @@ Syntax highlighters parse strings into HTML tags, allowing them to be
|
|||||||
individually styled with CSS. We can build a simple Preact syntax highlighter
|
individually styled with CSS. We can build a simple Preact syntax highlighter
|
||||||
like so:
|
like so:
|
||||||
|
|
||||||
```tsx
|
```tsx components/code.tsx
|
||||||
import Prism from "https://esm.sh/prismjs@1.29.0";
|
import Prism from "https://esm.sh/prismjs@1.29.0";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ export default function Counter(props: CounterProps) {
|
|||||||
Note how `useSignal` is within the `Counter` component. Then if we instantiate
|
Note how `useSignal` is within the `Counter` component. Then if we instantiate
|
||||||
some counters like this...
|
some counters like this...
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
<Counter start={3} />
|
<Counter start={3} />
|
||||||
<Counter start={4} />
|
<Counter start={4} />
|
||||||
```
|
```
|
||||||
@@ -179,7 +179,7 @@ function CartItem(props: CartItemProps) {
|
|||||||
|
|
||||||
Now we can add the islands to our site by doing the following:
|
Now we can add the islands to our site by doing the following:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/cart.tsx
|
||||||
<AddToCart product="Lemon" />
|
<AddToCart product="Lemon" />
|
||||||
<AddToCart product="Lime" />
|
<AddToCart product="Lime" />
|
||||||
<Cart />
|
<Cart />
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ Fresh's CSP implementation supports the following
|
|||||||
<details>
|
<details>
|
||||||
<summary>directives</summary>
|
<summary>directives</summary>
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export interface ContentSecurityPolicyDirectives {
|
export interface ContentSecurityPolicyDirectives {
|
||||||
// Fetch directives
|
// Fetch directives
|
||||||
/**
|
/**
|
||||||
@@ -175,7 +175,7 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
|
|
||||||
We can hit `http://localhost:8000/noCSP` and we should see the following:
|
We can hit `http://localhost:8000/noCSP` and we should see the following:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
This page doesn't use CSP at all. Styles will be applied.
|
This page doesn't use CSP at all. Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -212,7 +212,7 @@ export const config: RouteConfig = {
|
|||||||
|
|
||||||
We can hit `http://localhost:8000/incorrectCSP` and we should see the following:
|
We can hit `http://localhost:8000/incorrectCSP` and we should see the following:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
This page violates our configured CSP. Styles won't be applied.
|
This page violates our configured CSP. Styles won't be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -247,7 +247,7 @@ export const config: RouteConfig = {
|
|||||||
|
|
||||||
We can hit `http://localhost:8000/correctCSP` and we should see the following:
|
We can hit `http://localhost:8000/correctCSP` and we should see the following:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
This page adheres to our configured CSP. Styles will be applied.
|
This page adheres to our configured CSP. Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -282,7 +282,7 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
We can hit `http://localhost:8000/cspNoRouteConfig` and we should see the
|
We can hit `http://localhost:8000/cspNoRouteConfig` and we should see the
|
||||||
following:
|
following:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
This page violates our configured CSP. But we don't have a RouteConfig enabled, so Fresh doesn't know to use the CSP. Styles will be applied.
|
This page violates our configured CSP. But we don't have a RouteConfig enabled, so Fresh doesn't know to use the CSP. Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -342,7 +342,7 @@ export const handler = {
|
|||||||
We can hit `http://localhost:8000/incorrectCSPwithReport` and we should see the
|
We can hit `http://localhost:8000/incorrectCSPwithReport` and we should see the
|
||||||
following:
|
following:
|
||||||
|
|
||||||
```txt
|
```txt Response body
|
||||||
This page violates our configured CSP. But we're using "reportOnly". Styles will be applied.
|
This page violates our configured CSP. But we're using "reportOnly". Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -36,12 +36,7 @@ export default defineConfig({
|
|||||||
|
|
||||||
Let's bump that up to v1:
|
Let's bump that up to v1:
|
||||||
|
|
||||||
```diff
|
```diff fresh.config.ts
|
||||||
diff --git a/fresh.config.ts b/fresh.config.ts
|
|
||||||
index 548e16a..e00d557 100644
|
|
||||||
--- a/fresh.config.ts
|
|
||||||
+++ b/fresh.config.ts
|
|
||||||
@@ -1,5 +1,5 @@
|
|
||||||
import { defineConfig } from "$fresh/server.ts";
|
import { defineConfig } from "$fresh/server.ts";
|
||||||
-import twindPlugin from "$fresh/plugins/twind.ts";
|
-import twindPlugin from "$fresh/plugins/twind.ts";
|
||||||
+import twindPlugin from "$fresh/plugins/twindv1.ts";
|
+import twindPlugin from "$fresh/plugins/twindv1.ts";
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ ok | 1 passed (3 steps) | 0 failed (236ms)
|
|||||||
|
|
||||||
This function is typed as follows:
|
This function is typed as follows:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export async function createHandler(
|
export async function createHandler(
|
||||||
manifest: Manifest,
|
manifest: Manifest,
|
||||||
config: FreshConfig = {},
|
config: FreshConfig = {},
|
||||||
@@ -107,7 +107,7 @@ free to provide your own bag of options.
|
|||||||
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) is declared
|
[`FreshConfig`](https://deno.land/x/fresh/server.ts?s=FreshConfig) is declared
|
||||||
as follows:
|
as follows:
|
||||||
|
|
||||||
```ts
|
```ts fresh 🍋
|
||||||
export interface FreshConfig {
|
export interface FreshConfig {
|
||||||
build?: {
|
build?: {
|
||||||
outDir?: string;
|
outDir?: string;
|
||||||
|
|||||||
@@ -834,3 +834,10 @@ ol.nested li:before {
|
|||||||
.highlight-source-yml .string {
|
.highlight-source-yml .string {
|
||||||
color: var(--color-prettylights-syntax-string);
|
color: var(--color-prettylights-syntax-string);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.markdown-body pre.highlight-source-txt-files {
|
||||||
|
line-height: 1.35;
|
||||||
|
}
|
||||||
|
.highlight-source-txt-files .function {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ const LOGOS = [
|
|||||||
text: "Markdown",
|
text: "Markdown",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
lang: /^txt$/,
|
lang: /^txt(-files)?$/,
|
||||||
file: /\.txt$/,
|
file: /\.txt$/,
|
||||||
src: asset("/logos/text.svg"),
|
src: asset("/logos/text.svg"),
|
||||||
text: "Text",
|
text: "Text",
|
||||||
|
|||||||
@@ -6,5 +6,44 @@ import "prismjs/components/prism-diff.js";
|
|||||||
import "prismjs/components/prism-json.js";
|
import "prismjs/components/prism-json.js";
|
||||||
import "prismjs/components/prism-bash.js";
|
import "prismjs/components/prism-bash.js";
|
||||||
import "prismjs/components/prism-yaml.js";
|
import "prismjs/components/prism-yaml.js";
|
||||||
|
import "prismjs/components/prism-ignore.js";
|
||||||
|
|
||||||
|
/** Extends `sh` with `deno` as a function token in Shell/Bash languages */
|
||||||
|
Prism.languages.sh.deno = {
|
||||||
|
pattern: /(^|[\s;|&]|[<>]\()(?:deno)(?=$|[)\s;|&])/,
|
||||||
|
lookbehind: true,
|
||||||
|
alias: "function",
|
||||||
|
};
|
||||||
|
Prism.languages.bash.deno = Prism.languages.sh.deno;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds `txt-files` language for file-structure code blocks.
|
||||||
|
*
|
||||||
|
* - Comments: Makes `#` and everything after a comment
|
||||||
|
* - Operator: Matches the file structure symbols like `├──`, `└──`, and `│ `
|
||||||
|
* - Root: Matches `<root>` or `<project root>` to indicate the root of the file structure
|
||||||
|
* - Remaining text is rendered as plain text
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```txt-files
|
||||||
|
* <project root>
|
||||||
|
* ├── routes/ # File system based routes
|
||||||
|
* │ ├── _app.tsx # Renders the outer <html> content structure
|
||||||
|
* │ └── index.tsx # Renders /
|
||||||
|
* ├── dev.ts # Run this during development
|
||||||
|
* └── main.ts # Run this for production
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
Prism.languages["txt-files"] = {
|
||||||
|
comment: {
|
||||||
|
pattern: /#.*|$/,
|
||||||
|
greedy: true,
|
||||||
|
},
|
||||||
|
operator: /├──|└──|│\s+ /,
|
||||||
|
root: {
|
||||||
|
pattern: /<root>|<project root>/,
|
||||||
|
alias: "function",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
export { Prism };
|
export { Prism };
|
||||||
|
|||||||
Reference in New Issue
Block a user