diff --git a/example/pages/_render.ts b/example/pages/_render.ts index adca1582..29c3c825 100644 --- a/example/pages/_render.ts +++ b/example/pages/_render.ts @@ -1,32 +1,18 @@ // This module adds twind support. -import { - getStyleTagProperties, - virtualSheet, -} from "https://esm.sh/twind/sheets"; -import { h, setup } from "../deps.ts"; +import { virtualSheet } from "https://esm.sh/twind/sheets"; +import { setup } from "../deps.ts"; import { RenderContext, RenderFn } from "../server_deps.ts"; const sheet = virtualSheet(); -const initial = sheet.reset(); +sheet.reset(); setup({ sheet }); export function render(ctx: RenderContext, render: RenderFn) { const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null; - sheet.reset(snapshot || initial); + sheet.reset(snapshot || undefined); render(); - const newSnapshot = sheet.reset(initial); + ctx.styles.splice(0, ctx.styles.length, ...sheet.target); + const newSnapshot = sheet.reset(); ctx.state.set("twindSnapshot", newSnapshot); } - -export function postRender(ctx: RenderContext) { - const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null; - if (snapshot !== null) { - sheet.reset(snapshot); - const { id, textContent } = getStyleTagProperties(sheet); - ctx.head.push( - h("style", { id, dangerouslySetInnerHTML: { __html: textContent } }), - ); - } - sheet.reset(initial); -} diff --git a/example/pages/suspense.tsx b/example/pages/suspense.tsx new file mode 100644 index 00000000..fd3c592d --- /dev/null +++ b/example/pages/suspense.tsx @@ -0,0 +1,28 @@ +/** @jsx h */ + +import { h, Suspense, tw, useData } from "../deps.ts"; + +export default function SuspensePage() { + return ( + + Loading... +

