Add Partials (#1824)
This commit is contained in:
@@ -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>`;
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user