Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/check-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ jobs:
- run: node --test .github/scripts/*.test.cjs
- run: npx --yes playwright@1.56.1 install --with-deps chromium
- run: deno task test
- run: deno task test:static
- run: deno run -A build.npm.ts
env:
RELEASE_VERSION: 0.0.0-release-check
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ limitations, and reproducible performance measurements.
For lazy interactions on existing server DOM, see [resumption](docs/resumption.md).
Explicit boundaries carry JSON state and load named handlers on the first click.

For documentation and other static sites with interactive islands, see
[static site generation](docs/static-sites.md).

## What Makes Radi Different

Radi takes a unique approach compared to React, Preact, or even Solid:
Expand Down
4 changes: 4 additions & 0 deletions build.npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ async function start() {
name: "./server",
path: "./src/server.ts",
},
{
name: "./static",
path: "./src/static.ts",
},
{
name: "./jsx-runtime",
path: "./src/jsx-runtime.ts",
Expand Down
2 changes: 2 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"dev": "deno -A npm:esbuild playground/*.tsx --jsx-import-source=preact --jsx=automatic --watch --servedir=playground/www --outdir=playground/www --bundle",
"test": "deno -A --unstable-bundle @marcisbee/rion/test.cli --includes src",
"test:server": "deno test --config deno.server.json --allow-net=127.0.0.1 tests/server-runtime_test.tsx",
"test:static": "deno test -A --config deno.server.json tests/static-site_test.ts",
"bench:server": "deno run --config deno.server.json bench/server.ts",
"bench": "deno -A --unstable-bundle @marcisbee/rion/bench.cli --includes src",
"publish": "deno -A ./build.npm.ts && cd npm && npm publish --tag alpha"
Expand All @@ -14,6 +15,7 @@
"./client": "./src/client.ts",
"./resume": "./src/resume.ts",
"./server": "./src/server.ts",
"./static": "./src/static.ts",
"./server/jsx-runtime": "./src/server/jsx-runtime.ts",
"./server/jsx-dev-runtime": "./src/server/jsx-dev-runtime.ts",
"./jsx-runtime": "./src/jsx-runtime.ts",
Expand Down
1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 86 additions & 0 deletions docs/static-sites.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Static sites

`radi/static` generates complete HTML documents with the existing server
renderer. Routes map to directory indexes: `/` becomes `index.html` and
`/guide/` becomes `guide/index.html`. Deploy these files to any static host that
serves directory indexes. No Radi server is needed in production.

```ts
import { generateStaticSite } from 'radi/static';
import { createElement as h } from 'radi/server';
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';

await generateStaticSite([
{
path: '/',
title: 'Documentation',
render: () => h('h1', null, 'Welcome'),
},
{
path: '/guide/',
title: 'Guide',
render: async () => h('p', null, 'Content loaded at build time'),
},
], async (path, html) => {
const file = join('dist', path);
await mkdir(dirname(file), { recursive: true });
await writeFile(file, html);
});
```

Use the server JSX runtime (`jsxImportSource: "radi/server"`) for JSX pages.
`render` returns body content; `head` accepts additional server nodes such as
stylesheets and metadata, and `lang` defaults to `en`. Titles, attributes, and
content use the server renderer's escaping. Async content is fully resolved
before each document is written. Reactive functions are sampled at build time.

The writer receives a validated relative path and HTML string, and is awaited
before rendering the next page. All routes are validated before any rendering or
writes. Duplicate routes (including `/guide` and `/guide/`), dot segments,
encoded paths, queries, and fragments are rejected. Routes are literal decoded
paths; link to the trailing-slash URL. Unicode slugs are supported. Returned
paths list the generated documents. The writer owns filesystem permissions, safe
output-directory selection, cleanup, and deployment. Build into a fresh
directory for deployment: failures stop generation but do not roll back prior
writes, and removed routes are not deleted from an existing directory. Server
component failures retain the renderer's `ERROR:ComponentName` fallback.

## Interactive islands

Use `resumable` and `resumeClick` from `radi/server` inside page content, and
set that page's `bootstrap` to the public URL of a bundled classic script that
calls `resume(document, registry)` from `radi/resume`. The generator places this
blocking script in the head, before interactive HTML. Serve the bootstrap and
lazy handler bundles alongside the HTML. Pages without `bootstrap` have no
generated script. Asset paths are public URLs; use the correct prefix when
deploying under a subdirectory. Bundling and copying other assets remain the
build script's responsibility.

Each resumable boundary owns its JSON state. A click loads its registered
handler and updates existing DOM; static content and other islands remain
untouched. See [resumption](resumption.md) for the handler API, supported click
behavior, state restrictions, and failure handling.

Native function children identify dynamic locations, but cannot supply their
client module identity or captured state. Their `<!--$-->` markers alone cannot
reconstruct closures in a browser. This API therefore uses explicit resumable
islands; it does not automatically turn arbitrary functions or `onclick`
closures into client code. Such automation would need a compiler or explicit
module/state metadata. Do not use an ordinary client root to hydrate these
pages: it replaces its initial contents.

## Complete example

```sh
deno run -A examples/static-site.ts
# Deploy dist/static-site, or preview the exact generated files:
deno run -A examples/static-site.ts --serve
```

Open `http://127.0.0.1:4319/`. The home page has no JavaScript. The guide has
two independent counters that reuse the resumption example's lazy handler. The
preview serves files only; it does no request-time rendering.

Run `deno task test:static` to verify generation and both islands in Chromium.
Install Chromium first with `npx playwright@1.56.1 install chromium`.
86 changes: 86 additions & 0 deletions examples/static-site.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/** Build: deno run -A examples/static-site.ts [--serve] */
import { dirname, join } from 'node:path';
import { build, stop } from 'npm:esbuild';
import { generateStaticSite } from '../src/static.ts';
import { createElement as h, resumable, resumeClick } from '../src/server.ts';

