feat: allow plugins to modify HTML body (#2022)

Based on https://github.com/denoland/fresh/pull/1769 . Mostly added a
test.

---------

Co-authored-by: Adam Gregory <adam@aguilaengineering.com>
This commit is contained in:
Marvin Hagemeister
2023-11-10 13:59:41 +01:00
committed by GitHub
co-authored by Adam Gregory
parent 14cecc0a6f
commit 7ff2781fcd
11 changed files with 109 additions and 2 deletions
+3 -1
View File
@@ -80,7 +80,9 @@ client.
The `render` hook needs to synchronously return a The `render` hook needs to synchronously return a
[`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult) [`PluginRenderResult`](https://deno.land/x/fresh/server.ts?s=PluginRenderResult)
object. Additional CSS and JS modules can be added to be injected into the page object. Additional CSS and JS modules can be added to be injected into the page
by adding them to `styles`, `links` and `scripts` arrays in this object. by adding them to `styles`, `links` and `scripts` arrays in this object. The
plugin can also replace the the HTML in side the `<body>`-element of the page by
including a `htmlText` string in this object.
`styles` are injected into the `<head>` of the page as inline CSS. Each entry `styles` are injected into the `<head>` of the page as inline CSS. Each entry
can define the CSS text to inject, as well as an optional `id` for the style can define the CSS text to inject, as well as an optional `id` for the style
+8
View File
@@ -276,6 +276,10 @@ export async function render<Data>(
); );
} }
renderResults.push([plugin, res]); renderResults.push([plugin, res]);
if (res.htmlText !== undefined) {
bodyHtml = res.htmlText;
}
} else { } else {
bodyHtml = renderHtml(renderState); bodyHtml = renderHtml(renderState);
} }
@@ -308,6 +312,10 @@ export async function render<Data>(
`The 'renderAsync' function was not called by ${plugin?.name}'s async render hook.`, `The 'renderAsync' function was not called by ${plugin?.name}'s async render hook.`,
); );
} }
if (res.htmlText !== undefined) {
bodyHtml = res.htmlText;
}
} else { } else {
await opts.renderFn(ctx, () => renderSync().htmlText); await opts.renderFn(ctx, () => renderSync().htmlText);
+2
View File
@@ -601,6 +601,8 @@ export interface PluginRenderResult {
scripts?: PluginRenderScripts[]; scripts?: PluginRenderScripts[];
/** Link tags for the page */ /** Link tags for the page */
links?: PluginRenderLink[]; links?: PluginRenderLink[];
/** Body HTML transformed by the plugin */
htmlText?: string;
} }
export interface PluginRenderStyleTag { export interface PluginRenderStyleTag {
+12
View File
@@ -0,0 +1,12 @@
{
"lock": false,
"imports": {
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/"
},
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "preact"
}
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from "$fresh/server.ts";
export default defineConfig({
plugins: [
{
name: "html inject",
async renderAsync(ctx) {
await ctx.renderAsync();
return {
htmlText: "<h1>it works</h1>",
};
},
},
],
});
+17
View File
@@ -0,0 +1,17 @@
// DO NOT EDIT. This file is generated by Fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/index.tsx";
import { Manifest } from "$fresh/server.ts";
const manifest = {
routes: {
"./routes/index.tsx": $0,
},
islands: {},
baseUrl: import.meta.url,
} satisfies Manifest;
export default manifest;
+11
View File
@@ -0,0 +1,11 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
import config from "./fresh.config.ts";
await start(manifest, config);
@@ -0,0 +1,3 @@
export default function Foo() {
return <h1>it does not work</h1>;
}
+12
View File
@@ -14,6 +14,7 @@ import {
clickWhenListenerReady, clickWhenListenerReady,
runBuild, runBuild,
startFreshServer, startFreshServer,
withFakeServe,
withPageName, withPageName,
} from "./test_utils.ts"; } from "./test_utils.ts";
@@ -181,3 +182,14 @@ Deno.test("plugin script doesn't halt island execution", async () => {
}, },
); );
}); });
Deno.test("supports returning htmlText", async () => {
await withFakeServe(
"./tests/fixture_plugin_html/main.ts",
async (server) => {
const doc = await server.getHtml("/");
assertEquals(doc.body.textContent, "it works");
},
{ loadConfig: true },
);
});
+21 -1
View File
@@ -286,6 +286,7 @@ export async function fakeServe(
export async function withFakeServe( export async function withFakeServe(
name: string, name: string,
cb: (server: FakeServer) => Promise<void> | void, cb: (server: FakeServer) => Promise<void> | void,
options: { loadConfig?: boolean } = {},
) { ) {
const fixture = join(Deno.cwd(), name); const fixture = join(Deno.cwd(), name);
const dev = basename(name) === "dev.ts"; const dev = basename(name) === "dev.ts";
@@ -293,7 +294,26 @@ export async function withFakeServe(
const manifestPath = toFileUrl(join(dirname(fixture), "fresh.gen.ts")).href; const manifestPath = toFileUrl(join(dirname(fixture), "fresh.gen.ts")).href;
const manifestMod = await import(manifestPath); const manifestMod = await import(manifestPath);
const server = await fakeServe(manifestMod.default, { dev }); const configPath = join(dirname(fixture), "fresh.config.ts");
let config = { dev };
// For now we load config on a case by case basis, because something in
// twind (unsure) doesn't work well if multiple instances are running
if (options.loadConfig) {
try {
const stats = await Deno.stat(configPath);
if (stats.isFile) {
const m = await import(toFileUrl(configPath).href);
config = m.default;
config.dev = dev;
}
} catch {
// ignore
}
}
const server = await fakeServe(manifestMod.default, config);
await cb(server); await cb(server);
} }