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:
@@ -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);
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user