function counter(count: number) {
return resumable({ count }, [
h('button', { type: 'button', ...resumeClick('increment') }, 'Increment'),
h('p', null, 'Count: ', h('output', null, String(count))),
h('p', { role: 'status' }, 'Handler loads on the first click.'),
]);
}

export async function buildStaticExample(outDir: string): Promise<void> {
await Deno.mkdir(outDir, { recursive: true });
try {
for (const name of ['resumption-client', 'resumption-handler']) {
await build({
entryPoints: [new URL(`./${name}.ts`, import.meta.url).pathname],
outfile: join(outDir, `${name}.js`),
bundle: true,
minify: true,
format: name.endsWith('client') ? 'iife' : 'esm',
external: ['./resumption-handler.js'],
});
}
} finally {
stop();
}
await generateStaticSite([
{
path: '/',
title: 'Radi static site',
render: () => [
h('h1', null, 'Radi static site'),
h('p', null, 'Development example. This page needs no JavaScript.'),
h('a', { href: '/guide/' }, 'Interactive guide'),
],
},
{
path: '/guide/',
title: 'Interactive guide',
bootstrap: '/resumption-client.js',
render: async () => [
h('h1', null, 'Interactive guide'),
h('p', { id: 'static-content' }, 'Built once. Served as static files.'),
counter(0),
counter(10),
h('a', { href: '/' }, 'Home'),
],
},
], async (path, html) => {
const file = join(outDir, path);
await Deno.mkdir(dirname(file), { recursive: true });
await Deno.writeTextFile(file, html);
});
}

/** Example file server; rendering and bundling have already finished. */
export function serveStaticExample(outDir: string, port = 4319) {
const files: Record<string, string> = {
'/': 'index.html',
'/guide/': 'guide/index.html',
'/resumption-client.js': 'resumption-client.js',
'/resumption-handler.js': 'resumption-handler.js',
};
return Deno.serve({ hostname: '127.0.0.1', port }, async (request) => {
const file = files[new URL(request.url).pathname];
if (!file) return new Response('Not found', { status: 404 });
return new Response(await Deno.readFile(join(outDir, file)), {
headers: {
'content-type': file.endsWith('.js')
? 'text/javascript; charset=utf-8'
: 'text/html; charset=utf-8',
},
});
});
}

if (import.meta.main) {
const outDir = new URL('../dist/static-site/', import.meta.url).pathname;
await buildStaticExample(outDir);
console.log(`Static files written to ${outDir}`);
if (Deno.args.includes('--serve')) serveStaticExample(outDir);
}
67 changes: 67 additions & 0 deletions src/static.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { createElement as h, renderToStringAsync } from './server-html.ts';
import type { ServerChild } from './server-html.ts';

export interface StaticPage {
/** Root-relative route, e.g. / or /guide/getting-started/. */
path: string;
title: string;
/** Called once at build time. May return async server content. */
render: () => ServerChild;
head?: ServerChild;
lang?: string;
/** URL of a bundled classic script that installs radi/resume. */
bootstrap?: string;
}

export type StaticWriter = (path: string, html: string) => void | Promise<void>;

function outputPath(route: string): string {
if (
!route.startsWith('/') || /[\\%?#:\s<>"|*\u0000-\u001f\u007f]/u.test(route)
) {
throw new TypeError(`Invalid static route: ${route}`);
}
const parts = route.slice(1).split('/');
if (parts.at(-1) === '') parts.pop();
if (parts.some((part) => !part || part === '.' || part.endsWith('.'))) {
throw new TypeError(`Invalid static route: ${route}`);
}
return [...parts, 'index.html'].join('/');
}

async function renderPage(page: StaticPage): Promise<string> {
const document = h(
'html',
{ lang: page.lang ?? 'en' },
h(
'head',
null,
h('meta', { charset: 'utf-8' }),
h('meta', {
name: 'viewport',
content: 'width=device-width, initial-scale=1',
}),
h('title', null, page.title),
page.head ?? [],
// Capture is installed before the parser reaches interactive content.
page.bootstrap ? h('script', { src: page.bootstrap }) : [],
),
h('body', null, page.render()),
);
return '<!doctype html>' + await renderToStringAsync(document);
}

/** Generate one document at a time. The caller owns storage and asset bundling. */
export async function generateStaticSite(
pages: readonly StaticPage[],
write: StaticWriter,
): Promise<string[]> {
const paths = pages.map((page) => outputPath(page.path));
if (new Set(paths).size !== paths.length) {
throw new TypeError('Duplicate static routes');
}
for (const [index, page] of pages.entries()) {
await write(paths[index], await renderPage(page));
}
return paths;
}
Loading
Loading