From 73fd41be31c19a0b21643cc63a52d15ea1b5e865 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Mon, 7 Mar 2022 21:08:55 +0100 Subject: [PATCH] feat: add docs section to website (#108) --- .github/workflows/lighthouse.yml | 2 +- .vscode/settings.json | 3 +- README.md | 5 +- cli.ts | 2 +- docs/concepts/architechture.md | 1 + docs/concepts/data-fetching.md | 1 + docs/concepts/error-pages.md | 1 + docs/concepts/index.md | 1 + docs/concepts/islands.md | 1 + docs/concepts/middleware.md | 1 + docs/concepts/route-handlers.md | 1 + docs/concepts/routes.md | 82 +++++++ docs/concepts/routing.md | 1 + docs/concepts/static-files.md | 1 + docs/concepts/styling.md | 1 + docs/getting-started/adding-interactivity.md | 90 ++++++++ docs/getting-started/create-a-project.md | 46 ++++ docs/getting-started/create-a-route.md | 78 +++++++ docs/getting-started/custom-handlers.md | 65 ++++++ docs/getting-started/deploy-to-production.md | 25 +++ docs/getting-started/dynamic-routes.md | 49 ++++ docs/getting-started/fetching-data.md | 60 +++++ docs/getting-started/form-submissions.md | 72 ++++++ docs/getting-started/index.md | 17 ++ docs/getting-started/installation.md | 34 +++ docs/getting-started/running-locally.md | 37 ++++ docs/introduction/index.md | 37 ++++ docs/toc.json | 35 +++ makefile | 4 +- www/client_deps.ts | 4 +- www/components/DocsSidebar.tsx | 60 +++++ www/components/Footer.tsx | 33 +++ www/components/NavigationBar.tsx | 35 +++ www/components/WarningBanner.tsx | 15 ++ www/data/docs.ts | 64 ++++++ www/fresh.gen.ts | 8 +- www/routes/docs/[...slug].tsx | 221 +++++++++++++++++++ www/routes/gfm.css.ts | 46 ++++ www/routes/index.tsx | 75 +++---- www/server_deps.ts | 6 + 40 files changed, 1258 insertions(+), 62 deletions(-) create mode 100644 docs/concepts/architechture.md create mode 100644 docs/concepts/data-fetching.md create mode 100644 docs/concepts/error-pages.md create mode 100644 docs/concepts/index.md create mode 100644 docs/concepts/islands.md create mode 100644 docs/concepts/middleware.md create mode 100644 docs/concepts/route-handlers.md create mode 100644 docs/concepts/routes.md create mode 100644 docs/concepts/routing.md create mode 100644 docs/concepts/static-files.md create mode 100644 docs/concepts/styling.md create mode 100644 docs/getting-started/adding-interactivity.md create mode 100644 docs/getting-started/create-a-project.md create mode 100644 docs/getting-started/create-a-route.md create mode 100644 docs/getting-started/custom-handlers.md create mode 100644 docs/getting-started/deploy-to-production.md create mode 100644 docs/getting-started/dynamic-routes.md create mode 100644 docs/getting-started/fetching-data.md create mode 100644 docs/getting-started/form-submissions.md create mode 100644 docs/getting-started/index.md create mode 100644 docs/getting-started/installation.md create mode 100644 docs/getting-started/running-locally.md create mode 100644 docs/introduction/index.md create mode 100644 docs/toc.json create mode 100644 www/components/DocsSidebar.tsx create mode 100644 www/components/Footer.tsx create mode 100644 www/components/NavigationBar.tsx create mode 100644 www/components/WarningBanner.tsx create mode 100644 www/data/docs.ts create mode 100644 www/routes/docs/[...slug].tsx create mode 100644 www/routes/gfm.css.ts diff --git a/.github/workflows/lighthouse.yml b/.github/workflows/lighthouse.yml index 9fa7a051..2f8da383 100644 --- a/.github/workflows/lighthouse.yml +++ b/.github/workflows/lighthouse.yml @@ -23,6 +23,6 @@ jobs: run: npm install -g @lhci/cli@0.9.x - name: Run Lighthouse - run: lhci autorun --collect.url="$URL" --upload.target="temporary-public-storage" + run: lhci autorun --collect.url="$URL" --collect.url="$URL/docs/introduction" --upload.target="temporary-public-storage" env: LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} diff --git a/.vscode/settings.json b/.vscode/settings.json index e40716fd..e1533c2b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,4 @@ { "deno.enable": true, - "deno.lint": true, - "deno.unstable": true + "deno.lint": true } diff --git a/README.md b/README.md index 16909153..78b04c06 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ # fresh -Preact, but super edgy. +The next-gen web framework. Fresh is a web framework that lets you build projects very fast, highly dynamic, and without the need of a build step. Fresh embraces isomorphic JavaScript like @@ -22,9 +22,6 @@ the framework. - TypeScript out of the box - File-system routing à la Next.js -_1 Client side hydration can be enabled per page. By default **no -JS** is shipped to the client._ - ## Install To install, run the following command. This will add `fresh` CLI to your PATH. diff --git a/cli.ts b/cli.ts index cd1e63b0..b8fd20fb 100644 --- a/cli.ts +++ b/cli.ts @@ -5,7 +5,7 @@ import { manifestSubcommand } from "./src/cli/manifest.ts"; const VERSION = "0.1.0"; const help = `fresh ${VERSION} -Preact, but super edgy. +The next-gen web framework. To initalize a new project: fresh init ./myproject diff --git a/docs/concepts/architechture.md b/docs/concepts/architechture.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/architechture.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/data-fetching.md b/docs/concepts/data-fetching.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/data-fetching.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/error-pages.md b/docs/concepts/error-pages.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/error-pages.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/index.md b/docs/concepts/index.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/index.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/islands.md b/docs/concepts/islands.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/islands.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/middleware.md b/docs/concepts/middleware.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/middleware.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/route-handlers.md b/docs/concepts/route-handlers.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/route-handlers.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/routes.md b/docs/concepts/routes.md new file mode 100644 index 00000000..de0d56d1 --- /dev/null +++ b/docs/concepts/routes.md @@ -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
You are on the page '{props.url.href}'.
; +} +``` + +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
You are on the page '{props.url.href}'.
; +} +``` diff --git a/docs/concepts/routing.md b/docs/concepts/routing.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/routing.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/static-files.md b/docs/concepts/static-files.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/static-files.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/concepts/styling.md b/docs/concepts/styling.md new file mode 100644 index 00000000..86e8c7f4 --- /dev/null +++ b/docs/concepts/styling.md @@ -0,0 +1 @@ +> TODO(lucacasonato): this page still needs to be written diff --git a/docs/getting-started/adding-interactivity.md b/docs/getting-started/adding-interactivity.md new file mode 100644 index 00000000..a0cb69b5 --- /dev/null +++ b/docs/getting-started/adding-interactivity.md @@ -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 🎉; + } + + // Otherwise, we format the remaining time using `Intl.RelativeTimeFormat` and + // render it. + const secondsLeft = Math.floor((target.getTime() - now.getTime()) / 1000); + return {timeFmt.format(secondsLeft, "seconds")}; +} +``` + +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 ( +

