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.
This commit is contained in:
@@ -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.
|
||||
|
||||
+36
-10
@@ -168,18 +168,18 @@ export async function render<Data>(
|
||||
|
||||
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<Data>(
|
||||
}
|
||||
renderResults.push([plugin, res]);
|
||||
} else {
|
||||
realRender();
|
||||
renderInner();
|
||||
}
|
||||
if (bodyHtml === null) {
|
||||
throw new Error(
|
||||
@@ -200,13 +200,39 @@ export async function render<Data>(
|
||||
};
|
||||
}
|
||||
|
||||
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<PluginRenderFunctionResult> {
|
||||
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][] = [];
|
||||
|
||||
|
||||
+20
-2
@@ -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<PluginRenderResult>;
|
||||
}
|
||||
|
||||
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<PluginRenderFunctionResult>;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
@@ -35,6 +35,10 @@ Deno.test("/static page prerender", async () => {
|
||||
assertStringIncludes(body, '<style id="abc">body { color: red; }</style>');
|
||||
assert(!body.includes(`>{"v":[[],[]]}</script>`));
|
||||
assert(!body.includes(`import`));
|
||||
assertStringIncludes(
|
||||
body,
|
||||
'<style id="def">h1 { text-decoration: underline; }</style>',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("/with-island prerender", async () => {
|
||||
@@ -48,6 +52,10 @@ Deno.test("/with-island prerender", async () => {
|
||||
);
|
||||
assertStringIncludes(body, `>{"v":[[{}],["JS injected!"]]}</script>`);
|
||||
assertStringIncludes(body, `/plugin-js-inject-main.js"`);
|
||||
assertStringIncludes(
|
||||
body,
|
||||
'<style id="def">h1 { text-decoration: underline; } h1 { font-style: italic; }</style>',
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
|
||||
Reference in New Issue
Block a user