Something went wrong. Try again.
Small functional reactive frontend library
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205import { 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> | (() => 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<T> { list: Signal<T[]> | (() => T[]); key?: (item: T, index: number) => unknown;}
interface KeyedItemEntry { nodes: Node[];}
export const Repeat = <T,>( renderItem: (item: T, index: number) => ChildNodeInput, { list, key }: RepeatProps<T>): 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<unknown, KeyedItemEntry>();
const reconcile = (items: T[]) => { const parent = startAnchor.parentNode; if (!parent) return;
const nextKeyedEntries = new Map<unknown, KeyedItemEntry>(); 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;};