www: new fenced code block design (#1629)
This commit is contained in:
Vendored
+1
-2
@@ -15,7 +15,6 @@
|
|||||||
"@preact/signals-core@1.3.0": "https://esm.sh/@preact/signals-core@1.3.0",
|
"@preact/signals-core@1.3.0": "https://esm.sh/@preact/signals-core@1.3.0",
|
||||||
"$std/": "https://deno.land/std@0.193.0/",
|
"$std/": "https://deno.land/std@0.193.0/",
|
||||||
"$ga4": "https://raw.githubusercontent.com/denoland/ga4/main/mod.ts",
|
"$ga4": "https://raw.githubusercontent.com/denoland/ga4/main/mod.ts",
|
||||||
"$marked-mangle": "https://esm.sh/marked-mangle@1.0.1",
|
"$marked-mangle": "https://esm.sh/marked-mangle@1.0.1"
|
||||||
"$marked-smartypants": "https://esm.sh/marked-smartypants@1.0.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,8 +17,7 @@ special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
|||||||
properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
|
properties, e.g. `ctx.state.loggedIn = true`, but you can also replace the
|
||||||
entire object like `ctx.state = { loggedIn = true }`.
|
entire object like `ctx.state = { loggedIn = true }`.
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
// routes/_middleware.ts
|
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
interface State {
|
interface State {
|
||||||
@@ -27,7 +26,7 @@ interface State {
|
|||||||
|
|
||||||
export async function handler(
|
export async function handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext<State>,
|
ctx: MiddlewareHandlerContext<State>
|
||||||
) {
|
) {
|
||||||
ctx.state.data = "myData";
|
ctx.state.data = "myData";
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
@@ -36,8 +35,7 @@ export async function handler(
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts routes/myHandler.ts
|
||||||
// routes/myHandler.ts
|
|
||||||
export const handler: Handlers<any, { data: string }> = {
|
export const handler: Handlers<any, { data: string }> = {
|
||||||
GET(_req, ctx) {
|
GET(_req, ctx) {
|
||||||
return new Response(`middleware data is ${ctx.state.data}`);
|
return new Response(`middleware data is ${ctx.state.data}`);
|
||||||
@@ -52,7 +50,7 @@ specific first).
|
|||||||
|
|
||||||
For example, take a project with the following routes:
|
For example, take a project with the following routes:
|
||||||
|
|
||||||
```
|
```txt Project Structure
|
||||||
└── routes
|
└── routes
|
||||||
├── _middleware.ts
|
├── _middleware.ts
|
||||||
├── index.ts
|
├── index.ts
|
||||||
@@ -85,9 +83,7 @@ A single middleware file can also define multiple middlewares (all for the same
|
|||||||
route) by exporting an array of handlers instead of a single handler. For
|
route) by exporting an array of handlers instead of a single handler. For
|
||||||
example:
|
example:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
// routes/_middleware.ts
|
|
||||||
|
|
||||||
export const handler = [
|
export const handler = [
|
||||||
async function middleware1(req, ctx) {
|
async function middleware1(req, ctx) {
|
||||||
// do something
|
// do something
|
||||||
@@ -103,7 +99,7 @@ export const handler = [
|
|||||||
It should be noted that `middleware` has access to route parameters. If you're
|
It should be noted that `middleware` has access to route parameters. If you're
|
||||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||||
|
|
||||||
```ts
|
```ts routes/[tenant]/admin/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
@@ -148,7 +144,7 @@ for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
|
|||||||
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
||||||
create a `_middleware.ts` file in the `routes` folder like this:
|
create a `_middleware.ts` file in the `routes` folder like this:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
@@ -161,7 +157,7 @@ export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
|||||||
|
|
||||||
If you start up your server (`deno task start`) you'll see the following:
|
If you start up your server (`deno task start`) you'll see the following:
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
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.
|
||||||
The manifest has been generated for 4 routes and 1 islands.
|
The manifest has been generated for 4 routes and 1 islands.
|
||||||
|
|||||||
@@ -20,13 +20,13 @@ 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
|
```txt Project structure
|
||||||
/routes
|
└── routes
|
||||||
/_layout.tsx <-- applies to all routes here :(
|
├── _layout.tsx # applies to all routes here :(
|
||||||
/about.tsx
|
├── about.tsx
|
||||||
/career.tsx
|
├── career.tsx
|
||||||
/archive.tsx
|
├── archive.tsx
|
||||||
/contact.tsx
|
└── contact.tsx
|
||||||
```
|
```
|
||||||
|
|
||||||
We can solve this problem with route groups. A route group is a folder which has
|
We can solve this problem with route groups. A route group is a folder which has
|
||||||
@@ -34,25 +34,25 @@ a name that is wrapped in braces. For example `(pages)` would be considered a
|
|||||||
route and so would be `(marketing)`. This enables us to group related routes in
|
route and so would be `(marketing)`. This enables us to group related routes in
|
||||||
a folder and use a different `_layout` file for each group.
|
a folder and use a different `_layout` file for each group.
|
||||||
|
|
||||||
```txt
|
```txt Project structure
|
||||||
/routes
|
└── 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
|
||||||
/career.tsx
|
│ └── career.tsx
|
||||||
/(info)
|
└── (info)
|
||||||
/_layout.tsx <-- only applies to archive.tsx and contact.tsx
|
├── _layout.tsx # only applies to archive.tsx and contact.tsx
|
||||||
/archive.tsx
|
├── archive.tsx
|
||||||
/contact.tsx
|
└── contact.tsx
|
||||||
```
|
```
|
||||||
|
|
||||||
> ℹ️ Be careful about routes in different groups which match to the same URL.
|
> ℹ️ Be careful about routes in different groups which match to the same URL.
|
||||||
> Such scenarios will lead to ambiguity as to which route file should be picked.
|
> Such scenarios will lead to ambiguity as to which route file should be picked.
|
||||||
>
|
>
|
||||||
> ```txt
|
> ```txt Project structure
|
||||||
> /routes
|
> └── routes
|
||||||
> /(group-1)
|
> ├── (group-1)
|
||||||
> /about.tsx <-- Bad: Both routes map to the same `/about` url
|
> │ └── about.tsx # Bad: Maps to same `/about` url
|
||||||
> /(group-2)
|
> └── (group-2)
|
||||||
> /about.tsx <-- Bad: Both routes map to the same `/about` url
|
> └── about.tsx # Bad: Maps to same `/about` url
|
||||||
> ```
|
> ```
|
||||||
|
|||||||
@@ -7,16 +7,16 @@ An route layout is defined in a `_layout.tsx` file in any sub directory (at any
|
|||||||
level) under the `routes/` folder. It must contain a default export that is a
|
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.
|
regular Preact component. Only one such layout is allowed per sub directory.
|
||||||
|
|
||||||
```sh
|
```txt Project structure
|
||||||
routes/
|
└── routes
|
||||||
_app.tsx
|
├── sub
|
||||||
_layout.tsx # will be applied to all routes
|
│ ├── page.tsx
|
||||||
/sub
|
│ └── index.tss
|
||||||
index.tsx
|
├── other
|
||||||
page.tsx
|
│ ├── _layout.tsx # will be applied on top of `routes/_layout.tsx`
|
||||||
/other
|
│ └── page.tsx
|
||||||
_layout.tsx # will be applied on top of `routes/_layout.tsx`
|
├── _layout.tsx # will be applied to all routes
|
||||||
page.tsx
|
└── _app.tsx
|
||||||
```
|
```
|
||||||
|
|
||||||
The component to be wrapped is received via props, in addition to a few other
|
The component to be wrapped is received via props, in addition to a few other
|
||||||
@@ -24,9 +24,7 @@ things. This allows for the introduction of a global container functioning as a
|
|||||||
template which can be conditioned based on state and params. Note that any state
|
template which can be conditioned based on state and params. Note that any state
|
||||||
set by middleware is available via `props.state`.
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/sub/_layout.tsx
|
||||||
// routes/sub/_layout.tsx
|
|
||||||
|
|
||||||
import { LayoutProps } from "$fresh/server.ts";
|
import { LayoutProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function Layout({ Component, state }: LayoutProps) {
|
export default function Layout({ Component, state }: LayoutProps) {
|
||||||
@@ -45,20 +43,19 @@ 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:
|
||||||
|
|
||||||
```sh
|
```txt Project structure
|
||||||
routes/
|
└── routes
|
||||||
_layout.tsx
|
├── sub
|
||||||
/sub
|
│ ├── _layout_.tsx
|
||||||
_layout.tsx
|
│ ├── special.tsx # should not inherit layouts
|
||||||
index.tsx
|
│ └── index.tss
|
||||||
special.tsx # should not inherit layouts
|
└── _layout.tsx
|
||||||
```
|
```
|
||||||
|
|
||||||
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
To make `routes/sub/special.tsx` opt out of rendering layouts we can set
|
||||||
`rootLayout: true`.
|
`rootLayout: true`.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/sub/special.tsx
|
||||||
// routes/sub/special.tsx
|
|
||||||
import { RouteConfig } from "$fresh/server.ts";
|
import { RouteConfig } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const config: RouteConfig = {
|
export const config: RouteConfig = {
|
||||||
|
|||||||
@@ -12,9 +12,7 @@ things. This allows for the introduction of a global container functioning as a
|
|||||||
template which can be conditioned based on state and params. Note that any state
|
template which can be conditioned based on state and params. Note that any state
|
||||||
set by middleware is available via `props.state`.
|
set by middleware is available via `props.state`.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_app.tsx
|
||||||
// routes/_app.tsx
|
|
||||||
|
|
||||||
import { AppProps } from "$fresh/server.ts";
|
import { AppProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function App({ Component, state }: AppProps) {
|
export default function App({ Component, state }: AppProps) {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ component through the `data` property on the `props`.
|
|||||||
|
|
||||||
Here is an example:
|
Here is an example:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/projects/[id].tsx
|
||||||
interface Project {
|
interface Project {
|
||||||
name: string;
|
name: string;
|
||||||
stars: number;
|
stars: number;
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ caching **will** cause your project to not function correctly.
|
|||||||
|
|
||||||
Here is an example `Dockerfile` for a Fresh project:
|
Here is an example `Dockerfile` for a Fresh project:
|
||||||
|
|
||||||
```dockerfile
|
```dockerfile Dockerfile
|
||||||
FROM denoland/deno:1.35.0
|
FROM denoland/deno:1.35.0
|
||||||
|
|
||||||
ARG GIT_REVISION
|
ARG GIT_REVISION
|
||||||
@@ -53,13 +53,13 @@ CMD ["run", "-A", "main.ts"]
|
|||||||
|
|
||||||
To build your Docker image inside of a Git repository:
|
To build your Docker image inside of a Git repository:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
|
$ docker build --build-arg GIT_REVISION=$(git rev-parse HEAD) -t my-fresh-app .
|
||||||
```
|
```
|
||||||
|
|
||||||
Then run your Docker container:
|
Then run your Docker container:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
$ docker run -t -i -p 80:8000 my-fresh-app
|
$ docker run -t -i -p 80:8000 my-fresh-app
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ The 404 page can be customized by creating a `_404.tsx` file in the `routes/`
|
|||||||
folder. The file must have a default export that is a regular Preact component.
|
folder. The file must have a default export that is a regular Preact component.
|
||||||
A props object of type `UnknownPageProps` is passed in as an argument.
|
A props object of type `UnknownPageProps` is passed in as an argument.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_404.tsx
|
||||||
import { UnknownPageProps } from "$fresh/server.ts";
|
import { UnknownPageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function NotFoundPage({ url }: UnknownPageProps) {
|
export default function NotFoundPage({ url }: UnknownPageProps) {
|
||||||
@@ -29,7 +29,7 @@ In some cases, one needs to manually trigger the rendering of the 404 page, for
|
|||||||
example when the route did match, but the requested resource does not exist.
|
example when the route did match, but the requested resource does not exist.
|
||||||
This can be achieved with `ctx.renderNotFound`.
|
This can be achieved with `ctx.renderNotFound`.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/blog/[slug].tsx
|
||||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
@@ -60,7 +60,7 @@ The 500 page can be customized by creating a `_500.tsx` file in the `routes/`
|
|||||||
folder. The file must have a default export that is a regular Preact component.
|
folder. The file must have a default export that is a regular Preact component.
|
||||||
A props object of type `ErrorPageProps` is passed in as an argument.
|
A props object of type `ErrorPageProps` is passed in as an argument.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/_500.tsx
|
||||||
import { ErrorPageProps } from "$fresh/server.ts";
|
import { ErrorPageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function Error500Page({ error }: ErrorPageProps) {
|
export default function Error500Page({ error }: ErrorPageProps) {
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ or as a `POST` request with `multipart/form-data`.
|
|||||||
This example demonstrates how to handle `multipart/form-data` `<form>`
|
This example demonstrates how to handle `multipart/form-data` `<form>`
|
||||||
submissions:
|
submissions:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/subscribe.tsx
|
||||||
// routes/subscribe.tsx
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
|
|||||||
@@ -11,9 +11,7 @@ Islands are defined by creating a file in the `islands/` folder in a Fresh
|
|||||||
project. The name of this file must be a PascalCase or kebab-case name of the
|
project. The name of this file must be a PascalCase or kebab-case name of the
|
||||||
island.
|
island.
|
||||||
|
|
||||||
```tsx
|
```tsx islands/my-island.tsx
|
||||||
// islands/my-island.tsx
|
|
||||||
|
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
|
|
||||||
export default function MyIsland() {
|
export default function MyIsland() {
|
||||||
@@ -31,8 +29,7 @@ export default function MyIsland() {
|
|||||||
An island can be used in a page like a regular Preact component. Fresh will take
|
An island can be used in a page like a regular Preact component. Fresh will take
|
||||||
care of automatically re-hydrating the island on the client.
|
care of automatically re-hydrating the island on the client.
|
||||||
|
|
||||||
```tsx
|
```tsx route/index.tsx
|
||||||
// route/index.tsx
|
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
@@ -44,9 +41,7 @@ export default function Home() {
|
|||||||
|
|
||||||
Islands support passing JSX elements via the `children` property.
|
Islands support passing JSX elements via the `children` property.
|
||||||
|
|
||||||
```tsx
|
```tsx islands/my-island.tsx
|
||||||
// islands/my-island.tsx
|
|
||||||
|
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
import { ComponentChildren } from "preact";
|
import { ComponentChildren } from "preact";
|
||||||
|
|
||||||
@@ -70,8 +65,7 @@ export default function MyIsland({ children }: Props) {
|
|||||||
This allows you to pass static content rendered by the server to an island in
|
This allows you to pass static content rendered by the server to an island in
|
||||||
the browser.
|
the browser.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
// routes/index.tsx
|
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
@@ -108,10 +102,10 @@ 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
|
||||||
<!--frsh-myisland_default:default:0-->
|
<!--frsh-myisland_default:default:0-->
|
||||||
<div>
|
<div>
|
||||||
Counter is at 0.
|
Counter is at 0.
|
||||||
<button>+</button>
|
<button>+</button>
|
||||||
<!--frsh-slot-myisland_default:children-->
|
<!--frsh-slot-myisland_default:children-->
|
||||||
<p>This text is rendered on the server</p>
|
<p>This text is rendered on the server</p>
|
||||||
@@ -126,8 +120,7 @@ Islands can be nested within other islands as well. In that scenario they act
|
|||||||
like a normal Preact component, but still receive the serialized props if any
|
like a normal Preact component, but still receive the serialized props if any
|
||||||
were present.
|
were present.
|
||||||
|
|
||||||
```tsx
|
```tsx islands/other-island.tsx
|
||||||
// islands/other-island.tsx
|
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
import { ComponentChildren } from "preact";
|
import { ComponentChildren } from "preact";
|
||||||
|
|
||||||
@@ -147,8 +140,7 @@ export default function MyIsland({ children, foo }: Props) {
|
|||||||
<div>
|
<div>
|
||||||
<p>String from props: {foo}</p>
|
<p>String from props: {foo}</p>
|
||||||
<p>
|
<p>
|
||||||
<button onClick={() => number.value = randomNumber()}>Random</button>
|
<button onClick={() => (number.value = randomNumber())}>Random</button>{" "}
|
||||||
{" "}
|
|
||||||
number is: {number}.
|
number is: {number}.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -160,8 +152,7 @@ In essence, Fresh allows you to mix static and interactive parts in your app in
|
|||||||
a way that's most optimal for your use app. We'll keep sending only the
|
a way that's most optimal for your use app. We'll keep sending only the
|
||||||
JavaScript that is needed for the islands to the browser.
|
JavaScript that is needed for the islands to the browser.
|
||||||
|
|
||||||
```tsx
|
```tsx route/index.tsx
|
||||||
// route/index.tsx
|
|
||||||
import MyIsland from "../islands/my-island.tsx";
|
import MyIsland from "../islands/my-island.tsx";
|
||||||
import OtherIsland from "../islands/other-island.tsx";
|
import OtherIsland from "../islands/other-island.tsx";
|
||||||
|
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ be used to pass arbitrary data to downstream (or upstream) handlers. This
|
|||||||
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
special [\_app](/docs/concepts/app-wrapper.md) wrapper and normal
|
||||||
[routes](/docs/concepts/routes.md).
|
[routes](/docs/concepts/routes.md).
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
// routes/_middleware.ts
|
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
interface State {
|
interface State {
|
||||||
@@ -25,7 +24,7 @@ interface State {
|
|||||||
|
|
||||||
export async function handler(
|
export async function handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext<State>,
|
ctx: MiddlewareHandlerContext<State>
|
||||||
) {
|
) {
|
||||||
ctx.state.data = "myData";
|
ctx.state.data = "myData";
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
@@ -34,8 +33,7 @@ export async function handler(
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts routes/myHandler.ts
|
||||||
// routes/myHandler.ts
|
|
||||||
export const handler: Handlers<any, { data: string }> = {
|
export const handler: Handlers<any, { data: string }> = {
|
||||||
GET(_req, ctx) {
|
GET(_req, ctx) {
|
||||||
return new Response(`middleware data is ${ctx.state.data}`);
|
return new Response(`middleware data is ${ctx.state.data}`);
|
||||||
@@ -50,7 +48,7 @@ specific first).
|
|||||||
|
|
||||||
For example, take a project with the following routes:
|
For example, take a project with the following routes:
|
||||||
|
|
||||||
```
|
```txt Project Structure
|
||||||
└── routes
|
└── routes
|
||||||
├── _middleware.ts
|
├── _middleware.ts
|
||||||
├── index.ts
|
├── index.ts
|
||||||
@@ -83,9 +81,7 @@ A single middleware file can also define multiple middlewares (all for the same
|
|||||||
route) by exporting an array of handlers instead of a single handler. For
|
route) by exporting an array of handlers instead of a single handler. For
|
||||||
example:
|
example:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
// routes/_middleware.ts
|
|
||||||
|
|
||||||
export const handler = [
|
export const handler = [
|
||||||
async function middleware1(req, ctx) {
|
async function middleware1(req, ctx) {
|
||||||
// do something
|
// do something
|
||||||
@@ -101,7 +97,7 @@ export const handler = [
|
|||||||
It should be noted that `middleware` has access to route parameters. If you're
|
It should be noted that `middleware` has access to route parameters. If you're
|
||||||
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
running a fictitious `routes/[tenant]/admin/_middleware.ts` like this:
|
||||||
|
|
||||||
```ts
|
```ts routes/[tenant]/admin/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
@@ -146,7 +142,7 @@ for a `route`, as opposed to something like `http://localhost:8001/favicon.ico`.
|
|||||||
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
Initiate a new Fresh project (`deno run -A -r https://fresh.deno.dev/`) and then
|
||||||
create a `_middleware.ts` file in the `routes` folder like this:
|
create a `_middleware.ts` file in the `routes` folder like this:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
@@ -159,7 +155,7 @@ export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
|||||||
|
|
||||||
If you start up your server (`deno task start`) you'll see the following:
|
If you start up your server (`deno task start`) you'll see the following:
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
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.
|
||||||
The manifest has been generated for 4 routes and 1 islands.
|
The manifest has been generated for 4 routes and 1 islands.
|
||||||
|
|||||||
@@ -6,9 +6,7 @@ Plugins can dynamically add new functionality to Fresh without exposing
|
|||||||
significant complexity to the user. Users can add plugins by importing and
|
significant complexity to the user. Users can add plugins by importing and
|
||||||
initializing them in their `main.ts` file:
|
initializing them in their `main.ts` file:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
// main.ts
|
|
||||||
|
|
||||||
import { start } from "$fresh/server.ts";
|
import { start } from "$fresh/server.ts";
|
||||||
import manifest from "./fresh.gen.ts";
|
import manifest from "./fresh.gen.ts";
|
||||||
|
|
||||||
|
|||||||
@@ -25,9 +25,7 @@ the handler's `render` function.
|
|||||||
|
|
||||||
Let's look at a basic route that returns a plain text string:
|
Let's look at a basic route that returns a plain text string:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/plain.tsx
|
||||||
// routes/plain.tsx
|
|
||||||
|
|
||||||
import { HandlerContext, Handlers } from "$fresh/server.ts";
|
import { HandlerContext, Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
@@ -48,9 +46,7 @@ have a corresponding handler, a 405 HTTP error is returned.
|
|||||||
|
|
||||||
Now, let's render some HTML using the route component:
|
Now, let's render some HTML using the route component:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/html.tsx
|
||||||
// routes/html.tsx
|
|
||||||
|
|
||||||
import { PageProps } from "$fresh/server.ts";
|
import { PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function Page(props: PageProps) {
|
export default function Page(props: PageProps) {
|
||||||
@@ -71,9 +67,7 @@ should work.
|
|||||||
In the below example, a custom handler is used to add a custom header to the
|
In the below example, a custom handler is used to add a custom header to the
|
||||||
response after rendering the page component.
|
response after rendering the page component.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/html.tsx
|
||||||
// routes/html.tsx
|
|
||||||
|
|
||||||
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
|
import { HandlerContext, Handlers, PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
@@ -96,7 +90,7 @@ test these in isolation, but can become a bit cumbersome to maintain. They
|
|||||||
require some additional indirection of declaring an interface for the component
|
require some additional indirection of declaring an interface for the component
|
||||||
`Data` when you're passing it around through `ctx.render()`.
|
`Data` when you're passing it around through `ctx.render()`.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page.tsx
|
||||||
interface Data {
|
interface Data {
|
||||||
foo: number;
|
foo: number;
|
||||||
}
|
}
|
||||||
@@ -117,7 +111,7 @@ When a route has both a component and a `GET` handler, they are typically very
|
|||||||
closely coupled. With async route components you can merge the two together and
|
closely coupled. With async route components you can merge the two together and
|
||||||
avoid having to create the `Data` interface boilerplate.
|
avoid having to create the `Data` interface boilerplate.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page.tsx
|
||||||
// Async route component
|
// Async route component
|
||||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||||
const value = await loadFooValue();
|
const value = await loadFooValue();
|
||||||
@@ -130,7 +124,7 @@ can think of async route components inlining the `GET` handler into the
|
|||||||
component function. Note, that you can still add additional HTTP handlers in the
|
component function. Note, that you can still add additional HTTP handlers in the
|
||||||
same file like before.
|
same file like before.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/page.tsx
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
async POST(req) {
|
async POST(req) {
|
||||||
// ... do something here
|
// ... do something here
|
||||||
@@ -148,7 +142,7 @@ export default async function MyPage(req: Request, ctx: RouteContext) {
|
|||||||
Quite often a route handler needs to render a 404 page or bail out of rendering
|
Quite often a route handler needs to render a 404 page or bail out of rendering
|
||||||
in another manner. This can be done by returning a `Response` object.
|
in another manner. This can be done by returning a `Response` object.
|
||||||
|
|
||||||
```tsx
|
```tsx route/page.tsx
|
||||||
// Async route component
|
// Async route component
|
||||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||||
const value = await loadFooValue();
|
const value = await loadFooValue();
|
||||||
|
|||||||
@@ -41,9 +41,7 @@ Advanced use-cases can require that a more complex pattern be used for matching.
|
|||||||
A custom [URL pattern][urlpattern] can be specified in the route configuration.
|
A custom [URL pattern][urlpattern] can be specified in the route configuration.
|
||||||
This pattern will be used instead of the file path based pattern:
|
This pattern will be used instead of the file path based pattern:
|
||||||
|
|
||||||
```ts
|
```ts routes/x.ts
|
||||||
// routes/x.ts
|
|
||||||
|
|
||||||
import { RouteConfig } from "$fresh/server.ts";
|
import { RouteConfig } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const config: RouteConfig = {
|
export const config: RouteConfig = {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ In this page we discuss how the server can be configured during startup.
|
|||||||
|
|
||||||
The signature of the primary method looks like this:
|
The signature of the primary method looks like this:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
export async function start(routes: Manifest, opts: StartOptions = {});
|
export async function start(routes: Manifest, opts: StartOptions = {});
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ export interface RouterOptions {
|
|||||||
See the [docs](/docs/concepts/plugins) on this topic for more detail. But for
|
See the [docs](/docs/concepts/plugins) on this topic for more detail. But for
|
||||||
completion, you can do something like this to load plugins:
|
completion, you can do something like this to load plugins:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
|||||||
This allows you to specify the location where your site's static assets are
|
This allows you to specify the location where your site's static assets are
|
||||||
stored. Here's an example:
|
stored. Here's an example:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
await start(manifest, { staticDir: "./custom_static" });
|
await start(manifest, { staticDir: "./custom_static" });
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -81,6 +81,6 @@ By default Fresh uses URLs like `https://www.example.com/about`. If you'd like,
|
|||||||
you can configure this to `https://www.example.com/about/` by using the
|
you can configure this to `https://www.example.com/about/` by using the
|
||||||
`trailingSlash` setting.
|
`trailingSlash` setting.
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
await start(manifest, { router: { trailingSlash: true } });
|
await start(manifest, { router: { trailingSlash: true } });
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ version of this path that contains a build ID for cache busting. When the asset
|
|||||||
is requested at this "locked" path, it will be served with a cache lifetime of
|
is requested at this "locked" path, it will be served with a cache lifetime of
|
||||||
one year.
|
one year.
|
||||||
|
|
||||||
```jsx
|
```jsx routes/page.tsx
|
||||||
import { asset } from "$fresh/runtime.ts";
|
import { asset } from "$fresh/runtime.ts";
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ recommended patterns for Fresh projects.
|
|||||||
To run the auto updater, run the following command from the root of your
|
To run the auto updater, run the following command from the root of your
|
||||||
project:
|
project:
|
||||||
|
|
||||||
```bash
|
```sh Terminal
|
||||||
$ deno run -A -r https://fresh.deno.dev/update .
|
$ deno run -A -r https://fresh.deno.dev/update .
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ file in the root of your projects directory. Dependency versions are encoded
|
|||||||
into the URLs in this file. For example, here is how to update a project from
|
into the URLs in this file. For example, here is how to update a project from
|
||||||
Fresh 1.0.2 to 1.1.3, and update Preact to the latest version:
|
Fresh 1.0.2 to 1.1.3, and update Preact to the latest version:
|
||||||
|
|
||||||
```diff
|
```diff deno.json
|
||||||
{
|
{
|
||||||
"imports": {
|
"imports": {
|
||||||
- "$fresh/": "https://deno.land/x/fresh@1.0.2/",
|
- "$fresh/": "https://deno.land/x/fresh@1.0.2/",
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ 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
|
||||||
.
|
.
|
||||||
├── README.md
|
├── README.md
|
||||||
├── components
|
├── components
|
||||||
@@ -40,7 +40,7 @@ your choosing), then you'll need to do the following things:
|
|||||||
|
|
||||||
Here's what the diff of `deno.json` looks like:
|
Here's what the diff of `deno.json` looks like:
|
||||||
|
|
||||||
```diff
|
```diff deno.json
|
||||||
{
|
{
|
||||||
"lock": false,
|
"lock": false,
|
||||||
"tasks": {
|
"tasks": {
|
||||||
@@ -53,7 +53,7 @@ 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
|
||||||
.
|
.
|
||||||
├── README.md
|
├── README.md
|
||||||
├── deno.json
|
├── deno.json
|
||||||
|
|||||||
@@ -19,12 +19,12 @@ 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
|
||||||
├── routes
|
routes
|
||||||
│ └── api
|
└── api
|
||||||
│ └── users
|
└── users
|
||||||
│ ├── [id].ts
|
├── [id].ts
|
||||||
│ └── index.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
|
||||||
@@ -34,15 +34,12 @@ full files are available at the bottom for reference.
|
|||||||
|
|
||||||
`POST` (create) is used to create a resource.
|
`POST` (create) is used to create a resource.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/api/users/index.ts
|
||||||
// routes/api/users/index.ts
|
|
||||||
export const handler: Handlers<User | null> = {
|
export const handler: Handlers<User | null> = {
|
||||||
async POST(req, _ctx) {
|
async POST(req, _ctx) {
|
||||||
const user = await req.json() as User;
|
const user = (await req.json()) as User;
|
||||||
const userKey = ["user", user.id];
|
const userKey = ["user", user.id];
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().set(userKey, user).commit();
|
||||||
.set(userKey, user)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(JSON.stringify(user));
|
return new Response(JSON.stringify(user));
|
||||||
},
|
},
|
||||||
@@ -71,8 +68,7 @@ You should receive the same thing back:
|
|||||||
`GET` (read) is used to retrieve a resource and is by far the most common HTTP
|
`GET` (read) is used to retrieve a resource and is by far the most common HTTP
|
||||||
method. You can use `GET` to fetch database content, markdown, or static files.
|
method. You can use `GET` to fetch database content, markdown, or static files.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/api/users/[id].ts
|
||||||
// routes/api/users/[id].ts
|
|
||||||
export const handler: Handlers<User | null> = {
|
export const handler: Handlers<User | null> = {
|
||||||
async GET(_req, ctx) {
|
async GET(_req, ctx) {
|
||||||
const id = ctx.params.id;
|
const id = ctx.params.id;
|
||||||
@@ -102,19 +98,15 @@ The short version of it: `PUT` requires the entire object to be submitted, while
|
|||||||
|
|
||||||
An example of an update endpoint using `PUT`:
|
An example of an update endpoint using `PUT`:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/api/users/[id].ts
|
||||||
// routes/api/users/[id].ts
|
|
||||||
export const handler: Handlers<User | null> = {
|
export const handler: Handlers<User | null> = {
|
||||||
async PUT(req, ctx) {
|
async PUT(req, ctx) {
|
||||||
const id = ctx.params.id;
|
const id = ctx.params.id;
|
||||||
const user = await req.json() as User;
|
const user = (await req.json()) as User;
|
||||||
const userKey = ["user", id];
|
const userKey = ["user", id];
|
||||||
const userRes = await kv.get(userKey);
|
const userRes = await kv.get(userKey);
|
||||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().check(userRes).set(userKey, user).commit();
|
||||||
.check(userRes)
|
|
||||||
.set(userKey, user)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(JSON.stringify(user));
|
return new Response(JSON.stringify(user));
|
||||||
},
|
},
|
||||||
@@ -152,18 +144,14 @@ No need to send in the id in this case.
|
|||||||
|
|
||||||
`DELETE` (delete) is used to delete a resource.
|
`DELETE` (delete) is used to delete a resource.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/api/users/[id].ts
|
||||||
// routes/api/users/[id].ts
|
|
||||||
export const handler: Handlers<User | null> = {
|
export const handler: Handlers<User | null> = {
|
||||||
async DELETE(_req, ctx) {
|
async DELETE(_req, ctx) {
|
||||||
const id = ctx.params.id;
|
const id = ctx.params.id;
|
||||||
const userKey = ["user", id];
|
const userKey = ["user", id];
|
||||||
const userRes = await kv.get(userKey);
|
const userRes = await kv.get(userKey);
|
||||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().check(userRes).delete(userKey).commit();
|
||||||
.check(userRes)
|
|
||||||
.delete(userKey)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(`user ${id} deleted`);
|
return new Response(`user ${id} deleted`);
|
||||||
},
|
},
|
||||||
@@ -173,7 +161,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
|
||||||
user 2 deleted
|
user 2 deleted
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -210,23 +198,17 @@ export const handler: Handlers<User | null> = {
|
|||||||
const userKey = ["user", id];
|
const userKey = ["user", id];
|
||||||
const userRes = await kv.get(userKey);
|
const userRes = await kv.get(userKey);
|
||||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().check(userRes).delete(userKey).commit();
|
||||||
.check(userRes)
|
|
||||||
.delete(userKey)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(`user ${id} deleted`);
|
return new Response(`user ${id} deleted`);
|
||||||
},
|
},
|
||||||
async PUT(req, ctx) {
|
async PUT(req, ctx) {
|
||||||
const id = ctx.params.id;
|
const id = ctx.params.id;
|
||||||
const user = await req.json() as User;
|
const user = (await req.json()) as User;
|
||||||
const userKey = ["user", id];
|
const userKey = ["user", id];
|
||||||
const userRes = await kv.get(userKey);
|
const userRes = await kv.get(userKey);
|
||||||
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
if (!userRes.value) return new Response(`no user with id ${id} found`);
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().check(userRes).set(userKey, user).commit();
|
||||||
.check(userRes)
|
|
||||||
.set(userKey, user)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(JSON.stringify(user));
|
return new Response(JSON.stringify(user));
|
||||||
},
|
},
|
||||||
@@ -257,11 +239,9 @@ export const handler: Handlers<User | null> = {
|
|||||||
return new Response(JSON.stringify(users));
|
return new Response(JSON.stringify(users));
|
||||||
},
|
},
|
||||||
async POST(req, _ctx) {
|
async POST(req, _ctx) {
|
||||||
const user = await req.json() as User;
|
const user = (await req.json()) as User;
|
||||||
const userKey = ["user", user.id];
|
const userKey = ["user", user.id];
|
||||||
const ok = await kv.atomic()
|
const ok = await kv.atomic().set(userKey, user).commit();
|
||||||
.set(userKey, user)
|
|
||||||
.commit();
|
|
||||||
if (!ok) throw new Error("Something went wrong.");
|
if (!ok) throw new Error("Something went wrong.");
|
||||||
return new Response(JSON.stringify(user));
|
return new Response(JSON.stringify(user));
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -15,13 +15,10 @@ As per the above link, "simple" requests involve `GET`, `HEAD`, or `POST`
|
|||||||
requests. You can CORS enable all the routes affected by some `middleware` by
|
requests. You can CORS enable all the routes affected by some `middleware` by
|
||||||
doing the following:
|
doing the following:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(
|
export async function handler(req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
const origin = req.headers.get("Origin") || "*";
|
const origin = req.headers.get("Origin") || "*";
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
const headers = resp.headers;
|
const headers = resp.headers;
|
||||||
@@ -30,11 +27,11 @@ export async function handler(
|
|||||||
headers.set("Access-Control-Allow-Credentials", "true");
|
headers.set("Access-Control-Allow-Credentials", "true");
|
||||||
headers.set(
|
headers.set(
|
||||||
"Access-Control-Allow-Headers",
|
"Access-Control-Allow-Headers",
|
||||||
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With",
|
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With"
|
||||||
);
|
);
|
||||||
headers.set(
|
headers.set(
|
||||||
"Access-Control-Allow-Methods",
|
"Access-Control-Allow-Methods",
|
||||||
"POST, OPTIONS, GET, PUT, DELETE",
|
"POST, OPTIONS, GET, PUT, DELETE"
|
||||||
);
|
);
|
||||||
|
|
||||||
return resp;
|
return resp;
|
||||||
@@ -47,13 +44,10 @@ What about for one of the other HTTP methods? Then you'll need to be able to
|
|||||||
deal with "preflight requests". Let's imagine you're trying to support a
|
deal with "preflight requests". Let's imagine you're trying to support a
|
||||||
`DELETE` route. Then you'd need to do something like this:
|
`DELETE` route. Then you'd need to do something like this:
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export async function handler(
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
_req: Request,
|
|
||||||
ctx: MiddlewareHandlerContext,
|
|
||||||
) {
|
|
||||||
if (_req.method == "OPTIONS") {
|
if (_req.method == "OPTIONS") {
|
||||||
const resp = new Response(null, {
|
const resp = new Response(null, {
|
||||||
status: 204,
|
status: 204,
|
||||||
@@ -61,10 +55,7 @@ export async function handler(
|
|||||||
const origin = _req.headers.get("Origin") || "*";
|
const origin = _req.headers.get("Origin") || "*";
|
||||||
const headers = resp.headers;
|
const headers = resp.headers;
|
||||||
headers.set("Access-Control-Allow-Origin", origin);
|
headers.set("Access-Control-Allow-Origin", origin);
|
||||||
headers.set(
|
headers.set("Access-Control-Allow-Methods", "DELETE");
|
||||||
"Access-Control-Allow-Methods",
|
|
||||||
"DELETE",
|
|
||||||
);
|
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
const origin = _req.headers.get("Origin") || "*";
|
const origin = _req.headers.get("Origin") || "*";
|
||||||
@@ -75,11 +66,11 @@ export async function handler(
|
|||||||
headers.set("Access-Control-Allow-Credentials", "true");
|
headers.set("Access-Control-Allow-Credentials", "true");
|
||||||
headers.set(
|
headers.set(
|
||||||
"Access-Control-Allow-Headers",
|
"Access-Control-Allow-Headers",
|
||||||
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With",
|
"Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With"
|
||||||
);
|
);
|
||||||
headers.set(
|
headers.set(
|
||||||
"Access-Control-Allow-Methods",
|
"Access-Control-Allow-Methods",
|
||||||
"POST, OPTIONS, GET, PUT, DELETE",
|
"POST, OPTIONS, GET, PUT, DELETE"
|
||||||
);
|
);
|
||||||
|
|
||||||
return resp;
|
return resp;
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ Here you can define named groups, wildcards, regex groups, and other bits.
|
|||||||
Let's look at the example from the routing page more closely. We'll flesh out
|
Let's look at the example from the routing page more closely. We'll flesh out
|
||||||
the handler so that we end up with something like the following:
|
the handler so that we end up with something like the following:
|
||||||
|
|
||||||
```ts
|
```ts routes/x.tsx
|
||||||
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler = {
|
export const handler = {
|
||||||
@@ -47,7 +47,7 @@ show the following:
|
|||||||
|
|
||||||
Let's look at something a bit more complex:
|
Let's look at something a bit more complex:
|
||||||
|
|
||||||
```ts
|
```ts routes/api.tsx
|
||||||
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
import { HandlerContext, RouteConfig } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler = {
|
export const handler = {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Let's pretend you've just initialized a new Fresh project. You want to do some
|
|||||||
complicated setup that runs once, before the server is started. This is,
|
complicated setup that runs once, before the server is started. This is,
|
||||||
fortunately, quite easy. Here's how:
|
fortunately, quite easy. Here's how:
|
||||||
|
|
||||||
```diff
|
```diff main.ts
|
||||||
import { start } from "$fresh/server.ts";
|
import { start } from "$fresh/server.ts";
|
||||||
import manifest from "./fresh.gen.ts";
|
import manifest from "./fresh.gen.ts";
|
||||||
+import { Context } from "./routes/_middleware.ts";
|
+import { Context } from "./routes/_middleware.ts";
|
||||||
@@ -18,7 +18,7 @@ fortunately, quite easy. Here's how:
|
|||||||
|
|
||||||
So your full `main.ts` should look like this:
|
So your full `main.ts` should look like this:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
/// <reference no-default-lib="true" />
|
/// <reference no-default-lib="true" />
|
||||||
/// <reference lib="dom" />
|
/// <reference lib="dom" />
|
||||||
/// <reference lib="dom.iterable" />
|
/// <reference lib="dom.iterable" />
|
||||||
@@ -37,7 +37,7 @@ await start(manifest);
|
|||||||
|
|
||||||
But what's going on in this new `_middleware.ts` we've created?
|
But what's going on in this new `_middleware.ts` we've created?
|
||||||
|
|
||||||
```ts
|
```ts routes/_middleware.ts
|
||||||
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
import { MiddlewareHandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export interface State {
|
export interface State {
|
||||||
@@ -66,7 +66,7 @@ export class Context {
|
|||||||
|
|
||||||
export async function handler(
|
export async function handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext<State>,
|
ctx: MiddlewareHandlerContext<State>
|
||||||
) {
|
) {
|
||||||
ctx.state.context = Context.instance();
|
ctx.state.context = Context.instance();
|
||||||
const resp = await ctx.next();
|
const resp = await ctx.next();
|
||||||
|
|||||||
@@ -13,8 +13,7 @@ the web page. Some uses include:
|
|||||||
- Linking to resources like stylesheets using `<link>`
|
- Linking to resources like stylesheets using `<link>`
|
||||||
- Including third-party JavaScript code using `<script>`
|
- Including third-party JavaScript code using `<script>`
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
// routes/index.tsx
|
|
||||||
import { Head } from "$fresh/runtime.ts";
|
import { Head } from "$fresh/runtime.ts";
|
||||||
import Counter from "../islands/Counter.tsx";
|
import Counter from "../islands/Counter.tsx";
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,7 @@ The following file uses
|
|||||||
[dynamic routing](https://fresh.deno.dev/docs/getting-started/dynamic-routes) to
|
[dynamic routing](https://fresh.deno.dev/docs/getting-started/dynamic-routes) to
|
||||||
handle the three cases. It's assumed this file is called `[slug].tsx`:
|
handle the three cases. It's assumed this file is called `[slug].tsx`:
|
||||||
|
|
||||||
```ts
|
```ts routes/[slug].tsx
|
||||||
// routes/[slug].tsx
|
|
||||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||||
import { extract } from "$std/front_matter/yaml.ts";
|
import { extract } from "$std/front_matter/yaml.ts";
|
||||||
import { CSS, render } from "$gfm";
|
import { CSS, render } from "$gfm";
|
||||||
@@ -31,7 +30,7 @@ export const handler: Handlers<Page> = {
|
|||||||
let rawMarkdown = "";
|
let rawMarkdown = "";
|
||||||
if (ctx.params.slug === "remote") {
|
if (ctx.params.slug === "remote") {
|
||||||
const resp = await fetch(
|
const resp = await fetch(
|
||||||
`https://raw.githubusercontent.com/denoland/fresh/main/docs/introduction/index.md`,
|
`https://raw.githubusercontent.com/denoland/fresh/main/docs/introduction/index.md`
|
||||||
);
|
);
|
||||||
if (resp.status !== 200) {
|
if (resp.status !== 200) {
|
||||||
return ctx.render(undefined);
|
return ctx.render(undefined);
|
||||||
@@ -81,7 +80,7 @@ export default function MarkdownPage({ data }: PageProps<Page | null>) {
|
|||||||
|
|
||||||
The contents of the `text.md` file are the following:
|
The contents of the `text.md` file are the following:
|
||||||
|
|
||||||
```md
|
```md text.md
|
||||||
---
|
---
|
||||||
description: testFromText
|
description: testFromText
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ 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 `main.ts` like the following:
|
you'll end up with a `main.ts` like the following:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
/// <reference no-default-lib="true" />
|
/// <reference no-default-lib="true" />
|
||||||
/// <reference lib="dom" />
|
/// <reference lib="dom" />
|
||||||
/// <reference lib="dom.iterable" />
|
/// <reference lib="dom.iterable" />
|
||||||
@@ -26,7 +26,7 @@ This is a great start if your site is in English, but let's say you want to
|
|||||||
change the language, as per the `<html lang=asdf>` tag. Then you'll need to do
|
change the language, as per the `<html lang=asdf>` tag. Then you'll need to do
|
||||||
something like this:
|
something like this:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
/// <reference no-default-lib="true" />
|
/// <reference no-default-lib="true" />
|
||||||
/// <reference lib="dom" />
|
/// <reference lib="dom" />
|
||||||
/// <reference lib="dom.iterable" />
|
/// <reference lib="dom.iterable" />
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ All of this content is lifted from this great
|
|||||||
|
|
||||||
Imagine we have `Counter.tsx` like this:
|
Imagine we have `Counter.tsx` like this:
|
||||||
|
|
||||||
```ts
|
```tsx islands/Counter.tsx
|
||||||
// islands/Counter.tsx
|
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
import { Button } from "../components/Button.tsx";
|
import { Button } from "../components/Button.tsx";
|
||||||
|
|
||||||
@@ -37,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...
|
||||||
|
|
||||||
```ts
|
```tsx
|
||||||
<Counter start={3} />
|
<Counter start={3} />
|
||||||
<Counter start={4} />
|
<Counter start={4} />
|
||||||
```
|
```
|
||||||
@@ -49,8 +48,7 @@ here, yet.
|
|||||||
|
|
||||||
But we can switch things up by looking at a `SynchronizedSlider.tsx` like this:
|
But we can switch things up by looking at a `SynchronizedSlider.tsx` like this:
|
||||||
|
|
||||||
```ts
|
```tsx islands/SynchronizedSlider.tsx
|
||||||
// islands/SynchronizedSlider.tsx
|
|
||||||
import { Signal } from "@preact/signals";
|
import { Signal } from "@preact/signals";
|
||||||
|
|
||||||
interface SliderProps {
|
interface SliderProps {
|
||||||
@@ -67,7 +65,7 @@ export default function SynchronizedSlider(props: SliderProps) {
|
|||||||
min={1}
|
min={1}
|
||||||
max={100}
|
max={100}
|
||||||
value={props.slider.value}
|
value={props.slider.value}
|
||||||
onInput={(e) => props.slider.value = Number(e.currentTarget.value)}
|
onInput={(e) => (props.slider.value = Number(e.currentTarget.value))}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -75,8 +73,7 @@ export default function SynchronizedSlider(props: SliderProps) {
|
|||||||
|
|
||||||
Now if we were to do the following...
|
Now if we were to do the following...
|
||||||
|
|
||||||
```ts
|
```tsx routes/index.tsx
|
||||||
// routes/index.tsx
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const sliderSignal = useSignal(50);
|
const sliderSignal = useSignal(50);
|
||||||
return (
|
return (
|
||||||
@@ -96,15 +93,13 @@ they would all use the same value.
|
|||||||
We can also create a `signal` in a utility file and export it for consumption
|
We can also create a `signal` in a utility file and export it for consumption
|
||||||
across multiple places.
|
across multiple places.
|
||||||
|
|
||||||
```ts
|
```ts utils/cart.ts
|
||||||
// utils/cart.ts
|
|
||||||
import { signal } from "@preact/signals";
|
import { signal } from "@preact/signals";
|
||||||
|
|
||||||
export const cart = signal<string[]>([]);
|
export const cart = signal<string[]>([]);
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```tsx islands/AddToCart.tsx
|
||||||
// islands/AddToCart.tsx
|
|
||||||
import { Button } from "../components/Button.tsx";
|
import { Button } from "../components/Button.tsx";
|
||||||
import { cart } from "../utils/cart.ts";
|
import { cart } from "../utils/cart.ts";
|
||||||
|
|
||||||
@@ -116,18 +111,17 @@ interface AddToCartProps {
|
|||||||
export default function AddToCart(props: AddToCartProps) {
|
export default function AddToCart(props: AddToCartProps) {
|
||||||
return (
|
return (
|
||||||
<Button
|
<Button
|
||||||
onClick={() => cart.value = [...cart.value, props.product]}
|
onClick={() => (cart.value = [...cart.value, props.product])}
|
||||||
class="w-full"
|
class="w-full"
|
||||||
>
|
>
|
||||||
Add{cart.value.includes(props.product) ? " another" : ""}{" "}
|
Add{cart.value.includes(props.product) ? " another" : ""} "{props.product}
|
||||||
"{props.product}" to cart
|
" to cart
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```tsx islands/Cart.tsx
|
||||||
// islands/Cart.tsx
|
|
||||||
import { Button } from "../components/Button.tsx";
|
import { Button } from "../components/Button.tsx";
|
||||||
import { cart } from "../utils/cart.ts";
|
import { cart } from "../utils/cart.ts";
|
||||||
import * as icons from "../components/Icons.tsx";
|
import * as icons from "../components/Icons.tsx";
|
||||||
@@ -185,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:
|
||||||
|
|
||||||
```ts
|
```tsx
|
||||||
<AddToCart product="Lemon" />
|
<AddToCart product="Lemon" />
|
||||||
<AddToCart product="Lime" />
|
<AddToCart product="Lime" />
|
||||||
<Cart />
|
<Cart />
|
||||||
|
|||||||
@@ -145,8 +145,7 @@ applied to any of the directives.
|
|||||||
|
|
||||||
We'll start off by having an example stylesheet defined like this:
|
We'll start off by having an example stylesheet defined like this:
|
||||||
|
|
||||||
```css
|
```css static/example.css
|
||||||
/* static/example.css */
|
|
||||||
h1 {
|
h1 {
|
||||||
font-size: 25px;
|
font-size: 25px;
|
||||||
font-weight: normal;
|
font-weight: normal;
|
||||||
@@ -161,8 +160,7 @@ To kick things off, we'll create the following control route which doesn't do
|
|||||||
anything with CSP. We include a stylesheet to confirm that our sheet correctly
|
anything with CSP. We include a stylesheet to confirm that our sheet correctly
|
||||||
styles the response.
|
styles the response.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/noCSP.tsx
|
||||||
// routes/noCSP.tsx
|
|
||||||
import { RouteContext } from "$fresh/server.ts";
|
import { RouteContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function Home(req: Request, ctx: RouteContext) {
|
export default function Home(req: Request, ctx: RouteContext) {
|
||||||
@@ -177,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
|
||||||
This page doesn't use CSP at all. Styles will be applied.
|
This page doesn't use CSP at all. Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -188,8 +186,7 @@ closely, we're using the wrong URL! This will cause the browser to reject the
|
|||||||
stylesheet, due to the header that Fresh produces. We get a `(blocked:csp)`
|
stylesheet, due to the header that Fresh produces. We get a `(blocked:csp)`
|
||||||
status when the browser tries to request this resource.
|
status when the browser tries to request this resource.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/incorrectCSP.tsx
|
||||||
// routes/incorrectCSP.tsx
|
|
||||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||||
import { useCSP } from "$fresh/runtime.ts";
|
import { useCSP } from "$fresh/runtime.ts";
|
||||||
|
|
||||||
@@ -198,9 +195,7 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
if (!csp.directives.styleSrc) {
|
if (!csp.directives.styleSrc) {
|
||||||
csp.directives.styleSrc = [];
|
csp.directives.styleSrc = [];
|
||||||
}
|
}
|
||||||
csp.directives.styleSrc.push(
|
csp.directives.styleSrc.push("http://www.example.com");
|
||||||
"http://www.example.com",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -217,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
|
||||||
This page violates our configured CSP. Styles won't be applied.
|
This page violates our configured CSP. Styles won't be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -226,8 +221,7 @@ This page violates our configured CSP. Styles won't be applied.
|
|||||||
Let's fix our simple mistake and use the correct URL. Everything is working
|
Let's fix our simple mistake and use the correct URL. Everything is working
|
||||||
correctly here.
|
correctly here.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/correctCSP.tsx
|
||||||
// routes/correctCSP.tsx
|
|
||||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||||
import { useCSP } from "$fresh/runtime.ts";
|
import { useCSP } from "$fresh/runtime.ts";
|
||||||
|
|
||||||
@@ -236,9 +230,7 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
if (!csp.directives.styleSrc) {
|
if (!csp.directives.styleSrc) {
|
||||||
csp.directives.styleSrc = [];
|
csp.directives.styleSrc = [];
|
||||||
}
|
}
|
||||||
csp.directives.styleSrc.push(
|
csp.directives.styleSrc.push("http://localhost:8000/example.css");
|
||||||
"http://localhost:8000/example.css",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -255,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
|
||||||
This page adheres to our configured CSP. Styles will be applied.
|
This page adheres to our configured CSP. Styles will be applied.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -263,8 +255,7 @@ This page adheres to our configured CSP. Styles will be applied.
|
|||||||
|
|
||||||
What happens if we forget to use a `RouteConfig` in our route?
|
What happens if we forget to use a `RouteConfig` in our route?
|
||||||
|
|
||||||
```tsx
|
```tsx routes/cspNoRouteConfig.tsx
|
||||||
// routes/cspNoRouteConfig.tsx
|
|
||||||
import { RouteContext } from "$fresh/server.ts";
|
import { RouteContext } from "$fresh/server.ts";
|
||||||
import { useCSP } from "$fresh/runtime.ts";
|
import { useCSP } from "$fresh/runtime.ts";
|
||||||
|
|
||||||
@@ -273,16 +264,14 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
if (!csp.directives.styleSrc) {
|
if (!csp.directives.styleSrc) {
|
||||||
csp.directives.styleSrc = [];
|
csp.directives.styleSrc = [];
|
||||||
}
|
}
|
||||||
csp.directives.styleSrc.push(
|
csp.directives.styleSrc.push("http://www.example.com");
|
||||||
"http://www.example.com",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<h1>
|
<h1>
|
||||||
This page violates our configured CSP. But we don't have a{" "}
|
This page violates our configured CSP. But we don't have a{" "}
|
||||||
<code>RouteConfig</code>{" "}
|
<code>RouteConfig</code> enabled, so Fresh doesn't know to use the CSP.
|
||||||
enabled, so Fresh doesn't know to use the CSP. Styles will be applied.
|
Styles will be applied.
|
||||||
</h1>
|
</h1>
|
||||||
<link rel="stylesheet" type="text/css" href="example.css" />
|
<link rel="stylesheet" type="text/css" href="example.css" />
|
||||||
</>
|
</>
|
||||||
@@ -293,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
|
||||||
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.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -305,8 +294,7 @@ should be able to receive `POST` requests. If the `reportOnly` flag is enabled,
|
|||||||
then the browser will ignore the CSP headers and log any issues to the
|
then the browser will ignore the CSP headers and log any issues to the
|
||||||
`reportUri` destination.
|
`reportUri` destination.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/incorrectCSPwithReport.tsx
|
||||||
// routes/incorrectCSPwithReport.tsx
|
|
||||||
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
import { RouteConfig, RouteContext } from "$fresh/server.ts";
|
||||||
import { useCSP } from "$fresh/runtime.ts";
|
import { useCSP } from "$fresh/runtime.ts";
|
||||||
|
|
||||||
@@ -317,9 +305,7 @@ export default function Home(req: Request, ctx: RouteContext) {
|
|||||||
csp.directives.styleSrc = [];
|
csp.directives.styleSrc = [];
|
||||||
}
|
}
|
||||||
csp.directives.reportUri = "http://localhost:8000/reportHandler";
|
csp.directives.reportUri = "http://localhost:8000/reportHandler";
|
||||||
csp.directives.styleSrc.push(
|
csp.directives.styleSrc.push("http://www.example.com");
|
||||||
"http://www.example.com",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -337,8 +323,7 @@ export const config: RouteConfig = {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts routes/reportHandler.ts
|
||||||
// routes/reportHandler.ts
|
|
||||||
import { HandlerContext } from "$fresh/server.ts";
|
import { HandlerContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler = {
|
export const handler = {
|
||||||
@@ -357,14 +342,14 @@ 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
|
||||||
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.
|
||||||
```
|
```
|
||||||
|
|
||||||
We can then check our server and we'll see that `csp-reports.txt` has an entry
|
We can then check our server and we'll see that `csp-reports.txt` has an entry
|
||||||
like this:
|
like this:
|
||||||
|
|
||||||
```json
|
```json csp-reports.txt
|
||||||
{
|
{
|
||||||
"csp-report": {
|
"csp-report": {
|
||||||
"document-uri": "http://localhost:8000/incorrectCSPwithReport",
|
"document-uri": "http://localhost:8000/incorrectCSPwithReport",
|
||||||
|
|||||||
@@ -22,8 +22,7 @@ available.
|
|||||||
2. Create your pre-configured OAuth client instance. For reusability the
|
2. Create your pre-configured OAuth client instance. For reusability the
|
||||||
instance is stored in `utils/oauth2_client.ts`.
|
instance is stored in `utils/oauth2_client.ts`.
|
||||||
|
|
||||||
```ts
|
```ts utils/oauth2_client.ts
|
||||||
// utils/oauth2_client.ts
|
|
||||||
import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||||
|
|
||||||
export const oauth2Client = createGitHubOAuth2Client();
|
export const oauth2Client = createGitHubOAuth2Client();
|
||||||
@@ -35,8 +34,7 @@ available.
|
|||||||
Please ensure that the `callback` handler matches the authorization callback
|
Please ensure that the `callback` handler matches the authorization callback
|
||||||
URL in the configured OAuth application.
|
URL in the configured OAuth application.
|
||||||
|
|
||||||
```ts
|
```ts routes/signin.ts
|
||||||
// routes/signin.ts
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
import { signIn } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
import { signIn } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||||
import { oauth2Client } from "../utils/oauth2_client.ts";
|
import { oauth2Client } from "../utils/oauth2_client.ts";
|
||||||
@@ -48,8 +46,7 @@ available.
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts routes/signout.ts
|
||||||
// routes/signout.ts
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
import { signOut } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
import { signOut } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||||
|
|
||||||
@@ -60,8 +57,7 @@ available.
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
```ts
|
```ts routes/callback.ts
|
||||||
// routes/callback.ts
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
import { handleCallback } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
import { handleCallback } from "https://deno.land/x/deno_kv_oauth@v0.2.4/mod.ts";
|
||||||
import { oauth2Client } from "../utils/oauth2_client.ts";
|
import { oauth2Client } from "../utils/oauth2_client.ts";
|
||||||
@@ -77,8 +73,7 @@ available.
|
|||||||
|
|
||||||
4. Use Deno KV OAuth's helper functions where needed.
|
4. Use Deno KV OAuth's helper functions where needed.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
// routes/index.tsx
|
|
||||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||||
import {
|
import {
|
||||||
getSessionAccessToken,
|
getSessionAccessToken,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ How can you modify your project to no longer use the current release, but
|
|||||||
instead this one particular commit? Just make the following changes to your
|
instead this one particular commit? Just make the following changes to your
|
||||||
`deno.json`:
|
`deno.json`:
|
||||||
|
|
||||||
```diff
|
```diff deno.json
|
||||||
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
||||||
},
|
},
|
||||||
"imports": {
|
"imports": {
|
||||||
@@ -34,7 +34,7 @@ worry, you can use the same approach to reference any branch in a fork as well.
|
|||||||
Here's an example of referencing a feature in a forked repository that hasn't
|
Here's an example of referencing a feature in a forked repository that hasn't
|
||||||
been merged yet (at the time of writing this):
|
been merged yet (at the time of writing this):
|
||||||
|
|
||||||
```diff
|
```diff deno.json
|
||||||
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
"update": "deno run -A -r https://fresh.deno.dev/update ."
|
||||||
},
|
},
|
||||||
"imports": {
|
"imports": {
|
||||||
@@ -55,13 +55,13 @@ create a test project based on your local changes.
|
|||||||
|
|
||||||
Instead of doing it like this:
|
Instead of doing it like this:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
deno run -A -r https://fresh.deno.dev/
|
deno run -A -r https://fresh.deno.dev/
|
||||||
```
|
```
|
||||||
|
|
||||||
do it like this:
|
do it like this:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
deno run -A -r path/to/fresh/init.ts
|
deno run -A -r path/to/fresh/init.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -73,6 +73,6 @@ Of course there's no reason why you have to check out the Fresh source. You can
|
|||||||
create a project from the latest commit by combining the techniques on this page
|
create a project from the latest commit by combining the techniques on this page
|
||||||
like this:
|
like this:
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
deno run -A -r https://raw.githubusercontent.com/denoland/fresh/main/init.ts
|
deno run -A -r https://raw.githubusercontent.com/denoland/fresh/main/init.ts
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ 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 `main.ts` like the following:
|
you'll end up with a `main.ts` like the following:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
/// <reference no-default-lib="true" />
|
/// <reference no-default-lib="true" />
|
||||||
/// <reference lib="dom" />
|
/// <reference lib="dom" />
|
||||||
/// <reference lib="dom.iterable" />
|
/// <reference lib="dom.iterable" />
|
||||||
@@ -26,7 +26,7 @@ The template generates a Twind v0 project by default. If you want to use Twind
|
|||||||
v1 you can follow this guide. First of all, change the import path to use the
|
v1 you can follow this guide. First of all, change the import path to use the
|
||||||
`twindv1` plugin:
|
`twindv1` plugin:
|
||||||
|
|
||||||
```ts
|
```ts main.ts
|
||||||
/// <reference no-default-lib="true" />
|
/// <reference no-default-lib="true" />
|
||||||
/// <reference lib="dom" />
|
/// <reference lib="dom" />
|
||||||
/// <reference lib="dom.iterable" />
|
/// <reference lib="dom.iterable" />
|
||||||
@@ -45,7 +45,7 @@ await start(manifest, { plugins: [twindPlugin(twindConfig)] });
|
|||||||
The twind config object has changed significantly in v1, so we must also go
|
The twind config object has changed significantly in v1, so we must also go
|
||||||
change `twind.config.ts`. A good base looks like this:
|
change `twind.config.ts`. A good base looks like this:
|
||||||
|
|
||||||
```ts
|
```ts twind.config.ts
|
||||||
import { defineConfig, Preset } from "https://esm.sh/@twind/core@1.1.3";
|
import { defineConfig, Preset } from "https://esm.sh/@twind/core@1.1.3";
|
||||||
import presetTailwind from "https://esm.sh/@twind/preset-tailwind@1.1.4";
|
import presetTailwind from "https://esm.sh/@twind/preset-tailwind@1.1.4";
|
||||||
import presetAutoprefix from "https://esm.sh/@twind/preset-autoprefix@1.0.7";
|
import presetAutoprefix from "https://esm.sh/@twind/preset-autoprefix@1.0.7";
|
||||||
|
|||||||
@@ -9,9 +9,7 @@ through
|
|||||||
|
|
||||||
## 1. Create your routes
|
## 1. Create your routes
|
||||||
|
|
||||||
```tsx
|
```tsx routes/index.tsx
|
||||||
// routes/index.tsx
|
|
||||||
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
@@ -28,31 +26,19 @@ export const handler: Handlers = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
return (
|
return <div>Hello Deno!</div>;
|
||||||
<div>
|
|
||||||
Hello Deno!
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```tsx
|
```tsx routes/foo.tsx
|
||||||
// routes/foo.tsx
|
|
||||||
|
|
||||||
export default function FooPage() {
|
export default function FooPage() {
|
||||||
return (
|
return <div>Hello Foo!</div>;
|
||||||
<div>
|
|
||||||
Hello Foo!
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 2. Write your tests
|
## 2. Write your tests
|
||||||
|
|
||||||
```ts
|
```ts tests/main_test.ts
|
||||||
// tests/main_test.ts
|
|
||||||
|
|
||||||
import { createHandler, ServeHandlerInfo } from "$fresh/server.ts";
|
import { createHandler, ServeHandlerInfo } from "$fresh/server.ts";
|
||||||
import manifest from "../fresh.gen.ts";
|
import manifest from "../fresh.gen.ts";
|
||||||
import { assert, assertEquals } from "$std/testing/asserts.ts";
|
import { assert, assertEquals } from "$std/testing/asserts.ts";
|
||||||
@@ -81,10 +67,7 @@ Deno.test("HTTP assert test.", async (t) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await t.step("#3 GET /foo", async () => {
|
await t.step("#3 GET /foo", async () => {
|
||||||
const resp = await handler(
|
const resp = await handler(new Request("http://127.0.0.1/foo"), CONN_INFO);
|
||||||
new Request("http://127.0.0.1/foo"),
|
|
||||||
CONN_INFO,
|
|
||||||
);
|
|
||||||
const text = await resp.text();
|
const text = await resp.text();
|
||||||
assert(text.includes("<div>Hello Foo!</div>"));
|
assert(text.includes("<div>Hello Foo!</div>"));
|
||||||
});
|
});
|
||||||
@@ -93,7 +76,7 @@ Deno.test("HTTP assert test.", async (t) => {
|
|||||||
|
|
||||||
## 3. Run the tests
|
## 3. Run the tests
|
||||||
|
|
||||||
```sh
|
```sh Terminal
|
||||||
$ deno test --allow-read --allow-env --allow-net
|
$ deno test --allow-read --allow-env --allow-net
|
||||||
running 1 test from ./tests/main_test.ts
|
running 1 test from ./tests/main_test.ts
|
||||||
HTTP assert test. ...
|
HTTP assert test. ...
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
description: |
|
description: |
|
||||||
Add JavaScript based interactivity to your project without sacrificing user
|
Add JavaScript based interactivity to your project without sacrificing user
|
||||||
experience, by using Fresh's powerful islands system.
|
experience, by using Fresh's powerful islands system.
|
||||||
---
|
---
|
||||||
|
|
||||||
Up to now none of the pages in the demo project have contained any client side
|
Up to now none of the pages in the demo project have contained any client side
|
||||||
@@ -28,9 +28,7 @@ component. For example a counter component would be defined in the file
|
|||||||
|
|
||||||
Here is an example of an island component that counts down to a specific time.
|
Here is an example of an island component that counts down to a specific time.
|
||||||
|
|
||||||
```tsx
|
```tsx islands/Countdown.tsx
|
||||||
// islands/Countdown.tsx
|
|
||||||
|
|
||||||
import { useSignal } from "@preact/signals";
|
import { useSignal } from "@preact/signals";
|
||||||
import { useEffect } from "preact/hooks";
|
import { useEffect } from "preact/hooks";
|
||||||
|
|
||||||
@@ -55,7 +53,7 @@ export default function Countdown(props: { target: string }) {
|
|||||||
}, [props.target]);
|
}, [props.target]);
|
||||||
|
|
||||||
const secondsLeft = Math.floor(
|
const secondsLeft = Math.floor(
|
||||||
(target.getTime() - now.value.getTime()) / 1000,
|
(target.getTime() - now.value.getTime()) / 1000
|
||||||
);
|
);
|
||||||
|
|
||||||
// If the target date has passed, we stop counting down.
|
// If the target date has passed, we stop counting down.
|
||||||
@@ -73,9 +71,7 @@ To include this in a page component, one can just use the component normally.
|
|||||||
Fresh will take care of automatically mounting the island component on the
|
Fresh will take care of automatically mounting the island component on the
|
||||||
client with the correct props:
|
client with the correct props:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/countdown.tsx
|
||||||
// routes/countdown.tsx
|
|
||||||
|
|
||||||
import Countdown from "../islands/Countdown.tsx";
|
import Countdown from "../islands/Countdown.tsx";
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ will scaffold out a new project with some example files to get you started.
|
|||||||
|
|
||||||
To create a new project, run:
|
To create a new project, run:
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
deno run -A -r https://fresh.deno.dev
|
deno run -A -r https://fresh.deno.dev
|
||||||
cd fresh-project
|
cd fresh-project
|
||||||
deno task start
|
deno task start
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
description: |
|
description: |
|
||||||
Create a new route to a Fresh project by creating a new file in the `routes/`
|
Create a new route to a Fresh project by creating a new file in the `routes/`
|
||||||
folder.
|
folder.
|
||||||
---
|
---
|
||||||
|
|
||||||
After getting the project running locally, the next step is to add a new route
|
After getting the project running locally, the next step is to add a new route
|
||||||
@@ -34,9 +34,7 @@ This is done with JSX.
|
|||||||
> [Preact][preact], a lighter weight virtual dom library that works similar to
|
> [Preact][preact], a lighter weight virtual dom library that works similar to
|
||||||
> React.
|
> React.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/about.tsx
|
||||||
// routes/about.tsx
|
|
||||||
|
|
||||||
export default function AboutPage() {
|
export default function AboutPage() {
|
||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
|
|||||||
@@ -27,9 +27,7 @@ the HTTP method it handles.
|
|||||||
Here is an example of a custom `GET` handler that renders the page component and
|
Here is an example of a custom `GET` handler that renders the page component and
|
||||||
then adds a custom header to the response before returning it:
|
then adds a custom header to the response before returning it:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/about.tsx
|
||||||
// routes/about.tsx
|
|
||||||
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
@@ -54,9 +52,7 @@ Note that handlers do not need to call `ctx.render()`. This feature can be used
|
|||||||
to create API routes. Here is an API route that returns a random UUID as a JSON
|
to create API routes. Here is an API route that returns a random UUID as a JSON
|
||||||
response:
|
response:
|
||||||
|
|
||||||
```ts
|
```ts routes/api/random-uuid.ts
|
||||||
// routes/api/random-uuid.ts
|
|
||||||
|
|
||||||
import { Handlers } from "$fresh/server.ts";
|
import { Handlers } from "$fresh/server.ts";
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
|
|||||||
@@ -24,9 +24,7 @@ render a page. The module must once again expose a component as a default
|
|||||||
export. This time the component will receive the matched path segment properties
|
export. This time the component will receive the matched path segment properties
|
||||||
as arguments in its `props` object though.
|
as arguments in its `props` object though.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/greet/[name].tsx
|
||||||
// routes/greet/[name].tsx
|
|
||||||
|
|
||||||
import { PageProps } from "$fresh/server.ts";
|
import { PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
export default function GreetPage(props: PageProps) {
|
export default function GreetPage(props: PageProps) {
|
||||||
|
|||||||
@@ -17,9 +17,7 @@ The second `ctx` parameter is used to get the route parameters.
|
|||||||
Here is an example of a route that fetches user data from the GitHub API and
|
Here is an example of a route that fetches user data from the GitHub API and
|
||||||
renders it in a page component.
|
renders it in a page component.
|
||||||
|
|
||||||
```tsx
|
```tsx routes/github/[username].tsx
|
||||||
// routes/github/[username].tsx
|
|
||||||
|
|
||||||
import { RouteContext } from "$fresh/server.ts";
|
import { RouteContext } from "$fresh/server.ts";
|
||||||
|
|
||||||
interface GitHubResponse {
|
interface GitHubResponse {
|
||||||
@@ -30,14 +28,14 @@ interface GitHubResponse {
|
|||||||
|
|
||||||
export default async function Page(_req: Request, ctx: RouteContext) {
|
export default async function Page(_req: Request, ctx: RouteContext) {
|
||||||
const resp = await fetch(
|
const resp = await fetch(
|
||||||
`https://api.github.com/users/${ctx.params.username}`,
|
`https://api.github.com/users/${ctx.params.username}`
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
return <h1>An Error occurred</h1>;
|
return <h1>An Error occurred</h1>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { login, name, avatar_url } = await resp.json() as GitHubResponse;
|
const { login, name, avatar_url } = (await resp.json()) as GitHubResponse;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -29,9 +29,7 @@ any necessary processing on the form data, and then pass data to the
|
|||||||
Here is an example implementing a search form that filters an array of names
|
Here is an example implementing a search form that filters an array of names
|
||||||
server side:
|
server side:
|
||||||
|
|
||||||
```tsx
|
```tsx routes/search.tsx
|
||||||
// routes/search.tsx
|
|
||||||
|
|
||||||
import { Handlers, PageProps } from "$fresh/server.ts";
|
import { Handlers, PageProps } from "$fresh/server.ts";
|
||||||
|
|
||||||
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
|
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
|
||||||
@@ -59,7 +57,9 @@ export default function Page({ data }: PageProps<Data>) {
|
|||||||
<button type="submit">Search</button>
|
<button type="submit">Search</button>
|
||||||
</form>
|
</form>
|
||||||
<ul>
|
<ul>
|
||||||
{results.map((name) => <li key={name}>{name}</li>)}
|
{results.map((name) => (
|
||||||
|
<li key={name}>{name}</li>
|
||||||
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ The next step after scaffolding out a new project, is to actually start it. To
|
|||||||
do this you can just `deno task start`. Environment variables will be
|
do this you can just `deno task start`. Environment variables will be
|
||||||
automatically read from `.env`.
|
automatically read from `.env`.
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
$ deno task start
|
$ deno task start
|
||||||
Watcher Process started.
|
Watcher Process started.
|
||||||
🍋 Fresh ready
|
🍋 Fresh ready
|
||||||
@@ -38,19 +38,19 @@ you add a new route.
|
|||||||
If you want to change the port or host, modify the options bag of the `start()`
|
If you want to change the port or host, modify the options bag of the `start()`
|
||||||
call in `main.ts` to include an explicit port number:
|
call in `main.ts` to include an explicit port number:
|
||||||
|
|
||||||
```js
|
```js main.ts
|
||||||
await start(manifest, { port: 3000 });
|
await start(manifest, { port: 3000 });
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also change the port by setting the `PORT` environment variable:
|
You can also change the port by setting the `PORT` environment variable:
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
$ PORT=3000 deno task start
|
$ PORT=3000 deno task start
|
||||||
```
|
```
|
||||||
|
|
||||||
Combining all of this we get the following `deno run` command:
|
Combining all of this we get the following `deno run` command:
|
||||||
|
|
||||||
```
|
```sh Terminal
|
||||||
$ deno run --allow-net --allow-read --allow-env --allow-run --watch=static/,routes/ main.ts
|
$ deno run --allow-net --allow-read --allow-env --allow-run --watch=static/,routes/ main.ts
|
||||||
Watcher Process started.
|
Watcher Process started.
|
||||||
🍋 Fresh ready
|
🍋 Fresh ready
|
||||||
|
|||||||
+1
-2
@@ -14,8 +14,7 @@
|
|||||||
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3",
|
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3",
|
||||||
"$std/": "https://deno.land/std@0.193.0/",
|
"$std/": "https://deno.land/std@0.193.0/",
|
||||||
"$ga4": "https://raw.githubusercontent.com/denoland/ga4/main/mod.ts",
|
"$ga4": "https://raw.githubusercontent.com/denoland/ga4/main/mod.ts",
|
||||||
"$marked-mangle": "https://esm.sh/marked-mangle@1.0.1",
|
"$marked-mangle": "https://esm.sh/marked-mangle@1.0.1"
|
||||||
"$marked-smartypants": "https://esm.sh/marked-smartypants@1.0.1"
|
|
||||||
},
|
},
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
|
|||||||
@@ -10,13 +10,8 @@ import {
|
|||||||
TABLE_OF_CONTENTS,
|
TABLE_OF_CONTENTS,
|
||||||
TableOfContentsEntry,
|
TableOfContentsEntry,
|
||||||
} from "../../data/docs.ts";
|
} from "../../data/docs.ts";
|
||||||
import { frontMatter, gfm } from "../../utils/markdown.ts";
|
import { frontMatter, renderMarkdown } from "../../utils/markdown.ts";
|
||||||
import toc from "../../../docs/toc.ts";
|
import toc from "../../../docs/toc.ts";
|
||||||
import { mangle } from "$marked-mangle";
|
|
||||||
import { markedSmartypants } from "$marked-smartypants";
|
|
||||||
|
|
||||||
gfm.Marked.marked.use(mangle());
|
|
||||||
gfm.Marked.marked.use(markedSmartypants());
|
|
||||||
|
|
||||||
interface Data {
|
interface Data {
|
||||||
page: Page;
|
page: Page;
|
||||||
@@ -249,7 +244,7 @@ function DesktopSidebar(props: { path: string; page: Page }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function Content(props: { page: Page }) {
|
function Content(props: { page: Page }) {
|
||||||
const html = gfm.render(props.page.markdown);
|
const html = renderMarkdown(props.page.markdown);
|
||||||
return (
|
return (
|
||||||
<main class="py-6 overflow-hidden md:mr-4 lg:mr-32">
|
<main class="py-6 overflow-hidden md:mr-4 lg:mr-32">
|
||||||
<h1 class="text(4xl gray-900) tracking-tight font-extrabold mt-6 md:mt-0">
|
<h1 class="text(4xl gray-900) tracking-tight font-extrabold mt-6 md:mt-0">
|
||||||
|
|||||||
+39
-1
@@ -3,8 +3,20 @@ import { gfm } from "../utils/markdown.ts";
|
|||||||
|
|
||||||
// TODO(lucacasonato): hash the file and use the hash as the filename, and serve
|
// TODO(lucacasonato): hash the file and use the hash as the filename, and serve
|
||||||
// with high-cacheability headers.
|
// with high-cacheability headers.
|
||||||
|
function css(template: TemplateStringsArray, ...params: string[]) {
|
||||||
|
let out = "";
|
||||||
|
|
||||||
const CSS = `${gfm.CSS}
|
for (let i = 0; i < template.length; i++) {
|
||||||
|
out += template[i];
|
||||||
|
if (i < params.length) {
|
||||||
|
out += String(params[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const CSS = css`${gfm.CSS}
|
||||||
|
|
||||||
ol.nested {
|
ol.nested {
|
||||||
counter-reset: item;
|
counter-reset: item;
|
||||||
@@ -39,6 +51,32 @@ ol.nested li:before {
|
|||||||
.toggle:checked + .toggled {
|
.toggle:checked + .toggled {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fenced-code {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
.fenced-code pre {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
.fenced-code-header {
|
||||||
|
border-top-left-radius: .5rem;
|
||||||
|
border-top-right-radius: .5rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
background: #eaeef1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
.fenced-code-header + pre {
|
||||||
|
border-top-left-radius: 0 !important;
|
||||||
|
border-top-right-radius: 0 !important;
|
||||||
|
}
|
||||||
|
.fenced-code-title {
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
|
||||||
|
"Liberation Mono", "Courier New", monospace;
|
||||||
|
font-size: .8125rem;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export const handler: Handlers = {
|
export const handler: Handlers = {
|
||||||
|
|||||||
@@ -3,5 +3,116 @@ import "https://esm.sh/prismjs@1.29.0/components/prism-jsx.js?no-check";
|
|||||||
import "https://esm.sh/prismjs@1.29.0/components/prism-typescript.js?no-check";
|
import "https://esm.sh/prismjs@1.29.0/components/prism-typescript.js?no-check";
|
||||||
import "https://esm.sh/prismjs@1.29.0/components/prism-tsx.js?no-check";
|
import "https://esm.sh/prismjs@1.29.0/components/prism-tsx.js?no-check";
|
||||||
import "https://esm.sh/prismjs@1.29.0/components/prism-diff.js?no-check";
|
import "https://esm.sh/prismjs@1.29.0/components/prism-diff.js?no-check";
|
||||||
|
import "https://esm.sh/prismjs@1.29.0/components/prism-json.js?no-check";
|
||||||
|
import "https://esm.sh/prismjs@1.29.0/components/prism-bash.js?no-check";
|
||||||
|
|
||||||
export { extract as frontMatter } from "$std/front_matter/yaml.ts";
|
export { extract as frontMatter } from "$std/front_matter/yaml.ts";
|
||||||
|
|
||||||
|
import Prism from "https://esm.sh/prismjs@1.29.0";
|
||||||
|
import * as Marked from "https://esm.sh/marked@7.0.2";
|
||||||
|
import { escape as escapeHtml } from "$std/html/entities.ts";
|
||||||
|
import { mangle } from "$marked-mangle";
|
||||||
|
|
||||||
|
Marked.marked.use(mangle());
|
||||||
|
|
||||||
|
class DefaultRenderer extends Marked.Renderer {
|
||||||
|
text(text: string): string {
|
||||||
|
// Smartypants typography enhancement
|
||||||
|
return text
|
||||||
|
.replaceAll("...", "…")
|
||||||
|
.replaceAll("--", "—")
|
||||||
|
.replaceAll("---", "–")
|
||||||
|
.replaceAll(/(\w)'(\w)/g, "$1’$2")
|
||||||
|
.replaceAll(/s'/g, "s’")
|
||||||
|
.replaceAll("'", "’")
|
||||||
|
.replaceAll(/["](.*?)["]/g, "“$1”")
|
||||||
|
.replaceAll(/"(.*?)"/g, "“$1”")
|
||||||
|
.replaceAll(/['](.*?)[']/g, "‘$1’");
|
||||||
|
}
|
||||||
|
|
||||||
|
heading(
|
||||||
|
text: string,
|
||||||
|
level: 1 | 2 | 3 | 4 | 5 | 6,
|
||||||
|
raw: string,
|
||||||
|
slugger: Marked.Slugger,
|
||||||
|
): string {
|
||||||
|
const slug = slugger.slug(raw);
|
||||||
|
return `<h${level} id="${slug}"><a class="anchor" aria-hidden="true" tabindex="-1" href="#${slug}">#</a>${text}</h${level}>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
link(href: string, title: string | null, text: string) {
|
||||||
|
const titleAttr = title ? ` title="${title}"` : "";
|
||||||
|
if (href.startsWith("#")) {
|
||||||
|
return `<a href="${href}"${titleAttr}>${text}</a>`;
|
||||||
|
}
|
||||||
|
if (this.options.baseUrl) {
|
||||||
|
try {
|
||||||
|
href = new URL(href, this.options.baseUrl).href;
|
||||||
|
} catch (_) {
|
||||||
|
//
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return `<a href="${href}"${titleAttr} rel="noopener noreferrer">${text}</a>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
image(src: string, title: string | null, alt: string | null) {
|
||||||
|
return `<img src="${src}" alt="${alt ?? ""}" title="${title ?? ""}" />`;
|
||||||
|
}
|
||||||
|
|
||||||
|
code(code: string, info: string | undefined): string {
|
||||||
|
// format: tsx
|
||||||
|
// format: tsx my/file.ts
|
||||||
|
// format: tsx "This is my title"
|
||||||
|
let lang = "";
|
||||||
|
let title = "";
|
||||||
|
const match = info?.match(/^(\w+)\s*(.*)?$/);
|
||||||
|
if (match) {
|
||||||
|
lang = match[1].toLocaleLowerCase();
|
||||||
|
title = match[2] ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
let out = `<div class="fenced-code">`;
|
||||||
|
|
||||||
|
if (title) {
|
||||||
|
out += `<div class="fenced-code-header">
|
||||||
|
<span class="fenced-code-title lang-${lang}">
|
||||||
|
${title ? escapeHtml(String(title)) : " "}
|
||||||
|
</span>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const grammar = lang && Object.hasOwnProperty.call(Prism.languages, lang)
|
||||||
|
? Prism.languages[lang]
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (grammar === undefined) {
|
||||||
|
out += `<pre><code class="notranslate">${escapeHtml(code)}</code></pre>`;
|
||||||
|
} else {
|
||||||
|
const html = Prism.highlight(code, grammar, lang);
|
||||||
|
out +=
|
||||||
|
`<pre class="highlight highlight-source-${lang} notranslate lang-${lang}">${html}</pre>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
out += `</div>`;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarkdownOptions {
|
||||||
|
inline?: boolean;
|
||||||
|
}
|
||||||
|
export function renderMarkdown(
|
||||||
|
input: string,
|
||||||
|
opts: MarkdownOptions = {},
|
||||||
|
): string {
|
||||||
|
const markedOpts: Marked.MarkedOptions = {
|
||||||
|
gfm: true,
|
||||||
|
renderer: new DefaultRenderer(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const html = opts.inline
|
||||||
|
? Marked.parseInline(input, markedOpts) as string
|
||||||
|
: Marked.parse(input, markedOpts) as string;
|
||||||
|
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user