Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions docs/latest/advanced/head.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ export default define.page((ctx) => {
For more complex scenarios, or to set page metadata from
[islands](/docs/concepts/islands), Fresh ships with the `<Head>`-component.

> [info]: The `<Head>` component is not dynamic by default. It will not
> automatically update the document title or other head elements on the client
> side when component state changes. The head elements are set during server
> rendering or initial page load.

```tsx routes/about.tsx
import { Head } from "fresh/runtime";

Expand All @@ -64,6 +59,29 @@ export default define.page((ctx) => {
});
```

### Dynamic head updates from islands

The `<Head>` component works in [islands](/docs/concepts/islands) too. When
component state changes, the document head is updated automatically:

```tsx islands/MetaUpdater.tsx
import { useState } from "preact/hooks";
import { Head } from "fresh/runtime";

export default function MetaUpdater() {
const [title, setTitle] = useState("Welcome");

return (
<div>
<Head>
<title>{title}</title>
</Head>
<button onClick={() => setTitle("Updated!")}>Change title</button>
</div>
);
}
```

### Avoiding duplicate tags

You might end up with duplicate tags, when multiple `<Head />` components are
Expand All @@ -75,13 +93,15 @@ the matching element:
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
5. Only for `<link>` elements: Check if there is a `<link>` element with the
same `rel` attribute
6. No matching element was found, Fresh will create a new one and append it to
`<head>`

When multiple `<Head>` components render an element with the same key, the
**last one rendered wins**. Since Fresh renders top-down (app wrapper layout
route page component), a route page can override defaults set in `_app.tsx` by
using the same `key` prop.
**last one rendered wins**. Since Fresh renders top-down (app wrapper -> layout
-> route -> page component), a route page can override defaults set in
`_app.tsx` by using the same `key` prop.

> [info]: The `<title>`-tag is automatically deduplicated, even without a `key`
> prop.
154 changes: 88 additions & 66 deletions packages/fresh/src/runtime/client/preact_hooks_client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Fragment, h, options as preactOptions } from "preact";
import { Fragment, h, options as preactOptions, type VNode } from "preact";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
Expand All @@ -7,87 +7,109 @@ import {
} from "../shared_internal.ts";
import { BUILD_ID } from "@fresh/build-id";
import { renderToString } from "preact-render-to-string";
import { useEffect } from "preact/hooks";
import { useContext, useEffect } from "preact/hooks";
import { HeadContext } from "../head.ts";

// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;

function WrappedHead(
// deno-lint-ignore no-explicit-any
{ originalType, props, key }: { originalType: string; props: any; key: any },
) {
const enabled = useContext(HeadContext);

useEffect(() => {
if (!enabled) return;

const text = renderToString(h(Fragment, null, props.children));

if (originalType === "title") {
document.title = text;
return;
}

let matched: HTMLElement | null = null;
if (key) {
matched = document.head.querySelector(
`head [data-key="${key}"]`,
) as HTMLElement ?? null;
}

if (matched === null && props.id) {
matched = document.head.querySelector(
`#${props.id}`,
) as HTMLElement ??
null;
}

if (matched === null) {
if (originalType === "meta") {
matched = document.head.querySelector(
`head [name="${props.name}"]`,
) as HTMLElement ?? null;
} else if (originalType === "link" && props.rel) {
matched = document.head.querySelector(
`head link[rel="${props.rel}"]`,
) 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);
}, [originalType, props, key]);

if (enabled) {
return null;
}

return h(originalType, { ...props, _freshPatched: true });
}

const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);

if (typeof vnode.type === "string") {
const originalType = vnode.type;
if (typeof originalType === "string") {
if (CLIENT_NAV_ATTR in vnode.props) {
const value = vnode.props[CLIENT_NAV_ATTR];
if (typeof value === "boolean") {
vnode.props[CLIENT_NAV_ATTR] = String(value);
}
}
}

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-constant-condition
if (false) {
// deno-lint-ignore no-explicit-any
} else if (!(vnode.props as any)._freshPatched) {
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 as string);
}

if (matched.textContent !== text) {
matched.textContent = text;
}

applyProps(props, matched);
}, []);

return null;
const v = vnode as VNode<any>;
const props = vnode.props;
const key = vnode.key;
v.type = WrappedHead;
v.props = {
originalType,
props,
key,
};
break;
}
break;
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions packages/fresh/src/runtime/server/preact_hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,8 @@ options[OptionsType.DIFF] = (vnode) => {
continue;
} else if (originalType === "meta" && key === "content") {
continue;
} else if (originalType === "link" && key === "href") {
continue;
}

cacheKey += `::${props[key]}`;
Expand Down
22 changes: 22 additions & 0 deletions packages/fresh/tests/fixture_head/islands/DynamicMetaIsland.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";

export function DynamicMetaIsland() {
const [count, setCount] = useState(0);
const [ready, setReady] = useState(false);

useEffect(() => {
setReady(true);
}, []);

return (
<div class={ready ? "ready" : ""}>
<Head>
<meta name="foo" content={`value-${count}`} />
</Head>
<button type="button" onClick={() => setCount((v) => v + 1)}>
update
</button>
</div>
);
}
18 changes: 18 additions & 0 deletions packages/fresh/tests/fixture_head/islands/LinkIsland.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";

export function LinkIsland() {
const [ready, setReady] = useState(false);

useEffect(() => {
setReady(true);
}, []);

return (
<div class={ready ? "ready" : ""}>
<Head>
<link rel="canonical" href="https://example.com/ok" />
</Head>
</div>
);
}
19 changes: 19 additions & 0 deletions packages/fresh/tests/fixture_head/islands/MultiHeadA.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";

export function MultiHeadA() {
const [ready, setReady] = useState(false);

useEffect(() => {
setReady(true);
}, []);

return (
<div class={ready ? "ready-a" : ""}>
<Head>
<title>from island A</title>
<meta name="author" content="island-a" />
</Head>
</div>
);
}
18 changes: 18 additions & 0 deletions packages/fresh/tests/fixture_head/islands/MultiHeadB.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect, useState } from "preact/hooks";
import { Head } from "fresh/runtime";

export function MultiHeadB() {
const [ready, setReady] = useState(false);

useEffect(() => {
setReady(true);
}, []);

return (
<div class={ready ? "ready-b" : ""}>
<Head>
<meta name="description" content="from-island-b" />
</Head>
</div>
);
}
1 change: 1 addition & 0 deletions packages/fresh/tests/fixture_head/routes/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default function Page({ Component }: PageProps) {
<title>not ok</title>
<meta name="foo" content="not ok" />
<meta name="bar" content="not ok" />
<link rel="canonical" href="https://example.com/not-ok" />
<style>not ok</style>
<style id="style-id">not ok</style>
<template key="a">not ok</template>
Expand Down
5 changes: 5 additions & 0 deletions packages/fresh/tests/fixture_head/routes/dynamic_meta.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { DynamicMetaIsland } from "../islands/DynamicMetaIsland.tsx";

export default function Page() {
return <DynamicMetaIsland />;
}
5 changes: 5 additions & 0 deletions packages/fresh/tests/fixture_head/routes/link.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { LinkIsland } from "../islands/LinkIsland.tsx";

export default function Page() {
return <LinkIsland />;
}
11 changes: 11 additions & 0 deletions packages/fresh/tests/fixture_head/routes/multi.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { MultiHeadA } from "../islands/MultiHeadA.tsx";
import { MultiHeadB } from "../islands/MultiHeadB.tsx";

export default function Page() {
return (
<>
<MultiHeadA />
<MultiHeadB />
</>
);
}
Loading
Loading