From 56baffa96d229636229f11d1506c924f335c0f72 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Fri, 11 Jun 2021 13:59:55 +0200 Subject: [PATCH] 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. --- example/pages/index.tsx | 10 ++++- example/pages/x/[module].tsx | 34 +++++++++++++++ example/routes.gen.ts | 10 +++-- runtime.ts | 1 + src/runtime/deps.ts | 1 + src/runtime/hooks.ts | 60 ++++++++++++++++++++++++++ src/server/bundle.ts | 14 ++++-- src/server/context.ts | 6 +-- src/server/render.ts | 37 ---------------- src/server/render.tsx | 80 +++++++++++++++++++++++++++++++++++ tests/fixture/api_deps.ts | 1 - tests/fixture/pages/index.tsx | 8 +++- tests/main_test.ts | 17 +++++++- 13 files changed, 226 insertions(+), 53 deletions(-) create mode 100644 example/pages/x/[module].tsx create mode 100644 src/runtime/hooks.ts delete mode 100644 src/server/render.ts create mode 100644 src/server/render.tsx delete mode 100644 tests/fixture/api_deps.ts diff --git a/example/pages/index.tsx b/example/pages/index.tsx index d2356648..1fb90be7 100644 --- a/example/pages/index.tsx +++ b/example/pages/index.tsx @@ -17,10 +17,16 @@ function Counter() { const [count, setCount] = useState(0); return

{count}

- -
; diff --git a/example/pages/x/[module].tsx b/example/pages/x/[module].tsx new file mode 100644 index 00000000..5c754771 --- /dev/null +++ b/example/pages/x/[module].tsx @@ -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
Invalid module name.
; + } + + const url = `https://cdn.deno.land/${params.module}/meta/versions.json`; + const info = useData(url, fetcher); + + if (info === null) { + return
No module found with name `{params.module}`.
; + } + + const { latest, versions } = info; + return

+ The module `{params.module}` has {versions.length} versions, with {latest} + {" "} + being the most recent. +

; +} + +interface ModuleInfo { + latest: string; + versions: string[]; +} + +async function fetcher(url: string): Promise { + const resp = await fetch(url); + if (resp.status === 200) return resp.json(); + return null; +} diff --git a/example/routes.gen.ts b/example/routes.gen.ts index 85c56c74..1446eb27 100644 --- a/example/routes.gen.ts +++ b/example/routes.gen.ts @@ -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, }; diff --git a/runtime.ts b/runtime.ts index f3ad234a..6ec4c215 100644 --- a/runtime.ts +++ b/runtime.ts @@ -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"; diff --git a/src/runtime/deps.ts b/src/runtime/deps.ts index ff914e33..fc94a657 100644 --- a/src/runtime/deps.ts +++ b/src/runtime/deps.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"; diff --git a/src/runtime/hooks.ts b/src/runtime/hooks.ts new file mode 100644 index 00000000..91ba46ca --- /dev/null +++ b/src/runtime/hooks.ts @@ -0,0 +1,60 @@ +import { createContext, useContext } from "./deps.ts"; +import { IS_BROWSER } from "./utils.ts"; + +export const DATA_CONTEXT = createContext(new Map()); + +export type Fetcher = (key: string) => T | Promise; + +/** + * 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

The Deno standard library has {versions.length} versions, with {latest} being the most recent.

+ * } + * + * 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(key: string, fetcher: Fetcher): 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; +} diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 2bca9d85..1c3d4aea 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -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" }; diff --git a/src/server/context.ts b/src/server/context.ts index 9cfb4023..51420980 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -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, diff --git a/src/server/render.ts b/src/server/render.ts deleted file mode 100644 index 06d5c743..00000000 --- a/src/server/render.ts +++ /dev/null @@ -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; -} - -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 ` - - - ${ - options.preloads.map((src) => ``) - .join( - "\n ", - ) - } - ${ - options.imports.map((src) => ``) - .join( - "\n ", - ) - } - - - ${body} - - -`; -} diff --git a/src/server/render.tsx b/src/server/render.tsx new file mode 100644 index 00000000..79ea9907 --- /dev/null +++ b/src/server/render.tsx @@ -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; +} + +const MAX_SUSPENSE_DEPTH = 10; + +export async function render(opts: RenderOptions): Promise { + 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 => { + 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 = ( + + + {opts.preloads.map((src) => )} + {opts.imports.map((src) => )} + + +
+ `, + ``, + `