- TypeScript 99%
- HTML <1%
Reactive DOM Builder Library — Documentation #
This has been generated via an LLM tbh.
This library provides a lightweight, signal-driven alternative to JSX for building DOM trees, built on top of @preact/signals-core. It consists of two modules:
./src/core.ts— thehproxy for creating elements with reactive props, styles, classes, attributes, and children../src/dynamic-content.ts— structural control-flow helpers (Show,Repeat) and atxttemplate-literal helper, for reactivity that plainh()children can't express (conditionals, keyed lists).
Part 1: Usage Guide #
1.1 The h proxy — creating elements #
h is a Proxy typed against HTMLElementTagNameMap. Any tag name you access on it (h.div, h.span, h.input, h.button, …) returns a fully-typed factory function:
h.div(props?, children?) => HTMLDivElement
Basic example:
const el = h.div(
{ attrs: { id: "greeting" } },
["Hello, world!"]
);
document.body.appendChild(el);
Every tag on HTMLElementTagNameMap works out of the box — no need to register elements ahead of time. TypeScript will type-check props against the specific element interface (e.g. h.input(...) knows about .value, .checked, .type, etc.; h.div(...) does not).
1.2 DynamicValue<T> — the core reactivity primitive #
Almost every prop value can be one of three shapes:
type DynamicValue<T> = T | Signal<T> | ((el: HTMLElement) => T);
| Shape | Behavior |
|---|---|
Plain value (T) |
Used as-is, once. |
Signal<T> |
Read once for the initial render, then subscribed to — future signal changes update the DOM automatically. |
(el: HTMLElement) => T |
Called once, synchronously, with the element itself. Useful for values that depend on the element (e.g. measuring it) — but it is not re-run. It behaves like a plain value, not a live binding, despite the type name. |
⚠️ Only the Signal form is reactive. Functions are a one-shot computed-at-creation convenience, not a subscription mechanism.
1.3 Element props #
ElementProps<T> groups configuration into a few reserved keys, plus "everything else":
{
attrs?: Record<string, DynamicValue<string | number | boolean>>;
classList?: Record<string, DynamicValue<boolean>>;
style?: DynamicValue<string | StyleObject>;
on?: { [eventName: string]: (ev) => void };
// ...any other real property of the element (typed per-tag), each DynamicValue<T[prop]>
}
attrs — sets/removes real HTML attributes via setAttribute/removeAttribute.
true→ sets the attribute to""(e.g.disabled: true→disabled="").false→ attribute is not set initially, and removed if it becomesfalselater.- Any other value → coerced with
String(value). - Each attribute's value is tracked individually — a
Signalon one attribute doesn't affect others.
h.button({
attrs: {
disabled: isLoadingSignal, // reactive boolean attribute
"data-id": "42", // static
"aria-label": () => computeLabel(), // computed once at creation only
},
}, ["Submit"]);
classList — like attrs, but toggles CSS classes via classList.toggle(key, condition). Each key is tracked independently.
h.div({
classList: {
active: isActiveSignal,
"is-error": hasErrorSignal,
},
});
style — accepts either:
- a CSS string (
"color: red; padding: 4px") → setsel.style.cssText, or - a
StyleObject(Record<string, DynamicValue<string | number>>) → applied viaObject.assign(el.style, ...)after clearing the existingstyleattribute.
h.div({ style: "display:flex; gap:8px" });
h.div({
style: {
color: "tomato",
fontSize: 14, // numbers are assigned as-is (CSSOM does its own coercion)
backgroundColor: bgSignal,
},
});
on — DOM event listeners, attached once via addEventListener. Supports all standard HTMLElementEventMap keys plus arbitrary custom event name strings.
h.button({
on: {
click: (e) => console.log("clicked", e),
"my-custom-event": (e) => handle(e),
},
});
Everything else (restProps) — any other key is treated as a direct property assignment on the element (el[key] = value), not an attribute. This is how you set things like .value, .checked, .textContent, .innerHTML, .id, etc., and each one supports the full DynamicValue reactivity individually.
h.input({
value: nameSignal, // reactive property (not attribute)
placeholder: "Name",
disabled: false,
});
1.4 Children #
The second argument is a ChildNodeInput[] (or nested arrays thereof, flattened automatically). Accepted item types:
string/number— becomes a static text node.Node— appended directly (e.g. the result of anotherh.xxx(...)call, orShow(...)/Repeat(...)).Signal<any>— becomes a reactive text node: initial value rendered immediately, and the text node'stextContentupdates automatically whenever the signal changes.- Arrays — flattened recursively, so you can freely mix conditionally-built arrays.
h.p({}, [
"Count: ",
countSignal, // reactive text
" (", () => "static-ish but only computed once", ")",
]);
⚠️ A Signal child is only reactive as a text node. If the signal's .value is a Node, it will be stringified (e.g. "[object HTMLDivElement]"), not inserted as an element. For structural/element-level reactivity, use Show or Repeat (below), not a raw signal child.
1.5 Show — conditional rendering #
Show(children: () => ChildNodeInput, {
when: Signal<boolean> | (() => boolean),
fallback?: () => ChildNodeInput,
}): Node
childrenmust be a function that returns content — it's called (and its output freshly created) every timewhenbecomes true.whencan be aSignal<boolean>directly, or a plain function — if it's a function, it's wrapped incomputed(), so any signals you read inside it are automatically tracked as dependencies.fallbackis an optional function for the "else" branch (also freshly re-invoked each time).- Returns a
Node(aDocumentFragmentunder the hood) — use it directly as an item in another element'schildrenarray.
const isOpen = signal(false);
h.div({}, [
Show(() => h.div({}, ["Panel content"]), {
when: isOpen,
fallback: () => h.div({}, ["Closed"]),
}),
]);
Multi-signal condition, using a plain function:
Show(() => h.span({}, ["Ready!"]), {
when: () => user.value !== null && !loading.value,
});
1.6 Repeat — keyed list rendering #
Repeat<T>(renderItem: (item: T, index: number) => ChildNodeInput, {
list: Signal<T[]> | (() => T[]),
key?: (item: T, index: number) => unknown,
}): Node
renderItemis called once per unique key — as long as an item's key persists across re-renders, its DOM nodes (and any state/focus/reactive subscriptions inside them) are reused, not recreated. Only new keys trigger a freshrenderItemcall; removed keys have their nodes removed from the DOM.keydefaults to the item itself (object identity for objects, raw value for primitives). Always supply an explicitkeyif your list contains primitives or duplicate object references — see caveats.listfollows the sameSignalvs. plain-function convention asShow'swhen.- Reordering is handled by moving existing nodes rather than recreating them.
const todos = signal([{ id: 1, text: "Buy milk" }, { id: 2, text: "Walk dog" }]);
h.ul({}, [
Repeat(
(todo) => h.li({}, [todo.text]),
{ list: todos, key: (todo) => todo.id }
),
]);
1.7 txt — template-literal children helper #
A tagged-template convenience for interleaving text and dynamic children without manual array construction:
h.p({}, txt`Hello, ${nameSignal}! You have ${countSignal} items.`);
This just returns ["Hello, ", nameSignal, "! You have ", countSignal, " items."] — equivalent to writing the array by hand, but easier to read for text-heavy templates. Interpolated values follow the same ChildNodeInput rules as regular children (a Signal here is still reactive when consumed as an h() child, since it goes through appendChildNode).
1.8 Putting it together #
import { signal } from "@preact/signals-core";
import { h } from "./core";
import { Show, Repeat, txt } from "./dynamic-content";
const count = signal(0);
const items = signal<string[]>([]);
const showList = signal(true);
const app = h.div({ attrs: { id: "app" } }, [
h.button({ on: { click: () => count.value++ } }, txt`Clicked ${count} times`),
Show(
() => h.ul({}, [
Repeat(
(item, i) => h.li({}, [`${i}: ${item}`]),
{ list: items, key: (item, i) => i }
),
]),
{ when: showList, fallback: () => h.p({}, ["List hidden"]) }
),
]);
document.body.appendChild(app);
Part 2: Low-Level Explanation #
2.1 Architecture overview #
- Both modules depend on
@preact/signals-coreforSignal,computed, andeffect. - There is no virtual DOM.
h()creates real DOM nodes immediately and synchronously (document.createElement), and mutates them directly and imperatively when signals change. - Reactivity is layered on top of plain DOM APIs via
effect()subscriptions — each reactive prop/attribute/class/child gets its own independenteffect(), not one big effect per element. This means unrelated props can update independently without re-touching the whole node.
2.2 resolveValue and setupReactivity #
resolveValue(val, el):
if (typeof val === "function") return val(el);
if (isSignal(val)) return val.value;
return val;
This is used for the synchronous initial pass — it reads a Signal's current value without establishing a subscription (since it's called outside of an effect() context), and calls function-form values exactly once.
setupReactivity(val, el, callback) only does something if isSignal(val) is true. If so, it defers (see 2.6) into a deferToMacrotask callback that creates a Preact effect():
effect(() => {
const latest = val.value; // subscribes to val
if (!el.isConnected) { dispose(); return; } // lazy cleanup
if (initialRun) { initialRun = false; return; } // skip first firing
callback(latest);
});
Key mechanics:
- The first execution of the effect is intentionally a no-op (
initialRun) because the initial DOM state was already set synchronously viaresolveValuebefore this effect was even created — this avoids a redundant duplicate write. - Unmount detection is lazy, not immediate. The effect only checks
el.isConnectedwhen it re-runs (i.e. when its tracked signal changes again). If an element is removed from the DOM and its signal never fires again, the underlyingeffect()subscription is not disposed — it lingers, keeping a reference to the closure (and therefore the element and the signal graph) alive until either the signal changes again or everything becomes otherwise unreachable and gets garbage collected. This is a real (if usually minor) leak vector — see Caveats. - Function-form
DynamicValues never get aneffect()at all —setupReactivityonly branches onisSignal, so functions are permanently "static after first read."
2.3 applyStyles internals #
const resolved = resolveValue(styleProp, el);
if (typeof resolved === "string") {
el.style.cssText = resolved;
} else if (resolved && typeof resolved === "object") {
el.removeAttribute("style");
// resolve every StyleObject entry via resolveValue, then Object.assign onto el.style
}
Important subtlety: style is a single DynamicValue<string | StyleObject> — there is only one setupReactivity call for the whole prop, not one per CSS property. Compare this to attrs/classList/rest-props, which iterate per-key and call setupReactivity individually for each one.
Consequences:
- If you pass a plain
StyleObjectwhose individual values happen to beSignals, those nested signals are not automatically reactive, becauseisSignal(style)isfalsefor the outer object, so noeffect()is ever created forstyleat all. The nested signals only ever get read once, during the initial synchronousapplyStylescall (outside of any tracking context). - To get properties inside a style object to update reactively, the
styleprop itself must be aSignal(e.g.computed(() => ({ color: colorSignal.value, ...}))). Because the callback that re-invokesapplyStylesruns inside the effect body, any signal.valuereads that happen synchronously during that call (including nested ones insideapplyStyles/resolveValue) are tracked as dependencies of that effect from then on — but only from the second invocation onward, since the first invocation is skipped byinitialRun.
2.4 appendChildNode internals #
Recursively normalizes ChildNodeInput:
null/undefined→ skipped.- Arrays → recursed into, flattening nested arrays.
Signal→ aTextnode is created with the signal's current value, andsetupReactivitywirestextNode.textContent = val ?? ""on future changes. This is the only place incore.tswhere a bareSignalchild becomes reactive.Nodeinstance → appended directly, no wrapping.- Anything else →
String(child)wrapped in a staticTextnode.
2.5 The h Proxy internals #
h is new Proxy({}, { get(_, tagName) { return (props, children) => {...} } }). Accessing h.anything synthesizes a factory function on demand — no per-tag registration needed; this is purely a TypeScript-typing + ergonomics trick over document.createElement.
Inside the returned factory, prop application happens in two distinct passes, always in this order:
- Synchronous setup (executes immediately, before the function returns):
onlisteners attached →attrsinitial values set →classListinitial toggles →styleinitial apply → rest-props initial assignment. - Deferred reactivity setup (queued via
deferToMacrotask, executes after current stack + microtasks):attrs→classList→style→ rest-props, each wired viasetupReactivity.
children are appended after both prop passes are scheduled (step 2's effects aren't live yet, but step 1 already fully configured the element).
2.6 deferToMacrotask #
export const deferToMacrotask = (cb) => setTimeout(cb, 0);
All effect() creation for prop/attr/class/style/child reactivity is delayed by one macrotask (setTimeout(…, 0)), not a microtask. Rationale (inferred from behavior): it lets an entire tree of nested h() calls finish being constructed and attached to the DOM synchronously first, before any reactive subscriptions start firing — avoiding effects targeting elements that are still mid-construction or not yet inserted anywhere. A side effect is that reactivity is not "live" for a brief window (a few milliseconds) after element creation; any signal writes during that window are simply coalesced into whatever the signal's value is by the time the effect's first (skipped) run happens — no updates are lost, just delayed until the deferred effect exists.
2.7 Show internals #
- Creates a
DocumentFragmentcontaining a singleCommentanchor node. Returning a fragment means when it's inserted into a real parent (viaappendChild/appendChildNode), the fragment "dissolves" and its children (currently just the anchor) become live children of that parent — this is howShowlater findsanchor.parentNodeto know where to insert/remove content. reconcile(condition): removes all currently-tracked nodes (currentNodes), then callschildren()orfallback()fresh, normalizes the result to a flatNode[]vianormalizeToNodeArray, and inserts them withparent.insertBefore(fragment, anchor)— i.e., content is always positioned immediately before the anchor comment.- An initial synchronous
reconcile()call happens atShow()invocation time (not deferred), so first paint has correct content immediately, with no macrotask delay for the first render. - Subsequent reactivity:
whenis normalized into acomputed()if it was a plain function, then tracked the same deferred-effect()way described in 2.2 (skip-first-run + lazyisConnecteddisposal). normalizeToNodeArray(used here, distinct fromappendChildNodeincore.ts) treats a bareSignalvalue the same as any other non-Node primitive:String(input)once, with no subscription. This means a rawSignalreturned directly fromchildren()/fallback()(i.e., not wrapped in anh()call) will render its value once and never update — only content that flows back throughh()'s ownappendChildNodegets live text reactivity.- Content is fully torn down and rebuilt on every toggle — no diffing between the "shown" and "hidden" states, and no state preservation for whatever was inside.
2.8 Repeat internals #
- Similar fragment/anchor pattern, but with two anchor comments (
Repeat-Start,Repeat-End) bracketing the rendered items. - Maintains
keyedEntries: Map<unknown, { nodes: Node[] }>across reconciliations — this is the cache that enables node reuse. reconcile(items)algorithm:- Compute
nextKeys[]andnextKeyedEntriesby walking the newitemsarray in order. For each item, look up its key in the previouskeyedEntries; if found, reuse the cached{ nodes }entry as-is (no re-render); if not found, callrenderItem(item, i)and normalize the result into a fresh{ nodes }entry. - Removal pass: any key present in the old
keyedEntriesbut absent fromnextKeyedEntrieshas its nodes removed from the DOM (node.parentNode?.removeChild(node)). - Reorder/insert pass: walks from
startAnchor.nextSiblingas acursor, and for each item's node(s) in the new order, either advances the cursor (if the node is already correctly positioned) orinsertBefores it at the cursor position — this moves existing nodes rather than recreating them, minimizing DOM operations. keyedEntriesis replaced withnextKeyedEntriesfor the next pass.
- Compute
- Default
keyfunction:typeof item === "object" && item !== null ? item : item— effectively "the item itself" either way (object reference identity, or the raw primitive value for primitives). - Duplicate-key detection is a
console.warnonly — it does not throw or auto-correct. When two items resolve to the same key in the same pass, both positions innextKeyspoint at the same{nodes}entry object; since the same physical DOM node can't exist in two places, the reorder pass will simply move it to whichever position is processed later, leaving the earlier position without its expected content. listfollows the sameSignal-or-plain-function-wrapped-in-computed()convention asShow'swhen, with the same initial-synchronous-render + deferred-effect-for-updates + skip-first-run + lazy-disconnect-disposal behavior as everywhere else in this library.
2.9 txt internals #
Pure data transformation, no DOM/reactivity involved:
strings.forEach((str, i) => {
result.push(str);
if (i < values.length) result.push(values[i]);
});
It just interleaves the template's literal string segments with the interpolated ChildNodeInput values (in declaration order) into a single flat array — a straight [str0, val0, str1, val1, ..., strN] pattern. All reactivity behavior of the interpolated values is decided later, by whatever consumes the resulting array (appendChildNode if passed to h(), or the non-reactive normalizeToNodeArray if passed through Show/Repeat).
Part 3: Tips & Caveats (Summary) #
- Functions are not reactive.
(el) => valueis evaluated exactly once. If you need a live binding, use aSignal(orcomputed()), not a function. styleis reactive only as a whole. Nested per-property signals inside a plainStyleObjectare inert. To get reactive individual style properties, wrap the entirestylevalue in acomputed()(or a signal you replace wholesale).attrs,classList, and other element properties are tracked per-key. Unlikestyle, each entry in these gets its own independenteffect(), so mixing static and reactive values freely in the same object is safe and efficient.- A raw
Signalas anh()child only ever becomes a text node. It is stringified withString(...). Don't put aSignal<Node>orSignal<Node[]>there — useShow/Repeatfor structural reactivity instead. Show/Repeat's content-producing functions must be functions, not the content itself —Show(() => h.div(...), {...}), notShow(h.div(...), {...}). Passing the already-constructed node would call it once outside any reactivity, and would be reused (mutated) rather than freshly created.- A bare
Signalreturned fromShow'schildren/fallback(orRepeat'srenderItem) is not reactive —normalizeToNodeArraystringifies it once. Only signals consumed as children inside anh()call get live updates. Repeatneeds a goodkey. The default key is the item's own identity/value. For primitive lists (numbers, strings) or lists that may contain duplicate object references, always pass an explicitkey, typically index- or id-based, or you risk silently losing/misplacing duplicate-keyed rows (only aconsole.warn, not an error).- Reactivity setup is deferred by one macrotask (
setTimeout(…, 0)). There's a brief window right after element creation where signal writes won't visibly update the DOM yet — though no updates are lost, since only the latest value matters once the effect activates. Don't assume synchronous reactivity immediately after constructing an element. - No automatic cleanup on unmount. Effects check
el.isConnected(oranchor.isConnectedforShow/Repeat) but only when they re-fire due to a tracked signal changing — removing an element from the DOM does not itself dispose its subscriptions. If a signal a removed element depends on never changes again, that effect (and its closure) can linger. This is rarely a problem in typical usage but is worth knowing for very long-lived pages with many mount/unmount cycles bound to slow-changing signals. ShowandRepeatreturnDocumentFragments. Once inserted, only the anchor comment node(s) remain as a stable reference point — don't try to hold onto or re-insert the object returned byShow(...)/Repeat(...)a second time; it's a one-shot mount.onlisteners are static. There's no reactive way to swap an event handler through theonobject — attach once and use closures/signals inside the handler to vary behavior instead.Showfully re-creates its content on every toggle. There's no diffing between the "true" and "false" branches, so any local component state, focus, or scroll position inside the toggled content is lost on every switch. If you need to preserve state across a condition change, keep the element mounted and toggle visibility viastyle/classListinstead ofShow.