From dd4e584a3ea009836389607d2d44527b00e88d1d Mon Sep 17 00:00:00 2001 From: Tom Date: Tue, 6 Jun 2023 20:36:04 +1000 Subject: [PATCH] feat: async plugin rendering (#745) An async render hook is added to plugins that enables injecting stylesheets and scripts based on the rendered HTML text. --- docs/concepts/plugins.md | 26 +++++++++++ src/server/render.ts | 46 +++++++++++++++---- src/server/types.ts | 22 ++++++++- tests/fixture_plugin/options.ts | 9 +++- .../utils/css-inject-plugin-async.ts | 15 ++++++ tests/plugin_test.ts | 8 ++++ 6 files changed, 113 insertions(+), 13 deletions(-) create mode 100644 tests/fixture_plugin/utils/css-inject-plugin-async.ts diff --git a/docs/concepts/plugins.md b/docs/concepts/plugins.md index d1f31ec3..4ce4d7d6 100644 --- a/docs/concepts/plugins.md +++ b/docs/concepts/plugins.md @@ -99,3 +99,29 @@ serializable JavaScript value. For an example of a plugin that uses the `render` hook, see the first-party [Twind plugin](https://github.com/denoland/fresh/blob/main/plugins/twind.ts). + +### Hook: `renderAsync` + +This hook is largely the same as the `render` hook, with a couple of key +differences to make asynchronous style and script generation possible. It must +asynchronously return its +[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult), +either from an `async/await` function or wrapped within a promise. + +The render hook is called with the +[`AsyncPluginRenderContext`](https://deno.land/x/fresh/server.ts?s=AsyncPluginRenderContext) +object, which contains a `renderAsync()` method. This method must be invoked +during the render hook to actually render the page. It is a terminal error to +not call the `renderAsync()` method during the render hook. + +This is useful for when plugins are generating styles and scripts with +asynchronous dependencies based on the `htmlText`. Unlike the synchronous render +hook, async render hooks for multiple pages can be running at the same time. +This means that unlike the synchronous render hook, you can not use global +variables to propagate state between the render hook and the renderer. + +The `renderAsync` hooks start before any page rendering occurs, and finish after +all rendering is complete -- they wrap around the underlying JSX->string +rendering, plugin `render` hooks, and the +[`RenderFunction`](https://deno.land/x/fresh/server.ts?s=RenderFunction) that +may be provided to Fresh's `start` entrypoint in the `main.ts` file. diff --git a/src/server/render.ts b/src/server/render.ts index 7aa7ae81..58d43a5a 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -168,18 +168,18 @@ export async function render( let bodyHtml: string | null = null; - function realRender(): string { + function renderInner(): string { bodyHtml = renderToString(vnode); return bodyHtml; } - const plugins = opts.plugins.filter((p) => p.render !== null); + const syncPlugins = opts.plugins.filter((p) => p.render); const renderResults: [Plugin, PluginRenderResult][] = []; - function render(): PluginRenderFunctionResult { - const plugin = plugins.shift(); + function renderSync(): PluginRenderFunctionResult { + const plugin = syncPlugins.shift(); if (plugin) { - const res = plugin.render!({ render }); + const res = plugin.render!({ render: renderSync }); if (res === undefined) { throw new Error( `${plugin?.name}'s render hook did not return a PluginRenderResult object.`, @@ -187,7 +187,7 @@ export async function render( } renderResults.push([plugin, res]); } else { - realRender(); + renderInner(); } if (bodyHtml === null) { throw new Error( @@ -200,13 +200,39 @@ export async function render( }; } - await opts.renderFn(ctx, () => render().htmlText); + const asyncPlugins = opts.plugins.filter((p) => p.renderAsync); - if (bodyHtml === null) { - throw new Error("The `render` function was not called by the renderer."); + async function renderAsync(): Promise { + const plugin = asyncPlugins.shift(); + if (plugin) { + const res = await plugin.renderAsync!({ renderAsync }); + if (res === undefined) { + throw new Error( + `${plugin?.name}'s async render hook did not return a PluginRenderResult object.`, + ); + } + renderResults.push([plugin, res]); + if (bodyHtml === null) { + throw new Error( + `The 'renderAsync' function was not called by ${plugin?.name}'s async render hook.`, + ); + } + } else { + await opts.renderFn(ctx, () => renderSync().htmlText); + if (bodyHtml === null) { + throw new Error( + `The 'render' function was not called by the legacy async render hook.`, + ); + } + } + return { + htmlText: bodyHtml, + requiresHydration: ENCOUNTERED_ISLANDS.size > 0, + }; } - bodyHtml = bodyHtml as string; + await renderAsync(); + bodyHtml = bodyHtml as unknown as string; const moduleScripts: [string, string][] = []; diff --git a/src/server/types.ts b/src/server/types.ts index ca1423b9..71fa4578 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -269,11 +269,27 @@ export interface Plugin { * inject CSS into the page, or load additional JS files on the client. */ render?(ctx: PluginRenderContext): PluginRenderResult; + + /** The asynchronous render hook is called on the server every time some + * JSX needs to be turned into HTML, wrapped around all synchronous render + * hooks. The render hook needs to call the `ctx.renderAsync` function + * exactly once, and await the result. + * + * This is useful for when plugins are generating styles and scripts with + * asynchronous dependencies. Unlike the synchronous render hook, async render + * hooks for multiple pages can be running at the same time. This means that + * unlike the synchronous render hook, you can not use global variables to + * propagate state between the render hook and the renderer. + */ + renderAsync?(ctx: PluginAsyncRenderContext): Promise; } export interface PluginRenderContext { render: PluginRenderFunction; } +export interface PluginAsyncRenderContext { + renderAsync: PluginAsyncRenderFunction; +} export interface PluginRenderResult { /** CSS styles to be injected into the page. */ @@ -303,12 +319,14 @@ export interface PluginRenderScripts { } export type PluginRenderFunction = () => PluginRenderFunctionResult; +export type PluginAsyncRenderFunction = () => + | PluginRenderFunctionResult + | Promise; export interface PluginRenderFunctionResult { /** The HTML text that was rendered. */ htmlText: string; /** If the renderer encountered any islands that require hydration on the - * client. - */ + * client. */ requiresHydration: boolean; } diff --git a/tests/fixture_plugin/options.ts b/tests/fixture_plugin/options.ts index a31c710b..5555a284 100644 --- a/tests/fixture_plugin/options.ts +++ b/tests/fixture_plugin/options.ts @@ -1,5 +1,12 @@ import { FreshOptions } from "$fresh/server.ts"; import cssInjectPlugin from "./utils/css-inject-plugin.ts"; import jsInjectPlugin from "./utils/js-inject-plugin.ts"; +import cssInjectPluginAsync from "./utils/css-inject-plugin-async.ts"; -export default { plugins: [cssInjectPlugin, jsInjectPlugin] } as FreshOptions; +export default { + plugins: [ + cssInjectPlugin, + jsInjectPlugin, + cssInjectPluginAsync, + ], +} as FreshOptions; diff --git a/tests/fixture_plugin/utils/css-inject-plugin-async.ts b/tests/fixture_plugin/utils/css-inject-plugin-async.ts new file mode 100644 index 00000000..356ad1d4 --- /dev/null +++ b/tests/fixture_plugin/utils/css-inject-plugin-async.ts @@ -0,0 +1,15 @@ +import { Plugin } from "$fresh/server.ts"; + +let CSS_TO_INJECT = "h1 { text-decoration: underline; }"; + +export default { + name: "css-inject-async", + async renderAsync(ctx) { + await new Promise((res) => setTimeout(res, 50)); + const res = await ctx.renderAsync(); + if (res.requiresHydration) { + CSS_TO_INJECT += " h1 { font-style: italic; }"; + } + return { styles: [{ cssText: CSS_TO_INJECT, id: "def" }] }; + }, +} as Plugin; diff --git a/tests/plugin_test.ts b/tests/plugin_test.ts index a1ab0d60..86999f27 100644 --- a/tests/plugin_test.ts +++ b/tests/plugin_test.ts @@ -35,6 +35,10 @@ Deno.test("/static page prerender", async () => { assertStringIncludes(body, ''); assert(!body.includes(`>{"v":[[],[]]}`)); assert(!body.includes(`import`)); + assertStringIncludes( + body, + '', + ); }); Deno.test("/with-island prerender", async () => { @@ -48,6 +52,10 @@ Deno.test("/with-island prerender", async () => { ); assertStringIncludes(body, `>{"v":[[{}],["JS injected!"]]}`); assertStringIncludes(body, `/plugin-js-inject-main.js"`); + assertStringIncludes( + body, + '', + ); }); Deno.test({