feat: support suspending during SSR and useData (#27)
This commit adds support for suspending during JIT SSR rendering. Additionally this PR adds `useData` support. This hook is triggered during JIT render and can be used to fetch data. This data is sent to the client and returned there from calls to useData too.
This commit is contained in:
@@ -17,10 +17,16 @@ function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
return <div>
|
||||
<p>{count}</p>
|
||||
<button onClick={() => setCount(count - 1)} disabled={!IS_BROWSER}>
|
||||
<button
|
||||
onClick={() => setCount(count - 1)}
|
||||
disabled={!IS_BROWSER}
|
||||
>
|
||||
-1
|
||||
</button>
|
||||
<button onClick={() => setCount(count + 1)} disabled={!IS_BROWSER}>
|
||||
<button
|
||||
onClick={() => setCount(count + 1)}
|
||||
disabled={!IS_BROWSER}
|
||||
>
|
||||
+1
|
||||
</button>
|
||||
</div>;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { h, PageProps, useData } from "../../deps.ts";
|
||||
|
||||
export default function ModuleInfoPage({ params }: PageProps) {
|
||||
const module = params.module;
|
||||
|
||||
if (module.includes("/")) {
|
||||
return <div>Invalid module name.</div>;
|
||||
}
|
||||
|
||||
const url = `https://cdn.deno.land/${params.module}/meta/versions.json`;
|
||||
const info = useData(url, fetcher);
|
||||
|
||||
if (info === null) {
|
||||
return <div>No module found with name `{params.module}`.</div>;
|
||||
}
|
||||
|
||||
const { latest, versions } = info;
|
||||
return <p>
|
||||
The module `{params.module}` has {versions.length} versions, with {latest}
|
||||
{" "}
|
||||
being the most recent.
|
||||
</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;
|
||||
}
|
||||
@@ -3,14 +3,16 @@
|
||||
// To update this file, run `fresh routes`.
|
||||
|
||||
import * as $0 from "./pages/api/joke.ts";
|
||||
import * as $1 from "./pages/[name].tsx";
|
||||
import * as $2 from "./pages/index.tsx";
|
||||
import * as $1 from "./pages/x/[module].tsx";
|
||||
import * as $2 from "./pages/[name].tsx";
|
||||
import * as $3 from "./pages/index.tsx";
|
||||
|
||||
const routes = {
|
||||
pages: {
|
||||
"./pages/api/joke.ts": $0,
|
||||
"./pages/[name].tsx": $1,
|
||||
"./pages/index.tsx": $2,
|
||||
"./pages/x/[module].tsx": $1,
|
||||
"./pages/[name].tsx": $2,
|
||||
"./pages/index.tsx": $3,
|
||||
},
|
||||
baseUrl: import.meta.url,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./src/runtime/deps.ts";
|
||||
export * from "./src/runtime/types.ts";
|
||||
export * from "./src/runtime/utils.ts";
|
||||
export * from "./src/runtime/hooks.ts";
|
||||
|
||||
@@ -21,3 +21,4 @@ export {
|
||||
useRef,
|
||||
useState,
|
||||
} from "https://x.lcas.dev/preact@10.5.12/hooks.js";
|
||||
import "https://x.lcas.dev/preact@10.5.12/debug.js";
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
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;
|
||||
}
|
||||
+11
-3
@@ -119,11 +119,19 @@ function freshPlugin(pageList: Page[]): esbuild.Plugin {
|
||||
if (!page) return null;
|
||||
const contents = `
|
||||
import Page from "${page.url}";
|
||||
import { h, render } from "${runtime.href}";
|
||||
import { h, render, DATA_CONTEXT } from "${runtime.href}";
|
||||
|
||||
addEventListener("DOMContentLoaded", () => {
|
||||
const props = JSON.parse(document.getElementById("__FRSH_PROPS").textContent);
|
||||
render(h(Page, props), document.body);
|
||||
const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS").textContent);
|
||||
try {
|
||||
render(h(DATA_CONTEXT.Provider, { value: new Map(data) }, h(Page, { 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
`;
|
||||
return { contents, loader: "js" };
|
||||
|
||||
@@ -7,7 +7,7 @@ import { INTERNAL_PREFIX } from "./constants.ts";
|
||||
import { JS_PREFIX } from "./constants.ts";
|
||||
import { BUILD_ID } from "./constants.ts";
|
||||
import { ApiRoute, Page } from "./types.ts";
|
||||
import { render } from "./render.ts";
|
||||
import { render } from "./render.tsx";
|
||||
|
||||
export class ServerContext {
|
||||
#pages: Page[];
|
||||
@@ -77,11 +77,11 @@ export class ServerContext {
|
||||
for (const page of this.#pages) {
|
||||
const bundlePath = `/${page.name}.js`;
|
||||
const imports = [bundleAssetUrl(bundlePath)];
|
||||
routes[page.route] = (_, match) => {
|
||||
routes[page.route] = async (_, match) => {
|
||||
const preloads = this.#bundler.getPreloads(bundlePath).map(
|
||||
bundleAssetUrl,
|
||||
);
|
||||
const body = render({
|
||||
const body = await render({
|
||||
page,
|
||||
imports,
|
||||
preloads,
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { renderToString } from "./deps.ts";
|
||||
import * as rt from "../runtime/deps.ts";
|
||||
import { Page } from "./types.ts";
|
||||
|
||||
export interface RenderOptions {
|
||||
page: Page;
|
||||
imports: string[];
|
||||
preloads: string[];
|
||||
params: Record<string, string>;
|
||||
}
|
||||
|
||||
export function render(options: RenderOptions): string {
|
||||
const props = { params: options.params };
|
||||
const propsStr = JSON.stringify(props);
|
||||
const body = renderToString(rt.h(options.page.component, props));
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
${
|
||||
options.preloads.map((src) => `<link rel="modulepreload" href="${src}">`)
|
||||
.join(
|
||||
"\n ",
|
||||
)
|
||||
}
|
||||
${
|
||||
options.imports.map((src) => `<script src="${src}" type="module"></script>`)
|
||||
.join(
|
||||
"\n ",
|
||||
)
|
||||
}
|
||||
</head>
|
||||
<body>
|
||||
${body}
|
||||
<script id="__FRSH_PROPS" type="application/json">${propsStr}</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { renderToString } from "./deps.ts";
|
||||
import { h } from "../runtime/deps.ts";
|
||||
import { DATA_CONTEXT } from "../runtime/hooks.ts";
|
||||
import { Page } from "./types.ts";
|
||||
|
||||
export interface RenderOptions {
|
||||
page: Page;
|
||||
imports: string[];
|
||||
preloads: string[];
|
||||
params: Record<string, string>;
|
||||
}
|
||||
|
||||
const MAX_SUSPENSE_DEPTH = 10;
|
||||
|
||||
export async function render(opts: RenderOptions): Promise<string> {
|
||||
const props = { params: opts.params };
|
||||
|
||||
const dataCache = new Map();
|
||||
|
||||
const vnode = h(DATA_CONTEXT.Provider, {
|
||||
value: dataCache,
|
||||
children: h(opts.page.component, props),
|
||||
});
|
||||
|
||||
let suspended = 0;
|
||||
const render = (): string | Promise<string> => {
|
||||
if (++suspended > MAX_SUSPENSE_DEPTH) {
|
||||
throw new Error(
|
||||
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
return renderToString(vnode);
|
||||
} catch (e) {
|
||||
if (e && e.then) return e.then(render);
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
const bodyHtml = await render();
|
||||
|
||||
const html = template({
|
||||
bodyHtml,
|
||||
imports: opts.imports,
|
||||
preloads: opts.preloads,
|
||||
props: { params: opts.params, data: [...dataCache.entries()] },
|
||||
});
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
export interface TemplateOptions {
|
||||
bodyHtml: string;
|
||||
imports: string[];
|
||||
preloads: string[];
|
||||
props: unknown;
|
||||
}
|
||||
|
||||
export function template(opts: TemplateOptions): string {
|
||||
const props = JSON.stringify(opts.props);
|
||||
|
||||
const page = (
|
||||
<html>
|
||||
<head>
|
||||
{opts.preloads.map((src) => <link rel="modulepreload" href={src} />)}
|
||||
{opts.imports.map((src) => <script src={src} type="module"></script>)}
|
||||
</head>
|
||||
<body>
|
||||
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
|
||||
<script
|
||||
id="__FRSH_PROPS"
|
||||
type="application/json"
|
||||
dangerouslySetInnerHTML={{ __html: props }}
|
||||
/>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
return "<!DOCTYPE html>" + renderToString(page);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from "../../server.ts";
|
||||
@@ -1,8 +1,14 @@
|
||||
import { h, IS_BROWSER, useState } from "../deps.ts";
|
||||
import { h, IS_BROWSER, 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>
|
||||
);
|
||||
|
||||
+15
-2
@@ -11,10 +11,19 @@ Deno.test("/ page prerender", async () => {
|
||||
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
|
||||
const body = await resp.text();
|
||||
assertStringIncludes(body, "index.js");
|
||||
assertStringIncludes(body, "<p>Hello!</p>");
|
||||
assertStringIncludes(body, "<p>Viewing JIT render.</p>");
|
||||
assertStringIncludes(
|
||||
body,
|
||||
`<script id="__FRSH_PROPS" type="application/json">{"params":{}}</script>`,
|
||||
`<script id="__FRSH_PROPS" type="application/json">`,
|
||||
);
|
||||
assertStringIncludes(
|
||||
body,
|
||||
`"params":{}`,
|
||||
);
|
||||
assertStringIncludes(
|
||||
body,
|
||||
`"data":[["home","Hello!"]]`,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -28,7 +37,11 @@ Deno.test("/[name] page prerender", async () => {
|
||||
assertStringIncludes(body, "<div>Hello foo</div>");
|
||||
assertStringIncludes(
|
||||
body,
|
||||
`<script id="__FRSH_PROPS" type="application/json">{"params":{"name":"foo"}}</script>`,
|
||||
`<script id="__FRSH_PROPS" type="application/json">`,
|
||||
);
|
||||
assertStringIncludes(
|
||||
body,
|
||||
`"params":{"name":"foo"}`,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user