feat: a new "island" based architechture (#97)

This commit is contained in:
Luca Casonato
2022-03-04 19:49:27 +01:00
committed by GitHub
parent d441bf2489
commit 8daa280862
70 changed files with 820 additions and 972 deletions
+4 -1
View File
@@ -36,4 +36,7 @@ jobs:
run: deno cache --no-check src/cli/deps.ts src/runtime/deps.ts src/server/deps.ts
- name: Run tests
run: deno test -A --no-check
run: deno test -A --no-check=remote
- name: Type check website
run: deno cache --no-check=remote www/main.ts
+6 -6
View File
@@ -1,6 +1,6 @@
import { parseArgs } from "./src/cli/deps.ts";
import { initSubcommand } from "./src/cli/init.ts";
import { routesSubcommand } from "./src/cli/routes.ts";
import { manifestSubcommand } from "./src/cli/manifest.ts";
const VERSION = "0.1.0";
@@ -10,12 +10,12 @@ Preact, but super edgy.
To initalize a new project:
fresh init ./myproject
To (re-)generate route manifest:
fresh routes
To (re-)generate the manifest file:
fresh manifest
SUBCOMMANDS:
init Initalize a fresh project
routes (Re-)generate the route manifest file
manifest (Re-)generate the manifest file
`;
const args = parseArgs(Deno.args, {
@@ -34,8 +34,8 @@ switch (subcommand) {
case "init":
await initSubcommand(args);
break;
case "routes":
await routesSubcommand(args);
case "manifest":
await manifestSubcommand(args);
break;
default:
if (args.version) {
+35 -32
View File
@@ -4,35 +4,50 @@ Not all pages can be server rendered synchronously - some pages are dynamic and
require fetching some data from an external source. This data fetching is often
asynchronous.
Fresh supports asynchronous data fetch in server render using suspense. This
allows render to be interupted to wait for a promise to resolve. Once the
promise resolves, the render is retried.
Fresh supports asynchronous data fetching in handlers. This is not done during
rendering, but before rendering in the route
handler<!-- TODO: link route handlers page -->.
## `useData` hook
## Fetching data in a `handler`
To make using asynchronous data sources during server render super easy, fresh
exposes the `useData` hook. This hook takes a key and a fetcher function that
can return a promise. It is invoked once on the server. The server will wait
until the promise resolves, at which point it will render the page with the new
data.
To fetch data, you must first define a custom `handler` function. This function
is called when the route is requested. In there you can do some handling, and
then return a `Response` object. If you want to render the page, you can call
the `ctx.render` function. This returns a `Promise<Response>` that you can
return from the handler.
The fetcher for the `useData` hook is never run on the client. Instead the data
that was computed on the server during render will be used.
The `ctx.render` function takes a single argument, which is some data that you
want to pass to the page template. The data can be accessed in the template via
the `props.data` property.
Here is a usage example of a `useData` hook where the fetcher fetches the URL
provided as the key as JSON:
Here is a usage example of a `handler` fetches a URL as JSON and provides the
resulting data to the template:
```tsx
import { h, PageProps, useData } from "../deps.ts";
import { h, Handlers, PageProps, useData } from "../deps.ts";
export default function Page(_props: PageProps) {
const info = useData("https://cdn.deno.land/std/meta/versions.json", fetcher);
interface ModuleInfo {
latest: string;
versions: string[];
}
if (info === null) {
export const handler: Handlers<ModuleInfo> = {
async GET(ctx) {
const resp = await fetch("https://cdn.deno.land/std/meta/versions.json");
let data = null;
if (resp.status === 200) data = await resp.json();
return ctx.render(data);
},
};
export default function Page(props: PageProps<ModuleInfo>) {
const data = props.data;
if (data === null) {
return <div>Data not available.</div>;
}
const { latest, versions } = info;
const { latest, versions } = data;
return (
<p>
The Deno standard library has {versions.length} versions, with {latest}
@@ -41,19 +56,7 @@ export default function Page(_props: PageProps) {
</p>
);
}
interface ModuleInfo {
latest: string;
versions: string[];
}
async function fetcher(url: string): Promise<ModuleInfo | null> {
const resp = await fetch(url);
if (resp.status === 200) return resp.json();
return null;
}
```
The `useData` can not generate data client side. Calling `useData` on the client
with a key that no data was generated for on the server will result in `useData`
throwing an error.
If you want to fetch data client side, inside of an island, you can use
libraries like `"swr"`, or raw `useEffect` and `useState` as you usually would.
+1 -1
View File
@@ -1,6 +1,6 @@
# File system routing
The naming and location of files in the `pages` folder is important because
The naming and location of files in the `routes` folder is important because
these are used to specify the route where a specific API endpoint or HTML page
is available. This concept is called file system routing.
+5 -7
View File
@@ -66,13 +66,11 @@ to Deno Deploy with (or an organization you can access from that account). Then
follow the setup instructions for GitHub on your machine, and push your code
into the repository.
Now go back to GitHub and open the `main.ts` file that you pushed. Copy the URL
in the address bar. It should look something like this:
`https://github.com/lucacasonato/fresh/blob/main/example/main.ts`. Visit your
project on dash.deno.com, enter the URL you copied into the
`Link GitHub repository` input box in the project settings, and press `Link`.
You might need to grant the Deno Deploy app permission to the repository at this
point (follow prompts on the Deno Deploy dashboard).
Visit your project on dash.deno.com, go to the "Git" tab in the settings, select
your organization and repository, select your production branch (usually
`main`), and finally select your entrypoint module (`main.ts`. You might need to
grant the Deno Deploy app permission to the repository at this point (follow
prompts on the Deno Deploy dashboard).
Your project is now linked to Deno Deploy and will automatically deployed on
every push. Your project now has a URL you can visit to view your site live.
+14 -14
View File
@@ -1,24 +1,24 @@
# Project strcture
Initalizing a fresh project will generate multiple files. For now the most
important files are `main.ts`, `routes.gen.ts`, and the pages and api routes in
the `pages` subfolder.
important files are `main.ts`, `fresh.gen.ts`, the route modules in the `routes`
subdirectory, and the islands in the `islands` subdirectory.
The `main.ts` file is the entrypoint to your project. It is the file you link in
Deno Deploy, or run locally with the `deno` CLI.
The `routes.gen.ts` file is a manifest of all pages and api routes in a project.
When moving around or creating new pages, this file needs to be updated. This is
done automatically when you run the `fresh routes` command. You never have to
edit this file manually.
The `fresh.gen.ts` file is a manifest of all routes and islands in a project.
When moving around or creating new pages or islands, this file needs to be
updated. This is done automatically when you run the `fresh manifest` command.
You never have to edit this file manually.
The files in the `pages` subfolder describe the HTML pages and API endpoints of
your application. All pages can act as both API endpoints and possibly dynamic
HTML pages. More info about how the `pages` subfolder works can be found on the
The files in the `routes` subfolder describe the HTML pages and API endpoints of
your application. All routes can act as both API endpoints and dynamic HTML
pages. More info about how the `routes` subdirectory works can be found on the
[file system routing](./file-system-routing.md) page.
Finally there is a `deps.ts` and `api_deps.ts`. These files are the central
location for all external imports. The `deps.ts` file is used for runtime
dependencies (ones that are used both on the server and on the client), and the
`api_deps.ts` file is used for server only dependencies (for example ones used
in API routes).
Finally there is a `client_deps.ts` and `server_deps.ts`. These files are the
central location for all external imports. The `client_deps.ts` file is used for
runtime dependencies (ones that are used both in routes and islands), and the
`server_deps.ts` file is used for server only dependencies (for example ones
used in API routes or middleware).
+16
View File
@@ -0,0 +1,16 @@
# fresh project
### Usage
Start the project:
```
deno run -A --watch main.ts
```
After adding, removing, or moving a page in the `routes` or directory, or
adding, removing, or moving an island in the `islands` directory, run:
```
fresh manifest
```
@@ -1,2 +1 @@
export * from "../../runtime.ts";
export * from "../../server.ts";
+18
View File
@@ -0,0 +1,18 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./routes/index.tsx";
import * as $$0 from "./islands/Counter.tsx";
const manifest = {
routes: {
"./routes/index.tsx": $0,
},
islands: {
"./islands/Counter.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
+21
View File
@@ -0,0 +1,21 @@
/** @jsx h */
import { h, IS_BROWSER, useState } from "../client_deps.ts";
interface CounterProps {
start: number;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
-1
</button>
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
+1
</button>
</div>
);
}
@@ -1,11 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "../../server.ts";
import routes from "./routes.gen.ts";
import { start } from "./server_deps.ts";
import manifest from "./fresh.gen.ts";
await start(routes);
await start(manifest);
+15
View File
@@ -0,0 +1,15 @@
/** @jsx h */
import { h } from "../client_deps.ts";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<p>
Welcome to `fresh`. Try update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter start={3} />
</div>
);
}
+1
View File
@@ -0,0 +1 @@
export * from "../../server.ts";
-5
View File
@@ -1,5 +0,0 @@
{
"deno.enable": true,
"deno.lint": true,
"deno.unstable": true
}
-15
View File
@@ -1,15 +0,0 @@
# fresh project
### Usage
Start the project:
```
deno run -A --watch main.ts
```
After adding, removing, or moving a page in the `pages` directory, run:
```
fresh routes
```
-50
View File
@@ -1,50 +0,0 @@
/** @jsx h */
import { h, HandlerContext, PageConfig, Suspense, useData } from "../deps.ts";
import { getDatabase, Todo } from "../utils/database.ts";
export default function TodoListPage() {
return (
<div>
<h1>Your TODOs</h1>
<AddTodoForm />
<Suspense fallback={<p>Loading...</p>}>
<TodoList />
</Suspense>
</div>
);
}
function AddTodoForm() {
return (
<form method="POST">
<input type="text" name="text" />
<button type="submit" style="margin-left: 4px">Add</button>
</form>
);
}
function TodoList() {
const todos = useData<Todo[]>("todos", async () => {
const db = await getDatabase();
const todos = await db.listTodos();
return todos;
});
return (
<ul>
{todos.map((todo) => <li key={todo.id}>{todo.text}</li>)}
</ul>
);
}
export const handler = {
async POST(ctx: HandlerContext): Promise<Response> {
const form = await ctx.req.formData();
const text = form.get("text");
if (typeof text !== "string") {
return new Response("misformed form", { status: 400 });
}
const db = await getDatabase();
await db.addTodo(text);
return Response.redirect(ctx.req.url, 303);
},
};
-14
View File
@@ -1,14 +0,0 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./pages/index.tsx";
const routes = {
pages: {
"./pages/index.tsx": $0,
},
baseUrl: import.meta.url,
};
export default routes;
-43
View File
@@ -1,43 +0,0 @@
import { Client } from "https://raw.githubusercontent.com/denodrivers/postgres/72f523cb9d8f863204a3fa02f52d534e7ce30ccf/mod.ts";
export interface Todo {
id: number;
text: string;
}
class Database {
#client: Client;
constructor(client: Client) {
this.#client = client;
}
static async connect() {
const client = new Client(Deno.env.get("DATABASE_URL"));
await client.connect();
await client.queryObject`CREATE TABLE IF NOT EXISTS todos (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL
)`;
return new Database(client);
}
async listTodos(): Promise<Todo[]> {
const { rows } = await this.#client.queryObject<Todo>`SELECT * FROM todos`;
return rows;
}
async addTodo(text: string): Promise<Todo> {
const { rows } = await this.#client.queryObject<Todo>`
INSERT INTO todos (text) VALUES (${text})
RETURNING *
`;
return rows[0];
}
}
const db: Database | Promise<Database> = Database.connect();
export async function getDatabase(): Promise<Database> {
return await db;
}
+1 -1
View File
@@ -5,7 +5,7 @@ lint:
deno lint
test:
deno test -A --no-check
deno test -A --no-check=remote
dev:
deno run -A --watch=www/static --no-check www/main.ts
-2
View File
@@ -1,7 +1,5 @@
export * from "./src/runtime/deps.ts";
export * from "./src/runtime/types.ts";
export * from "./src/runtime/suspense.ts";
export * from "./src/runtime/utils.ts";
export * from "./src/runtime/hooks.ts";
export * from "./src/runtime/head.ts";
export * from "./src/runtime/csp.ts";
+51 -34
View File
@@ -1,6 +1,6 @@
import { join, resolve } from "./deps.ts";
import { error } from "./error.ts";
import { routes } from "./routes.ts";
import { manifest } from "./manifest.ts";
const help = `fresh init
@@ -57,30 +57,50 @@ async function init(directory: string) {
}
}
await Deno.mkdir(join(directory, "pages", "api"), { recursive: true });
const DEPS_TS = `export * from "${new URL(
await Deno.mkdir(join(directory, "routes", "api"), { recursive: true });
await Deno.mkdir(join(directory, "islands"), { recursive: true });
const CLIENT_DEPS_TS = `export * from "${new URL(
"../../runtime.ts",
import.meta.url,
)}";\n`;
await Deno.writeTextFile(join(directory, "deps.ts"), DEPS_TS);
const PAGES_INDEX_TSX = `/** @jsx h */
import { h, IS_BROWSER, PageConfig, useState } from "../deps.ts";
await Deno.writeTextFile(join(directory, "client_deps.ts"), CLIENT_DEPS_TS);
const SERVER_DEPS_TS = `export * from "${new URL(
"../../server.ts",
import.meta.url,
)}";\n`;
await Deno.writeTextFile(join(directory, "server_deps.ts"), SERVER_DEPS_TS);
const ROUTES_INDEX_TSX = `/** @jsx h */
import { h } from "../client_deps.ts";
import Counter from "../islands/Counter.tsx";
export default function Home() {
return (
<div>
<p>
Welcome to \`fresh\`. Try update this message in the ./pages/index.tsx
Welcome to \`fresh\`. Try update this message in the ./routes/index.tsx
file, and refresh.
</p>
<Counter />
<p>{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}</p>
<Counter start={3} />
</div>
);
}
`;
await Deno.writeTextFile(
join(directory, "routes", "index.tsx"),
ROUTES_INDEX_TSX,
);
function Counter() {
const [count, setCount] = useState(0);
const ISLANDS_COUNTER_TSX = `/** @jsx h */
import { h, IS_BROWSER, useState } from "../client_deps.ts";
interface CounterProps {
start: number;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div>
<p>{count}</p>
@@ -93,31 +113,26 @@ function Counter() {
</div>
);
}
export const config: PageConfig = { runtimeJS: true };
`;
await Deno.writeTextFile(
join(directory, "pages", "index.tsx"),
PAGES_INDEX_TSX,
join(directory, "islands", "Counter.tsx"),
ISLANDS_COUNTER_TSX,
);
const PAGES_GREET_TSX = `/** @jsx h */
import { h } from "../deps.ts";
interface Props {
params: Record<string, string | string[]>;
}
const ROUTES_GREET_TSX = `/** @jsx h */
import { h, PageProps } from "../client_deps.ts";
export default function Greet(props: Props) {
export default function Greet(props: PageProps) {
return <div>Hello {props.params.name}</div>;
}
`;
await Deno.writeTextFile(
join(directory, "pages", "[name].tsx"),
PAGES_GREET_TSX,
join(directory, "routes", "[name].tsx"),
ROUTES_GREET_TSX,
);
const serverUrl = new URL("../../server.ts", import.meta.url);
const PAGES_API_JOKE_TS = `import { HandlerContext } from "${serverUrl}";
const ROUTES_API_JOKE_TS =
`import { HandlerContext } from "../server_deps.ts";
// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/
const JOKES = [
@@ -140,19 +155,20 @@ export const handler = (_ctx: HandlerContext): Response => {
};
`;
await Deno.writeTextFile(
join(directory, "pages", "api", "joke.ts"),
PAGES_API_JOKE_TS,
join(directory, "routes", "api", "joke.ts"),
ROUTES_API_JOKE_TS,
);
const MAIN_TS = `/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "${serverUrl}";
import routes from "./routes.gen.ts";
import { start } from "./server_deps.ts";
import manifest from "./fresh.gen.ts";
await start(routes);
await start(manifest);
`;
await Deno.writeTextFile(
join(directory, "main.ts"),
@@ -168,10 +184,11 @@ Start the project:
deno run -A --watch main.ts
\`\`\`
After adding, removing, or moving a page in the \`pages\` directory, run:
After adding, removing, or moving a page in the \`routes\` or directory, or adding,
removing, or moving an island in the \`islands\` directory, run:
\`\`\`
fresh routes
fresh manifest
\`\`\`
`;
await Deno.writeTextFile(
@@ -179,5 +196,5 @@ fresh routes
README_MD,
);
await routes(directory);
await manifest(directory);
}
+137
View File
@@ -0,0 +1,137 @@
import { join, resolve, toFileUrl, walk } from "./deps.ts";
const help = `fresh manifest
Regenerate the fresh.gen.ts manifest for your fresh project.
To regenerate the mapping in the current directory:
fresh manifest
To regenerate the mapping in the './foobar' subdirectory:
fresh manifest ./foobar
USAGE:
fresh manifest [OPTIONS] [DIRECTORY]
OPTIONS:
-h, --help Prints help information
`;
export interface Args {
help: boolean;
}
// deno-lint-ignore no-explicit-any
export async function manifestSubcommand(rawArgs: Record<string, any>) {
const args: Args = {
help: !!rawArgs.help,
};
const directory: string | null = typeof rawArgs._[0] === "string"
? rawArgs._[0]
: Deno.cwd();
if (args.help) {
console.log(help);
Deno.exit(0);
}
await manifest(directory);
}
export async function manifest(directory: string) {
directory = resolve(directory);
const routes = [];
try {
const routesDir = join(directory, "./routes");
const routesUrl = toFileUrl(routesDir);
// TODO(lucacasonato): remove the extranious Deno.readDir when
// https://github.com/denoland/deno_std/issues/1310 is fixed.
for await (const _ of Deno.readDir(routesDir)) {
// do nothing
}
const routesFolder = walk(routesDir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
});
for await (const entry of routesFolder) {
if (entry.isFile) {
const file = toFileUrl(entry.path).href.substring(
routesUrl.href.length,
);
routes.push(file);
}
}
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// Do nothing.
} else {
throw err;
}
}
const islands = [];
try {
const islandsDir = join(directory, "./islands");
const islandsUrl = toFileUrl(islandsDir);
// TODO(lucacasonato): remove the extranious Deno.readDir when
// https://github.com/denoland/deno_std/issues/1310 is fixed.
for await (const _ of Deno.readDir(islandsDir)) {
// do nothing
}
const islandsFolder = walk(islandsDir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
});
for await (const entry of islandsFolder) {
if (entry.isFile) {
const file = toFileUrl(entry.path).href.substring(
islandsUrl.href.length,
);
islands.push(file);
}
}
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// Do nothing.
} else {
throw err;
}
}
const output = `// DO NOT EDIT. This file is generated by \`fresh\`.
// This file SHOULD be checked into source version control.
// To update this file, run \`fresh routes\`.
${
routes.map((file, i) => `import * as $${i} from "./routes${file}";`).join(
"\n",
)
}
${
islands.map((file, i) => `import * as $$${i} from "./islands${file}";`)
.join("\n")
}
const manifest = {
routes: {
${
routes.map((file, i) => `${JSON.stringify(`./routes${file}`)}: $${i},`)
.join("\n ")
}
},
islands: {
${
islands.map((file, i) => `${JSON.stringify(`./islands${file}`)}: $$${i},`)
.join("\n ")
}
},
baseUrl: import.meta.url,
};
export default manifest;
`;
const manifestPath = join(directory, "./fresh.gen.ts");
await Deno.writeTextFile(manifestPath, output);
console.log("Manifest generated and written to", manifestPath);
}
-78
View File
@@ -1,78 +0,0 @@
import { join, resolve, toFileUrl, walk } from "./deps.ts";
const help = `fresh routes
Regenerate the route mapping for your fresh project.
To regenerate the mapping in the current directory:
fresh routes
To regenerate the mapping in the './foobar' subdirectory:
fresh routes ./foobar
USAGE:
fresh routes [OPTIONS] [DIRECTORY]
OPTIONS:
-h, --help Prints help information
`;
export interface Args {
help: boolean;
}
// deno-lint-ignore no-explicit-any
export async function routesSubcommand(rawArgs: Record<string, any>) {
const args: Args = {
help: !!rawArgs.help,
};
const directory: string | null = typeof rawArgs._[0] === "string"
? rawArgs._[0]
: Deno.cwd();
if (args.help) {
console.log(help);
Deno.exit(0);
}
await routes(directory);
}
export async function routes(directory: string) {
directory = resolve(directory);
const files = [];
const pagesDir = join(directory, "./pages");
const pagesUrl = toFileUrl(pagesDir);
const folder = walk(pagesDir, {
includeDirs: false,
includeFiles: true,
exts: ["tsx", "jsx", "ts", "js"],
});
for await (const entry of folder) {
if (entry.isFile) {
const file = toFileUrl(entry.path).href.substring(pagesUrl.href.length);
files.push(file);
}
}
const output = `// DO NOT EDIT. This file is generated by \`fresh\`.
// This file SHOULD be checked into source version control.
// To update this file, run \`fresh routes\`.
${files.map((file, i) => `import * as $${i} from "./pages${file}";`).join("\n")}
const routes = {
pages: {
${
files.map((file, i) => `${JSON.stringify(`./pages${file}`)}: $${i},`)
.join("\n ")
}
},
baseUrl: import.meta.url,
};
export default routes;
`;
const routeManifestPath = join(directory, "./routes.gen.ts");
await Deno.writeTextFile(routeManifestPath, output);
console.log("Route manifest generated and written to", routeManifestPath);
}
+3 -3
View File
@@ -1,4 +1,4 @@
export * from "https://esm.sh/preact@10.5.14";
export * from "https://esm.sh/preact@10.6.6";
export {
useCallback,
useContext,
@@ -11,7 +11,7 @@ export {
useReducer,
useRef,
useState,
} from "https://esm.sh/preact@10.5.14/hooks";
} from "https://esm.sh/preact@10.6.6/hooks";
export type {
CreateHandle,
EffectCallback,
@@ -20,4 +20,4 @@ export type {
Reducer,
Ref,
StateUpdater,
} from "https://esm.sh/preact@10.5.14/hooks";
} from "https://esm.sh/preact@10.6.6/hooks";
-60
View File
@@ -1,60 +0,0 @@
import { createContext, useContext } from "./deps.ts";
import { IS_BROWSER } from "./utils.ts";
export const DATA_CONTEXT = createContext(new Map<string, unknown>());
export type Fetcher<T> = (key: string) => T | Promise<T>;
/**
* The `useData` hook can be used to fetch some data during JIT rendering.
* On the client the hook will return the data that was computed during JIT
* rendering. If `useData` is called on the client with a different key than
* during JIT rendering, an error will occur.
*
* The fetcher can be asynchronous. The render will be suspended while waiting
* for the asynchronous data to be ready. Once the promise is ready we rerender.
* Because of the suspense it is possible that a page or component can be
* rendered more than once during a JIT render.
*
* ```tsx
* export default function App() {
* const { latest, versions } = useData("https://cdn.deno.land/std/meta/versions.json", fetcher);
* return <p>The Deno standard library has {versions.length} versions, with {latest} being the most recent.</p>
* }
*
* async function fetcher(url: string) {
* const resp = await fetch(url);
* return resp.json();
* }
* ```
*
* @param key A unique identifier for this data.
* @param fetcher The function used to fetch data based on the above key.
* @returns The the data that the promise returned from `fetcher` resolves to.
*/
export function useData<T>(key: string, fetcher: Fetcher<T>): T {
const DATA_CACHE = useContext(DATA_CONTEXT);
// If there is no data or pending promise for this key in the data cache yet,
// call the fetcher, store it into the cache, and possibly suspend.
if (!DATA_CACHE.has(key)) {
if (IS_BROWSER) {
throw new Error(
`'useData' can not fetch new data on the client. The JIT render did not generate data for key '${key}'.`,
);
}
const data = fetcher(key);
if (data instanceof Promise) {
data.then((data) => {
DATA_CACHE.set(key, data);
});
}
DATA_CACHE.set(key, data);
}
const data = DATA_CACHE.get(key);
// If the data is a promise, suspend the component.
if (data instanceof Promise) throw data;
// else return the data.
return data as T;
}
-33
View File
@@ -1,33 +0,0 @@
import {
ComponentChild,
ComponentChildren,
createContext,
Fragment,
h,
useContext,
} from "./deps.ts";
import { IS_BROWSER } from "./utils.ts";
export const SUSPENSE_CONTEXT = createContext<ComponentChildren[]>([]);
export interface SuspenseProps {
fallback: ComponentChild;
children: ComponentChildren;
}
export function Suspense(props: SuspenseProps) {
if (IS_BROWSER) {
throw new Error(`'<Suspense>' is not supported on the client yet.`);
}
const suspenseData = useContext(SUSPENSE_CONTEXT);
const id = suspenseData.push(props.children);
return h(
Fragment,
null,
h("template", { id: `S:${id}` }),
props.fallback,
h("template", { id: `E:${id}` }),
);
}
+5 -6
View File
@@ -1,8 +1,7 @@
import { ComponentType } from "./deps.ts";
export interface PageProps<
T extends Record<string, unknown> = Record<string, unknown>,
> {
// deno-lint-ignore no-explicit-any
export interface PageProps<T = any> {
/** The URL of the request that resulted in this page being rendered. */
url: URL;
@@ -21,10 +20,10 @@ export interface PageProps<
params: Record<string, string>;
/**
* Additional data passed into `HandlerContext.render`. Not present by
* default.
* Additional data passed into `HandlerContext.render`. Defaults to
* `undefined`.
*/
renderData?: T;
data: T;
}
export interface AppProps {
+35 -40
View File
@@ -1,5 +1,5 @@
import { denoPlugin, esbuild, esbuildTypes, toFileUrl } from "./deps.ts";
import { Page } from "./types.ts";
import { Island } from "./types.ts";
let esbuildInitalized: boolean | Promise<void> = false;
async function ensureEsbuildInialized() {
@@ -20,22 +20,20 @@ async function ensureEsbuildInialized() {
}
export class Bundler {
#pages: Page[];
#islands: Island[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
#preloads = new Map<string, string[]>();
constructor(pages: Page[]) {
this.#pages = pages;
constructor(islands: Island[]) {
this.#islands = islands;
}
async bundle() {
const entryPoints: Record<string, string> = {};
for (const page of this.#pages) {
if (page.component !== undefined && page.runtimeJS) {
entryPoints[page.name] = `fresh:///${page.name}`;
}
for (const island of this.#islands) {
entryPoints[island.id] = `fresh:///${island.id}`;
}
const absWorkingDir = Deno.cwd();
await ensureEsbuildInialized();
const bundle = await esbuild.build({
@@ -50,21 +48,21 @@ export class Bundler {
absWorkingDir,
outfile: "",
platform: "neutral",
plugins: [freshPlugin(this.#pages), denoPlugin()],
plugins: [freshPlugin(this.#islands), denoPlugin()],
splitting: true,
target: ["chrome90", "firefox88", "safari13"],
treeShaking: true,
write: false,
});
const metafileOutputs = bundle.metafile!.outputs;
// const metafileOutputs = bundle.metafile!.outputs;
for (const path in metafileOutputs) {
const meta = metafileOutputs[path];
const imports = meta.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => `/${path}`);
this.#preloads.set(`/${path}`, imports);
}
// for (const path in metafileOutputs) {
// const meta = metafileOutputs[path];
// const imports = meta.imports
// .filter(({ kind }) => kind === "import-statement")
// .map(({ path }) => `/${path}`);
// this.#preloads.set(`/${path}`, imports);
// }
const cache = new Map<string, Uint8Array>();
const absDirUrlLength = toFileUrl(absWorkingDir).href.length;
@@ -94,18 +92,18 @@ export class Bundler {
return cache.get(path) ?? null;
}
getPreloads(path: string): string[] {
return this.#preloads.get(path) ?? [];
}
// getPreloads(path: string): string[] {
// return this.#preloads.get(path) ?? [];
// }
}
function freshPlugin(pageList: Page[]): esbuildTypes.Plugin {
function freshPlugin(islands: Island[]): esbuildTypes.Plugin {
const runtime = new URL("../../runtime.ts", import.meta.url);
const pageMap = new Map<string, Page>();
const islandMap = new Map<string, Island>();
for (const page of pageList) {
pageMap.set(`/${page.name}`, page);
for (const island of islands) {
islandMap.set(`/${island.id}`, island);
}
return {
@@ -127,24 +125,21 @@ function freshPlugin(pageList: Page[]): esbuildTypes.Plugin {
): esbuildTypes.OnLoadResult | null | undefined {
const url = new URL(args.path);
const path = url.pathname;
const page = pageMap.get(path);
if (!page) return null;
const island = islandMap.get(path);
if (!island) return null;
const contents = `
import Page from "${page.url}";
import { h, render, DATA_CONTEXT } from "${runtime.href}";
import ${island.name} from "${island.url}";
import { h, render } from "${runtime.href}";
addEventListener("DOMContentLoaded", () => {
const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS")?.textContent ?? "{}");
try {
render(h(DATA_CONTEXT.Provider, { value: new Map(data ?? []) }, h(Page, { params: params ?? {} })), document.getElementById("__FRSH"));
} catch(err) {
if (err instanceof Promise) {
console.error("Render tried to suspend without a suspense boundary.");
} else {
console.error("Render threw an error:", err);
}
class ${island.name}Island extends HTMLElement {
constructor() {
super();
const props = JSON.parse(this.getAttribute("props"));
render(h(${island.name}, props), this);
}
});
}
customElements.define("frsh-${island.id}", ${island.name}Island);
`;
return { contents, loader: "js" };
},
-36
View File
@@ -1,36 +0,0 @@
(() => {
/** Replace a suspense component with it's final variant. */
window.$SR = (id) => {
const targetStart = document.getElementById("S:" + id);
const targetEnd = document.getElementById("E:" + id);
const replacement = document.getElementById("R:" + id);
replacement.parentNode.removeChild(replacement);
while (targetStart.nextSibling !== targetEnd) {
targetStart.parentNode.removeChild(targetStart.nextSibling);
}
while (replacement.firstChild) {
targetStart.parentNode.insertBefore(replacement.firstChild, targetEnd);
}
targetStart.parentNode.removeChild(targetStart);
targetEnd.parentNode.removeChild(targetEnd);
};
/** @type {HTMLStyleElement} */
const sheetElement = document.getElementById("__FRSH_STYLE");
const rules = sheetElement.childNodes[0]?.textContent.split("\n");
if (rules !== undefined) {
sheetElement.removeChild(sheetElement.firstChild);
for (const rule of rules) {
sheetElement.append(document.createTextNode(rule));
}
}
/** Insert new style rules. */
window.$ST = (inserts) => {
for (const [rule, index] of inserts) {
sheetElement.insertBefore(
document.createTextNode(rule),
sheetElement.childNodes[index],
);
}
};
})();
+79 -88
View File
@@ -6,7 +6,7 @@ import {
toFileUrl,
walk,
} from "./deps.ts";
import { Routes } from "./mod.ts";
import { Manifest } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import { ALIVE_URL, INTERNAL_PREFIX, REFRESH_JS_URL } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
@@ -16,6 +16,7 @@ import {
ErrorPage,
ErrorPageModule,
Handler,
Island,
Middleware,
MiddlewareModule,
Page,
@@ -26,11 +27,7 @@ import {
UnknownPageModule,
} from "./types.ts";
import { render as internalRender } from "./render.tsx";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { h } from "../runtime/deps.ts";
interface StaticFile {
@@ -49,6 +46,7 @@ interface StaticFile {
export class ServerContext {
#dev: boolean;
#pages: Page[];
#islands: Island[];
#staticFiles: StaticFile[];
#bundler: Bundler;
#renderer: Renderer;
@@ -59,6 +57,7 @@ export class ServerContext {
constructor(
pages: Page[],
islands: Island[],
staticFiles: StaticFile[],
renderer: Renderer,
middleware: Middleware,
@@ -67,36 +66,38 @@ export class ServerContext {
error: ErrorPage,
) {
this.#pages = pages;
this.#islands = islands;
this.#staticFiles = staticFiles;
this.#renderer = renderer;
this.#middleware = middleware;
this.#app = app;
this.#notFound = notFound;
this.#error = error;
this.#bundler = new Bundler(pages);
this.#bundler = new Bundler(this.#islands);
this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy).
}
/**
* Process the routes into individual components and pages.
* Process the manifest into individual components and pages.
*/
static async fromRoutes(routes: Routes): Promise<ServerContext> {
// Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href;
static async fromManifest(manifest: Manifest): Promise<ServerContext> {
// Get the manifest' base URL.
const baseUrl = new URL("./", manifest.baseUrl).href;
// Extract all routes, and prepare them into the `Page` structure.
const pages: Page[] = [];
const islands: Island[] = [];
let renderer: Renderer = DEFAULT_RENDERER;
let middleware: Middleware = DEFAULT_MIDDLEWARE;
let app: AppModule = DEFAULT_APP;
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
let error: ErrorPage = DEFAULT_ERROR;
for (const [self, module] of Object.entries(routes.pages)) {
for (const [self, module] of Object.entries(manifest.routes)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("pages".length);
const path = url.substring(baseUrl.length).substring("routes".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const name = baseRoute.replace("/", "-");
if (!path.startsWith("/_")) {
@@ -111,7 +112,7 @@ export class ServerContext {
component &&
typeof handler === "object" && handler.GET === undefined
) {
handler.GET = ({ render }) => render!();
handler.GET = ({ render }) => render();
}
const page: Page = {
route,
@@ -119,7 +120,6 @@ export class ServerContext {
name,
component,
handler,
runtimeJS: Boolean(config?.runtimeJS ?? false),
csp: Boolean(config?.csp ?? false),
};
pages.push(page);
@@ -145,7 +145,7 @@ export class ServerContext {
const { default: component, config } = (module as UnknownPageModule);
let { handler } = (module as UnknownPageModule);
if (component && handler === undefined) {
handler = ({ render }) => render!();
handler = ({ render }) => render();
}
notFound = {
@@ -164,7 +164,7 @@ export class ServerContext {
const { default: component, config } = (module as ErrorPageModule);
let { handler } = (module as ErrorPageModule);
if (component && handler === undefined) {
handler = ({ render }) => render!();
handler = ({ render }) => render();
}
error = {
@@ -181,9 +181,21 @@ export class ServerContext {
}
sortRoutes(pages);
for (const [self, module] of Object.entries(manifest.islands)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("islands".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const name = baseRoute.replace("/", "");
const id = name.toLowerCase();
islands.push({ id, name, url, component: module.default });
}
const staticFiles: StaticFile[] = [];
try {
const staticFolder = new URL("./static", routes.baseUrl);
const staticFolder = new URL("./static", manifest.baseUrl);
// TODO(lucacasonato): remove the extranious Deno.readDir when
// https://github.com/denoland/deno_std/issues/1310 is fixed.
for await (const _ of Deno.readDir(fromFileUrl(staticFolder))) {
@@ -227,6 +239,7 @@ export class ServerContext {
}
return new ServerContext(
pages,
islands,
staticFiles,
renderer,
middleware,
@@ -277,84 +290,67 @@ export class ServerContext {
);
}
const genRender = (page: Page, status: number) => {
const bundlePath = `/${page.name}.js`;
const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : [];
const genRender = <Data = undefined>(
page: Page<Data> | UnknownPage | ErrorPage,
status: number,
) => {
const imports: string[] = [];
if (this.#dev) {
imports.push(REFRESH_JS_URL);
}
return (
req: Request,
params: Record<string, string | string[]>,
params: Record<string, string>,
error?: unknown,
) => {
if (page.component === undefined) return undefined;
return async (renderData?: Record<string, unknown>) => {
const preloads = page.runtimeJS
? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
: [];
const body = internalRender({
page,
app: this.#app,
imports,
preloads,
renderer: this.#renderer,
url: new URL(req.url),
params,
renderData,
error,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
let firstChunk: string;
const iterator = body[Symbol.asyncIterator]();
return (data?: Data) => {
if (page.component === undefined) {
throw new Error("This page does not have a component to render.");
}
const preloads: string[] = [];
let resp;
try {
const { value, done } = await iterator.next();
if (done) throw new Error("Body is empty.");
firstChunk = value[0];
const csp: ContentSecurityPolicy | undefined = value[1];
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
resp = internalRender({
page,
islands: this.#islands,
app: this.#app,
imports,
preloads,
renderer: this.#renderer,
url: new URL(req.url),
params,
data,
error,
});
} catch (err) {
console.error("Error rendering page", err);
throw new Response("500 Internal Server Error", {
return new Response("500 Internal Server Error", {
status: 500,
headers: {
"content-type": "text/plain",
},
});
}
const bodyStream = new ReadableStream<Uint8Array>({
async start(controller) {
controller.enqueue(new TextEncoder().encode(firstChunk));
try {
for await (const chunk of body) {
controller.enqueue(new TextEncoder().encode(chunk as string));
}
} catch (err) {
console.log("Rendering failed:\n", err);
controller.enqueue(
new TextEncoder().encode("500 Internal Server Error"),
);
}
controller.close();
},
});
return new Response(bodyStream, { status, headers });
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
return new Response(body, { status, headers });
};
};
};
@@ -378,17 +374,16 @@ export class ServerContext {
const unknownHandlerRender = genRender(this.#notFound, 404);
const unknownHandler = (req: Request) =>
(this.#notFound.handler as Handler)({
this.#notFound.handler({
req,
match: {},
render: unknownHandlerRender(req, {}),
});
const errorHandlerRender = genRender(this.#error, 500);
const errorHandler = (req: Request, error: unknown) =>
(this.#notFound.handler as Handler)({
this.#error.handler({
req,
match: {},
error,
render: errorHandlerRender(req, {}, error),
});
@@ -485,10 +480,6 @@ export class ServerContext {
};
}
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
const DEFAULT_RENDERER: Renderer = {
render(_ctx, render) {
render();
+1 -1
View File
@@ -1,5 +1,5 @@
// -- preact --
export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.14";
export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.20?deps=preact@10.6.6";
// -- std --
export {
+14 -5
View File
@@ -2,26 +2,35 @@ import { ServerContext } from "./context.ts";
import { listenAndServe } from "./deps.ts";
import {
AppModule,
ErrorPageModule,
IslandModule,
MiddlewareModule,
PageModule,
RendererModule,
UnknownPageModule,
} from "./types.ts";
export type { Handler, HandlerContext, Handlers } from "./types.ts";
export { RenderContext } from "./render.tsx";
export type { RenderFn } from "./render.tsx";
export interface Routes {
pages: Record<
export interface Manifest {
routes: Record<
string,
PageModule | RendererModule | MiddlewareModule | AppModule
| PageModule
| RendererModule
| MiddlewareModule
| AppModule
| ErrorPageModule
| UnknownPageModule
>;
islands: Record<string, IslandModule>;
baseUrl: string;
}
export { ServerContext };
export async function start(routes: Routes) {
const ctx = await ServerContext.fromRoutes(routes);
export async function start(routes: Manifest) {
const ctx = await ServerContext.fromManifest(routes);
console.log("Server listening on http://localhost:8000");
await listenAndServe(":8000", ctx.handler());
}
+89 -204
View File
@@ -1,29 +1,35 @@
/** @jsx h */
import { renderToString } from "./deps.ts";
import { ComponentChildren, h } from "../runtime/deps.ts";
import { DATA_CONTEXT } from "../runtime/hooks.ts";
import { AppModule, ErrorPage, Page, Renderer, UnknownPage } from "./types.ts";
import {
ErrorPageProps,
PageProps,
UnknownPageProps,
} from "../runtime/types.ts";
import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts";
ComponentChildren,
ComponentType,
h,
options,
VNode,
} from "../runtime/deps.ts";
import {
AppModule,
ErrorPage,
Island,
Page,
Renderer,
UnknownPage,
} from "./types.ts";
import { HEAD_CONTEXT } from "../runtime/head.ts";
import { REFRESH_JS_URL } from "./constants.ts";
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
export interface RenderOptions {
page: Page | UnknownPage | ErrorPage;
export interface RenderOptions<Data> {
page: Page<Data> | UnknownPage | ErrorPage;
islands: Island[];
app: AppModule;
imports: string[];
preloads: string[];
url: URL;
params: Record<string, string | string[]>;
renderer: Renderer;
renderData?: Record<string, unknown>;
data?: Data;
error?: unknown;
}
@@ -87,8 +93,6 @@ export class RenderContext {
}
}
const MAX_SUSPENSE_DEPTH = 10;
function defaultCsp() {
return {
directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] },
@@ -118,14 +122,14 @@ function defaultCsp() {
* sent to the client. On the client the HTML will be slotted into the DOM
* at the location of the original `<Suspense>` node.
*/
export async function* render(
opts: RenderOptions,
): AsyncIterable<string | [string, ContentSecurityPolicy | undefined]> {
export function render<Data>(
opts: RenderOptions<Data>,
): [string, ContentSecurityPolicy | undefined] {
const props: Record<string, unknown> = {
params: opts.params,
url: opts.url,
route: opts.page.route,
renderData: opts.renderData,
data: opts.data,
};
if (opts.error) {
props.error = opts.error;
@@ -134,93 +138,48 @@ export async function* render(
const csp: ContentSecurityPolicy | undefined = opts.page.csp
? defaultCsp()
: undefined;
const dataCache = new Map();
const suspenseQueue: ComponentChildren[] = [];
const headComponents: ComponentChildren[] = [];
const vnode = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(DATA_CONTEXT.Provider, {
value: dataCache,
children: h(SUSPENSE_CONTEXT.Provider, {
value: suspenseQueue,
children: h(opts.app.default, {
Component() {
return h(opts.page.component!, props);
},
}),
}),
children: h(opts.app.default, {
Component() {
return h(opts.page.component! as ComponentType<unknown>, props);
},
}),
}),
});
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route);
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
csp.directives = newCsp.directives;
csp.reportOnly = newCsp.reportOnly;
}
// Clear the suspense queue
suspenseQueue.splice(0, suspenseQueue.length);
// Clear the head components
headComponents.splice(0, headComponents.length);
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
csp.directives = newCsp.directives;
csp.reportOnly = newCsp.reportOnly;
}
// Clear the head components
headComponents.splice(0, headComponents.length);
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
// Setup the interesting VNode types
ISLANDS.splice(0, ISLANDS.length, ...opts.islands);
let body: string | null = null;
let promise: Promise<unknown> | null = null;
// Clear the encountered vnodes
ENCOUNTERED_ISLANDS.clear();
function render() {
try {
body = renderToString(vnode);
return body;
} catch (e) {
if (e && e.then) {
promise = e;
return "";
}
throw e;
}
}
let bodyHtml: string | null = null;
opts.renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const bodyHtml = await renderWithRenderer();
let templateProps: {
props: PageProps | UnknownPageProps | ErrorPageProps;
data?: [string, unknown][];
} | undefined = { props, data: [...dataCache.entries()] };
if (templateProps.data!.length === 0) {
delete templateProps.data;
function render() {
bodyHtml = renderToString(vnode);
return bodyHtml;
}
// If this is a static render (runtimeJS is false), then we don't need to
// render the props into the template.
if (
opts.imports.length === 0 ||
(opts.imports.length === 1 && opts.imports[0] === REFRESH_JS_URL)
) {
templateProps = undefined;
opts.renderer.render(ctx, render);
if (bodyHtml === null) {
throw new Error("`render` function not called by renderer.");
}
const imports = opts.imports.map((url) => {
@@ -234,120 +193,32 @@ export async function* render(
return [url, randomNonce] as const;
});
for (const island of ENCOUNTERED_ISLANDS) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
const url = bundleAssetUrl(`/${island.id}.js`);
imports.push([url, randomNonce] as const);
}
const html = template({
bodyHtml,
headComponents,
imports,
preloads: opts.preloads,
styles: ctx.styles,
props: templateProps,
lang: ctx.lang,
});
const suspenseNonces = suspenseQueue.map(() => {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
return randomNonce;
});
let suspenseScript = "";
if (suspenseQueue.length > 0) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
// minified client-side JS
suspenseScript = '<script nonce="' + randomNonce +
'">(()=>{window.$SR=t=>{const e=document.getElementById("S:"+t),o=document.getElementById("E:"+t),d=document.getElementById("R:"+t);for(d.parentNode.removeChild(d);e.nextSibling!==o;)e.parentNode.removeChild(e.nextSibling);for(;d.firstChild;)e.parentNode.insertBefore(d.firstChild,o);e.parentNode.removeChild(e),o.parentNode.removeChild(o)};const n=document.getElementById("__FRSH_STYLE"),r=n.childNodes[0]?.textContent.split(`\n`);if(r!==void 0){n.removeChild(n.firstChild);for(const t of r)n.append(document.createTextNode(t))}window.$ST=t=>{for(const[e,o]of t)n.insertBefore(document.createTextNode(e),n.childNodes[o])}})();\n</script>';
}
let clientStyles = [...ctx.styles];
yield [html + suspenseScript, csp];
// TODO(lucacasonato): parallelize this
for (const [id, children] of suspenseQueue.entries()) {
let [fragment, script] = await suspenseRender(
opts.renderer,
ctx,
id + 1,
children,
);
const cssInserts: [string, number][] = [];
for (const [i, style] of ctx.styles.entries()) {
if (!clientStyles.includes(style)) {
cssInserts.push([style, i]);
}
}
clientStyles = [...ctx.styles];
if (cssInserts.length > 0) {
script = `$ST(${JSON.stringify(cssInserts)});\n${script};`;
}
yield `${fragment}<script nonce="${suspenseNonces[id]}">${script}</script>`;
}
return [html, csp];
}
export async function suspenseRender(
renderer: Renderer,
ctx: RenderContext,
id: number,
children: ComponentChildren,
): Promise<[string, string]> {
const dataCache = new Map();
const vnode = h(DATA_CONTEXT.Provider, {
value: dataCache,
children,
});
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
let body: string | null = null;
let promise: Promise<unknown> | null = null;
function render() {
try {
body = renderToString(vnode);
return body;
} catch (e) {
if (e && e.then) {
promise = e;
return "";
}
throw e;
}
}
renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const html = await renderWithRenderer();
return [`<div hidden id="R:${id}">${html}</div>`, `$SR(${id});`];
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
export interface TemplateOptions {
@@ -356,7 +227,6 @@ export interface TemplateOptions {
imports: (readonly [string, string])[];
styles: string[];
preloads: string[];
props: unknown;
lang: string;
}
@@ -377,20 +247,35 @@ export function template(opts: TemplateOptions): string {
/>
{opts.headComponents}
</head>
<body>
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
{opts.props !== undefined
? (
<script
id="__FRSH_PROPS"
type="application/json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }}
/>
)
: null}
</body>
<body dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} />
</html>
);
return "<!DOCTYPE html>" + renderToString(page);
}
// Set up a preact option hook to track when vnode with custom functions are
// created.
const ISLANDS: Island[] = [];
const ENCOUNTERED_ISLANDS: Set<Island> = new Set([]);
const originalHook = options.vnode;
let ignoreNext = false;
options.vnode = (vnode) => {
const originalType = vnode.type as ComponentType<unknown>;
if (typeof vnode.type === "function") {
const island = ISLANDS.find((island) => island.component === originalType);
if (island) {
if (ignoreNext) {
ignoreNext = false;
return;
}
ENCOUNTERED_ISLANDS.add(island);
vnode.type = (props) => {
ignoreNext = true;
const child = h(originalType, props);
return h(`frsh-${island.id}`, { props: JSON.stringify(props) }, child);
};
}
}
if (originalHook) originalHook(vnode);
};
+27 -11
View File
@@ -27,24 +27,32 @@ export interface ErrorPageModule {
config?: PageConfig;
}
export interface HandlerContext {
export interface IslandModule {
// deno-lint-ignore no-explicit-any
default: ComponentType<any>;
}
export interface HandlerContext<T = unknown> {
req: Request;
match: Record<string, string>;
render?: (args?: Record<string, unknown>) => Promise<Response>;
render: (data?: T) => Response;
}
export interface UnknownHandlerContext {
req: Request;
render?: () => Promise<Response>;
render: () => Response;
}
export interface ErrorHandlerContext {
req: Request;
error: unknown;
render?: () => Promise<Response>;
render: () => Response;
}
export type Handler = (ctx: HandlerContext) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
export type Handler<T = any> = (
ctx: HandlerContext<T>,
) => Response | Promise<Response>;
export type UnknownHandler = (
ctx: UnknownHandlerContext,
) => Response | Promise<Response>;
@@ -52,17 +60,18 @@ export type ErrorHandler = (
ctx: ErrorHandlerContext,
) => Response | Promise<Response>;
export type Handlers = {
[K in typeof router.METHODS[number]]?: Handler;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any> = {
[K in typeof router.METHODS[number]]?: Handler<T>;
};
export interface Page {
// deno-lint-ignore no-explicit-any
export interface Page<Data = any> {
route: string;
url: string;
name: string;
component?: ComponentType<PageProps>;
handler: Handler | Handlers;
runtimeJS: boolean;
component?: ComponentType<PageProps<Data>>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
@@ -111,3 +120,10 @@ export interface Middleware {
export interface AppModule {
default: ComponentType<AppProps>;
}
export interface Island {
id: string;
name: string;
url: string;
component: ComponentType<unknown>;
}
+46
View File
@@ -0,0 +1,46 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./routes/_middleware.ts";
import * as $1 from "./routes/_404.tsx";
import * as $2 from "./routes/failure.ts";
import * as $3 from "./routes/api/get_only.ts";
import * as $4 from "./routes/books/[id].tsx";
import * as $5 from "./routes/_render.ts";
import * as $6 from "./routes/props/[id].tsx";
import * as $7 from "./routes/_app.tsx";
import * as $8 from "./routes/static.tsx";
import * as $9 from "./routes/intercept_args.tsx";
import * as $10 from "./routes/wildcard.tsx";
import * as $11 from "./routes/intercept.tsx";
import * as $12 from "./routes/[name].tsx";
import * as $13 from "./routes/_500.tsx";
import * as $14 from "./routes/index.tsx";
import * as $$0 from "./islands/Test.tsx";
const manifest = {
routes: {
"./routes/_middleware.ts": $0,
"./routes/_404.tsx": $1,
"./routes/failure.ts": $2,
"./routes/api/get_only.ts": $3,
"./routes/books/[id].tsx": $4,
"./routes/_render.ts": $5,
"./routes/props/[id].tsx": $6,
"./routes/_app.tsx": $7,
"./routes/static.tsx": $8,
"./routes/intercept_args.tsx": $9,
"./routes/wildcard.tsx": $10,
"./routes/intercept.tsx": $11,
"./routes/[name].tsx": $12,
"./routes/_500.tsx": $13,
"./routes/index.tsx": $14,
},
islands: {
"./islands/Test.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
+7
View File
@@ -0,0 +1,7 @@
/** @jsx h */
import { h } from "../client_deps.ts";
export default function Test(props: { message: string }) {
return <p>{props.message}</p>;
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { start } from "../../server.ts";
import routes from "./routes.gen.ts";
import { start } from "./server_deps.ts";
import routes from "./fresh.gen.ts";
await start(routes);
-19
View File
@@ -1,19 +0,0 @@
/** @jsx h */
import { h, IS_BROWSER, PageConfig, useData } from "../deps.ts";
export default function Home() {
const message = useData("home", (key) => {
return new Promise<string>((resolve) => {
setTimeout(() => resolve("Hello!"), 100);
});
});
return (
<div>
<p>{message}</p>
<p>{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}</p>
</div>
);
}
export const config: PageConfig = { runtimeJS: true };
-31
View File
@@ -1,31 +0,0 @@
/** @jsx h */
import { h } from "../deps.ts";
import { HandlerContext } from "../../../server.ts";
interface renderData extends Record<string, unknown> {
info: string;
}
export default function Page({
renderData,
}: {
renderData: renderData;
}) {
return <div>{renderData.info}</div>;
}
export const handler = {
GET({ req, render }: HandlerContext) {
if (req.headers.get("accept")?.includes("text/html")) {
return render!({
info: "intercepted",
} as renderData);
} else {
return new Response("This is plain text");
}
},
POST() {
return new Response("POST response");
},
};
-9
View File
@@ -1,9 +0,0 @@
/** @jsx h */
import { h, PageConfig, PageProps } from "../../deps.ts";
export default function Home(props: PageProps) {
return <div>{JSON.stringify(props)}</div>;
}
export const config: PageConfig = { runtimeJS: true };
-42
View File
@@ -1,42 +0,0 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./pages/index.tsx";
import * as $1 from "./pages/static.tsx";
import * as $2 from "./pages/intercept_args.tsx";
import * as $3 from "./pages/_render.ts";
import * as $4 from "./pages/props/[id].tsx";
import * as $5 from "./pages/failure.ts";
import * as $6 from "./pages/_middleware.ts";
import * as $7 from "./pages/books/[id].tsx";
import * as $8 from "./pages/wildcard.tsx";
import * as $9 from "./pages/api/get_only.ts";
import * as $10 from "./pages/_500.tsx";
import * as $11 from "./pages/intercept.tsx";
import * as $12 from "./pages/_404.tsx";
import * as $13 from "./pages/[name].tsx";
import * as $14 from "./pages/_app.tsx";
const routes = {
pages: {
"./pages/index.tsx": $0,
"./pages/static.tsx": $1,
"./pages/intercept_args.tsx": $2,
"./pages/_render.ts": $3,
"./pages/props/[id].tsx": $4,
"./pages/failure.ts": $5,
"./pages/_middleware.ts": $6,
"./pages/books/[id].tsx": $7,
"./pages/wildcard.tsx": $8,
"./pages/api/get_only.ts": $9,
"./pages/_500.tsx": $10,
"./pages/intercept.tsx": $11,
"./pages/_404.tsx": $12,
"./pages/[name].tsx": $13,
"./pages/_app.tsx": $14,
},
baseUrl: import.meta.url,
};
export default routes;
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, PageConfig } from "../deps.ts";
import { h } from "../client_deps.ts";
interface Props {
params: Record<string, string | string[]>;
@@ -9,5 +9,3 @@ interface Props {
export default function Greet(props: Props) {
return <div>Hello {props.params.name}</div>;
}
export const config: PageConfig = { runtimeJS: true };
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, UnknownPageProps } from "../deps.ts";
import { h, UnknownPageProps } from "../client_deps.ts";
export default function NotFoundPage({ url }: UnknownPageProps) {
return <p>404 not found: {url.pathname}</p>;
@@ -1,6 +1,6 @@
/** @jsx h */
import { ErrorPageProps, h } from "../deps.ts";
import { ErrorPageProps, h } from "../client_deps.ts";
export default function Error500Page({ error }: ErrorPageProps) {
return <p>500 internal error: {(error as Error).message}</p>;
@@ -1,7 +1,7 @@
/** @jsx h */
/** @jsxFrag Fragment */
import { AppProps, Fragment, h, Head } from "../deps.ts";
import { AppProps, Fragment, h, Head } from "../client_deps.ts";
export default function App(props: AppProps) {
return (
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, PageConfig, PageProps } from "../../deps.ts";
import { h, PageConfig, PageProps } from "../../client_deps.ts";
export default function Page(props: PageProps) {
return <div>Book {props.params.id}</div>;
+13
View File
@@ -0,0 +1,13 @@
/** @jsx h */
import { h, IS_BROWSER } from "../client_deps.ts";
import Test from "../islands/Test.tsx";
export default function Home() {
return (
<div>
<Test message="Hello!" />
<p>{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}</p>
</div>
);
}
@@ -1,6 +1,6 @@
/** @jsx h */
import { h } from "../deps.ts";
import { h } from "../client_deps.ts";
import { HandlerContext } from "../../../server.ts";
export default function Page() {
@@ -10,7 +10,7 @@ export default function Page() {
export const handler = {
GET({ req, render }: HandlerContext) {
if (req.headers.get("accept")?.includes("text/html")) {
return render!();
return render();
} else {
return new Response("This is plain text");
}
+27
View File
@@ -0,0 +1,27 @@
/** @jsx h */
import { h, PageProps } from "../client_deps.ts";
import { HandlerContext, Handlers } from "../../../server.ts";
interface Data extends Record<string, unknown> {
info: string;
}
export default function Page({ data }: PageProps<Data>) {
return <div>{data.info}</div>;
}
export const handler: Handlers<Data> = {
GET({ req, render }) {
if (req.headers.get("accept")?.includes("text/html")) {
return render({
info: "intercepted",
});
} else {
return new Response("This is plain text");
}
},
POST() {
return new Response("POST response");
},
};
+7
View File
@@ -0,0 +1,7 @@
/** @jsx h */
import { h, PageProps } from "../../client_deps.ts";
export default function Home(props: PageProps) {
return <div>{JSON.stringify(props)}</div>;
}
@@ -1,6 +1,6 @@
/** @jsx h */
import { h } from "../deps.ts";
import { h } from "../client_deps.ts";
export default function StaticPage() {
return <p>This is a static page.</p>;
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, PageConfig, PageProps } from "../deps.ts";
import { h, PageConfig, PageProps } from "../client_deps.ts";
export default function WildcardPage({ params }: PageProps) {
if (typeof params.path === "string") {
+1
View File
@@ -0,0 +1 @@
export * from "../../server.ts";
+5 -18
View File
@@ -1,8 +1,8 @@
import { ServerContext } from "../server.ts";
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
import routes from "./fixture/routes.gen.ts";
import manifest from "./fixture/fresh.gen.ts";
const ctx = await ServerContext.fromRoutes(routes);
const ctx = await ServerContext.fromManifest(manifest);
const router = ctx.handler();
Deno.test("/ page prerender", async () => {
@@ -13,16 +13,12 @@ Deno.test("/ page prerender", async () => {
assertEquals(resp.headers.get("server"), "fresh test server");
const body = await resp.text();
assertStringIncludes(body, `<html lang="en">`);
assertStringIncludes(body, "index.js");
assertStringIncludes(body, "test.js");
assertStringIncludes(body, "<p>Hello!</p>");
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
assertStringIncludes(
body,
`<script id="__FRSH_PROPS" type="application/json">`,
);
assertStringIncludes(
body,
`"data":[["home","Hello!"]]`,
`props="{&quot;message&quot;:&quot;Hello!&quot;}">`,
);
assertStringIncludes(
body,
@@ -38,7 +34,7 @@ Deno.test("/props/123 page prerender", async () => {
const body = await resp.text();
assertStringIncludes(
body,
`{"props":{"params":{"id":"123"},"url":"https://fresh.deno.dev/props/123","route":"/props/:id"}}`,
`{&quot;params&quot;:{&quot;id&quot;:&quot;123&quot;},&quot;url&quot;:&quot;https://fresh.deno.dev/props/123&quot;,&quot;route&quot;:&quot;/props/:id&quot;}`,
);
});
@@ -48,16 +44,7 @@ Deno.test("/[name] page prerender", async () => {
assertEquals(resp.status, 200);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
assertStringIncludes(body, "[name].js");
assertStringIncludes(body, "<div>Hello bar</div>");
assertStringIncludes(
body,
`<script id="__FRSH_PROPS" type="application/json">`,
);
assertStringIncludes(
body,
`"params":{"name":"bar"}`,
);
});
Deno.test("/intercept - GET html", async () => {
+7
View File
@@ -0,0 +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 };
if (IS_BROWSER) {
setup({});
}
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, tw } from "../deps.ts";
import { h, tw } from "../client_deps.ts";
export function RoundedButton(props: h.JSX.HTMLAttributes<HTMLButtonElement>) {
return (
+1 -1
View File
@@ -1,6 +1,6 @@
/** @jsx h */
import { h, tw } from "../deps.ts";
import { h, tw } from "../client_deps.ts";
export function IconMinus() {
return (
-13
View File
@@ -1,13 +0,0 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
export * from "../runtime.ts";
import { IS_BROWSER } from "../runtime.ts";
import { setup, tw } from "https://esm.sh/twind";
export { setup, tw };
if (IS_BROWSER) {
setup({});
}
+20
View File
@@ -0,0 +1,20 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./routes/_render.ts";
import * as $1 from "./routes/index.tsx";
import * as $$0 from "./islands/Counter.tsx";
const manifest = {
routes: {
"./routes/_render.ts": $0,
"./routes/index.tsx": $1,
},
islands: {
"./islands/Counter.tsx": $$0,
},
baseUrl: import.meta.url,
};
export default manifest;
+34
View File
@@ -0,0 +1,34 @@
/** @jsx h */
import { h, IS_BROWSER, tw, useState } from "../client_deps.ts";
import { RoundedButton } from "../components/Button.tsx";
import { IconMinus, IconPlus } from "../components/Icons.tsx";
interface CounterProps {
start: number;
}
export default function Counter(props: CounterProps) {
const [count, setCount] = useState(props.start);
return (
<div
class={tw
`bg-gray-100 p-4 border border-gray-200 flex items-center justify-around`}
>
<RoundedButton
title="Subtract 1"
onClick={() => setCount(count - 1)}
disabled={!IS_BROWSER}
>
<IconMinus />
</RoundedButton>
<div class={tw`text-3xl`}>{count}</div>
<RoundedButton
title="Add 1"
onClick={() => setCount(count + 1)}
disabled={!IS_BROWSER}
>
<IconPlus />
</RoundedButton>
</div>
);
}
+8 -2
View File
@@ -1,4 +1,10 @@
import { start } from "../server.ts";
import routes from "./routes.gen.ts";
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "./server_deps.ts";
import routes from "./fresh.gen.ts";
await start(routes);
-16
View File
@@ -1,16 +0,0 @@
// DO NOT EDIT. This file is generated by `fresh`.
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./pages/index.tsx";
import * as $1 from "./pages/_render.ts";
const routes = {
pages: {
"./pages/index.tsx": $0,
"./pages/_render.ts": $1,
},
baseUrl: import.meta.url,
};
export default routes;
@@ -1,8 +1,7 @@
// This module adds twind support.
import { virtualSheet } from "https://esm.sh/twind/sheets";
import { setup } from "../deps.ts";
import { RenderContext, RenderFn } from "../server_deps.ts";
import { setup } from "../client_deps.ts";
import { RenderContext, RenderFn, virtualSheet } from "../server_deps.ts";
const sheet = virtualSheet();
sheet.reset();
+48 -9
View File
@@ -1,18 +1,24 @@
/** @jsx h */
/** @jsxFrag Fragment */
import { Fragment, h, Head, tw } from "../deps.ts";
import { Fragment, h, Head, tw } from "../client_deps.ts";
import Counter from "../islands/Counter.tsx";
export default function MainPage() {
return (
<>
<Head>
<title>fresh - The next-gen web framework.</title>
<meta
name="description"
content="The next-gen web framework. Just in time edge rendering, island based interactivity, and no configuration TypeScript support."
/>
</Head>
<Hero />
<NavigationBar active="/" />
<Intro />
<GettingStarted />
<Example />
</>
);
}
@@ -28,9 +34,9 @@ function Hero() {
<h1 class={title}>
fresh
</h1>
<h3 class={subtitle}>
<p class={subtitle}>
The next-gen web framework.
</h3>
</p>
</section>
);
}
@@ -79,7 +85,7 @@ function Intro() {
<b>Just-in-time rendering</b> on the edge.
</li>
<li>
<b>Selective client hydration</b> for maximum interactivity.
<b>Island based client hydration</b> for maximum interactivity.
</li>
<li>
<b>Zero runtime overhead</b>: no JS is shipped to the client by
@@ -106,14 +112,14 @@ function Intro() {
function GettingStarted() {
return (
<section class={tw`max-w-screen-sm mx-auto my-16 px(4 sm:6 md:8)`}>
<h3 id="getting-started" class={tw`text(xl gray-600) font-bold`}>
<h2 id="getting-started" class={tw`text(xl gray-600) font-bold`}>
<a href="#getting-started" class={tw`hover:underline`}>
Getting started
</a>
</h3>
</h2>
<p class={tw`my-4 text-gray-600`}>
To get started, make sure you have the{" "}
<a href="https://deno.land" class={tw`text-blue-500 hover:underline`}>
<a href="https://deno.land" class={tw`text-blue-600 hover:underline`}>
Deno CLI
</a>{" "}
installed.
@@ -143,7 +149,7 @@ function GettingStarted() {
You can now open{" "}
<a
href="http://localhost:8000"
class={tw`text-blue-500 hover:underline`}
class={tw`text-blue-600 hover:underline`}
>
http://localhost:8000
</a>{" "}
@@ -151,7 +157,40 @@ function GettingStarted() {
</p>
<p class={tw`my-4 text-gray-600`}>
A more in-depth getting started guide is available in{" "}
<a href="/docs" class={tw`text-blue-500 hover:underline`}>the docs</a>.
<a href="/docs" class={tw`text-blue-600 hover:underline`}>the docs</a>.
</p>
</section>
);
}
const timeFmt = new Intl.DateTimeFormat("en-US", {
timeStyle: "long",
hour12: false,
});
function Example() {
return (
<section
class={tw`max-w-screen-sm mx-auto my-16 px(4 sm:6 md:8)`}
>
<h2 id="example" class={tw`text(xl gray-600) font-bold`}>
<a href="#example" class={tw`hover:underline`}>
Example
</a>
</h2>
<p class={tw`my-4 text-gray-600`}>
This text is being server side rendered on the fly. It was rendered at
{" "}
{timeFmt.format(new Date())}.
</p>
<p class={tw`my-4 text-gray-600`}>
The counter below was rendered on the server with a starting value of 3,
and was then hydrated on the client to provide interactivity. Try out
the buttons!
</p>
<Counter start={3} />
<p class={tw`my-4 text-gray-600`}>
Only the JS required to render that counter is sent to the client.
</p>
</section>
);
+1
View File
@@ -1 +1,2 @@
export * from "../server.ts";
export { virtualSheet } from "https://esm.sh/twind@0.16.16/sheets";