www: move latest docs into latest folder (#1522)

This commit is contained in:
Marvin Hagemeister
2023-07-25 13:42:01 +02:00
committed by GitHub
parent b2416126b8
commit 2e8460e5c1
44 changed files with 1 additions and 1 deletions
@@ -0,0 +1,96 @@
---
description: |
Add JavaScript based interactivity to your project without sacrificing user
experience, by using Fresh's powerful islands system.
---
Up to now none of the pages in the demo project have contained any client side
JavaScript. This is great for resiliency and performance, but it can also limit
the possibilities of interactivity. In many current generation web frameworks,
you get the choice of shipping no JavaScript to the client or shipping a
renderer for the entire page.
This is not very flexible, especially considering that most pages will only have
small pieces of content that require interactivity. For example, an otherwise
static page might need a little bit of JavaScript to power an image carousel or
"buy now" button. This model is often called
[islands architecture][islands-architecture]. This refers to a page having
little "islands" of interactivity, in a sea of otherwise static content.
Fresh embraces this model. All pages are rendered server side, but you can
create "island components" that are _also_ rendered client side. To do this,
Fresh projects have a special `islands/` folder. The modules in this folder each
encapsulate a single island component. The name of the module should be the
[pascal case][pascal-case] or [kebab case][kebab-case] name of the island
component. For example a counter component would be defined in the file
`islands/Counter.tsx`. A buy now button could be defined in the file
`islands/buy-now-button.tsx`.
Here is an example of an island component that counts down to a specific time.
```tsx
// islands/Countdown.tsx
import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
const timeFmt = new Intl.RelativeTimeFormat("en-US");
// The target date is passed as a string instead of as a `Date`, because the
// props to island components need to be JSON (de)serializable.
export default function Countdown(props: { target: string }) {
const target = new Date(props.target);
const now = useSignal(new Date());
// Set up an interval to update the `now` date every second with the current
// date as long as the component is mounted.
useEffect(() => {
const timer = setInterval(() => {
if (now.value > target) {
clearInterval(timer);
}
now.value = new Date();
}, 1000);
return () => clearInterval(timer);
}, [props.target]);
const secondsLeft = Math.floor(
(target.getTime() - now.value.getTime()) / 1000,
);
// If the target date has passed, we stop counting down.
if (secondsLeft <= 0) {
return <span>🎉</span>;
}
// Otherwise, we format the remaining time using `Intl.RelativeTimeFormat` and
// render it.
return <span>{timeFmt.format(secondsLeft, "seconds")}</span>;
}
```
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
client with the correct props:
```tsx
// routes/countdown.tsx
import Countdown from "../islands/Countdown.tsx";
export default function Page() {
const date = new Date();
date.setHours(date.getHours() + 1);
return (
<p>
The big event is happening <Countdown target={date.toISOString()} />.
</p>
);
}
```
The page that is rendered on the client now has an interactive countdown.
[islands-architecture]: https://jasonformat.com/islands-architecture
[pascal-case]: https://en.wiktionary.org/wiki/Pascal_case
[kebab-case]: https://en.wiktionary.org/wiki/kebab_case
@@ -0,0 +1,60 @@
---
description: |
Create a new Fresh project by running the Fresh project creation tool. This
scaffolds out the various files and folders a Fresh project needs.
---
New Fresh projects can be created by using the Fresh project creation tool. It
will scaffold out a new project with some example files to get you started.
To create a new project, run:
```
deno run -A -r https://fresh.deno.dev
cd fresh-project
deno task start
```
This will scaffold out the new project, then switch into the newly created
directory, and then start the development server.
This will create a directory containing some files and directories. There are 4
files that are strictly necessary to run a Fresh project:
- **`dev.ts`**: This is the development entry point for your project. This is
the file that you run to start your project. This file doesn't need to be
called `dev.ts`, but this is the convention.
- **`main.ts`**: This is the production entry point for your project. It is the
file that you link to Deno Deploy. This file doesn't actually need to be
`main.ts`, but this is the convention.
- **`fresh.gen.ts`**: This is the manifest file that contains information about
your routes and islands. This file is automatically generated in development
based on your `routes/` and `islands/` folders.
A **`deno.json`** file is also created in the project directory. This file does
two things:
- It defines the "imports" field. This is an [import map][import-map] that is
used to manage dependencies for the project. This allows for easy importing
and updating of dependencies.
- It registers a "start" [task][task-runner] to run the project without having
to type a long `deno run` command.
Two important folders are also created that contain your routes and islands
respectively:
- **`routes/`**: This folder contains all of the routes in your project. The
names of each file in this folder correspond to the path where that page will
be accessed. Code inside of this folder is never directly shipped to the
client. You'll learn more about how routes work in the next section.
- **`islands/`**: This folder contains all of the interactive islands in your
project. The name of each file corresponds to the name of the island defined
in that file. Code inside of this folder can be run from both client and
server. You'll learn more about islands later in this chapter.
Finally a **`static/`** folder is created that contains static files that are
automatically served "as is". [Learn more about static files][static-files].
[import-map]: https://deno.land/manual/linking_to_external_code/import_maps
[task-runner]: https://deno.land/manual/tools/task_runner
[static-files]: ../concepts/static-files
@@ -0,0 +1,60 @@
---
description: |
Create a new route to a Fresh project by creating a new file in the `routes/`
folder.
---
After getting the project running locally, the next step is to add a new route
to the project. Routes encapsulate the logic for handling requests to a
particular path in your project. They can be used to handle API requests or
render HTML pages. For now we are going to do the latter.
Routes are defined as files in the `routes` directory. The file name of the
module is important: it is used to determine the path that the route will
handle. For example, if the file name is `index.js`, the route will handle
requests to `/`. If the file name is `about.js`, the route will handle requests
to `/about`. If the file name is `contact.js` and is placed inside of the
`routes/about/` folder, the route will handle requests to `/about/contact`. This
concept is called _File-system routing_. You can learn more about it on the
[_Concepts: Routing_][concepts-routing] page.
Route files that render HTML are JavaScript or TypeScript modules that export a
JSX component as their default export. This component will be rendered for every
request to the route's path. The component receives a few properties that can be
used to customize the rendered output, such as the current route, the url of the
request, state set by middleware, and handler data (more on the last two later).
In the demo project we'll create a route to handle the `/about` page. To do
this, one needs to create a new `routes/about.tsx` file. In this file, we can
declare a component that should be rendered every time a user visits the page.
This is done with JSX.
> ℹ️ To learn more about JSX, you can read [this article][jsx] in the React
> documentation. Beware that Fresh does not use React, but rather
> [Preact][preact], a lighter weight virtual dom library that works similar to
> React.
```tsx
// routes/about.tsx
export default function AboutPage() {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
}
```
The new page will be visible at `http://localhost:8000/about`.
<!-- You can find more in depth information about routes on the
[_Concepts: Routes_][concepts-routes] documentation page. The following
pages in the _Getting Started_ guide will also explain more features of routes. -->
[concepts-routing]: /docs/concepts/routing
[jsx]: https://reactjs.org/docs/introducing-jsx.html
[preact]: https://preactjs.com/
<!-- [concepts-routes]: /docs/concepts/routes -->
@@ -0,0 +1,70 @@
---
description: |
Add custom handlers to a route to customize HTTP headers, implement API
routes, do data fetching for a rendered page, or handle form submissions.
---
Routes actually consist of two parts: handlers, and the page component. Up to
now, only the page component has been discussed in this chapter.
Handlers are functions in the form of `Request => Response` or
`Request => Promise<Response>` that are called when a request is made to a
particular route. There can be one handler that covers all HTTP methods or one
handler per method.
The handler has access to the `Request` object that backs the request to the
route and must return a `Response` object. The response object can either be
created manually (for example a JSON response for an API route), or it can be
created by rendering the page component. By default, all routes that don't
define a custom handler use a default handler that just renders the page
component.
To define a handler in a route module, one must export it as a named export with
the name `handler`. Handlers can have two forms: a plain function (catchall for
all HTTP methods) or a plain object where each property is a function named by
the HTTP method it handles.
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:
```tsx
// routes/about.tsx
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
async GET(_req, ctx) {
const resp = await ctx.render();
resp.headers.set("X-Custom-Header", "Hello");
return resp;
},
};
export default function AboutPage() {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
}
```
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
response:
```ts
// routes/api/random-uuid.ts
import { Handlers } from "$fresh/server.ts";
export const handler: Handlers = {
GET(_req) {
const uuid = crypto.randomUUID();
return new Response(JSON.stringify(uuid), {
headers: { "Content-Type": "application/json" },
});
},
};
```
@@ -0,0 +1,31 @@
---
description: |
Deploy a Fresh application to Deno Deploy in seconds, making it available on
the edge globally - resulting in fantastic user latency worldwide.
---
As a final step in the getting started guide, we'll deploy the demo site to the
public internet using [Deno Deploy][deno-deploy]. Deno Deploy is a globally
distributed edge runtime built by the Deno company that allows developers to
quickly and painlessly deploy web applications to the internet. Deno Deploy has
edge nodes all over the world that serve traffic. Because of this, users
worldwide have fantastic latency because their traffic is served from a server
that is physically close to them.
To deploy to Deno Deploy, we'll make use of the GitHub integration. To use this
the code needs to be pushed to a repository on GitHub. Once this has been done,
one must go to the [Deno Deploy dashboard][deno-deploy-dashboard] and create a
new project.
After creating the project, head to the "Git" tab in the project settings,
select the repository, the production branch (`main`) and the entrypoint file
(`main.ts`). This will link the project to the repository and automatically
deploy it to the internet. The project will now be available at
https://$PROJECT_NAME.deno.dev.
Every time the code in the GitHub repository is updated, it will be deployed
either as a preview or production deployment. Production deployments are only
created for changes to the default/production branch (often `main`).
[deno-deploy]: https://deno.com/deploy
[deno-deploy-dashboard]: https://dash.deno.com/projects
@@ -0,0 +1,52 @@
---
description: |
Create a dynamic route in Fresh by adding a dynamic segment to the route name
in the routes' file name on disk: `/greet/[name].tsx`.
---
The `/about` route created on the last page is pretty static. It does not matter
what query or path parameters are passed to the route, it will always render the
same page. Let's create a `/greet/:name` that will render a page with a greeting
that contains the name passed in the path.
Before diving in, a quick refresher on "dynamic" routes. Dynamic routes don't
just match a single static path, but rather a whole bunch of different paths
based on a pattern. For example, the `/greet/:name` route will match the paths
`/greet/Luca` and `/John`, but not `/greet/Luca/John`.
Fresh supports dynamic routes out of the box through file system routing. To
make any path segment dynamic, just put square brackets around that segment in
the file name. For example the `/greet/:name` route maps to the file name
`routes/greet/[name].tsx`.
Just like the static `/about` route, the dynamic `/greet/:name` route will
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
as arguments in its `props` object though.
```tsx
// routes/greet/[name].tsx
import { PageProps } from "$fresh/server.ts";
export default function GreetPage(props: PageProps) {
const { name } = props.params;
return (
<main>
<p>Greetings to you, {name}!</p>
</main>
);
}
```
The `PageProps` interface actually contains a bunch of useful properties that
can be used to customize the rendered output. Next to the matched url pattern
parameters, the raw `url`, and the `route` name can also be found in here.
Navigating to `http://localhost:8000/greet/Luca` will now render a page showing
"Greetings to you, Luca!".
The [_Concepts: Routing_][concepts-routing] page has more information about
dynamic routes, especially about how to create more advanced dynamic routes.
[concepts-routing]: /docs/concepts/routing
@@ -0,0 +1,64 @@
---
description: |
Fetch data for routes dynamically by creating a custom handler and passing
data to the render function.
---
All of the pages in the demo project so far have not used any dynamic data
during rendering. In real projects, this is often different. In many cases you
may need to read a file from disk (e.g. markdown for a blog post), or fetch some
user data from an API or database.
These operations are all asynchronous. Rendering however, is always synchronous.
Instead of fetching data directly during rendering, it should be loaded in a
route's `handler` function and then passed to the page component via first
argument to `ctx.render()`.
The data that is passed to `ctx.render()` can then be accessed via the
`props.data` field on the page component.
Here is an example of a route that fetches user data from the GitHub API and
renders it in a page component.
```tsx
// routes/github/[username].tsx
import { Handlers, PageProps } from "$fresh/server.ts";
interface User {
login: string;
name: string;
avatar_url: string;
}
export const handler: Handlers<User | null> = {
async GET(_, ctx) {
const { username } = ctx.params;
const resp = await fetch(`https://api.github.com/users/${username}`);
if (resp.status === 404) {
return ctx.render(null);
}
const user: User = await resp.json();
return ctx.render(user);
},
};
export default function Page({ data }: PageProps<User | null>) {
if (!data) {
return <h1>User not found</h1>;
}
return (
<div>
<img src={data.avatar_url} width={64} height={64} />
<h1>{data.name}</h1>
<p>{data.login}</p>
</div>
);
}
```
The data is first fetched inside of the handler by making an API call to GitHub.
If the API call succeeds, the data is passed to the page component. If the API
call fails, the page component is rendered with `null` as the data. The page
component grabs the data from the props and renders it.
@@ -0,0 +1,79 @@
---
description: |
Robustly handle user inputs using HTML `<form>` elements client side, and form
submission handlers server side.
---
Forms are a common mechanism for letting users interact with applications. In
the last few years it has become more and more common for web applications to
move form submission entirely to the client. This can have useful properties for
interactivity, but it is much worse for resiliency and user experience as a
whole. Browsers have great built in systems for form submission, revolving
around the HTML `<form>` element.
Fresh builds the core of its form submission infrastructure around the native
`<form>` element. This page explains how to use `<form>` in Fresh, and the next
chapter explains how to progressively enhance your forms with client side
JavaScript to make them more interactive.
The way forms work in the browser, is that they perform an HTML navigation
action when the user submits the form. In most cases this means that when the
form is submitted, a `GET` or `POST` request is sent to the server with the form
data, which then responds with a new page to render.
Fresh can handle both `GET` and `POST` requests through the
[custom handlers][custom-handlers] feature of routes. The handlers can perform
any necessary processing on the form data, and then pass data to the
`ctx.render()` call to render a new page.
Here is an example implementing a search form that filters an array of names
server side:
```tsx
// routes/search.tsx
import { Handlers, PageProps } from "$fresh/server.ts";
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
interface Data {
results: string[];
query: string;
}
export const handler: Handlers<Data> = {
GET(req, ctx) {
const url = new URL(req.url);
const query = url.searchParams.get("q") || "";
const results = NAMES.filter((name) => name.includes(query));
return ctx.render({ results, query });
},
};
export default function Page({ data }: PageProps<Data>) {
const { results, query } = data;
return (
<div>
<form>
<input type="text" name="q" value={query} />
<button type="submit">Search</button>
</form>
<ul>
{results.map((name) => <li key={name}>{name}</li>)}
</ul>
</div>
);
}
```
When the user submits the form, the browser will navigate to `/search` with the
query set as the `q` query parameter in the URL. The `GET` handler will then
filter the names array based on the query, and pass it to the page component for
rendering.
[Learn more about using forms in Fresh][concepts-forms].
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
[custom-handlers]: /docs/getting-started/custom-handlers
[concepts-forms]: /docs/concepts/forms
+24
View File
@@ -0,0 +1,24 @@
---
description: |
In this chapter of the Fresh documentation, you'll be introduced to the
framework. Create a new project, run it locally, edit and create pages, fetch
data, handle user interactions, and deploy it.
---
In this chapter of the Fresh documentation, you'll be introduced to the
framework. You'll learn how to create a new project, run it locally, edit and
create pages, fetch data, handle user interactions, and how to then deploy the
project to [Deno Deploy][deno-deploy].
The documentation assumes you have Deno 1.35.0 or later installed.
To install Deno, follow the
[installation instructions in the Deno manual][manual-installation].
For the best user experience, you should also set up your editor or IDE to play
nice with Deno. Documentation for this can also be found
[in the manual][manual-editors].
[deno-deploy]: https://deno.com/deploy
[manual-installation]: https://deno.land/manual/getting_started/installation
[manual-editors]: https://deno.land/manual/getting_started/setup_your_environment
@@ -0,0 +1,64 @@
---
description: |
To start a Fresh project, just run `deno task start`. This will start the
project with default permission flags, in watch mode.
---
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
automatically read from `.env`.
```
$ deno task start
Watcher Process started.
🍋 Fresh ready
Local: http://localhost:8000
```
If you want to start manually without Deno task, `deno run` the `main.ts` with
the appropriate flags. You will need to provide permission flags for:
- **`--allow-net`**: This is required to start the HTTP server.
- **`--allow-read`**: This is required to read (static) files from disk.
- **`--allow-env`**: This is required to read environment variables that can be
used to configure your project.
- **`--allow-run`**: This is required to shell out to `deno` and `esbuild` under
the hood during development to do type stripping. In production this is done
using a WebAssembly binary.
For development, you also want to run with the [`--watch` flag][--watch], so the
Fresh server will automatically reload whenever you make a change to your code.
By default `--watch` only watches over files in your module graph. Some project
files like static files are not part of the module graph, but you probably want
to restart/reload whenever you make a change to them too. This can be done by
passing the extra folder as an argument: `--watch=static/`. You should also add
`routes/` to the watch list, so that the server restarts automatically whenever
you add a new route.
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:
```js
await start(manifest, { port: 3000 });
```
You can also change the port by setting the `PORT` environment variable:
```
$ PORT=3000 deno task start
```
Combining all of this we get the following `deno run` command:
```
$ deno run --allow-net --allow-read --allow-env --allow-run --watch=static/,routes/ main.ts
Watcher Process started.
🍋 Fresh ready
Local: http://localhost:8000
```
If you now visit http://localhost:8000, you can see the running project. Try
change some of the text in `routes/index.tsx` and see how the page updates
automatically when you save the file.
[--watch]: https://deno.land/manual/getting_started/command_line_interface#watch-mode