import { computed, effect, Signal } from "@preact/signals-core"; import { type ChildNodeInput, deferToMacrotask } from "./core.ts"; const normalizeToNodeArray = (input: ChildNodeInput): Node[] => { if (input === null || input === undefined) return []; if (Array.isArray(input)) { return input.flatMap((c) => normalizeToNodeArray(c)); } if (input instanceof Node) { return [input]; } // Handled primitives or Signals returning primitives return [document.createTextNode(String(input))]; }; export interface ShowProps { when: Signal | (() => boolean); fallback?: () => ChildNodeInput; } export const Show = ( children: () => ChildNodeInput, { when, fallback }: ShowProps ): Node => { const parentContainer = document.createDocumentFragment(); const anchor = document.createComment("Show-Anchor"); parentContainer.appendChild(anchor); const conditionSignal = typeof when === "function" ? computed(when) : when; let currentNodes: Node[] = []; const reconcile = (condition: boolean) => { const parent = anchor.parentNode; if (!parent) return; // 1. Unmount previous nodes currentNodes.forEach((node) => { if (node.parentNode) { node.parentNode.removeChild(node); } }); currentNodes = []; // 2. Resolve content for current state const rawContent = condition ? children() : fallback ? fallback() : null; if (rawContent === null || rawContent === undefined) return; const nextNodes = normalizeToNodeArray(rawContent); const fragment = document.createDocumentFragment(); nextNodes.forEach((node) => fragment.appendChild(node)); currentNodes = nextNodes; // 3. Insert new nodes directly before anchor parent.insertBefore(fragment, anchor); }; // Synchronous initial renderpass reconcile(Boolean(conditionSignal.value)); deferToMacrotask(() => { let isInitial = true; const dispose = effect(() => { const latestCondition = conditionSignal.value; if (!anchor.isConnected) { dispose(); return; } if (isInitial) { isInitial = false; return; } reconcile(Boolean(latestCondition)); }); }); return parentContainer; }; // --- Repeat Component --- export interface RepeatProps { list: Signal | (() => T[]); key?: (item: T, index: number) => unknown; } interface KeyedItemEntry { nodes: Node[]; } export const Repeat = ( renderItem: (item: T, index: number) => ChildNodeInput, { list, key }: RepeatProps ): Node => { const parentContainer = document.createDocumentFragment(); const startAnchor = document.createComment("Repeat-Start"); const endAnchor = document.createComment("Repeat-End"); parentContainer.appendChild(startAnchor); parentContainer.appendChild(endAnchor); const listSignal = typeof list === "function" ? computed(list) : list; const getKey = key ?? ((item: T) => typeof item === "object" && item !== null ? (item as unknown) : item); // key -> cached nodes array representing that item let keyedEntries = new Map(); const reconcile = (items: T[]) => { const parent = startAnchor.parentNode; if (!parent) return; const nextKeyedEntries = new Map(); const nextKeys: unknown[] = new Array(items.length); for (let i = 0; i < items.length; i++) { const itemKey = getKey(items[i], i); if (nextKeyedEntries.has(itemKey)) { console.warn( `[Repeat] Duplicate key "${String(itemKey)}" — provide a \`key\` ` + `function that returns a unique value per item.` ); } nextKeys[i] = itemKey; let entry = keyedEntries.get(itemKey); if (!entry) { const rawOutput = renderItem(items[i], i); entry = { nodes: normalizeToNodeArray(rawOutput) }; } nextKeyedEntries.set(itemKey, entry); } // 1. Remove entries no longer present in list for (const [oldKey, entry] of keyedEntries) { if (!nextKeyedEntries.has(oldKey)) { entry.nodes.forEach((node) => node.parentNode?.removeChild(node)); } } // 2. Reorder / Insert nodes in single pass let cursor = startAnchor.nextSibling; for (let i = 0; i < nextKeys.length; i++) { const entry = nextKeyedEntries.get(nextKeys[i])!; for (let j = 0; j < entry.nodes.length; j++) { const node = entry.nodes[j]; if (cursor === node) { cursor = cursor.nextSibling; } else { parent.insertBefore(node, cursor); } } } keyedEntries = nextKeyedEntries; }; // Synchronous initial pass reconcile(listSignal.value); deferToMacrotask(() => { let isInitial = true; const dispose = effect(() => { const items = listSignal.value; if (!startAnchor.isConnected) { dispose(); return; } if (isInitial) { isInitial = false; return; } reconcile(items); }); }); return parentContainer; }; // --- Template Tag Helper --- export const txt = ( strings: TemplateStringsArray, ...values: ChildNodeInput[] ): ChildNodeInput[] => { const result = [] as ChildNodeInput[]; strings.forEach((str, i) => { result.push(str); if (i < values.length) { result.push(values[i]); } }); return result; };