Add Partials (#1824)

This commit is contained in:
Marvin Hagemeister
2023-09-27 13:34:30 +02:00
committed by GitHub
parent d9829e25e6
commit 665d35bbc2
92 changed files with 3271 additions and 116 deletions
+10
View File
@@ -0,0 +1,10 @@
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
export const PARTIAL_ATTR = "fh-partial";
export const LOADING_ATTR = "fh-loading";
export const DATA_KEY_ATTR = "data-fresh-key";
export const enum PartialMode {
REPLACE,
APPEND,
PREPEND,
}
+20
View File
@@ -0,0 +1,20 @@
import { ComponentChildren, VNode } from "preact";
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
+450 -73
View File
@@ -1,4 +1,5 @@
import {
Component,
ComponentChildren,
ComponentType,
Fragment,
@@ -8,6 +9,15 @@ import {
VNode,
} from "preact";
import { assetHashingHook } from "../utils.ts";
import { type SerializedState } from "../../server/rendering/fresh_tags.tsx";
import type { Signal } from "@preact/signals";
import {
DATA_KEY_ATTR,
LOADING_ATTR,
PARTIAL_ATTR,
PARTIAL_SEARCH_PARAM,
PartialMode,
} from "../../constants.ts";
function createRootFragment(
parent: Element,
@@ -20,8 +30,10 @@ function createRootFragment(
) {
// @ts-ignore this is fine
return parent.__k = {
_frshRootFrag: true,
nodeType: 1,
parentNode: parent,
nextSibling: null,
get firstChild() {
const child = startMarker.nextSibling;
if (child === endMarker) return null;
@@ -61,14 +73,17 @@ function isTextNode(node: Node): node is Text {
return node.nodeType === Node.TEXT_NODE;
}
function isElementNode(node: Node): node is HTMLElement {
return node.nodeType === Node.ELEMENT_NODE;
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
}
type IslandRegistry = Record<string, Record<string, ComponentType>>;
export function revive(
islands: Record<string, Record<string, ComponentType>>,
islands: IslandRegistry,
// deno-lint-ignore no-explicit-any
props: any[],
) {
const result: RenderRequest[] = [];
_walkInner(
islands,
props,
@@ -78,11 +93,35 @@ export function revive(
// later during iteration
[h(Fragment, null)],
document.body,
result,
);
for (let i = 0; i < result.length; i++) {
const { vnode, marker, rootFragment } = result[i];
const _render = () => {
render(
vnode,
rootFragment,
);
if (marker.kind === MarkerKind.Partial) {
// deno-lint-ignore no-explicit-any
partials.set(marker.text, (vnode as any).__c);
}
};
"scheduler" in window
// `scheduler.postTask` is async but that can easily
// fire in the background. We don't want waiting for
// the hydration of an island block us.
// @ts-ignore scheduler API is not in types yet
? scheduler!.postTask(_render)
: setTimeout(_render, 0);
}
}
function ServerComponent(
props: { children: ComponentChildren },
props: { children: ComponentChildren; id: string },
): ComponentChildren {
return props.children;
}
@@ -101,25 +140,38 @@ function addPropsChild(parent: VNode, vnode: ComponentChildren) {
}
}
class PartialComp extends Component<
{ children?: ComponentChildren; mode: number; name: string }
> {
render() {
return this.props.children;
}
}
const enum MarkerKind {
Island,
Slot,
Partial,
}
interface Marker {
kind: MarkerKind;
// We can remove this once we drop support for RTS <6.1.0 where
// we rendered incorrect comments leading to `!--` and `--` being
// included in the comment text. Therefore this is a normalized
// string representing the actual intended comment value which makes
// a bunch of stuff easier.
text: string;
startNode: Text | Comment | null;
endNode: Text | Comment | null;
}
export interface RenderRequest {
vnode: VNode;
marker: Marker;
rootFragment: HTMLElement;
}
// Useful for debugging
const SHOW_MARKERS = false;
const partials = new Map<string, PartialComp>();
/**
* Replace comment markers with empty text nodes to hide them
* in DevTools. This is done to avoid user confusion.
@@ -161,6 +213,7 @@ function addChildrenFromTemplate(
markerStack: Marker[],
vnodeStack: VNode[],
comment: string,
result: RenderRequest[],
) {
const [id, exportName, n] = comment.slice("/frsh-".length).split(
":",
@@ -186,6 +239,7 @@ function addChildrenFromTemplate(
markerStack,
vnodeStack,
node,
result,
);
markerStack.pop();
@@ -227,6 +281,7 @@ function _walkInner(
markerStack: Marker[],
vnodeStack: VNode[],
node: Node | Comment,
result: RenderRequest[],
) {
let sib: Node | null = node;
while (sib !== null) {
@@ -251,7 +306,30 @@ function _walkInner(
kind: MarkerKind.Slot,
});
// @ts-ignore TS gets confused
vnodeStack.push(h(ServerComponent, { key: comment }));
vnodeStack.push(h(ServerComponent, { id: comment }));
} else if (comment.startsWith("frsh-partial")) {
// TODO: Partial key
const [_, name, mode, key] = comment.split(":");
markerStack.push({
startNode: sib,
text: name,
endNode: null,
kind: MarkerKind.Partial,
});
vnodeStack.push(
h(PartialComp, { name, key, mode: +mode }),
);
} else if (comment.startsWith("frsh-key")) {
const key = comment.slice("frsh-key:".length);
vnodeStack.push(h(Fragment, { key }));
} else if (comment.startsWith("/frsh-key")) {
const vnode = vnodeStack.pop();
const parent = vnodeStack[vnodeStack.length - 1]!;
addPropsChild(parent, vnode);
sib = sib.nextSibling;
continue;
} else if (
marker !== null && (
comment.startsWith("/frsh") ||
@@ -263,28 +341,28 @@ function _walkInner(
marker.endNode = sib;
markerStack.pop();
const parent = markerStack.length > 0
? markerStack[markerStack.length - 1]
: null;
if (marker.kind === MarkerKind.Slot) {
// If we're closing a slot than it's assumed that we're
// inside an island
if (parent?.kind === MarkerKind.Island) {
const vnode = vnodeStack.pop();
const vnode = vnodeStack.pop();
// For now only `props.children` is supported.
const islandParent = vnodeStack[vnodeStack.length - 1]!;
// Overwrite serialized `{__slot: "children"}` with the
// actual vnode child.
islandParent.props.children = vnode;
}
// For now only `props.children` is supported.
const islandParent = vnodeStack[vnodeStack.length - 1]!;
// Overwrite serialized `{__slot: "children"}` with the
// actual vnode child.
islandParent.props.children = vnode;
hideMarker(marker);
sib = marker.endNode.nextSibling;
continue;
} else if (marker.kind === MarkerKind.Island) {
// We're ready to revive this island if it has
} else if (
marker !== null && (
marker.kind === MarkerKind.Island ||
marker.kind === MarkerKind.Partial
)
) {
// We're ready to revive this island or partial if it has
// no roots of its own. Otherwise we'll treat it
// as a standard component
if (markerStack.length === 0) {
@@ -297,6 +375,7 @@ function _walkInner(
markerStack,
vnodeStack,
comment,
result,
);
}
vnodeStack.pop();
@@ -305,30 +384,23 @@ function _walkInner(
hideMarker(marker);
const _render = () =>
render(
vnode,
createRootFragment(
parentNode,
marker.startNode!,
marker.endNode!,
// deno-lint-ignore no-explicit-any
) as any as HTMLElement,
);
const rootFragment = createRootFragment(
parentNode,
marker.startNode!,
marker.endNode,
// deno-lint-ignore no-explicit-any
) as any as HTMLElement;
"scheduler" in window
// `scheduler.postTask` is async but that can easily
// fire in the background. We don't want waiting for
// the hydration of an island block us.
// @ts-ignore scheduler API is not in types yet
? scheduler!.postTask(_render)
: setTimeout(_render, 0);
result.push({
vnode,
marker,
rootFragment,
});
sib = marker.endNode.nextSibling;
continue;
} else if (parent?.kind === MarkerKind.Slot) {
// Treat the island as a standard component when it
// has an island parent or a slot parent
} else {
// Treat as a standard component
const vnode = vnodeStack[vnodeStack.length - 1];
if (vnode && vnode.props.children == null) {
addChildrenFromTemplate(
@@ -337,6 +409,7 @@ function _walkInner(
markerStack,
vnodeStack,
comment,
result,
);
// Didn't find any template tag, proceed as usual
@@ -352,13 +425,19 @@ function _walkInner(
const parent = vnodeStack[vnodeStack.length - 1]!;
addPropsChild(parent, vnode);
if (marker.kind === MarkerKind.Partial) {
// deno-lint-ignore no-explicit-any
partials.set(marker.text, (vnode as any).__c);
}
sib = marker.endNode.nextSibling;
continue;
}
}
} else if (comment.startsWith("frsh")) {
// We're opening a new island
const [id, exportName, n] = comment.slice(5).split(":");
const [id, exportName, n, key] = comment.slice(5).split(":");
const islandProps = props[Number(n)];
markerStack.push({
@@ -367,67 +446,260 @@ function _walkInner(
text: comment,
kind: MarkerKind.Island,
});
const vnode = h(islands[id][exportName], islandProps);
if (key) vnode.key = key;
vnodeStack.push(vnode);
}
} else if (isTextNode(sib)) {
const parentVNode = vnodeStack[vnodeStack.length - 1]!;
if (
marker !== null && marker.kind === MarkerKind.Slot
marker !== null &&
(marker.kind === MarkerKind.Slot ||
marker.kind === MarkerKind.Partial)
) {
addPropsChild(parentVNode, sib.data);
}
} else {
const parentVNode = vnodeStack[vnodeStack.length - 1];
if (
marker !== null &&
marker.kind === MarkerKind.Slot && isElementNode(sib)
) {
// Parse the server rendered DOM into vnodes that we can
// attach to the virtual-dom tree. In the future, once
// Preact supports a way to skip over subtrees, this
// can be dropped.
const childLen = sib.childNodes.length;
const props: Record<string, unknown> = {
children: childLen <= 1 ? null : [],
};
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
props[attr.nodeName] =
if (isElementNode(sib)) {
if (
marker !== null &&
(marker.kind === MarkerKind.Slot ||
marker.kind === MarkerKind.Partial)
) {
// Parse the server rendered DOM into vnodes that we can
// attach to the virtual-dom tree. In the future, once
// Preact supports a way to skip over subtrees, this
// can be dropped.
const childLen = sib.childNodes.length;
const newProps: Record<string, unknown> = {
children: childLen <= 1 ? null : [],
};
let hasKey = false;
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
if (attr.nodeName === DATA_KEY_ATTR) {
hasKey = true;
newProps.key = attr.nodeValue;
continue;
} else if (attr.nodeName === LOADING_ATTR) {
console.log(attr.nodeName, attr.nodeValue);
const idx = attr.nodeValue;
const sig = props[Number(idx)][LOADING_ATTR].value;
// deno-lint-ignore no-explicit-any
(sib as any)._freshIndicator = sig;
}
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
newProps[attr.nodeName] =
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
}
// Remove internal fresh key
if (hasKey) sib.removeAttribute(DATA_KEY_ATTR);
const vnode = h(sib.localName, newProps);
addPropsChild(parentVNode, vnode);
vnodeStack.push(vnode);
} else {
// Outside of any partial or island
const idx = sib.getAttribute(LOADING_ATTR);
if (idx !== null) {
console.log(props);
const sig = props[Number(idx)][LOADING_ATTR].value;
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
(sib as any)._freshIndicator = sig;
}
}
const vnode = h(sib.localName, props);
addPropsChild(parentVNode, vnode);
vnodeStack.push(vnode);
}
// TODO: What about script tags?
if (
sib.firstChild && (sib.nodeName !== "SCRIPT")
) {
_walkInner(islands, props, markerStack, vnodeStack, sib.firstChild);
_walkInner(
islands,
props,
markerStack,
vnodeStack,
sib.firstChild,
result,
);
}
// Pop vnode if current marker is a slot or we are an island marker
// that was created inside another island
// Pop vnode if current marker is not the a top rendering
// component
if (
marker !== null &&
(marker.kind === MarkerKind.Slot ||
markerStack.length > 1 &&
markerStack[markerStack.length - 2].kind === MarkerKind.Island)
marker.kind !== MarkerKind.Island
) {
vnodeStack.pop();
}
}
if (sib !== null) {
sib = sib.nextSibling;
}
}
}
const partialErrorMessage = `Unable to process partial response.`;
async function fetchPartials(url: URL, init?: RequestInit) {
url.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
const res = await fetch(url, init);
await applyPartials(res);
}
/**
* Apply partials from a HTML response
*/
export async function applyPartials(res: Response): Promise<void> {
if (!res.ok) {
throw new Error(partialErrorMessage);
}
const contentType = res.headers.get("Content-Type");
if (contentType !== "text/html; charset=utf-8") {
throw new Error(partialErrorMessage);
}
const resText = await res.text();
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
const promises: Promise<void>[] = [];
// Preload all islands because they need to be available synchronously
// for rendering later
const islands: IslandRegistry = {};
const dataRaw = doc.getElementById("__FRSH_PARTIAL_DATA")!;
let data: {
islands: Record<string, string>;
signals: string | null;
deserializer: string | null;
} | null = null;
if (dataRaw !== null) {
data = JSON.parse(dataRaw.textContent!);
promises.push(
...Array.from(Object.entries(data!.islands)).map(async (entry) => {
islands[entry[0]] = await import(`${entry[1]}`);
}),
);
}
const stateDom = doc.getElementById("__FRSH_STATE")?.textContent;
let state: SerializedState = [[], []];
// Load all dependencies
let signal: (<T>(value: T) => Signal<T>) | undefined;
if (data !== null && data.signals !== null) {
promises.push(
import(data.signals).then((m) => {
signal = m.signal;
}),
);
}
let deserialize:
| ((str: string, signal?: <T>(value: T) => Signal<T>) => unknown)
| undefined;
if (stateDom && data && data.deserializer !== null) {
promises.push(
import(data.deserializer).then((mod) => deserialize = mod.deserialize),
);
}
await Promise.all(promises);
if (deserialize) {
state = deserialize(stateDom!, signal) as SerializedState;
}
// Collect all partials and build up the vnode tree
const encounteredPartials: RenderRequest[] = [];
let startNode = null;
let sib: ChildNode | null = doc.body.firstChild;
while (sib !== null) {
if (isCommentNode(sib)) {
const comment = sib.data;
if (comment.startsWith("frsh-partial")) {
startNode = sib;
} else if (comment.startsWith("/frsh-partial")) {
// Create a fake DOM node that spans the partial we discovered.
// We need to include the partial markers itself for _walkInner
// to register them.
const rootFrag = {
_frshRootFrag: true,
nodeType: 1,
nextSibling: null,
firstChild: startNode,
parentNode: doc.body,
get childNodes() {
const children: ChildNode[] = [startNode!];
let node = startNode!;
while ((node = node.nextSibling) !== null) {
children.push(node);
}
return children;
},
// deno-lint-ignore no-explicit-any
} as any as HTMLElement;
_walkInner(
islands,
state[0] ?? [],
[],
[h(Fragment, null)],
rootFrag,
encounteredPartials,
);
}
}
sib = sib.nextSibling;
}
// Update all encountered partials
for (let i = 0; i < encounteredPartials.length; i++) {
const { vnode, marker } = encounteredPartials[i];
const instance = partials.get(marker.text);
if (!instance) {
console.warn(`Partial "${marker.text}" not found. Skipping...`);
} else {
// deno-lint-ignore no-explicit-any
const mode = (vnode.props as any).mode;
const children = vnode.props.children;
// Modify children depending on the replace mode
if (mode === PartialMode.REPLACE) {
instance.props.children = children;
} else {
const oldChildren = instance.props.children;
const newChildren = Array.isArray(oldChildren)
? oldChildren
: [oldChildren];
if (mode === PartialMode.APPEND) {
newChildren.push(children);
} else {
newChildren.unshift(children);
}
instance.props.children = newChildren;
}
instance.setState({});
}
}
}
const originalHook = options.vnode;
@@ -435,3 +707,108 @@ options.vnode = (vnode) => {
assetHashingHook(vnode);
if (originalHook) originalHook(vnode);
};
// Keep track of history state to apply forward or backward animations
let index = history.state?.index || 0;
if (!history.state) {
history.replaceState({ index }, document.title);
}
document.addEventListener("click", async (e) => {
let el = e.target;
if (el && el instanceof HTMLElement) {
// Check if we clicked inside an anchor link
if (el.nodeName !== "A") {
el = el.closest("a");
}
if (
// Check that we're still dealing with an anchor tag
el && el instanceof HTMLAnchorElement &&
// Check if it's an internal link
el.href && (!el.target || el.target === "_self") &&
el.origin === location.origin &&
// Check if it was a left click and not a right click
e.button === 0 &&
// Check that the user doesn't press a key combo to open the
// link in a new tab or something
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
// Check that the event isn't aborted already
!e.defaultPrevented
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation.
// There are two cases to account for:
// 1. Partial request
// 2. Normal request (turbolink-style)
const settingEl = el.closest("[fresh-client-nav]");
if (
partial === null && (
settingEl === null ||
settingEl.getAttribute("fresh-client-nav") !== "true"
)
) {
return;
}
// deno-lint-ignore no-explicit-any
const indicator = (el as any)._freshIndicator;
if (indicator !== undefined) {
indicator.value = true;
}
e.preventDefault();
try {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (el.href !== window.location.href) {
index++;
history.pushState({ index }, "", el.href);
}
const partialUrl = new URL(
partial ? partial : el.href,
location.origin,
);
await fetchPartials(partialUrl);
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
}
}
});
// deno-lint-ignore no-window-prefix
window.addEventListener("popstate", async () => {
const nextIdx = history.state?.index ?? index + 1;
index = nextIdx;
// If we have the body partial, then we assume that we can
// do a full client-side navigation. Otherwise do a full
// page navigation.
if (partials.has("body")) {
const url = new URL(location.href, location.origin);
await fetchPartials(url);
} else {
window.location.href = location.href;
}
});
// Form submit
document.addEventListener("submit", async (e) => {
const el = e.target;
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
const partial = el.getAttribute(PARTIAL_ATTR);
if (partial !== null) {
e.preventDefault();
const url = new URL(partial, location.origin);
await fetchPartials(url);
}
}
});
+41 -9
View File
@@ -6,6 +6,8 @@ import { Plugin, PluginRenderResult, PluginRenderStyleTag } from "../types.ts";
import { ContentSecurityPolicy, nonce } from "../../runtime/csp.ts";
import { h } from "preact";
export type SerializedState = [islands: unknown[], plugins: unknown[]];
export function renderFreshTags(
renderState: RenderState,
opts: {
@@ -18,6 +20,8 @@ export function renderFreshTags(
pluginRenderResults: [Plugin, PluginRenderResult][];
},
) {
const { isPartial } = renderState;
if (opts.csp) {
opts.csp.directives.scriptSrc = [
...opts.csp.directives.scriptSrc ?? [],
@@ -33,15 +37,17 @@ export function renderFreshTags(
const preloadSet = new Set<string>();
function addImport(path: string): string {
const url = bundleAssetUrl(`/${path}`);
preloadSet.add(url);
for (const depPath of opts.dependenciesFn(path)) {
const url = bundleAssetUrl(`/${depPath}`);
if (!isPartial) {
preloadSet.add(url);
for (const depPath of opts.dependenciesFn(path)) {
const url = bundleAssetUrl(`/${depPath}`);
preloadSet.add(url);
}
}
return url;
}
const state: [islands: unknown[], plugins: unknown[]] = [
const state: SerializedState = [
renderState.islandProps,
[],
];
@@ -62,12 +68,17 @@ export function renderFreshTags(
// Serialize the state into the <script id=__FRSH_STATE> tag and generate the
// inline script to deserialize it. This script starts by deserializing the
// state in the tag. This potentially requires importing @preact/signals.
let hasSignals = false;
let requiresDeserializer = false;
if (state[0].length > 0 || state[1].length > 0) {
const res = serialize(state);
const escapedState = htmlEscapeJsonString(res.serialized);
opts.bodyHtml +=
`<script id="__FRSH_STATE" type="application/json" nonce="${renderState.getNonce()}">${escapedState}</script>`;
hasSignals = res.hasSignals;
requiresDeserializer = res.requiresDeserializer;
if (res.requiresDeserializer) {
const url = addImport("deserializer.js");
script += `import { deserialize } from "${url}";`;
@@ -102,25 +113,46 @@ export function renderFreshTags(
script += `import p${i} from "${url}";runPlugin(p${i},STATE[1][${i}]);`;
}
// Finally, it loads all island scripts and hydrates the islands using the
// reviver from the "main" script.
if (renderState.encounteredIslands.size > 0) {
if (renderState.encounteredIslands.size > 0 || renderState.partialCount > 0) {
// Load the main.js script
const url = addImport("main.js");
script += `import { revive } from "${url}";`;
}
// Finally, it loads all island scripts and hydrates the islands using the
// reviver from the "main" script.
let islandRegistry = "";
const islandMapping: Record<string, string> = {};
if (renderState.encounteredIslands.size > 0) {
// Prepare the inline script that loads and revives the islands
let islandRegistry = "";
for (const island of renderState.encounteredIslands) {
const url = addImport(`island-${island.id}.js`);
script +=
`import * as ${island.name}_${island.exportName} from "${url}";`;
islandRegistry += `${island.id}:${island.name}_${island.exportName},`;
islandMapping[island.id] = url;
}
script += `revive({${islandRegistry}}, STATE[0]);`;
}
// Always revive to detect partials
script += `const propsArr = typeof STATE !== "undefined" ? STATE[0] : [];`;
script += `revive({${islandRegistry}}, propsArr);`;
// Append the inline script.
if (isPartial && Object.keys(islandMapping).length > 0) {
const escapedData = htmlEscapeJsonString(
JSON.stringify({
islands: islandMapping,
signals: hasSignals ? addImport("signals.js") : null,
deserializer: requiresDeserializer
? addImport("deserializer.js")
: null,
}),
);
const nonce = renderState.csp ? ` nonce="${renderState.getNonce()}` : "";
opts.bodyHtml +=
`<script id="__FRSH_PARTIAL_DATA" type="application/json"${nonce}">${escapedData}</script>`;
}
if (script !== "") {
opts.bodyHtml +=
`<script type="module" nonce="${renderState.getNonce()}">${script}</script>`;
+76 -19
View File
@@ -1,6 +1,7 @@
import {
Component,
type ComponentChildren,
ComponentType,
Fragment,
h,
isValidElement,
@@ -9,9 +10,11 @@ import {
type VNode,
} from "preact";
import { assetHashingHook } from "../../runtime/utils.ts";
import { Partial, PartialProps } from "../../runtime/Partial.tsx";
import { renderToString } from "preact-render-to-string";
import { RenderState } from "./state.ts";
import { Island } from "../types.ts";
import { DATA_KEY_ATTR, LOADING_ATTR, PartialMode } from "../../constants.ts";
// See: https://github.com/preactjs/preact/blob/7748dcb83cedd02e37b3713634e35b97b26028fd/src/internal.d.ts#L3C1-L16
enum HookType {
@@ -55,7 +58,7 @@ let current: RenderState | null = null;
// passed as children.
let ownerStack: VNode[] = [];
// Keep track of all available islands
const islandByComponent = new Map();
const islandByComponent = new Map<ComponentType, Island>();
export function setAllIslands(islands: Island[]) {
for (let i = 0; i < islands.length; i++) {
const island = islands[i];
@@ -133,6 +136,29 @@ function excludeChildren(props: Record<string, unknown>) {
return out;
}
/**
* Check if the current component was rendered in an island
*/
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
let tmpVNode = vnode;
let owner;
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
if (islandByComponent.has(owner.type as ComponentType)) {
return true;
}
tmpVNode = owner;
}
return false;
}
function encodePartialMode(mode: PartialProps["mode"]): PartialMode {
if (mode === "replace") return PartialMode.REPLACE;
else if (mode === "append") return PartialMode.APPEND;
else if (mode === "prepend") return PartialMode.PREPEND;
throw new Error(`Unknown partial mode "${mode}"`);
}
const patched = new WeakSet<VNode>();
const oldVNodeHook = options.vnode;
@@ -159,6 +185,16 @@ options.vnode = (vnode) => {
props["ON" + key.slice(2)] = value;
}
}
// Don't do key preservation for nodes in <head>.
if (
vnode.key && vnode.type !== "meta" && vnode.type !== "title" &&
vnode.type !== "style" && vnode.type !== "script" && vnode.type !== "link"
) {
props[DATA_KEY_ATTR] = vnode.key;
} else if (props[LOADING_ATTR]) {
// Avoid automatic signals unwrapping
props[LOADING_ATTR] = { value: props[LOADING_ATTR] };
}
} else if (
current && typeof vnode.type === "function" && vnode.type !== Fragment &&
ownerStack.length > 0
@@ -221,32 +257,29 @@ options.__b = (vnode: VNode<Record<string, unknown>>) => {
});
}
vnode.type = Fragment;
} else if (LOADING_ATTR in vnode.props) {
current.islandProps.push({
[LOADING_ATTR]: vnode.props[LOADING_ATTR],
});
vnode.props[LOADING_ATTR] = current.islandProps.length - 1;
}
} else if (typeof vnode.type === "function" && vnode.type !== Fragment) {
} else if (typeof vnode.type === "function") {
// Detect island vnodes and wrap them with a marker
const island = islandByComponent.get(vnode.type);
patchIsland:
if (
vnode.type !== Fragment &&
island &&
!patched.has(vnode)
) {
// Keep track of whether we are inside an island to warn about
// hooks usage
current.islandCounter++;
// Check if an island is rendered inside another island, not just
// passed as a child.In that case we treat it like a normal
// Component. Example:
// function Island() {}
// function Island() {
// return <OtherIsland />
// }
let tmpVNode = vnode;
let owner;
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
if (islandByComponent.has(owner.type)) {
break patchIsland;
}
tmpVNode = owner;
if (hasIslandOwner(current, vnode)) {
break patchIsland;
}
// At this point we know that we need to patch the island. Mark the
@@ -304,9 +337,34 @@ options.__b = (vnode: VNode<Record<string, unknown>>) => {
return wrapWithMarker(
child,
`frsh-${island.id}:${island.exportName}:${islandProps.length - 1}`,
`frsh-${island.id}:${island.exportName}:${islandProps.length - 1}:${
vnode.key ?? ""
}`,
);
};
// deno-lint-ignore no-explicit-any
} else if (vnode.type === (Partial as any)) {
current.partialCount++;
if (hasIslandOwner(current, vnode)) {
throw new Error(
`<Partial> components cannot be used inside islands.`,
);
}
const mode = encodePartialMode(
// deno-lint-ignore no-explicit-any
(vnode.props as any).mode ?? "replace",
);
vnode.props.children = wrapWithMarker(
vnode.props.children,
`frsh-partial:${vnode.props.name}:${mode}:${vnode.key ?? ""}`,
);
} else if (vnode.key) {
const child = h(vnode.type, vnode.props);
vnode.type = Fragment;
vnode.props = {
children: wrapWithMarker(child, `frsh-key:${vnode.key}`),
};
}
}
}
@@ -324,9 +382,6 @@ options.__r = (vnode) => {
options.diffed = (vnode: VNode<Record<string, unknown>>) => {
if (typeof vnode.type === "function") {
if (vnode.type !== Fragment) {
if (patched.has(vnode) && current) {
current.islandCounter--;
}
ownerStack.pop();
} else if (vnode.props.__freshHead) {
if (current) {
@@ -338,11 +393,13 @@ options.diffed = (vnode: VNode<Record<string, unknown>>) => {
};
options.__h = (component, idx, type) => {
// deno-lint-ignore no-explicit-any
const vnode = (component as any).__v;
// Warn when using stateful hooks outside of islands
if (
// Only error for stateful hooks for now.
(type === HookType.useState || type === HookType.useReducer) && current &&
current.islandCounter === 0 &&
!islandByComponent.has(vnode.type) && !hasIslandOwner(current, vnode) &&
!current.error
) {
const name = HookType[type];
+4 -1
View File
@@ -1,6 +1,7 @@
import { type ComponentChildren, type VNode } from "preact";
import { Island } from "../types.ts";
import { ContentSecurityPolicy } from "../../runtime/csp.ts";
import { PARTIAL_SEARCH_PARAM } from "../../constants.ts";
export interface RenderStateRouteOptions {
url: URL;
@@ -36,8 +37,9 @@ export class RenderState {
ownerStack: VNode[] = [];
owners = new Map<VNode, VNode>();
#nonce = "";
islandCounter = 0;
error: Error | null = null;
isPartial: boolean;
partialCount = 0;
constructor(
routeOptions: RenderStateRouteOptions,
@@ -49,6 +51,7 @@ export class RenderState {
this.routeOptions = routeOptions;
this.csp = csp;
this.componentStack = componentStack;
this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM);
if (error) this.routeOptions.error = error;
}