+ The big event is happening . +

+ ); +} +``` + +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 diff --git a/docs/getting-started/create-a-project.md b/docs/getting-started/create-a-project.md new file mode 100644 index 00000000..db768f4c --- /dev/null +++ b/docs/getting-started/create-a-project.md @@ -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. diff --git a/docs/getting-started/create-a-route.md b/docs/getting-started/create-a-route.md new file mode 100644 index 00000000..790038e4 --- /dev/null +++ b/docs/getting-started/create-a-route.md @@ -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 ( +
+

About

+

This is the about page.

+
+ ); +} +``` + +> ℹ️ 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`. + + + +[concepts-routing]: /docs/concepts/routing +[jsx]: https://reactjs.org/docs/introducing-jsx.html +[preact]: https://preactjs.com/ + + diff --git a/docs/getting-started/custom-handlers.md b/docs/getting-started/custom-handlers.md new file mode 100644 index 00000000..057ce531 --- /dev/null +++ b/docs/getting-started/custom-handlers.md @@ -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` 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 ( +
+

About

+

This is the about page.

+
+ ); +} +``` + +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" }, + }); + }, +}; +``` diff --git a/docs/getting-started/deploy-to-production.md b/docs/getting-started/deploy-to-production.md new file mode 100644 index 00000000..e2f51457 --- /dev/null +++ b/docs/getting-started/deploy-to-production.md @@ -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 diff --git a/docs/getting-started/dynamic-routes.md b/docs/getting-started/dynamic-routes.md new file mode 100644 index 00000000..7e9a9b91 --- /dev/null +++ b/docs/getting-started/dynamic-routes.md @@ -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 ( +
+

Greetings to you, {name}!

+
+ ); +} +``` + +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 diff --git a/docs/getting-started/fetching-data.md b/docs/getting-started/fetching-data.md new file mode 100644 index 00000000..7b5c5ee6 --- /dev/null +++ b/docs/getting-started/fetching-data.md @@ -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 = { + 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) { + if (!data) { + return

User not found

; + } + + return ( +
+ +

{data.name}

+

{data.login}

+
+ ); +} +``` + +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. diff --git a/docs/getting-started/form-submissions.md b/docs/getting-started/form-submissions.md new file mode 100644 index 00000000..4e64df31 --- /dev/null +++ b/docs/getting-started/form-submissions.md @@ -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 `
` element. + +`fresh` builds the core of it's form submission infrastructure around the native +`` element. This page explains how to use `` 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 = { + 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) { + const { results, query } = data; + return ( +
+ + + + +
    + {results.map((name) =>
  • {name}
  • )} +
