import { Component, type ComponentChildren, type ComponentType, Fragment, h, render, type VNode, } from "preact"; import { type CustomParser, parse } from "../../jsonify/parse.ts"; import { computed, signal } from "@preact/signals"; import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.ts"; const enum RootKind { Island, Partial, } interface IslandReq { kind: RootKind.Island; name: string; propsIdx: number; key: string | null; start: Comment | Text; end: Comment | Text | null; } interface PartialReq { kind: RootKind.Partial; name: string; key: string | null; start: Comment | Text; end: Comment | Text | null; } interface ReviveContext { roots: Array; stack: Array; slots: Map; slotIdStack: number[]; } interface SlotRef { kind: typeof SLOT_SYMBOL; name: string; id: number; } const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT"); function isSlotRef(x: unknown): x is SlotRef { return x !== null && typeof x === "object" && "kind" in x && x.kind === SLOT_SYMBOL; } export type DeserializedProps = { props: Record; slots: SlotRef[]; }[]; export const ACTIVE_PARTIALS = new Map(); export class PartialComp extends Component< { children?: ComponentChildren; mode: PartialMode; name: string } > { override componentDidMount() { ACTIVE_PARTIALS.set(this.props.name, this); } render() { return this.props.children; } } PartialComp.displayName = "Partial"; export function revive( props: Record, component: ComponentType, container: HTMLElement, slots: ReviveContext["slots"], allProps: DeserializedProps, ) { const _render = () => { for (const propName in props) { const value = props[propName]; if (isSlotRef(value)) { const marker = slots.get(value.id); if (marker !== undefined) { const root = h(Fragment, null); const slotContainer = createRootFragment( container, marker.start, marker.end!, ); domToVNode( allProps, [root], [Marker.Slot], slotContainer, marker.end!, ); props[propName] = root; } else { const template = document.querySelector( `#frsh-${value.id}-${value.name}`, ) as HTMLTemplateElement | null; if (template !== null) { const root = h(Fragment, null); domToVNode(allProps, [root], [Marker.Slot], template.content, null); props[propName] = root; } } } } // TODO: explore hydrate? render(h(component, props), container as unknown as HTMLElement); }; // deno-lint-ignore no-window "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); } export const ISLAND_REGISTRY = new Map(); export const CUSTOM_PARSER: CustomParser = { Signal: (value: unknown) => signal(value), Computed: (value: unknown) => computed(() => value), Slot: (value: { name: string; id: number }): SlotRef => { return { kind: SLOT_SYMBOL, name: value.name, id: value.id }; }, }; export function createReviveCtx(): ReviveContext { return { roots: [], stack: [], slots: new Map(), slotIdStack: [], }; } export function boot( initialIslands: Record, islandProps: string, ) { const ctx = createReviveCtx(); _walkInner(ctx, document.body); const keys = Object.keys(initialIslands); for (let i = 0; i < keys.length; i++) { const name = keys[i]; ISLAND_REGISTRY.set(name, initialIslands[name]); } const allProps = parse( islandProps, CUSTOM_PARSER, ); for (let i = 0; i < ctx.roots.length; i++) { const root = ctx.roots[i]; if (root.end === null) continue; // Check that the browser didn't reparent our markers due to // invalid HTML nesting (e.g.
inside

). When this // happens the start and end markers end up under different // parents and hydration would fail with a DOMException. if (root.start.parentNode !== root.end.parentNode) { const label = root.kind === RootKind.Island ? `island "${root.name}"` : `partial "${root.name}"`; // deno-lint-ignore no-console console.error( `Sweet hydration error: the ${label} has invalid HTML nesting. ` + `Its start and end markers were reparented by the browser into ` + `different DOM nodes. This is usually caused by placing a ` + `block-level element (like

) inside an inline element ` + `(like

or ). Check the HTML around this ${ root.kind === RootKind.Island ? "island" : "partial" } for invalid nesting.`, ); continue; } const container = createRootFragment( // deno-lint-ignore no-explicit-any root.start.parentNode as any, root.start, root.end, ); if (root.kind === RootKind.Island) { const props = allProps[root.propsIdx].props; const component = ISLAND_REGISTRY.get(root.name)!; revive(props, component, container, ctx.slots, allProps); } else if (root.kind === RootKind.Partial) { const props: Record = { name: root.name, children: null, }; const domRoot = h(Fragment, null); domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!); props.children = domRoot.props.children; // deno-lint-ignore no-explicit-any revive(props, PartialComp as any, container, ctx.slots, allProps); } } } const SHOW_MARKERS = false; interface FreshMarker extends Text { _frshMarker: string; } export function isFreshMarkerText(node: Node): node is FreshMarker { return node.nodeType === Node.TEXT_NODE && // deno-lint-ignore no-explicit-any typeof (node as any)._frshMarker === "string"; } /** * Replace comment markers with empty text nodes to hide them * in DevTools. This is done to avoid user confusion. */ export function maybeHideMarker(marker: Comment): Comment | Text { if (SHOW_MARKERS) return marker; const text = new Text("") as FreshMarker; text._frshMarker = marker.data; marker.parentNode!.insertBefore(text, marker); marker.remove(); return text; } function _walkInner( ctx: ReviveContext, node: Node | Comment, ) { if (isElementNode(node)) { // No need to traverse into