Small functional reactive frontend library
Files
README.md

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 — the h proxy for creating elements with reactive props, styles, classes, attributes, and children.
  • ./src/dynamic-content.ts — structural control-flow helpers (Show, Repeat) and a txt template-literal helper, for reactivity that plain h() 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 becomes false later.
  • Any other value → coerced with String(value).
  • Each attribute's value is tracked individually — a Signal on 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") → sets el.style.cssText, or
  • a StyleObject (Record<string, DynamicValue<string | number>>) → applied via Object.assign(el.style, ...) after clearing the existing style attribute.
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 another h.xxx(...) call, or Show(...)/Repeat(...)).
  • Signal<any> — becomes a reactive text node: initial value rendered immediately, and the text node's textContent updates 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
  • children must be a function that returns content — it's called (and its output freshly created) every time when becomes true.
  • when can be a Signal<boolean> directly, or a plain function — if it's a function, it's wrapped in computed(), so any signals you read inside it are automatically tracked as dependencies.
  • fallback is an optional function for the "else" branch (also freshly re-invoked each time).
  • Returns a Node (a DocumentFragment under the hood) — use it directly as an item in another element's children array.
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
  • renderItem is 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 fresh renderItem call; removed keys have their nodes removed from the DOM.
  • key defaults to the item itself (object identity for objects, raw value for primitives). Always supply an explicit key if your list contains primitives or duplicate object references — see caveats.
  • list follows the same Signal vs. plain-function convention as Show's when.
  • 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-core for Signal, computed, and effect.
  • 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 independent effect(), 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 via resolveValue before this effect was even created — this avoids a redundant duplicate write.
  • Unmount detection is lazy, not immediate. The effect only checks el.isConnected when 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 underlying effect() 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 an effect() at all — setupReactivity only branches on isSignal, 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 StyleObject whose individual values happen to be Signals, those nested signals are not automatically reactive, because isSignal(style) is false for the outer object, so no effect() is ever created for style at all. The nested signals only ever get read once, during the initial synchronous applyStyles call (outside of any tracking context).
  • To get properties inside a style object to update reactively, the style prop itself must be a Signal (e.g. computed(() => ({ color: colorSignal.value, ...}))). Because the callback that re-invokes applyStyles runs inside the effect body, any signal .value reads that happen synchronously during that call (including nested ones inside applyStyles/resolveValue) are tracked as dependencies of that effect from then on — but only from the second invocation onward, since the first invocation is skipped by initialRun.

2.4 appendChildNode internals #

Recursively normalizes ChildNodeInput:

  1. null/undefined → skipped.
  2. Arrays → recursed into, flattening nested arrays.
  3. Signal → a Text node is created with the signal's current value, and setupReactivity wires textNode.textContent = val ?? "" on future changes. This is the only place in core.ts where a bare Signal child becomes reactive.
  4. Node instance → appended directly, no wrapping.
  5. Anything else → String(child) wrapped in a static Text node.

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:

  1. Synchronous setup (executes immediately, before the function returns): on listeners attached → attrs initial values set → classList initial toggles → style initial apply → rest-props initial assignment.
  2. Deferred reactivity setup (queued via deferToMacrotask, executes after current stack + microtasks): attrs → classList → style → rest-props, each wired via setupReactivity.

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 DocumentFragment containing a single Comment anchor node. Returning a fragment means when it's inserted into a real parent (via appendChild/appendChildNode), the fragment "dissolves" and its children (currently just the anchor) become live children of that parent — this is how Show later finds anchor.parentNode to know where to insert/remove content.
  • reconcile(condition): removes all currently-tracked nodes (currentNodes), then calls children() or fallback() fresh, normalizes the result to a flat Node[] via normalizeToNodeArray, and inserts them with parent.insertBefore(fragment, anchor) — i.e., content is always positioned immediately before the anchor comment.
  • An initial synchronous reconcile() call happens at Show() invocation time (not deferred), so first paint has correct content immediately, with no macrotask delay for the first render.
  • Subsequent reactivity: when is normalized into a computed() if it was a plain function, then tracked the same deferred-effect() way described in 2.2 (skip-first-run + lazy isConnected disposal).
  • normalizeToNodeArray (used here, distinct from appendChildNode in core.ts) treats a bare Signal value the same as any other non-Node primitive: String(input) once, with no subscription. This means a raw Signal returned directly from children()/fallback() (i.e., not wrapped in an h() call) will render its value once and never update — only content that flows back through h()'s own appendChildNode gets 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:
    1. Compute nextKeys[] and nextKeyedEntries by walking the new items array in order. For each item, look up its key in the previous keyedEntries; if found, reuse the cached { nodes } entry as-is (no re-render); if not found, call renderItem(item, i) and normalize the result into a fresh { nodes } entry.
    2. Removal pass: any key present in the old keyedEntries but absent from nextKeyedEntries has its nodes removed from the DOM (node.parentNode?.removeChild(node)).
    3. Reorder/insert pass: walks from startAnchor.nextSibling as a cursor, and for each item's node(s) in the new order, either advances the cursor (if the node is already correctly positioned) or insertBefores it at the cursor position — this moves existing nodes rather than recreating them, minimizing DOM operations.
    4. keyedEntries is replaced with nextKeyedEntries for the next pass.
  • Default key function: 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.warn only — it does not throw or auto-correct. When two items resolve to the same key in the same pass, both positions in nextKeys point 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.
  • list follows the same Signal-or-plain-function-wrapped-in-computed() convention as Show's when, 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) #

  1. Functions are not reactive. (el) => value is evaluated exactly once. If you need a live binding, use a Signal (or computed()), not a function.
  2. style is reactive only as a whole. Nested per-property signals inside a plain StyleObject are inert. To get reactive individual style properties, wrap the entire style value in a computed() (or a signal you replace wholesale).
  3. attrs, classList, and other element properties are tracked per-key. Unlike style, each entry in these gets its own independent effect(), so mixing static and reactive values freely in the same object is safe and efficient.
  4. A raw Signal as an h() child only ever becomes a text node. It is stringified with String(...). Don't put a Signal<Node> or Signal<Node[]> there — use Show/Repeat for structural reactivity instead.
  5. Show/Repeat's content-producing functions must be functions, not the content itself — Show(() => h.div(...), {...}), not Show(h.div(...), {...}). Passing the already-constructed node would call it once outside any reactivity, and would be reused (mutated) rather than freshly created.
  6. A bare Signal returned from Show's children/fallback (or Repeat's renderItem) is not reactive — normalizeToNodeArray stringifies it once. Only signals consumed as children inside an h() call get live updates.
  7. Repeat needs a good key. 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 explicit key, typically index- or id-based, or you risk silently losing/misplacing duplicate-keyed rows (only a console.warn, not an error).
  8. 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.
  9. No automatic cleanup on unmount. Effects check el.isConnected (or anchor.isConnected for Show/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.
  10. Show and Repeat return DocumentFragments. 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 by Show(...)/Repeat(...) a second time; it's a one-shot mount.
  11. on listeners are static. There's no reactive way to swap an event handler through the on object — attach once and use closures/signals inside the handler to vary behavior instead.
  12. Show fully 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 via style/classList instead of Show.