+
+ ); +} +``` + +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. + + + +[custom-handlers]: /docs/getting-started/custom-handlers diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md new file mode 100644 index 00000000..5d9c7223 --- /dev/null +++ b/docs/getting-started/index.md @@ -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 diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 00000000..01bf207d --- /dev/null +++ b/docs/getting-started/installation.md @@ -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 +``` diff --git a/docs/getting-started/running-locally.md b/docs/getting-started/running-locally.md new file mode 100644 index 00000000..d7a264b5 --- /dev/null +++ b/docs/getting-started/running-locally.md @@ -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. diff --git a/docs/introduction/index.md b/docs/introduction/index.md new file mode 100644 index 00000000..498630f8 --- /dev/null +++ b/docs/introduction/index.md @@ -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 diff --git a/docs/toc.json b/docs/toc.json new file mode 100644 index 00000000..613f1db5 --- /dev/null +++ b/docs/toc.json @@ -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"] + ] + } +} diff --git a/makefile b/makefile index 52bb2619..ec3c2e03 100644 --- a/makefile +++ b/makefile @@ -6,6 +6,8 @@ lint: test: deno test -A --no-check=remote + deno cache --no-check=remote www/main.ts + deno cache --no-check=remote examples/counter/main.ts dev: - deno run -A --watch=www/static,src/ --no-check www/main.ts \ No newline at end of file + deno run -A --watch=www/static,src/,docs/ --no-check www/main.ts \ No newline at end of file diff --git a/www/client_deps.ts b/www/client_deps.ts index 052a148e..dab8219e 100644 --- a/www/client_deps.ts +++ b/www/client_deps.ts @@ -1,7 +1,7 @@ export * from "../runtime.ts"; import { IS_BROWSER } from "../runtime.ts"; -import { setup, tw } from "https://esm.sh/twind@0.16.16"; -export { setup, tw }; +import { apply, setup, tw } from "https://esm.sh/twind@0.16.16"; +export { apply, setup, tw }; if (IS_BROWSER) { setup({}); } diff --git a/www/components/DocsSidebar.tsx b/www/components/DocsSidebar.tsx new file mode 100644 index 00000000..d7e881a6 --- /dev/null +++ b/www/components/DocsSidebar.tsx @@ -0,0 +1,60 @@ +/** @jsx h */ + +import { apply, h, tw } from "../client_deps.ts"; +import { + CATEGORIES, + TableOfContentsCategory, + TableOfContentsCategoryEntry, +} from "../data/docs.ts"; + +export default function DocsSidebar(props: { path: string }) { + return ( +
    + {CATEGORIES.map((category) => ( + + ))} +
