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
+16 -1
View File
@@ -87,7 +87,22 @@
"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"
]
},
"lint": {
"rules": {
+76
View File
@@ -0,0 +1,76 @@
---
description: Modify the document head in Fresh
---
The
[`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/head)-element
is a crucial element in HTML to set metadata for a page. It allows you to:
- Set the document title with `<title>`
- Specify page metadata with `<meta>`
- Link to resources like stylesheets with `<link>`
- Include JavaScript code with `<script>`
> [info]: The outer HTML structure including `<head>` is typically created
> inside `_app.tsx`.
## Passing metadata from `ctx.state`
For simple scenarios passing metadata along from a handler or a middleware by
writing to `ctx.state` is often sufficient.
```tsx routes/_app.tsx
import { define } from "../util.ts";
export default define.page((ctx) => {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>{ctx.state.title ?? "Welcome!"}</title>
</head>
<body>
<ctx.Component />
</body>
</html>
);
});
```
## Using the `<Head>`-component
For more complex scenarios, or to set page metadata from islands, Fresh ships
with the `<Head>`-component.
```tsx routes/about.tsx
import { Head } from "fresh/runtime";
export default define.page((ctx) => {
return (
<div>
<Head>
<title>About me</title>
</Head>
<h1>About me</h1>
<p>I like Fresh!</p>
</div>
);
});
```
### Avoiding duplicate tags
You might end up with duplicate tags, when multiple `<Head />` components are
rendered on the same page. Fresh will employ the following strategies to find
the matching element:
1. For `<title>` elements Fresh will set `document.title` directly
2. Check if an element with the same `key` exists
3. Check if an element with the same `id` attribute
4. Only for `<meta>` elements: Check if there is a `<meta>` element with the
same `name` attribute
5. No matching element was found, Fresh will create a new one and append it to
`<head>`
> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
> prop.
-47
View File
@@ -147,53 +147,6 @@ accordingly.
}
```
## Removal of `<Head>` component
The `<Head>` component was used in Fresh 1.x to add additional tags to the
`<head>` portion of an HTML document from anywhere on the page. This feature was
removed in preparation and due to performance concerns as it required a complex
machinery in the background to work.
Instead, passing head-related data is best done via `ctx.state`, which can be
easily set through the [define helper](/docs/canary/advanced/define).
```tsx
// utils.ts
export interface State {
title?: string;
}
export const define = createDefine<State>();
// routes/about.tsx
import { define } from "../utils.ts";
export default define.page(function AboutPage(ctx) {
// Set a route specific data in a handler
ctx.state.title = "About Me";
return (
<div>
<h1>About Me</h1>
</div>
);
});
// Render that in _app.tsx
export default define.page(function App({ Component, state }) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{state.title ? <title>{state.title}</title> : null}
</head>
<body>
<Component />
</body>
</html>
);
});
```
## Update deployment settings
Fresh 2 requires assets to be build during deployment instead of building them
-195
View File
@@ -1,195 +0,0 @@
---
description: |
Modify <head> content by passing state between AppWrapper/Layout and routes.
---
It's a common requirement for specific pages to need changes to content inside
the `<head>` tag.
- Setting the document title using `<title>`
- Specifying page metadata using `<meta>`
- Linking to resources like stylesheets using `<link>`
- Including third-party JavaScript code using `<script>`
## App Wrapper with State
The recommended way to modify content in `<head>` is to use an app wrapper in
combination with `Context.state`.
### 1. State
The first step can be to define the possible state available on `Context`. In
this example, the `State` is very general to allow very flexible usage.
```ts util.ts
import { createDefine } from "fresh";
import type { JSX } from "preact";
export interface State {
title?: string;
metas?: JSX.IntrinsicElements["meta"][];
links?: JSX.IntrinsicElements["link"][];
scripts?: JSX.IntrinsicElements["script"][];
}
export const define = createDefine<State>();
```
### 2. App wrapper
After defining the State, create the App Wrapper to render the HTML with the
provided State.
```tsx routes/_app.tsx
import { define } from "../util.ts";
export default define.page(function AppWrapper(ctx) {
const { title, links, metas, scripts } = ctx.state;
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title ? `${title} | My App` : "My App"}</title>
{metas?.map((attrs, i) => <meta key={i} {...attrs} />)}
{links?.map((attrs, i) => <link key={i} {...attrs} />)}
{scripts?.map((attrs, i) => <script key={i} {...attrs} />)}
</head>
<body>
<ctx.Component />
</body>
</html>
);
});
```
### 3. Route data
Then it's up to each route to update the State with `<head>` data you want to
add for that route. For this to work correctly, the State must be set in a route
handler. Inside the route Component is too late, as it runs after the App
Wrapper.
```tsx routes/index.tsx
import { page } from "fresh";
import { asset } from "fresh/runtime";
import { define } from "../util.ts";
const hero = asset("/hero.webp");
export const handler = define.handlers(({ state: s }) => {
s.title = "Home";
s.metas = [{ name: "description", content: "Welcome to the homepage!" }];
s.links = [
{ rel: "stylesheet", href: asset("/home.css"), type: "text/css" },
{ rel: "preload", href: hero, as: "image", type: "image/webp" },
];
s.scripts = [{ src: "https://example.com/script.js" }];
return page();
});
export default define.page(function Home() {
return <img class="hero" src={hero} alt="Hero Image" />;
});
```
If it's very common to add e.g. `title`/`description` to many pages, it can help
a lot to [create State helpers](#state-helper-utility). This can reduce
boilerplate for creating handlers that set metadata on `ctx.state`.
## Using Multiple Layouts
Layouts can be used to use shared `<head>` content for groups of pages. The base
HTML layout can be used as a shared component.
```tsx components/AppWrapper.tsx
import type { RenderableProps } from "preact";
import type { State } from "../util.ts";
export function AppWrapper(props: RenderableProps<State>) {
const { title, styles, children } = props;
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{title ? `${title} | My App` : "My App"}</title>
{styles?.map((url, i) => <link key={i} rel="stylesheet" href={url} />)}
</head>
<body>{children}</body>
</html>
);
}
```
The component above can then be used by multiple layouts that needs to share the
same `<head>` content.
```tsx routes/docs/_layout.tsx
import { asset } from "fresh/runtime";
import { define } from "../util.ts";
import { AppWrapper } from "../component/AppWrapper.tsx";
export default define.page(function DocsLayout() {
return (
<AppWrapper title="Docs" styles={[asset("/docs.css")]}>
<h1>Welcome to Docs!</h1>
</AppWrapper>
);
});
```
```tsx routes/blog/_layout.tsx
import { asset } from "fresh/runtime";
import { define } from "../util.ts";
import { AppWrapper } from "../component/AppWrapper.tsx";
export default define.page(function BlogLayout() {
return (
<AppWrapper title="Blog" styles={[asset("/blog.css")]}>
<h1>My blog</h1>
</AppWrapper>
);
});
```
## State helper utility
There's many ways to use abstractions or structure your code when using Fresh.
If many pages needs to set metadata, but otherwise does not require a handler,
it can be handy to create a utility for this.
```ts util.ts
export interface State {
title?: string;
description?: string;
}
export const define = createDefine<State>();
export const pageMetadataHandler = (title: string, description?: string) =>
define.handlers((ctx) => {
ctx.state.title = title;
ctx.state.description = description;
});
```
This helper can reduce boilerplate when creating many routes where each route
needs unique metadata.
```tsx routes/blog.tsx
import { pageMetadataHandler } from "../utils.ts";
export const handlers = pageMetadataHandler("Blog", "Read about ...");
```
```tsx routes/about.tsx
import { pageMetadataHandler } from "../utils.ts";
export const handlers = pageMetadataHandler("About", "Our company ...");
```
+1 -1
View File
@@ -54,6 +54,7 @@ const toc: RawTableOfContents = {
["forms", "Forms", "link:canary"],
["define", "Define Helpers", "link:canary"],
["environment-variables", "Environment Variables", "link:canary"],
["head", "Modifying <head>", "link:canary"],
],
},
deployment: {
@@ -85,7 +86,6 @@ const toc: RawTableOfContents = {
pages: [
["migration-guide", "Migration Guide", "link:canary"],
["daisyui", "daisyUI", "link:canary"],
["modifying-the-head", "Modifying the <head>", "link:canary"],
["creating-a-crud-api", "Creating a CRUD API", "link:latest"],
["markdown", "Rendering Markdown", "link:canary"],
["rendering-raw-html", "Rendering raw HTML", "link:canary"],
+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",
],
},
};
+1
View File
@@ -3,6 +3,7 @@ import type { Context } from "fresh";
const REDIRECTS: Record<string, string> = {
"/docs/getting-started/fetching-data":
"/docs/getting-started/custom-handlers",
"/docs/canary/examples/modifying-the-head": "/docs/canary/advanced/head",
};
export async function handler<T>(ctx: Context<T>) {