feat: bring back <Head> component (#3249)

This PR brings back the `<Head>` component from Fresh 1.x . The
implementation is much cleaner than back then and also works client-side
now too.
This commit is contained in:
Marvin Hagemeister
2025-08-25 15:40:47 +02:00
committed by GitHub
parent bf25d10a84
commit 1daca75489
27 changed files with 916 additions and 326 deletions
+47 -8
View File
@@ -7,6 +7,7 @@ import {
isValidElement,
type VNode,
} from "preact";
import { jsxTemplate } from "preact/jsx-runtime";
import { SpanStatusCode } from "@opentelemetry/api";
import type { ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
@@ -215,19 +216,23 @@ export class Context<State> {
vnode = result;
}
let appChild = vnode;
// deno-lint-ignore no-explicit-any
let appVNode: VNode<any>;
let hasApp = true;
if (isAsyncAnyComponent(appDef)) {
const child = vnode;
props.Component = () => child;
props.Component = () => appChild;
const result = await renderAsyncAnyComponent(appDef, props);
if (result instanceof Response) {
return result;
}
vnode = result;
appVNode = result;
} else if (appDef !== null) {
const child = vnode;
vnode = h(appDef, {
Component: () => child,
appVNode = h(appDef, {
Component: () => appChild,
config: this.config,
data: null,
error: this.error,
@@ -238,6 +243,9 @@ export class Context<State> {
state: this.state,
url: this.url,
});
} else {
hasApp = false;
appVNode = appChild ?? h(Fragment, null);
}
const headers = init.headers !== undefined
@@ -270,12 +278,22 @@ export class Context<State> {
try {
setRenderState(state);
return preactRender(
const inner = preactRender(
vnode ?? h(Fragment, null),
this,
state,
headers,
!hasApp,
);
if (!hasApp) {
return inner;
}
appChild = jsxTemplate([inner]);
const outer = preactRender(appVNode, this, state, true);
return outer;
} catch (err) {
if (err instanceof Error) {
span.recordException(err);
@@ -287,6 +305,27 @@ export class Context<State> {
}
throw err;
} finally {
// Add preload headers
const basePath = this.config.basePath;
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
? state.buildCache.clientEntry.slice(1)
: state.buildCache.clientEntry;
let link = `<${
encodeURI(`${basePath}${runtimeUrl}`)
}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
const specifier = `${basePath}${
island.file.startsWith(".") ? island.file.slice(1) : island.file
}`;
link += `, <${
encodeURI(specifier)
}>; rel="modulepreload"; as="script"`;
});
if (link !== "") {
headers.append("Link", link);
}
state.clear();
setRenderState(null);
+16 -1
View File
@@ -24,7 +24,22 @@ export async function checkDenoCompilerOptions(root: string) {
// Check precompile option
if (denoJson.config.compilerOptions?.jsx === "precompile") {
const expected = ["a", "img", "source", "body", "html", "head"];
const expected = [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template",
];
const skipped = denoJson.config.compilerOptions.jsxPrecompileSkipElements;
if (!skipped || expected.some((name) => !skipped.includes(name))) {
throw new Error(
+31 -53
View File
@@ -8,7 +8,6 @@ import {
import {
FreshScripts,
type RenderState,
setRenderState,
} from "./runtime/server/preact_hooks.tsx";
import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
@@ -61,61 +60,40 @@ export function preactRender<State, Data>(
vnode: VNode,
ctx: PageProps<Data, State>,
state: RenderState,
headers: Headers,
renderFallback: boolean,
) {
try {
let res = renderToString(vnode);
// We require a the full outer DOM structure so that browser put
// comment markers in the right place in the DOM.
if (!state.renderedHtmlBody) {
let scripts = "";
if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) {
scripts = renderToString(h(FreshScripts, null));
}
res = `<body>${res}${scripts}</body>`;
let res = renderToString(vnode);
if (!renderFallback) return res;
// We require a the full outer DOM structure so that browser put
// comment markers in the right place in the DOM.
if (!state.renderedHtmlBody) {
let scripts = "";
if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) {
scripts = renderToString(h(FreshScripts, null));
}
if (!state.renderedHtmlHead) {
let head = `<head><meta charset="utf-8">`;
const entryAssets = state.buildCache.getEntryAssets();
for (let i = 0; i < entryAssets.length; i++) {
const asset = entryAssets[i];
if (asset.endsWith(".css")) {
head += `<link rel="stylesheet" href="${escapeHtml(asset)}">`;
}
}
res = `${head}</head>${res}`;
}
if (!state.renderedHtmlTag) {
res = `<html>${res}</html>`;
}
return `<!DOCTYPE html>${res}`;
} finally {
// Add preload headers
const basePath = ctx.config.basePath;
const runtimeUrl = state.buildCache.clientEntry.startsWith(".")
? state.buildCache.clientEntry.slice(1)
: state.buildCache.clientEntry;
let link = `<${
encodeURI(`${basePath}${runtimeUrl}`)
}>; rel="modulepreload"; as="script"`;
state.islands.forEach((island) => {
const specifier = `${basePath}${
island.file.startsWith(".") ? island.file.slice(1) : island.file
}`;
link += `, <${encodeURI(specifier)}>; rel="modulepreload"; as="script"`;
});
if (link !== "") {
headers.append("Link", link);
}
state.clear();
setRenderState(null);
res = `<body>${res}${scripts}</body>`;
}
if (!state.renderedHtmlHead) {
let head = `<head><meta charset="utf-8">`;
const entryAssets = state.buildCache.getEntryAssets();
for (let i = 0; i < entryAssets.length; i++) {
const asset = entryAssets[i];
if (asset.endsWith(".css")) {
head += `<link rel="stylesheet" href="${escapeHtml(asset)}">`;
}
}
res = `${head}</head>${res}`;
}
if (!state.renderedHtmlTag) {
res = `<html>${res}</html>`;
}
return `<!DOCTYPE html>${res}`;
}
export type PageProps<Data = unknown, T = unknown> =
@@ -1,6 +1,16 @@
import { options } from "preact";
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
import { Fragment, h, options as preactOptions } from "preact";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
type InternalPreactOptions,
OptionsType,
} from "../shared_internal.tsx";
import { BUILD_ID } from "@fresh/build-id";
import { renderToString } from "preact-render-to-string";
import { useEffect } from "preact/hooks";
// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
@@ -15,5 +25,92 @@ options.vnode = (vnode) => {
}
}
const originalType = vnode.type;
if (typeof originalType === "string") {
switch (originalType) {
case "title":
case "meta":
case "link":
case "script":
case "style":
case "base":
case "noscript":
case "template":
// deno-lint-ignore no-explicit-any
vnode.type = (props: any) => {
useEffect(() => {
const text = renderToString(h(Fragment, null, props.children));
if (originalType === "title") {
document.title = text;
return;
}
let matched: HTMLElement | null = null;
if (vnode.key) {
matched = document.head.querySelector(
`head [data-key="${vnode.key}"]`,
) as HTMLElement ?? null;
}
if (matched === null && props.id) {
matched = document.head.querySelector(
`#${props.name}`,
) as HTMLElement ??
null;
}
if (matched === null) {
if (originalType === "meta") {
matched = document.head.querySelector(
`head [name="${props.name}"]`,
) as HTMLElement ?? null;
} else if (originalType === "base") {
matched = document.head.querySelector(originalType) ?? null;
}
}
if (matched === null) {
matched = document.createElement(originalType);
}
if (matched.textContent !== text) {
matched.textContent = text;
}
applyProps(props, matched);
}, []);
return null;
};
break;
}
}
oldVNodeHook?.(vnode);
};
const oldDiff = options[OptionsType.DIFF];
options[OptionsType.DIFF] = (vnode) => {
oldDiff?.(vnode);
};
// deno-lint-ignore no-explicit-any
function applyProps(props: Record<string, any>, el: HTMLElement) {
const keys = Object.keys(props);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = props[key];
if (key === "children") {
continue;
}
if (value === null || value === undefined || value === false) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import { type ComponentChildren, createContext } from "preact";
export const HeadContext = createContext(false);
export interface HeadProps {
children?: ComponentChildren;
}
export function Head(props: HeadProps): ComponentChildren {
return <HeadContext value>{props.children}</HeadContext>;
}
@@ -19,6 +19,7 @@ import {
assetHashingHook,
CLIENT_NAV_ATTR,
DATA_FRESH_KEY,
OptionsType,
PartialMode,
setActiveUrl,
} from "../shared_internal.tsx";
@@ -32,16 +33,8 @@ import { escape as escapeHtml } from "@std/html";
import { HttpError } from "../../error.ts";
import { getCodeFrame } from "../../dev/middlewares/error_overlay/code_frame.tsx";
import { escapeScript } from "../../utils.ts";
const enum OptionsType {
ATTR = "attr",
VNODE = "vnode",
HOOK = "__h",
DIFF = "__b",
RENDER = "__r",
DIFFED = "diffed",
ERROR = "__e",
}
import { HeadContext } from "../head.tsx";
import { useContext } from "preact/hooks";
interface InternalPreactOptions extends PreactOptions {
[OptionsType.ATTR](name: string, value: unknown): string | void;
@@ -80,6 +73,8 @@ export class RenderState {
owners = new Map<VNode, VNode>();
ownerStack: InternalVNode[] = [];
headComponents = new Map<string, VNode>();
// TODO: merge into bitmask field
renderedHtmlTag = false;
renderedHtmlBody = false;
@@ -286,11 +281,94 @@ options[OptionsType.DIFF] = (vnode) => {
}
}
// Append component to render remaining head nodes
const remaining = h(RemainingHead, null);
if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(remaining);
} else if (
vnode.props.children !== null &&
typeof vnode.props.children === "object"
) {
vnode.props.children = [vnode.props.children, remaining];
} else {
vnode.props.children = remaining;
}
break;
}
case "body":
RENDER_STATE!.renderedHtmlBody = true;
break;
case "title":
case "meta":
case "link":
case "script":
case "style":
case "base":
case "noscript":
case "template":
{
if (PATCHED.has(vnode)) {
break;
}
const originalType = vnode.type;
let cacheKey: string | null = vnode.key ??
(originalType === "title" ? "title" : null);
if (cacheKey === null) {
// deno-lint-ignore no-explicit-any
const props = vnode.props as any;
const keys = Object.keys(vnode.props);
keys.sort();
cacheKey = `${originalType}`;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === "children" || key === "nonce" || key === "ref") {
continue;
} else if (key === "dangerouslySetInnerHTML") {
cacheKey += String(props[key].__html);
continue;
} else if (originalType === "meta" && key === "content") {
continue;
}
cacheKey += `::${props[key]}`;
}
}
const originalKey = vnode.key;
// deno-lint-ignore no-explicit-any
(vnode as any).type = (props: any) => {
const value = useContext(HeadContext);
if (originalKey) {
props["data-key"] = originalKey;
}
const vnode = h(originalType, props);
PATCHED.add(vnode);
if (RENDER_STATE !== null) {
if (value) {
RENDER_STATE.headComponents.set(cacheKey, vnode);
return null;
} else if (value !== undefined) {
const cached = RENDER_STATE.headComponents.get(cacheKey);
if (cached !== undefined) {
RENDER_STATE.headComponents.delete(cacheKey);
return cached;
}
}
}
return vnode;
};
}
break;
}
if (
@@ -333,6 +411,13 @@ options[OptionsType.DIFFED] = (vnode) => {
oldDiffed?.(vnode);
};
function RemainingHead() {
if (RENDER_STATE !== null && RENDER_STATE.headComponents.size > 0) {
return h(Fragment, null, ...RENDER_STATE.headComponents.values());
}
return null;
}
interface SlotProps {
name: string;
id: number;
+2
View File
@@ -52,3 +52,5 @@ export function Partial(props: PartialProps): VNode {
return props.children as any;
}
Partial.displayName = "Partial";
export { Head, type HeadProps } from "./head.tsx";
+30 -1
View File
@@ -1,4 +1,4 @@
import type { VNode } from "preact";
import type { Component, Options as PreactOptions, VNode } from "preact";
import { ASSET_CACHE_BUST_KEY } from "../constants.ts";
export const DATA_CURRENT = "data-current";
@@ -6,6 +6,35 @@ export const DATA_ANCESTOR = "data-ancestor";
export const DATA_FRESH_KEY = "data-frsh-key";
export const CLIENT_NAV_ATTR = "f-client-nav";
export const enum OptionsType {
ATTR = "attr",
VNODE = "vnode",
HOOK = "__h",
DIFF = "__b",
RENDER = "__r",
DIFFED = "diffed",
ERROR = "__e",
}
export interface InternalVNode extends VNode {
__c: Component | null;
__: InternalVNode | null;
}
export interface InternalPreactOptions extends PreactOptions {
[OptionsType.ATTR](name: string, value: unknown): string | void;
[OptionsType.VNODE](vnode: InternalVNode): void;
[OptionsType.HOOK](component: Component, index: number, type: number): void;
[OptionsType.DIFF](vnode: InternalVNode): void;
[OptionsType.RENDER](vnode: InternalVNode): void;
[OptionsType.DIFFED](vnode: InternalVNode): void;
[OptionsType.ERROR](
error: unknown,
vnode: InternalVNode,
oldVNode: InternalVNode,
): void;
}
export const enum UrlMatchKind {
None,
Ancestor,
+16 -1
View File
@@ -33,7 +33,22 @@ Deno.test("Docs Code example checks", async () => {
lib: ["dom", "dom.asynciterable", "deno.ns", "deno.unstable"],
jsx: "precompile",
jsxImportSource: "preact",
jsxPrecompileSkipElements: ["a", "img", "source", "body", "html", "head"],
jsxPrecompileSkipElements: [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template",
],
},
};
await Deno.writeTextFile(
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function MetaIsland() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<meta name="foo" content="ok" />
</Head>
</div>
);
}
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function StyleIdIsland() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<style id="style-id">ok</style>
</Head>
</div>
);
}
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function TemplateIsland() {
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<template key="a">ok</template>
</Head>
</div>
);
}
@@ -0,0 +1,22 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";
export function TitleIsland() {
const [s, set] = useState(0);
const [ready, setReady] = useState(false);
useEffect(() => {
setReady(true);
}, []);
return (
<div class={ready ? "ready" : ""}>
<Head>
<title>Count: {s}</title>
</Head>
<button type="button" onClick={() => set((v) => v + 1)}>
update {s}
</button>
</div>
);
}
@@ -0,0 +1,22 @@
import type { PageProps } from "@fresh/core";
export default function Page({ Component }: PageProps) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>not ok</title>
<meta name="foo" content="not ok" />
<meta name="bar" content="not ok" />
<style>not ok</style>
<style id="style-id">not ok</style>
<template key="a">not ok</template>
<template key="b">not ok</template>
<template>not ok</template>
</head>
<body>
<Component />
</body>
</html>
);
}
@@ -0,0 +1,5 @@
import { StyleIdIsland } from "../islands/StyleIdIsland.tsx";
export default function Page() {
return <StyleIdIsland />;
}
@@ -0,0 +1,5 @@
import { TemplateIsland } from "../islands/TemplateIsland.tsx";
export default function Page() {
return <TemplateIsland />;
}
@@ -0,0 +1,5 @@
import { MetaIsland } from "../islands/MetaIsland.tsx";
export default function Page() {
return <MetaIsland />;
}
@@ -0,0 +1,5 @@
import { TitleIsland } from "../islands/TitleIsland.tsx";
export default function Page() {
return <TitleIsland />;
}
@@ -5,6 +5,21 @@
"compilerOptions": {
"jsx": "precompile",
"jsxImportSource": "preact",
"jsxPrecompileSkipElements": ["a", "img", "source", "body", "html", "head"]
"jsxPrecompileSkipElements": [
"a",
"img",
"source",
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template"
]
}
}
+317
View File
@@ -0,0 +1,317 @@
import { App, staticFiles } from "fresh";
import { Head } from "fresh/runtime";
import {
buildProd,
parseHtml,
waitFor,
withBrowserApp,
} from "./test_utils.tsx";
import { expect } from "@std/expect";
import { FakeServer } from "../src/test_utils.ts";
import * as path from "@std/path";
Deno.test("Head - ssr - updates title", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>not ok</title>
</head>
<body>
<Component />
</body>
</html>
);
})
.get("/", (ctx) => {
return ctx.render(
<>
<h1>heading</h1>
<Head>
<title>ok</title>
</Head>
</>,
);
}).handler();
const server = new FakeServer(handler);
const res = await server.get("/");
const doc = parseHtml(await res.text());
expect(doc.querySelector("title")?.textContent).toEqual("ok");
expect(doc.querySelector("h1")?.textContent).toEqual("heading");
});
Deno.test("Head - ssr - updates meta", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ok</title>
<meta name="foo" content="not ok" />
</head>
<body>
<Component />
</body>
</html>
);
})
.get("/", (ctx) => {
return ctx.render(
<>
<h1>heading</h1>
<Head>
<meta name="foo" content="ok" />
</Head>
</>,
);
}).handler();
const server = new FakeServer(handler);
const res = await server.get("/");
const doc = parseHtml(await res.text());
const meta = doc.querySelector("meta[name='foo']") as HTMLMetaElement;
expect(meta.content).toEqual("ok");
});
Deno.test("Head - ssr - updates style", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ok</title>
<meta name="foo" content="not ok" />
</head>
<body>
<Component />
</body>
</html>
);
})
.get("/", (ctx) => {
return ctx.render(
<>
<h1>heading</h1>
<Head>
<style>ok</style>
</Head>
</>,
);
}).handler();
const server = new FakeServer(handler);
const res = await server.get("/");
const doc = parseHtml(await res.text());
const meta = doc.querySelector("style") as HTMLStyleElement;
expect(meta.textContent).toEqual("ok");
});
Deno.test("Head - ssr - merge keyed", async () => {
const handler = new App()
.appWrapper(({ Component }) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ok</title>
<style>not ok</style>
<style key="a">not ok</style>
</head>
<body>
<Component />
</body>
</html>
);
})
.get("/", (ctx) => {
return ctx.render(
<>
<h1>heading</h1>
<Head>
<style key="a">ok</style>
</Head>
</>,
);
}).handler();
const server = new FakeServer(handler);
const res = await server.get("/");
const doc = parseHtml(await res.text());
const last = doc.head.lastChild;
expect(last?.textContent).toEqual("ok");
});
Deno.test({
name: "Head - client - set title",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/title`);
await page.locator(".ready").wait();
await page.locator("button").click();
await waitFor(async () => {
const title = await page.evaluate(() => document.title);
return title === "Count: 1";
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - match meta",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/meta`);
await page.locator(".ready").wait();
await waitFor(async () => {
const metas = await page.evaluate(() => {
const metas = Array.from(
document.querySelectorAll("meta[name]"),
) as HTMLMetaElement[];
return metas.map((
el: HTMLMetaElement,
) => ({ name: el.name, content: el.content }));
});
try {
expect(metas).toEqual([
{ name: "foo", content: "ok" },
{ name: "bar", content: "not ok" },
]);
return true;
} catch {
return false;
}
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - match style by id",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/id`);
await page.locator(".ready").wait();
await waitFor(async () => {
const styles = await page.evaluate(() => {
const els = Array.from(
document.querySelectorAll("head style"),
) as HTMLStyleElement[];
return els.map((
el: HTMLStyleElement,
) => ({ id: el.id, text: el.textContent }));
});
try {
expect(styles).toEqual([
{ id: "", text: "not ok" },
{ id: "style-id", text: "ok" },
]);
return true;
} catch {
return false;
}
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "Head - client - match key",
fn: async () => {
const applyCache = await buildProd({
root: path.join(import.meta.dirname!, "fixture_head"),
});
const app = new App({})
.use(staticFiles())
.fsRoutes();
applyCache(app);
await withBrowserApp(app, async (page, address) => {
await page.goto(`${address}/key`);
await page.locator(".ready").wait();
await waitFor(async () => {
const tpls = await page.evaluate(() => {
const els = Array.from(
document.querySelectorAll("head template"),
) as HTMLTemplateElement[];
return els.map((
el: HTMLTemplateElement,
) => ({
key: el.getAttribute("data-key"),
text: el.content.textContent,
}));
});
try {
expect(tpls).toEqual([
{ key: "a", text: "ok" },
{ key: "b", text: "not ok" },
{ key: null, text: "not ok" },
]);
return true;
} catch {
return false;
}
});
});
},
sanitizeOps: false,
sanitizeResources: false,
});
+24 -5
View File
@@ -359,6 +359,12 @@ export const app = new App<State>();
app.use(staticFiles());
// Pass a shared value from a middleware
app.use(async (ctx) => {
ctx.state.shared = "hello";
return await ctx.next();
});
// this is the same as the /api/:name route defined via a file. feel free to delete this!
app.get("/api2/:name", (ctx) => {
const name = ctx.params.name;
@@ -400,25 +406,30 @@ export function Button(props: ButtonProps) {
const UTILS_TS = `import { createDefine } from "fresh";
// This specifies the type of "ctx.state" which is used to share
// data among middlewares, layouts and routes.
export interface State {
title: string;
shared: string;
}
export const define = createDefine<State>();`;
await writeFile("utils.ts", UTILS_TS);
const ROUTES_HOME = `import { useSignal } from "@preact/signals";
import { Head } from "fresh/runtime";
import { define } from "../utils.ts";
import Counter from "../islands/Counter.tsx";
export default define.page(function Home(ctx) {
const count = useSignal(3);
ctx.state.title = count.value + " Fresh Counter" +
(Math.abs(count.value) === 1 ? "" : "s");
console.log("Shared value " + ctx.state.shared);
return (
<div class="px-4 py-8 mx-auto fresh-gradient min-h-screen">
<Head>
<title>Fresh counter: {count}</title>
</Head>
<div class="max-w-screen-md mx-auto flex flex-col items-center justify-center">
<img
class="my-6"
@@ -441,13 +452,13 @@ export default define.page(function Home(ctx) {
const APP_WRAPPER = `import { define } from "../utils.ts";
export default define.page(function App({ Component, state }) {
export default define.page(function App({ Component }) {
return (
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{state.title ?? "${path.basename(projectDir)}"}</title>
<title>${path.basename(projectDir)}</title>
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
@@ -532,6 +543,14 @@ if (Deno.args.includes("build")) {
"body",
"html",
"head",
"title",
"meta",
"script",
"link",
"style",
"base",
"noscript",
"template",
],
},
};