feat: Support setting <html> in _app template (#1617)

This commit is contained in:
Marvin Hagemeister
2023-08-11 18:40:20 +02:00
committed by GitHub
parent d601f4cef4
commit 86f92114d8
27 changed files with 414 additions and 95 deletions
+6 -1
View File
@@ -59,5 +59,10 @@ jobs:
- name: Type check project
run: deno task check:types
- name: Run tests
- name: Run tests Windows
if: matrix.os == 'windows-latest'
run: deno test -A
- name: Run tests macOS + Linux
if: matrix.os != 'windows-latest'
run: deno test -A --parallel
+1 -1
View File
@@ -8,7 +8,7 @@
"twind/": "https://esm.sh/twind@0.16.19/",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3",
"@preact/signals-core@1.2.3": "https://esm.sh/@preact/signals-core@1.2.3",
+1 -1
View File
@@ -7,7 +7,7 @@
"$fresh/": "../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
},
+37 -32
View File
@@ -137,35 +137,29 @@ CMD ["run", "-A", "main.ts"]
);
}
const ROUTES_INDEX_TSX = `import { Head } from "$fresh/runtime.ts";
import { useSignal } from "@preact/signals";
const ROUTES_INDEX_TSX = `import { useSignal } from "@preact/signals";
import Counter from "../islands/Counter.tsx";
export default function Home() {
const count = useSignal(3);
return (
<>
<Head>
<title>${basename(resolvedDirectory)}</title>
</Head>
<div class="px-4 py-8 mx-auto bg-[#86efac]">
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
<div class="px-4 py-8 mx-auto bg-[#86efac]">
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
src="/logo.svg"
width="128"
height="128"
alt="the Fresh logo: a sliced lemon dripping with juice"
/>
<h1 class="text-4xl font-bold">Welcome to Fresh</h1>
<p class="my-4">
Try updating this message in the
<code class="mx-2">./routes/index.tsx</code> file, and refresh.
</p>
<Counter count={count} />
</div>
</>
</div>
);
}
`;
@@ -436,23 +430,34 @@ const APP_WRAPPER = useTwind
export default function App({ Component }: AppProps) {
return (
<>
<Component />
</>
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${basename(resolvedDirectory)}</title>
</head>
<body>
<Component />
</body>
</html>
);
}
`
: `import { AppProps } from "$fresh/server.ts";
import { Head } from "$fresh/runtime.ts";
export default function App({ Component }: AppProps) {
return (
<>
<Head>
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${basename(resolvedDirectory)}</title>
<link rel="stylesheet" href="/styles.css" />
</Head>
<Component />
</>
</head>
<body>
<Component />
</body>
</html>
);
}
`;
+1 -1
View File
@@ -1,5 +1,5 @@
export const RECOMMENDED_PREACT_VERSION = "10.15.1";
export const RECOMMENDED_PREACT_RTS_VERSION = "6.2.0";
export const RECOMMENDED_PREACT_RTS_VERSION = "6.2.1";
export const RECOMMENDED_PREACT_SIGNALS_VERSION = "1.1.3";
export const RECOMMENDED_PREACT_SIGNALS_CORE_VERSION = "1.2.3";
export const RECOMMENDED_TWIND_VERSION = "0.16.19";
+113 -35
View File
@@ -45,12 +45,36 @@ export interface AdvancedPreactOptions extends PreactOptions {
/** Attach a hook that is invoked before a vnode has rendered. */
__r?(vnode: VNode): void;
errorBoundaries?: boolean;
/** before diff hook */
__b?(vnode: VNode): void;
}
const options = preactOptions as AdvancedPreactOptions;
// Enable error boundaries in Preact.
options.errorBoundaries = true;
// These values keep track of whether the user rendered the <html>,
// <head> and <body> element. Basically, the outer document. We
// keep track of this, because we only know the full sets of
// elements we should put in `<head>` after having completed
// rendering the page.
let RENDERING_USER_TEMPLATE = false;
interface OuterDocument {
// deno-lint-ignore no-explicit-any
title: VNode<any> | null;
html: Record<string, unknown> | null;
head: Record<string, unknown> | null;
body: Record<string, unknown> | null;
headNodes: { type: string; props: Record<string, unknown> }[];
}
let OUTER_DOCUMENT: OuterDocument = {
title: null,
html: null,
head: null,
body: null,
headNodes: [],
};
export interface RenderOptions<Data> {
request: Request;
// deno-lint-ignore no-explicit-any
@@ -209,6 +233,17 @@ export async function render<Data>(
// Clear previous slots
SLOTS_TRACKER.clear();
// Clear rendering state
RENDERING_USER_TEMPLATE = false;
headChildren = false;
OUTER_DOCUMENT = {
title: null,
body: null,
head: null,
html: null,
headNodes: [],
};
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
@@ -432,7 +467,19 @@ export async function render<Data>(
};
}
RENDERING_USER_TEMPLATE = true;
await renderAsync();
RENDERING_USER_TEMPLATE = false;
const idx = headComponents.findIndex((vnode) =>
vnode !== null && typeof vnode === "object" && "type" in vnode &&
props !== null && vnode.type === "title"
);
if (idx !== -1) {
OUTER_DOCUMENT.title = headComponents[idx] as VNode<{ children: string }>;
headComponents.splice(idx, 1);
}
if (asyncRenderResponse !== undefined) {
return asyncRenderResponse;
}
@@ -563,48 +610,37 @@ export async function render<Data>(
}
const preloads = [...preloadSet];
const html = template({
bodyHtml,
headComponents,
moduleScripts,
preloads,
lang: ctx.lang,
});
return [html, csp];
}
export interface TemplateOptions {
bodyHtml: string;
headComponents: ComponentChildren[];
moduleScripts: (readonly [string, string])[];
preloads: string[];
lang: string;
}
export function template(opts: TemplateOptions): string {
const page = h(
"html",
{ lang: opts.lang },
OUTER_DOCUMENT.html ?? { lang: ctx.lang },
h(
"head",
null,
h("meta", { charSet: "UTF-8" }),
h("meta", {
name: "viewport",
content: "width=device-width, initial-scale=1.0",
}),
opts.preloads.map((src) =>
h("link", { rel: "modulepreload", href: src })
),
opts.moduleScripts.map(([src, nonce]) =>
OUTER_DOCUMENT.head,
// Add some tags ourselves if the user uses the legacy
// _app template rendering style where we provided the outer
// HTML document.
!renderedHtmlTag ? h("meta", { charSet: "UTF-8" }) : null,
!renderedHtmlTag
? h("meta", {
name: "viewport",
content: "width=device-width, initial-scale=1.0",
})
: null,
OUTER_DOCUMENT.title,
OUTER_DOCUMENT.headNodes.map((node) => h(node.type, node.props)),
// Fresh scripts
preloads.map((src) => h("link", { rel: "modulepreload", href: src })),
moduleScripts.map(([src, nonce]) =>
h("script", { src: src, nonce: nonce, type: "module" })
),
opts.headComponents,
headComponents,
),
h("body", { dangerouslySetInnerHTML: { __html: opts.bodyHtml } }),
h("body", { dangerouslySetInnerHTML: { __html: bodyHtml } }),
);
return "<!DOCTYPE html>" + renderToString(page);
const html = "<!DOCTYPE html>" + renderToString(page);
return [html, csp];
}
const supportsUnstableComments = renderToString(h(Fragment, {
@@ -666,6 +702,8 @@ const islandOwners = new Map<VNode, VNode>();
const originalHook = options.vnode;
let ignoreNext = false;
let headChildren = false;
let renderedHtmlTag = false;
options.vnode = (vnode) => {
assetHashingHook(vnode);
const originalType = vnode.type as ComponentType<unknown>;
@@ -737,7 +775,7 @@ options.vnode = (vnode) => {
);
};
}
} else if (typeof vnode.type === "string" && vnode.props !== null) {
} else {
// Work around `preact/debug` string event handler error which
// errors when an event handler gets a string. This makes sense
// on the client where this is a common vector for XSS. On the
@@ -757,10 +795,48 @@ options.vnode = (vnode) => {
if (originalHook) originalHook(vnode);
};
function excludeChildren(props: Record<string, unknown>) {
const out: Record<string, unknown> = {};
for (const k in props) {
if (k !== "children") out[k] = props[k];
}
return out;
}
// Keep track of owners
const oldDiff = options.__b;
const oldDiffed = options.diffed;
const oldRender = options.__r;
const oldCommit = options.__c;
options.__b = (vnode: VNode<Record<string, unknown>>) => {
if (RENDERING_USER_TEMPLATE && typeof vnode.type === "string") {
if (vnode.type === "html") {
renderedHtmlTag = true;
OUTER_DOCUMENT.html = excludeChildren(vnode.props);
vnode.type = Fragment;
} else if (vnode.type === "head") {
OUTER_DOCUMENT.head = excludeChildren(vnode.props);
headChildren = true;
vnode.type = Fragment;
vnode.props = {
__freshHead: true,
children: vnode.props.children,
};
} else if (vnode.type === "body") {
OUTER_DOCUMENT.body = excludeChildren(vnode.props);
vnode.type = Fragment;
} else if (headChildren) {
if (vnode.type === "title") {
OUTER_DOCUMENT.title = h("title", vnode.props);
vnode.props = { children: null };
} else {
OUTER_DOCUMENT.headNodes.push({ type: vnode.type, props: vnode.props });
}
vnode.type = Fragment;
}
}
oldDiff?.(vnode);
};
options.__r = (vnode) => {
if (
typeof vnode.type === "function" &&
@@ -770,10 +846,12 @@ options.__r = (vnode) => {
}
oldRender?.(vnode);
};
options.diffed = (vnode) => {
options.diffed = (vnode: VNode<Record<string, unknown>>) => {
if (typeof vnode.type === "function") {
if (vnode.type !== Fragment) {
ownerStack.pop();
} else if (vnode.props.__freshHead) {
headChildren = false;
}
}
oldDiffed?.(vnode);
-14
View File
@@ -1,14 +0,0 @@
import { template } from "./render.ts";
import { assertStringIncludes } from "../../tests/deps.ts";
Deno.test("check lang", () => {
const lang = "fr";
const body = template({
bodyHtml: "",
headComponents: [],
moduleScripts: [],
preloads: [],
lang,
});
assertStringIncludes(body, `<html lang="${lang}">`);
});
+56
View File
@@ -458,3 +458,59 @@ Deno.test("fresh-update", async function fn(t) {
assertEquals(code, 0);
}
});
Deno.test("fresh-update add _app.tsx if not present", async function fn(t) {
// Preparation
const tmpDirName = await Deno.makeTempDir();
const cliProcess = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(Deno.cwd(), "init.ts"),
".",
],
cwd: tmpDirName,
stdin: "null",
stdout: "null",
});
await cliProcess.output();
const appTsx = path.join(tmpDirName, "routes", "_app.tsx");
await Deno.remove(appTsx);
await t.step("execute update command", async () => {
await updateAndVerify(
/The manifest has been generated for \d+ routes and \d+ islands./,
);
});
await t.step("add _app.tsx", async () => {
const raw = await Deno.readTextFile(appTsx);
assert(raw.includes("<html>"), `<html>-tag not found in _app.tsx`);
});
async function updateAndVerify(expected: RegExp) {
const cliProcess = new Deno.Command(Deno.execPath(), {
args: [
"run",
"-A",
path.join(Deno.cwd(), "update.ts"),
".",
],
cwd: tmpDirName,
stdin: "null",
stdout: "piped",
});
const { code, stdout } = await cliProcess.output();
const output = new TextDecoder().decode(stdout);
assertMatch(
output,
expected,
);
assertEquals(code, 0);
}
});
+68
View File
@@ -0,0 +1,68 @@
import {
assertNotSelector,
assertSelector,
assertTextMany,
fetchHtml,
withFresh,
} from "$fresh/tests/test_utils.ts";
Deno.test("doesn't apply internal app template", async () => {
await withFresh(
"./tests/fixture_explicit_app/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}`);
// Doesn't render internal app template
assertNotSelector(doc, "body body");
assertSelector(doc, "html > head");
assertSelector(doc, "html > body");
assertSelector(doc, `meta[charset="utf-8"]`);
assertSelector(
doc,
`meta[name="viewport"][content="width=device-width, initial-scale=1.0"]`,
);
assertTextMany(doc, "title", ["fresh title"]);
// Still renders page
assertSelector(doc, "body > .inner-body > .page");
},
);
});
Deno.test("user _app works with <Head>", async () => {
await withFresh(
"./tests/fixture_explicit_app/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/head`);
// Doesn't render internal app template
assertNotSelector(doc, "body body");
assertSelector(doc, "html > head");
assertSelector(doc, "html > body");
assertSelector(doc, `meta[charset="utf-8"]`);
assertSelector(
doc,
`meta[name="viewport"][content="width=device-width, initial-scale=1.0"]`,
);
assertSelector(
doc,
`meta[name="fresh"][content="test"]`,
);
// Still renders page
assertSelector(doc, "body > .inner-body > .page");
},
);
});
Deno.test("don't duplicate <title>", async () => {
await withFresh(
"./tests/fixture_explicit_app/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/title`);
assertTextMany(doc, "title", ["foo bar"]);
},
);
});
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.5",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.3.1"
},
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1"
},
"compilerOptions": {
"jsx": "react-jsx",
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1"
},
"compilerOptions": {
"jsx": "react-jsx",
+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");
+21
View File
@@ -0,0 +1,21 @@
// 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/_app.tsx";
import * as $1 from "./routes/head.tsx";
import * as $2 from "./routes/index.tsx";
import * as $3 from "./routes/title.tsx";
const manifest = {
routes: {
"./routes/_app.tsx": $0,
"./routes/head.tsx": $1,
"./routes/index.tsx": $2,
"./routes/title.tsx": $3,
},
islands: {},
baseUrl: import.meta.url,
};
export default manifest;
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
@@ -0,0 +1,25 @@
import { AppProps, Handler } from "$fresh/server.ts";
export const handler: Handler = (_req, ctx) => {
ctx.state.lang = "de";
return ctx.render();
};
export default function App(
{ Component, state }: AppProps<unknown, { lang: string }>,
) {
return (
<html lang={state.lang}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>fresh title</title>
</head>
<body>
<div class="inner-body">
<Component />
</div>
</body>
</html>
);
}
@@ -0,0 +1,12 @@
import { Head } from "$fresh/runtime.ts";
export default function Home() {
return (
<div class="page">
<Head>
<meta name="fresh" content="test" />
</Head>
/head
</div>
);
}
@@ -0,0 +1,7 @@
export default function Home() {
return (
<div class="page">
Home
</div>
);
}
@@ -0,0 +1,12 @@
import { Head } from "$fresh/runtime.ts";
export default function Home() {
return (
<div class="page">
<Head>
<title>foo bar</title>
</Head>
/title
</div>
);
}
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1"
},
"compilerOptions": {
"jsx": "react-jsx",
+1 -1
View File
@@ -7,7 +7,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.16.0",
"preact/": "https://esm.sh/preact@10.16.0/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
},
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
},
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1"
},
"compilerOptions": {
"jsx": "react-jsx",
+1 -1
View File
@@ -4,7 +4,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0"
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1"
},
"compilerOptions": {
"jsx": "react-jsx",
+1 -1
View File
@@ -7,7 +7,7 @@
"$fresh/": "../../",
"preact": "https://esm.sh/preact@10.11.0",
"preact/": "https://esm.sh/preact@10.11.0/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.0.3",
"@preact/signals-core": "https://esm.sh/*@preact/signals-core@1.0.1"
},
+29
View File
@@ -1,4 +1,5 @@
import {
basename,
dirname,
existsSync,
extname,
@@ -230,6 +231,34 @@ await start(manifest, { plugins: [twindPlugin(twindConfig)] });\n`;
}
}
// Add default _app.tsx if not present
const routes = Array.from(Deno.readDirSync(join(srcDirectory, "routes")));
if (!routes.find((entry) => entry.isFile && entry.name.startsWith("_app."))) {
const APP_TSX = `import { AppProps } from "$fresh/server.ts";
export default function App({ Component }: AppProps) {
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${basename(resolvedDirectory)}</title>
</head>
<body>
<Component />
</body>
</html>
);
}`;
await Deno.writeTextFile(
join(srcDirectory, "routes", "_app.tsx"),
APP_TSX,
);
}
console.log(routes);
// await Deno.writeTextFile(MAIN_TS_PATH, MAIN_TS);
const manifest = await collect(srcDirectory);
await generate(srcDirectory, manifest);
+1 -1
View File
@@ -9,7 +9,7 @@
"twind/": "https://esm.sh/twind@0.16.19/",
"preact": "https://esm.sh/preact@10.15.1",
"preact/": "https://esm.sh/preact@10.15.1/",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.0",
"preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.2.1",
"@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
"@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3",
"$std/": "https://deno.land/std@0.193.0/",