feat: add docs section to website (#108)

This commit is contained in:
Luca Casonato
2022-03-07 21:08:55 +01:00
committed by GitHub
parent 026ed86f40
commit 73fd41be31
40 changed files with 1258 additions and 62 deletions
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+82
View File
@@ -0,0 +1,82 @@
> TODO(lucacasonato): complete this page
At it's core, routes describe how a request for a given path should be handled,
and what the response should be. To do this, routes have two main parts: the
handler, and the component. A route can have either one, or both, but never
neither.
The handler is a function that is called for every request to the route. It
needs to return a response that is then sent to the client. The response could
be anything: a plain text string, a JSON object, an HTML page, a WebSocket
connection, a streaming file, or pretty much anything else. The handler is
passed a `render` function that it can call to invoke rendering the component.
The component is the template for a page. It is a JSX element that is rendered
on the server. The page component gets passed props that can be used by it to
determine exactly what should be rendered. By default the request URL, the
matches from the URL pattern match, and any data passed to the handler's
`render` function are passed to the component as props.
Let's look at a basic route that returns a plain text string:
```tsx
// routes/plain.tsx
import { HandlerContext, Handlers } from "../server_deps.ts";
export const handler: Handlers = {
GET(ctx: HandlerContext) {
return new Response("Hello World");
},
};
```
To define a handler, one needs to export a `handler` function or object from the
route module. If the handler is an object, each key in the object is the name of
the HTTP method that the handler should be called for. For example the `GET`
handler above is called for `GET` requests. If the handler is a function, it is
called for all requests regardless of the method.
Now, let's render some HTML using the route component. Another example:
```tsx
// routes/html.tsx
/** @jsx h */
import { h, PageProps } from "../client_deps.ts";
export default function Page(props: PageProps) {
return <div>You are on the page '{props.url.href}'.</div>;
}
```
The page component needs to be the default export of the route module. It is
passed props that can be used to render the page.
As you can see in the second example, if no handler is explicitly defined a
default handler is used that just renders out the page component if present. You
can also override the default handler though to modify how exactly rendering
should work.
In the below example, a custom handler is used to add a custom header to the
response after rendering the page component.
```tsx
// routes/html.tsx
/** @jsx h */
import { h, PageProps } from "../client_deps.ts";
import { HandlerContext, Handlers } from "../server_deps.ts";
export const handler: Handlers = {
GET(ctx: HandlerContext) {
const resp = ctx.render();
resp.headers.set("X-Custom-Header", "Hello World");
return resp;
},
};
export default function Page(props: PageProps) {
return <div>You are on the page '{props.url.href}'.</div>;
}
```
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
+1
View File
@@ -0,0 +1 @@
> TODO(lucacasonato): this page still needs to be written
@@ -0,0 +1,90 @@
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 a otherwise
static page might need a little bit of JavaScript to power a image carousel or
"buy now" button. This model is often called
[islands architechture][islands-architechture]. 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 name of the island component. For example a counter component would
be defined in the file `islands/Counter.tsx`. A buy now button would be defined
in the file `islands/BuyNowButton.tsx`.
Here is an example of an island component that counts down to a specific time.
```tsx
// islands/Countdown.tsx
/** @jsx h */
import { h, useEffect, useMemo, useState } from "../client_deps.ts";
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, setNow] = useState(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(() => {
setNow(new Date());
if (now > target) {
clearInterval(timer);
}
}, 1000);
return () => clearInterval(timer);
}, [props.target]);
// If the target date has passed, we stop counting down.
if (now > target) {
return <span>🎉</span>;
}
// Otherwise, we format the remaining time using `Intl.RelativeTimeFormat` and
// render it.
const secondsLeft = Math.floor((target.getTime() - now.getTime()) / 1000);
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
/** @jsx h */
import { h } from "../client_deps.ts";
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>
);
}
```
Before trying this out, one must run `fresh manifest` again to update the
`fresh.gen.ts` file with the new island component. Just like routes, island
components need to be registered in the manifest file. This means that
`fresh manifest` needs to be run every time a new island component is added,
removed, or renamed.
[islands-architechture]: https://jasonformat.com/islands-architecture
+46
View File
@@ -0,0 +1,46 @@
New `fresh` projects can be created with the `fresh` CLI tool. It will scaffold
out a new project with some example files to get you started.
To create a new project in the directory `"my-project"`, run:
```
$ fresh init my-project
Manifest generated and written to ./my-project/fresh.gen.ts
```
This will create a directory containing a bunch of files. Out of all of the
files, only two are strictly necessary for a fresh project:
- **`main.ts`**: This is the entrypoint for your project. It is the file that
will you run to start your fresh application. This file doesn't actually need
to be called `main.ts`, but it's best practice to call the entrypoint
`main.ts`.
- **`fresh.gen.ts`**: This is the manifest file that contains information about
your routes and islands. This file is automatically generated based on your
`routes/` and `islands/` folder by the `fresh` CLI when running the
`fresh manifest` command.
In addition to these two files, two other files are created that manage
dependencies:
- **`client_deps.ts`**: This file contains dependencies that you need on the
client, and possibly also on the server. It should be assumed that all of the
dependencies referenced by this file will be shipped to the client. By
default, it just re-exports the `fresh` runtime.
- **`server_deps.ts`**: This file contains dependencies that are only used on
the server. These are often things like database drivers, API clients, or
other code that should only be executed on the server. This file should never
be referenced by modules that might be shipped to the client. By default this
just re-exports the `fresh` server libraries.
Finally, two folders are 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 corresponds 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.
+78
View File
@@ -0,0 +1,78 @@
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, and handler data (more on that 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
/** @jsx h */
import { h } from "../client_deps.ts";
export default function AboutPage() {
return (
<main>
<h1>About</h1>
<p>This is the about page.</p>
</main>
);
}
```
> ℹ️ The first two lines are the JSX pragma, and the import for the JSX create
> element function. These are just boilerplate. You don't need to know exactly
> what they do - they just ensure that JSX get's rendered correctly.
This alone is not yet enough to actually view the page in the browser though. If
one tries to visit `http://localhost:8000/about`, the server will return a 404
code.
Before `fresh` can render the page, the `fresh.gen.ts` manifest needs to be
updated to reflect this new route. To do this, one can run the `fresh manifest`
command:
```
$ fresh manifest
Manifest generated and written to ./my-project/fresh.gen.ts
```
> ℹ️ Updating the manifest needs to be done every time you add, remove, or
> rename a page. It does not need to be done if just the contents of a page are
> edited.
Now the 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 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 -->
+65
View File
@@ -0,0 +1,65 @@
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
/** @jsx h */
import { h, Handlers } from "../client_deps.ts";
export const handler: Handlers = {
GET(req, ctx) {
const resp = 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 "../client_deps.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,25 @@
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 is now be available at
https://$PROJECT_NAME.deno.dev.
Everytime 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
+49
View File
@@ -0,0 +1,49 @@
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 `/greet/John`, but not `/greet` or `/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 it's `props` object though.
```tsx
// routes/greet/[name].tsx
/** @jsx h */
import { h, PageProps } from "../../client_deps.ts";
export default function AboutPage(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.
As this is a new page, the manifest needs to be updated again: `fresh manifest`.
Navigating to `https://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
+60
View File
@@ -0,0 +1,60 @@
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
/** @jsx h */
import { h, PageProps } from "../../client_deps.ts";
import { Handlers } from "../../server_deps.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.
+72
View File
@@ -0,0 +1,72 @@
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 is 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 it's 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 peform a 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
/** @jsx h */
import { h, PageProps } from "../../client_deps.ts";
import { Handlers } from "../../server_deps.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.
<!-- TODO(lucacasonato): link to todo app example when that is built again -->
[custom-handlers]: /docs/getting-started/custom-handlers
+17
View File
@@ -0,0 +1,17 @@
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.12.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
+34
View File
@@ -0,0 +1,34 @@
`fresh` comes with a CLI tool, conveniently also called `fresh`. It is used to
scaffold new projects and generate the fresh manifest (more on that later). This
tool is only needed to create a new project, or to re-generate the fresh
manifest after you have added, removed, or renamed a pages or islands in an
existing project.
The CLI tool is not required for most development or in CI, as `fresh` does not
have a build step. This means that if you are only doing some light editing on
an existing project, you do not need to install or use the `fresh` CLI.
To install the `fresh` CLI:
```
deno install -A -f --no-check -n fresh https://raw.githubusercontent.com/lucacasonato/fresh/main/cli.ts
```
The tool should now be available as `fresh` in your terminal. To try out if
installation was successful you can just run `fresh` without any arguments:
```
$ fresh
fresh 0.1.0
The next-gen web framework.
To initalize a new project:
fresh init ./myproject
To (re-)generate the manifest file:
fresh manifest
SUBCOMMANDS:
init Initalize a fresh project
manifest (Re-)generate the manifest file
```
+37
View File
@@ -0,0 +1,37 @@
The next step after scaffolding out a new project, is to actually start it. To
do this you can just `deno run` the `main.ts` file 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, 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/`.
Finally you might want to add a `--no-check` flag to disable the type checking
during development. Typically many people already get type checking from their
editor through the use of the Deno language server, so this is a good way to
speed up the inner loop iteration time. During CI you probably want to run with
`--no-check=remote` disable type checking of remote dependencies (because these
are out of your control).
Combining all of this we get the following `deno run` command:
```
$ deno run --allow-net --allow-read --allow-env --allow-run --watch=static/ --no-check main.ts
Watcher Process started.
Server listening on 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.
+37
View File
@@ -0,0 +1,37 @@
`fresh` is a full stack modern web framework for JavaScript and TypeScript
developers, designed to make it trivial to create high-quality, performant, and
personalized web applications. You can use it to create your home page, a blog,
a large web application like GitHub or Twitter, or anything else you can think
of.
At it's core, `fresh` is a combination of a routing framework and templating
engine that renders pages on demand, on the server. In addition to this
just-in-time (JIT) rendering on the server, `fresh` also provides an interface
for seamlessly rendering some components on the client for maximum
interactivity. The framework uses [Preact][preact] and JSX for rendering and
templating on both the server and the client.
`fresh` also does not have a build step. The code you write is also directly the
code that is run on the server, and the code that is executed on the client. Any
necessary transpilation of TypeScript or JSX to plain JavaScript is done on the
fly, just when it is needed. This allows for insanely fast iteration loops, and
very very fast deployments.
`fresh` projects can be deployed manually to any platform with `deno`, but it is
intended to be deployed to an edge runtime like [Deno Deploy][deno-deploy] for
the best experience.
Some stand out features:
- No build step
- Zero config necessary
- JIT rendering on the edge
- Tiny & fast (no client JS is required by the framework)
- Optional client side hydration of individual components
- Highly resilient because of progressive enhancement and use of native browser
features
- TypeScript out of the box
- File-system routing à la Next.js
[preact]: https://preactjs.com
[deno-deploy]: https://deno.com/deploy
+35
View File
@@ -0,0 +1,35 @@
{
"introduction": {
"title": "Introduction"
},
"getting-started": {
"title": "Getting Started",
"pages": [
["installation", "Installation"],
["create-a-project", "Create a project"],
["running-locally", "Running locally"],
["create-a-route", "Create a route"],
["dynamic-routes", "Dynamic routes"],
["custom-handlers", "Custom handlers"],
["fetching-data", "Fetching data"],
["form-submissions", "Form submissions"],
["adding-interactivity", "Adding interactivity"],
["deploy-to-production", "Deploy to production"]
]
},
"concepts": {
"title": "Concepts",
"pages": [
["architechture", "Architecture"],
["routes", "Routes"],
["route-handlers", "Route handlers"],
["islands", "Interactive islands"],
["static-files", "Static files"],
["middleware", "Route middleware"],
["error-pages", "Error pages"],
["routing", "Routing"],
["data-fetching", "Data fetching"],
["styling", "Styling"]
]
}
}