+ )} + > + +
+ ); +} + +export function SuspendedComponent() { + const data = useData("Loaded", delayer); + return

{data}!

; +} + +// A function that returns a promise that resolves after a delay with the given +// value. +function delayer(key: string) { + return new Promise((resolve) => setTimeout(() => resolve(key), 2000)); +} diff --git a/example/routes.gen.ts b/example/routes.gen.ts index c41b0b09..8291dc13 100644 --- a/example/routes.gen.ts +++ b/example/routes.gen.ts @@ -2,19 +2,21 @@ // This file SHOULD be checked into source version control. // To update this file, run `fresh routes`. -import * as $0 from "./pages/api/joke.ts"; +import * as $0 from "./pages/index.tsx"; import * as $1 from "./pages/_render.ts"; -import * as $2 from "./pages/x/[module].tsx"; -import * as $3 from "./pages/[name].tsx"; -import * as $4 from "./pages/index.tsx"; +import * as $2 from "./pages/suspense.tsx"; +import * as $3 from "./pages/api/joke.ts"; +import * as $4 from "./pages/[name].tsx"; +import * as $5 from "./pages/x/[module].tsx"; const routes = { pages: { - "./pages/api/joke.ts": $0, + "./pages/index.tsx": $0, "./pages/_render.ts": $1, - "./pages/x/[module].tsx": $2, - "./pages/[name].tsx": $3, - "./pages/index.tsx": $4, + "./pages/suspense.tsx": $2, + "./pages/api/joke.ts": $3, + "./pages/[name].tsx": $4, + "./pages/x/[module].tsx": $5, }, baseUrl: import.meta.url, }; diff --git a/makefile b/makefile index de188d5f..b5a9f9f4 100644 --- a/makefile +++ b/makefile @@ -5,7 +5,7 @@ lint: deno lint test: - deno test --no-check -A + deno test -A watch_example: - deno run -A --unstable --watch example/main.ts \ No newline at end of file + deno run -A --unstable --watch --no-check example/main.ts \ No newline at end of file diff --git a/runtime.ts b/runtime.ts index 6ec4c215..bc2962f8 100644 --- a/runtime.ts +++ b/runtime.ts @@ -1,4 +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"; diff --git a/src/runtime/suspense.ts b/src/runtime/suspense.ts new file mode 100644 index 00000000..8a8999dd --- /dev/null +++ b/src/runtime/suspense.ts @@ -0,0 +1,33 @@ +import { + ComponentChild, + ComponentChildren, + createContext, + Fragment, + h, + useContext, +} from "./deps.ts"; +import { IS_BROWSER } from "./utils.ts"; + +export const SUSPENSE_CONTEXT = createContext([]); + +export interface SuspenseProps { + fallback: ComponentChild; + children: ComponentChildren; +} + +export function Suspense(props: SuspenseProps) { + if (IS_BROWSER) { + throw new Error(`'' 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}` }), + ); +} diff --git a/src/server/client.js b/src/server/client.js new file mode 100644 index 00000000..be011790 --- /dev/null +++ b/src/server/client.js @@ -0,0 +1,34 @@ +(() => { + /** 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`); + 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], + ); + } + }; +})(); diff --git a/src/server/context.ts b/src/server/context.ts index 6dcc372d..6adeddaf 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -144,11 +144,12 @@ export class ServerContext { params: Record, ) => { if (page.component === undefined) return undefined; + // deno-lint-ignore require-await const render = async () => { const preloads = page.runtimeJS ? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl) : []; - const body = await internalRender({ + const body = internalRender({ page, imports, preloads, @@ -156,7 +157,15 @@ export class ServerContext { url: new URL(req.url), params, }); - return new Response(body, { + const bodyStream = new ReadableStream({ + async start(controller) { + for await (const chunk of body) { + controller.enqueue(new TextEncoder().encode(chunk)); + } + controller.close(); + }, + }); + return new Response(bodyStream, { status: 200, headers: { "content-type": "text/html; charset=utf-8", @@ -243,7 +252,6 @@ const DEFAULT_RENDERER: Renderer = { render(_ctx, render) { render(); }, - postRender(_ctx) {}, }; /** diff --git a/src/server/render.tsx b/src/server/render.tsx index d7e2c061..07973c04 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -1,10 +1,11 @@ /** @jsx h */ import { renderToString } from "./deps.ts"; -import { ComponentChild, h } from "../runtime/deps.ts"; +import { ComponentChild, ComponentChildren, h } from "../runtime/deps.ts"; import { DATA_CONTEXT } from "../runtime/hooks.ts"; import { Page, Renderer } from "./types.ts"; import { PageProps } from "../runtime/types.ts"; +import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts"; export interface RenderOptions { page: Page; @@ -20,7 +21,7 @@ export type RenderFn = () => void; export class RenderContext { #id: string; #state: Map = new Map(); - #head: ComponentChild[] = []; + #styles: string[] = []; #url: URL; #route: string; #lang = "en"; @@ -46,10 +47,13 @@ export class RenderContext { } /** - * Items to add to the for this render. + * All of the CSS style rules that should be inlined into the document. + * Adding to this list across multiple renders is supported (even across + * suspense!). The CSS rules will always be inserted on the client in the + * order specified here. */ - get head(): ComponentChild[] { - return this.#head; + get styles(): string[] { + return this.#styles; } /** The URL of the page being rendered. */ @@ -74,20 +78,49 @@ export class RenderContext { const MAX_SUSPENSE_DEPTH = 10; -export async function render(opts: RenderOptions): Promise { +/** + * This function renders out a page. Rendering is asynchronous, and streaming. + * Rendering happens in multiple steps, because of the need to handle suspense. + * + * 1. The page's vnode tree is constructed. + * 2. The page's vnode tree is passed to the renderer. + * - If the rendering throws a promise, the promise is awaited before + * continuing. This allows the renderer to handle async hooks. + * - Once the rendering throws no more promises, the initial render is + * complete and a body string is returned. + * - During rendering, every time a `` is rendered, it, and it's + * attached children are recorded for later rendering. + * 3. Once the inital render is complete, the body string is fitted into the + * HTML wrapper template. + * 4. The full inital render in the template is yielded to be sent to the + * client. + * 5. Now the suspended vnodes are rendered. These are individually rendered + * like described in step 2 above. Once each node is done rendering, it + * wrapped in some boilderplate HTML, and suffixed with some JS, and then + * sent to the client. On the client the HTML will be slotted into the DOM + * at the location of the original `` node. + */ +export async function* render(opts: RenderOptions): AsyncIterable { const props = { params: opts.params, url: opts.url, route: opts.page.route }; const dataCache = new Map(); + const suspenseQueue: ComponentChildren[] = []; const vnode = h(DATA_CONTEXT.Provider, { value: dataCache, - children: h(opts.page.component!, props), + children: h(SUSPENSE_CONTEXT.Provider, { + value: suspenseQueue, + children: h(opts.page.component!, props), + }), }); const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route); let suspended = 0; const renderWithRenderer = (): string | Promise => { + // Clear the suspense queue + suspenseQueue.splice(0, suspenseQueue.length); + if (++suspended > MAX_SUSPENSE_DEPTH) { throw new Error( `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, @@ -122,8 +155,6 @@ export async function render(opts: RenderOptions): Promise { const bodyHtml = await renderWithRenderer(); - opts.renderer.postRender(ctx, bodyHtml); - let templateProps: { props: PageProps; data?: [string, unknown][]; @@ -142,18 +173,96 @@ export async function render(opts: RenderOptions): Promise { bodyHtml, imports: opts.imports, preloads: opts.preloads, - head: ctx.head, + styles: ctx.styles, props: templateProps, lang: ctx.lang, }); - return html; + let clientStyles = [...ctx.styles]; + yield html; + + if (suspenseQueue.length > 0) { + // minified client-side JS + yield `` + .replaceAll("\n", "\\n"); + } + + // TODO(lucacasonato): parallelize this + for (const [id, children] of suspenseQueue.entries()) { + const fragment = 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) { + yield ``; + } + + yield fragment; + } +} + +export async function suspenseRender( + renderer: Renderer, + ctx: RenderContext, + id: number, + children: ComponentChildren, +): Promise { + const dataCache = new Map(); + + const vnode = h(DATA_CONTEXT.Provider, { + value: dataCache, + children, + }); + + let suspended = 0; + const renderWithRenderer = (): string | Promise => { + if (++suspended > MAX_SUSPENSE_DEPTH) { + throw new Error( + `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, + ); + } + + let body: string | null = null; + let promise: Promise | null = null; + + function render() { + try { + body = renderToString(vnode); + } 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).then(renderWithRenderer); + } else { + throw new Error("`render` function not called by renderer."); + } + }; + + const html = await renderWithRenderer(); + + return ``; } export interface TemplateOptions { bodyHtml: string; imports: string[]; - head: ComponentChild[]; + styles: string[]; preloads: string[]; props: unknown; lang: string; @@ -165,7 +274,10 @@ export function template(opts: TemplateOptions): string { {opts.preloads.map((src) => )} {opts.imports.map((src) => )} - {opts.head} +