+ ); +} + +const link = apply`text(gray-900 hover:gray-600)`; +const linkActive = apply`text(blue-600 hover:blue-500)`; + +export function SidebarCategory(props: { + path: string; + category: TableOfContentsCategory; +}) { + const outerItem = tw`my-2 block`; + const innerList = tw`pl-4 list-decimal` + " nested"; + + const { title, href, entries } = props.category; + const outerLink = tw`${href == props.path ? linkActive : link} font-bold`; + + return ( +
  • + {title} + {entries.length > 0 && ( +
      + {entries.map((entry) => ( + + ))} +
    + )} +
  • + ); +} + +export function SidebarEntry(props: { + path: string; + entry: TableOfContentsCategoryEntry; +}) { + const innerItem = tw`my-0.5`; + + const { title, href } = props.entry; + const innerLink = tw`${href == props.path ? linkActive : link} font-normal`; + return ( +
  • + {title} +
  • + ); +} diff --git a/www/components/Footer.tsx b/www/components/Footer.tsx new file mode 100644 index 00000000..64719577 --- /dev/null +++ b/www/components/Footer.tsx @@ -0,0 +1,33 @@ +/** @jsx h */ + +import { h, tw } from "../client_deps.ts"; + +const LINKS = [ + { + title: "Source", + href: "https://github.com/lucacasonato/fresh", + }, +]; + +export default function Footer() { + const footer = tw + `border(t-2 gray-200) bg-gray-100 h-32 flex flex-col gap-4 justify-center`; + const inner = tw + `mx-auto max-w-screen-lg flex items-center justify-center gap-8`; + const linkStyle = tw`text-gray-600 hover:underline`; + const copyright = tw`text(gray-600 center)`; + return ( +
    +
    + {LINKS.map((link) => ( + + {link.title} + + ))} +
    +
    + © {new Date().getFullYear()} the fresh authors +
    +
    + ); +} diff --git a/www/components/NavigationBar.tsx b/www/components/NavigationBar.tsx new file mode 100644 index 00000000..af734015 --- /dev/null +++ b/www/components/NavigationBar.tsx @@ -0,0 +1,35 @@ +/** @jsx h */ + +import { h, tw } from "../client_deps.ts"; + +export default function NavigationBar(props: { active: string }) { + const items = [ + { + name: "Home", + href: "/", + }, + { + name: "Docs", + href: "/docs", + }, + ]; + + return ( + + ); +} diff --git a/www/components/WarningBanner.tsx b/www/components/WarningBanner.tsx new file mode 100644 index 00000000..4cc10cac --- /dev/null +++ b/www/components/WarningBanner.tsx @@ -0,0 +1,15 @@ +/** @jsx h */ + +import { h, tw } from "../client_deps.ts"; + +export default function WarningBanner() { + const warning = tw`bg-yellow-100 border(1 yellow-200) p-4 mb-4`; + return ( +
    + ⚠️ Do not use `fresh` for production usecases yet, unless you are very + actively tracking the `fresh` repository for updates. The framework is + still undergoing very frequent core functionality changes. You can expect + a mostly stable release around the end of March 2022. +
    + ); +} diff --git a/www/data/docs.ts b/www/data/docs.ts new file mode 100644 index 00000000..86849585 --- /dev/null +++ b/www/data/docs.ts @@ -0,0 +1,64 @@ +import RAW_TOC from "../../docs/toc.json" assert { type: "json" }; + +type RawTableOfContents = Record; + +interface RawTableOfContentsEntry { + title: string; + pages?: [string, string][]; +} + +export interface TableOfContentsEntry { + slug: string; + title: string; + category?: string; + href: string; + file: string; +} + +export interface TableOfContentsCategory { + title: string; + href: string; + entries: TableOfContentsCategoryEntry[]; +} + +export interface TableOfContentsCategoryEntry { + title: string; + href: string; +} + +export const TABLE_OF_CONTENTS: Record = {}; +export const CATEGORIES: TableOfContentsCategory[] = []; + +for (const parent in (RAW_TOC as unknown as RawTableOfContents)) { + const rawEntry = (RAW_TOC as unknown as RawTableOfContents)[parent]; + const href = `/docs/${parent}`; + const file = `docs/${parent}/index.md`; + const entry = { + slug: parent, + title: rawEntry.title, + href, + file, + }; + TABLE_OF_CONTENTS[parent] = entry; + const category: TableOfContentsCategory = { + title: rawEntry.title, + href, + entries: [], + }; + CATEGORIES.push(category); + if (rawEntry.pages) { + for (const [id, title] of rawEntry.pages) { + const slug = `${parent}/${id}`; + const href = `/docs/${slug}`; + const file = `docs/${slug}.md`; + const entry = { slug, title, category: parent, href, file }; + TABLE_OF_CONTENTS[slug] = entry; + category.entries.push({ + title, + href, + }); + } + } +} + +export const SLUGS = Object.keys(TABLE_OF_CONTENTS); diff --git a/www/fresh.gen.ts b/www/fresh.gen.ts index adee4760..cc82899f 100644 --- a/www/fresh.gen.ts +++ b/www/fresh.gen.ts @@ -3,13 +3,17 @@ // To update this file, run `fresh routes`. import * as $0 from "./routes/_render.ts"; -import * as $1 from "./routes/index.tsx"; +import * as $1 from "./routes/gfm.css.ts"; +import * as $2 from "./routes/docs/[...slug].tsx"; +import * as $3 from "./routes/index.tsx"; import * as $$0 from "./islands/Counter.tsx"; const manifest = { routes: { "./routes/_render.ts": $0, - "./routes/index.tsx": $1, + "./routes/gfm.css.ts": $1, + "./routes/docs/[...slug].tsx": $2, + "./routes/index.tsx": $3, }, islands: { "./islands/Counter.tsx": $$0, diff --git a/www/routes/docs/[...slug].tsx b/www/routes/docs/[...slug].tsx new file mode 100644 index 00000000..1df39d95 --- /dev/null +++ b/www/routes/docs/[...slug].tsx @@ -0,0 +1,221 @@ +/** @jsx h */ +/** @jsxFrag Fragment */ + +import { apply, Fragment, h, Head, PageProps, tw } from "../../client_deps.ts"; +import { gfm, Handlers } from "../../server_deps.ts"; +import DocsSidebar from "../../components/DocsSidebar.tsx"; +import Footer from "../../components/Footer.tsx"; +import NavigationBar from "../../components/NavigationBar.tsx"; +import WarningBanner from "../../components/WarningBanner.tsx"; +import { + SLUGS, + TABLE_OF_CONTENTS, + TableOfContentsEntry, +} from "../../data/docs.ts"; + +interface Data { + page: Page; +} + +interface Page extends TableOfContentsEntry { + markdown: string; +} + +export const handler: Handlers = { + async GET(_req, ctx) { + const slug = ctx.params.slug; + if (slug === "") { + return new Response("", { + status: 307, + headers: { location: "/docs/introduction" }, + }); + } + const entry = TABLE_OF_CONTENTS[slug]; + if (!entry) { + return new Response("404 Page not found", { + status: 404, + }); + } + const url = new URL(`../../../${entry.file}`, import.meta.url); + const markdown = await Deno.readTextFile(url); + const page = { ...entry, markdown }; + const resp = ctx.render({ page }); + return resp; + }, +}; + +export default function DocsPage(props: PageProps) { + return ( + <> + + {props.data.page?.title ?? "Not Found"} | fresh docs + + +
    + +
    +