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:
Christian Svensson
2025-08-01 09:07:42 +02:00
committed by GitHub
parent 1cecb372a6
commit a2de5154ec
57 changed files with 280 additions and 214 deletions
+1 -1
View File
@@ -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
represents the children of this component.
```tsx
```tsx main.tsx
function AppWrapper({ Component }) {
return (
<html lang="en">
+16 -8
View File
@@ -9,32 +9,40 @@ expliciteness of types, other's like the convenience of `define.*` helpers.
Without define helpers:
```ts
interface State {
```ts util.ts
export interface State {
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);
}
async function otherMiddleware(ctx: Context<State>): Promise<Response> {
export async function otherMiddleware(ctx: Context<State>): Promise<Response> {
return new Response("other " + ctx.state.foo);
}
```
With define helpers:
```ts
```ts util.ts
// 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
const myMiddleware = define.middleware((ctx) => {
export const myMiddleware = define.middleware((ctx) => {
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);
});
```
+5 -5
View File
@@ -20,7 +20,7 @@ Fresh supports two kind of error pages:
To add an error page use [`app.onError()`](/docs/canary/concepts/app#onerror).
```ts
```ts main.ts
const app = new App()
.onError("*", (ctx) => {
console.log(`Error: ${ctx.error}`);
@@ -36,7 +36,7 @@ will be invoked.
You can also nest error pages:
```ts
```ts main.ts
const app = new App()
// Top level error page
.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()`
handler, Fresh ensures that every 404 error will invoke this callback.
```ts
```ts main.ts
const app = new App()
// Top level error page
.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
error code, you can use Fresh's `HttpError` class.
```ts
```ts middleware/auth.ts
import { HttpError } from "fresh";
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:
```ts
```ts main.ts
app.onError((ctx) => {
if (ctx.error instanceof HttpError) {
const status = ctx.error.status;
+4 -4
View File
@@ -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
represents the children of this component.
```tsx
```tsx main.tsx
function PageLayout({ Component }) {
return (
<div>
@@ -25,7 +25,7 @@ const app = new App()
If you browse to the `/` route, Fresh will render the following HTML
```html
```html Response body
<div>
<h1>hello world</h1>
<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.
```ts
```ts main.ts
app.layout("/foo/bar", MyComponent, { skipInheritedLayouts: true });
```
Ignore the app wrapper component:
```ts
```ts main.ts
app.layout("/foo/bar", MyComponent, { skipAppWrapper: true });
```
+3 -3
View File
@@ -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
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" 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
UI which displays log messages or similar list-like data.
```tsx
```tsx routes/log.tsx
export default function LogView() {
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
`f-client-nav={false}` on the element or one of the ancestor elements.
```tsx
```tsx routes/_app.tsx
<body f-client-nav>
{/* This will cause a partial navigation */}
<a href="/docs/page1">With partials</a>
+2 -2
View File
@@ -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
defined.
```tsx
```tsx main.ts
const app = new App()
.use(staticFiles())
.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
middleware _after_ a `.get()` handler, it won't be included.
```ts
```ts main.ts
const app = new App()
.use((ctx) => {
// Will be called for all middlewares
+3 -3
View File
@@ -24,7 +24,7 @@ if (Deno.args.includes("build")) {
You can customize the builder by passing options.
```ts
```ts dev.ts
const builder = new Builder({
// Browser target for generated code. Maps to https://esbuild.github.io/api/#target
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
same API that Fresh uses internally.
```ts
```ts dev.ts
const builder = new Builder();
// 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.
```ts
```ts dev.ts
builder.onTransformStaticFile({
pluginName: "My cool plugin",
filter: /\.css$/,
+9 -8
View File
@@ -36,7 +36,8 @@ const app = new App({ root: import.meta.url })
Example project structure:
```sh Project structure
```txt-files Project structure
<project root>
├── deno.json
├── main.ts
├── dev.ts
@@ -104,7 +105,7 @@ suggested by the URL segment.
Let's illustrate that with an example:
```txt
```txt Example page layout
/about -> layout A
/career -> layout A
/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
can only have one `_layout` file.
```txt Project structure
└── routes
```txt-files Project structure
└── <root>/routes
   ├── _layout.tsx # applies to all routes here :(
   ├── about.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
routes in a folder and use a different `_layout` file for each group.
```txt Project structure
└── routes
```txt-files Project structure
└── <root>/routes
   ├── (marketing)
   │ ├── _layout.tsx # only applies to about.tsx and career.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
> picked.
>
> ```txt Project structure
> └── routes
> ```txt-files Project structure
> └── <root>/routes
>    ├── (group-1)
>    │ └── about.tsx # Bad: Maps to same `/about` url
>    └── (group-2)
+6 -4
View File
@@ -28,7 +28,7 @@ export default function MyIsland() {
An island can be used anywhere like a regular Preact component. Fresh will take
care of making it interactive on the client.
```tsx
```tsx main.tsx
import MyIsland from "../islands/my-island.tsx";
const app = new App()
@@ -56,9 +56,11 @@ deserialization.
> [warn]: Passing functions to an island is not supported.
>
> ```tsx
> // WRONG
> <MyIsland onClick={() => console.log("hey")} />;
> ```tsx routes/example.tsx
> export default function () {
> // WRONG
> return <MyIsland onClick={() => console.log("hey")} />;
> }
> ```
### Passing JSX
+4 -3
View File
@@ -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
Preact component. Only one such layout is allowed per sub directory.
```txt Project structure
```txt-files Project structure
<project root>
└── routes
   ├── sub
   │ ├── 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
structure like this:
```txt Project structure
└── routes
```txt-files Project structure
└── <root>/routes
   ├── sub
   │ ├── _layout_.tsx
   │ ├── special.tsx # should not inherit layouts
+2 -2
View File
@@ -11,7 +11,7 @@ returns a
are typically used to set HTTP Headers, measure response times or fetch data and
pass it to another middleware.
```tsx
```tsx main.ts
const app = new App<{ greeting: string }>()
.use((ctx) => {
// 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:
```ts
```ts middleware/my-middleware.ts
import { define } from "./utils.ts";
const middleware = define.middleware(async (ctx) => {
+1 -1
View File
@@ -6,7 +6,7 @@ description: |
Routing defines which middlewares and routes should respond to a particular
request.
```ts
```ts main.ts
const app = new App()
.get("/", () => new Response("hello")) // Responds to: GET /
.get("/other", () => new Response("other")) // Responds to: GET /other
+13 -8
View File
@@ -9,7 +9,7 @@ disk for optimal performance with
[`ETag`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag)
headers.
```ts
```ts main.ts
import { staticFiles } from "fresh";
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
`<img>` and `<source>` tags.
```tsx
```tsx main.tsx
// 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
`data-fresh-disable-lock` attribute.
```tsx
```tsx main.tsx
// 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
@@ -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
with a cache lifetime of one year.
```tsx
```tsx routes/about.tsx
import { asset } from "fresh/runtime";
// Adding caching headers manually
<a href={asset("/brochure.pdf")}>View brochure</a>;
export default function About() {
// Adding caching headers manually
return <a href={asset("/brochure.pdf")}>View brochure</a>;
}
```
+1 -1
View File
@@ -17,7 +17,7 @@ which contains the optimized assets.
> [info]: The `_fresh` folder should not be committed to git. Exclude it via
> `.gitignore`.
>
> ```sh .gitignore
> ```gitignore .gitignore
> # Ignore fresh build directory
> _fresh/
> ```
+2 -2
View File
@@ -19,7 +19,7 @@ styling current links where applicable.
The aria-current attribute is easily styled with CSS using attribute 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 */
a[aria-current="page"] {
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.
For Tailwindcss, use the syntax:
```tsx
```tsx components/Menu.tsx
function Menu() {
return (
<a href="/foo" class="aria-[current]:text-green-600">
+5 -5
View File
@@ -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.
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
@import "tailwindcss";
+ @plugin "daisyui";
```
```diff static/styles.css
@import "tailwindcss";
+ @plugin "daisyui";
```
Now you're ready to use daisyUI.
+2 -2
View File
@@ -14,7 +14,7 @@ can transform markdown to html.
1. Run `deno install jsr:@deno/gfm`
2. Create a markdown file like `content.md`:
```md
```md path/to/content.md
## some heading
and some interesting text here
@@ -24,7 +24,7 @@ and some interesting text here
4. Add a route that renders that file
```tsx
```tsx main.ts
import { CSS, render as renderMarkdown } from "@deno/gfm";
const CONTENT = `## some heading
+23 -22
View File
@@ -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
update by running it in your project directory:
```sh
```sh Terminal
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
anymore either.
```diff
routes/
dev.ts
- fresh.gen.ts
- fresh.config.ts
main.ts
```diff Project structure
<project root>
├── routes/
├── dev.ts
- ├── fresh.gen.ts
- ├── fresh.config.ts
└── main.ts
```
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:
```ts
```ts dev.ts
import { Builder } from "fresh/dev";
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
`_error.tsx` template.
```diff
routes/
- ├── _404.tsx
- ├── _500.tsx
+ ├── _error.tsx
└── ...
```diff Project structure
└── <root>/routes/
- ├── _404.tsx
- ├── _500.tsx
+ ├── _error.tsx
└── ...
```
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`
```tsx
// about.tsx
```tsx routes/about.tsx
export const handler = {
GET(ctx) {
// Set a route specific data in a handler
@@ -138,8 +138,9 @@ export const handler = {
return page();
},
};
```
// Render that in _app.tsx
```tsx routes/_app.tsx
export default function AppWrapper(ctx: Context) {
return (
<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
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, 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`
object is stored on the context object as `ctx.req`.
```diff
```diff middleware.ts
- const middleware = (req, ctx) => new Response("ok");
+ const middleware = (ctx) => new Response("ok");
```
Same is true for handlers:
```diff
```diff route/page.tsx
export const handler = {
- GET(req, ctx) {
+ GET(ctx) {
@@ -208,7 +209,7 @@ Same is true for handlers:
...and async route components:
```diff
```diff routes/my-page.tsx
- export default async function MyPage(req: Request, ctx: RouteContext) {
+ export default async function MyPage(props: PageProps) {
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
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
// performance reasons.
const builder = new Builder();
+2 -2
View File
@@ -10,13 +10,13 @@ situations.
To address this you can render raw HTML via Preact's `dangerouslySetInnerHTML`
prop:
```tsx
```tsx routes/dynamic-html.tsx
<div dangerouslySetInnerHTML={{ __html: "<h1>This is raw HTML</h1>" }} />;
```
This will output:
```html
```html Response body
<div>
<h1>This is raw HTML</h1>
</div>
+2 -2
View File
@@ -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 folder should look like this:
```sh Project structure
<project dir>
```txt-files Project structure
<project root>
├── islands/ # Components that need JS to run client-side
│ └── Counter.tsx
├── routes/ # File system based routes
+1 -1
View File
@@ -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
web applications.
```tsx
```tsx main.tsx
import { App } from "fresh";
const app = new App()
+1 -1
View File
@@ -7,7 +7,7 @@ The `cors()` middleware can be used to add
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.
```ts
```ts main.ts
import { cors } from "fresh";
const app = new App()
+1 -1
View File
@@ -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
from.
```ts
```ts main.ts
const app = new App();
app.use(csrf());
+1 -1
View File
@@ -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
go.
```ts
```ts middleware/fresh.ts
const addXFreshHeader = define.middleware(async (ctx) => {
const res = await ctx.next();
res.headers.set("X-Fresh", "served by Fresh");
+1 -1
View File
@@ -41,7 +41,7 @@ For more information on how to use tailwindcss, check out
You can customize the tailwind plugin via the following options:
```ts
```ts dev.ts
tailwind(builder, app, {
// Exclude certain files from processing
exclude: ["/admin/**", "*.temp.css"],
+2 -2
View File
@@ -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
request respectively.
```ts
```ts main.ts
import { trailingSlashes } from "fresh";
const app = new App()
@@ -16,7 +16,7 @@ const app = new App()
Always append a trailing slash:
```ts
```ts main.ts
import { trailingSlashes } from "fresh";
const app = new App()
+3 -3
View File
@@ -13,7 +13,7 @@ write tests.
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.
```ts
```ts middleware.test.ts
import { expect } from "@std/expect";
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
[layouts](/docs/canary/advanced/layouts) can be tested in the same way.
```tsx
```tsx routes/_app.test.tsx
import { expect } from "@std/expect";
import { App } from "fresh";
@@ -77,7 +77,7 @@ Deno.test("App Wrapper - renders title and content", async () => {
Same can be done for layouts.
```tsx
```tsx routes/_layout.test.tsx
import { expect } from "@std/expect";
import { App } from "fresh";