sigula

Tiny web framework with fine-grained signal reactivity

A minimal, signal-based web framework with fine-grained reactivity. No virtual DOM — just direct, minimal updates to the real DOM.

Features

  • Fine-grained signal reactivity. When a signal changes, only the DOM nodes that depend on it are updated — not the whole component tree.
  • Declarative sources + precise bindings. Describe state with signals, then bind them precisely to a text node, an attribute, or an effect.
  • No virtual DOM. No VNodes, no diffing, no reconciliation pass. Direct real DOM operations.
  • Native string templates. html is a tagged template over plain JavaScript strings. No compiler, no JSX transform.
  • Batched, coalesced updates. Writes queue in a microtask; a signal touched many times before the flush runs each dependent binding once, against the final value.
  • Ultra small. Around 4.5KB minified and gzipped, with an API surface you can read in one sitting.
  • TypeScript first. Full type inference for signals, template bindings, and patch commands.
  • Zero tooling. ESM-only, sideEffects: false, no build step required to author components.

Installation

pnpm add sigula

Sigula is ESM-only and ships type declarations. Importing the module is side-effect free; the DOM is only touched when you actually render.

Quick Start

1. Render something

main.ts
import {html, render} from 'sigula';

const app = document.querySelector('#app')!;

render(html`<h1>Hello, world!</h1>`, app);

html is a tagged template: it parses the string into a real DOM fragment and returns a View. render(view, node) appends that fragment to the element you pass and returns a disposer, so a mounted tree can be torn down completely later.

Read more about templates →

2. Make it reactive

main.ts
const name = sig('Alice');

render(html`<h1>Hello, ${name}!</h1>`, app);

name.update('Bob'); // only the text node changes

sig creates a signal — a value container. Interpolating a signal in a content position upgrades it to a text() view automatically, so ${name} and ${text(name)} are equivalent. When name.update('Bob') runs, Sigula writes to just that text node and touches nothing else.

Read more about signals →

3. Handle events and patch attributes

main.ts
const count = sig(0);
const color = compute(count, (v) => (v >= 0 ? 'green' : 'red'));

html`<p ${patch(style('color', color))}>${count}</p>`;

Text belongs in a content position, but dynamic attributes belong in an attribute position and must be wrapped in patch(...). Here compute derives color from count, and style('color', color) keeps the inline style in sync. on('click', …) registers the listener once at mount; writing to a signal inside it is what drives updates.

Read more about patch →

4. Split into components

counter.ts
const Counter = (initial: number): View => {
  const count = sig(initial);
  return html`<div>
    <span>${count}</span>
    <button ${patch(on('click', () => count.trans((v) => v + 1)))}>+1</button>
  </div>`;
};

There is no component class, lifecycle, or registration — a component is just a function that returns a View. Because the function body runs exactly once, sig(initial) is the local state; there are no hooks and no re-run semantics to reason about.

Read more about the architecture →

5. Render lists

lists.ts
import {html, list, repeat, sig} from 'sigula';

const fruits = ['apple', 'banana', 'cherry'];      // static — rendered once
const todos = sig([{id: 1, label: 'write docs'}]); // reactive — keyed

html`<div>
  <ul>${list(fruits, (fruit) => html`<li>${fruit}</li>`)}</ul>

  <ul>${repeat(todos, {
    key: (t) => String(t.id),
    view: (t) => html`<li>${t.label}</li>`,
  })}</ul>
</div>`;

Use list(items, viewFn) for a fixed array: it calls viewFn once per item and appends the results, with no keying or reconciliation. Use repeat(sig, {key, view}) for a reactive array: it matches items by key and reuses, moves, creates, or removes as few DOM nodes as possible.

Read more about control flow →

6. Control flow

conditional.ts
import {compute, html, sig, text, view} from 'sigula';

const count = sig(0);
const isEmpty = compute(count, (v) => v === 0);

html`<div>${view(isEmpty, (empty) =>
  empty ? text('nothing yet') : html`<p>count: ${count}</p>`,
)}</div>`;

compute turns one signal into another: here isEmpty is derived from count. view(sig, viewFn) then swaps the rendered view whenever that signal changes — when count becomes non-zero the empty message is replaced with the paragraph, and the old view is torn down.

Read more about derived signals →

Demo

Equation

Equation.ts
import {compute, html, on, patch, sig, type Sig, type View} from 'sigula';

export const Equation = (): View => {
  // --- State: two writable signals hold the inputs ---
  const x = sig(0);
  const y = sig(1);

  // --- Derived state: compute() reads the source signals and re-runs only
  // when one of them changes. Each result is itself a signal you can bind. ---
  const s = {x, y};
  const sum = compute(s, (v) => v.x + v.y);
  const diff = compute(s, (v) => v.x - v.y);
  const product = compute(s, (v) => v.x * v.y);
  const quotient = compute(s, (v) => (v.y === 0 ? Number.NaN : v.x / v.y));
  const squareDiff = compute(s, (v) => v.x * v.x - v.y * v.y);

  // Renders one input: its current value plus two buttons. Pressing a button
  // writes to the signal with trans(); every derived value above then updates.
  const stepper = (label: string, value: Sig<number>): View => html`
    <div class="flex items-center justify-between gap-2">
      <span class="font-mono text-sm text-[var(--text-h)]">${label} = ${value}</span>
      <span class="flex gap-1">
        <button ${patch(on('click', () => value.trans((v) => v - 1)))} class="rounded-md border border-[var(--border)] bg-[var(--bg)] px-2 py-0.5 text-xs text-[var(--text-h)] transition hover:border-[var(--accent-border)]">-1</button>
        <button ${patch(on('click', () => value.trans((v) => v + 1)))} class="rounded-md border border-[var(--border)] bg-[var(--bg)] px-2 py-0.5 text-xs text-[var(--text-h)] transition hover:border-[var(--accent-border)]">+1</button>
      </span>
    </div>`;

  // Renders a label and a derived result. Interpolating a signal in a content
  // position creates a binding from that signal to this one text node.
  const row = (label: string, result: Sig<number>): View => html`
    <div class="flex items-baseline justify-between gap-3 border-b border-[var(--border)] py-1.5 last:border-0">
      <span class="text-sm text-[var(--text)]">${label}</span>
      <span class="font-mono text-sm text-[var(--text-h)]">${result}</span>
    </div>`;

  // The component function runs exactly once, so the signals above are its
  // state and these bindings live until the view is disposed.
  return html`<div class="rounded-xl border border-[var(--border)] bg-[var(--bg-soft)] p-4">
    <div class="grid gap-2">
      ${stepper('x', x)}
      ${stepper('y', y)}
    </div>
    <div class="mt-4">
      ${row('sum: x + y', sum)}
      ${row('difference: x - y', diff)}
      ${row('product: x * y', product)}
      ${row('quotient: x / y', quotient)}
      ${row('x² - y²', squareDiff)}
    </div>
  </div>`;
};

How it works

  1. State. Two writable signals, x and y, hold the inputs.
  2. Derive. compute({x, y}, …) produces sum, difference, product, quotient and x² − y². Each derived signal recomputes only when x or y changes.
  3. Bind. Every result is interpolated into the template, so Sigula keeps a binding from the signal to that exact text node.
  4. Update. The +1 / −1 buttons call x.trans / y.trans to write a new value; queued bindings then update only the affected nodes.

Live demo

x = 0
y = 1
sum: x + y 1
difference: x - y -1
product: x * y 0
quotient: x / y 0
x² - y² -1

Todos

Todos.ts
import {
  compute,
  html,
  on,
  patch,
  repeat,
  sig,
  style,
  type Sig,
  type View,
  val,
  view,
} from 'sigula';

interface Todo {
  id: number;
  text: string;
  done: Sig<boolean>;
}

export const Todos = (): View => {
  // --- State ---
  const input = sig(''); // what the user is typing
  const todos = sig<Todo[]>([
    // seeded with a mix of active and done items
    {id: 1, text: 'Learn signals', done: sig(true)},
    {id: 2, text: 'Try the Equation demo', done: sig(false)},
    {id: 3, text: 'Read Core Concepts', done: sig(true)},
    {id: 4, text: 'Build something', done: sig(false)},
  ]);
  const filter = sig<'all' | 'active' | 'done'>('all');

  // --- Derived state ---
  // compute() re-runs when todos or filter change. It also reads each todo's
  // nested `done` signal, so toggling one must call todos.notify() (see toggle).
  const visible = compute({todos, filter}, (v) => {
    switch (v.filter) {
      case 'active':
        return v.todos.filter((t) => !t.done.get());
      case 'done':
        return v.todos.filter((t) => t.done.get());
      default:
        return v.todos;
    }
  });

  // An empty list is a separate derived signal so the view can swap cleanly.
  const isEmpty = compute(visible, (v) => v.length <= 0);

  // --- Actions ---
  // trans() replaces the array with a new one, so the signal sees a new value.
  const add = (event: Event): void => {
    event.preventDefault();
    if (!input.get().trim()) return;
    todos.trans((items) => [
      ...items,
      {id: Date.now(), text: input.get().trim(), done: sig(false)},
    ]);
    input.update('');
  };

  const remove = (id: number): void => {
    todos.trans((items) => items.filter((item) => item.id !== id));
  };

  // Flip the todo's own `done` signal, then notify() the list so the derived
  // `visible` list recomputes (nested signal reads are not tracked by compute).
  const toggle = (item: Todo): void => {
    item.done.trans((v) => !v);
    todos.notify();
  };

  // One row per todo: clicking the label toggles it, and style() keeps the
  // strikethrough in sync with the todo's `done` signal.
  const itemView = (item: Todo): View => html`<li class="flex items-center justify-between gap-2 border-b border-[var(--border)] py-1.5 last:border-0">
    <span
      ${patch(
        on('click', () => toggle(item)),
        style('textDecoration', compute(item.done, (v): string => (v ? 'line-through' : 'none'))),
      )}
      class="cursor-pointer select-none"
    >${item.text}</span>
    <button ${patch(on('click', () => remove(item.id)))} class="rounded-md px-2 text-[var(--text)] transition hover:text-[var(--accent)]">×</button>
  </li>`;

  const filterButton = (value: 'all' | 'active' | 'done'): View => html`<button type="button" ${patch(on('click', () => filter.update(value)))} class="rounded-md border border-[var(--border)] px-2 py-0.5 text-xs text-[var(--text)] capitalize transition hover:border-[var(--accent-border)]">${value}</button>`;

  // --- View ---
  // val(input) keeps the field's value in sync; view(isEmpty) swaps between the
  // empty message and the list; repeat() keys items by id, moving the fewest
  // nodes when the list changes.
  return html`<div class="rounded-xl border border-[var(--border)] bg-[var(--bg-soft)] p-4">
    <form ${patch(on('submit', add))} class="flex gap-2">
      <input ${patch(
        val(input),
        on('input', (event) => {
          const target = event.target;
          if (target instanceof HTMLInputElement) input.update(target.value);
        }),
      )} placeholder="What needs doing?" class="min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--bg)] px-2 py-1 text-sm text-[var(--text-h)] outline-none focus:border-[var(--accent-border)]" />
      <button type="submit" class="rounded-md bg-gradient-to-r from-[var(--accent-strong)] to-[var(--accent-strong-to)] px-3 py-1 text-sm font-medium text-white transition hover:opacity-90">Add</button>
    </form>
    <div class="my-3 flex gap-1">
      ${filterButton('all')}${filterButton('active')}${filterButton('done')}
    </div>
    ${view(isEmpty, (empty) =>
      empty
        ? html`<p class="py-4 text-center text-sm text-[var(--text)]">Nothing here yet.</p>`
        : html`<ul>
            ${repeat(visible, {key: (item) => String(item.id), view: (item) => itemView(item)})}
          </ul>`,
    )}
  </div>`;
};

How it works

  1. State. input, todos, and filter are signals, and each todo's done flag is itself a signal.
  2. Derive. visible = compute({todos, filter}, …) filters the list, and isEmpty = compute(visible, …) drives the empty state.
  3. Mutate. Adding and removing replace the todos array via trans; toggling a todo flips its done signal and calls todos.notify() so the derived list recomputes.
  4. Render. view(isEmpty) swaps between the empty message and the list, and repeat keys items by id so only the necessary nodes move.

Live demo

  • Learn signals
  • Try the Equation demo
  • Read Core Concepts
  • Build something

Core Concepts

The whole architecture in one picture

Sig holds a value + a list of Binds state
Bind { sig, context, cmd } the edge
Cmd (value, context) => void the work
View { node, boundary(), cleanBinds() } DOM region
Patch deferred commands for one element DOM region
Queue one global microtask, coalesced per Bind scheduling

Everything else in the library is a convenience layer over these five pieces: a signal holds a value and a list of bindings; a binding is {sig, context, cmd}; a command does the work; a view is a DOM region; and a patch is a set of deferred commands for one element.

Signals: sig

A Sig<T> is a value container that owns a list of bindings. It never touches the DOM itself.

signals.ts
const count = sig(0);

count.get();              // 0 — read the current value
count.update(1);          // set; dependents notified only if not deeply equal
count.update(1);          // no-op: deeply equal, nothing is scheduled
count.forceUpdate(1);     // set and always notify (even when equal)
count.trans((v) => v + 1);// apply a function to the current value
count.notify();           // re-run dependents without changing the value
MethodPurpose
get()Read the current value.
update(v)Write, skipping the notification when eq(v, current).
forceUpdate(v)Write and always notify. Use after a structurally-equal-but-new value.
trans(fn)update(fn(current)) — the idiomatic way to derive the next state.
notify()Re-run dependents against the current value. Use after mutating a held object/array in place.
addBind / removeBind / getBindsLow-level binding management; prefer createBind or the template APIs.

Equality is deep by default: update compares with eq, delegating to a.equals(b) when the value implements Equatable. sig(v, {eq}) accepts a custom comparator.

In-place mutation needs notify(). Sigula does not proxy your objects, so mutating a held array or object is invisible to update:

mutation.ts
const items = sig<string[]>([]);
items.get().push('a');   // value object mutated, no write detected
items.notify();          // ← tell dependents to re-run

Bindings: the unit of reactivity

A binding is a three-field record — the entire reactive primitive:

bind.ts
interface Bind<T, C> {
  sig: Sig<T>;                    // what it observes
  context: C;                     // where the result goes (a text node, an element, …)
  cmd: (val: T, ctx: C) => void;  // what to do with the new value
  removed: boolean;
  queued?: boolean;
}

So "fine-grained" is literal: text(name) creates a bind whose context is one Text node and whose cmd is node.textContent = String(val). Nothing else in the tree is involved.

bindings.ts
const name = sig('Alice');
const v = text(name);   // Bind{ sig: name, context: {node: <Text>}, cmd: textCmd }

name.update('Bob');     // → textCmd('Bob', {node}) → that one node changes

Because a Cmd is just a function, the same model covers DOM writes, derived values, and arbitrary side effects: compute(source, fn) is a bind that writes to another signal, and effect(source, fn) is a bind that runs fn with the new value — immediately and on every change — and returns a disposer.

Derived signals: compute

compute returns a DerivedSig<T>, which is a Sig you cannot write to. Two overloads:

compute.ts
const x = sig(1);
const doubled = compute(x, (v) => v * 2);          // from one signal

const sum = compute({x, y}, (v) => v.x + v.y);     // from a record of signals

With the record form, fn receives the matching record of values (ValRecord<S>), fully typed. Derived signals compose: a DerivedSig is a valid source for another compute, and a valid interpolation target in a template.

Derived signals are lazy about upstream. A DerivedSig detaches from its sources when it loses its last consumer (which happens whenever a view() subtree is hidden), and re-links and recomputes once when a consumer comes back. You get the memory savings without manual disposal.

Templates: html

html.ts
const html = (strs: TemplateStringsArray, ...rawItems: HtmlItem[]): View;

html is a tagged template over native HTML strings — no compiler, no DSL, no JSX pragma. Interpolations fall into two positions, and the distinction is the one rule to memorize:

PositionWhat goes thereExample
Content (child slot)a View, text, raw, a Sig, or any primitive<h1>${name}</h1>
Attribute (inside a tag)a Patch from patch(...)<input ${patch(val(name))} />

Anything interpolated in a content position that is not already a View or Patch is coerced with text(), i.e. escaped and rendered as String(value):

coercion.ts
const sigItem  = sig('signal item');
const strItem  = 'string data';
const numItem  = 2026;
const htmlItem = html`<span>Html Span Element</span>`;

render(
  html`<p>${sigItem} / ${strItem} / ${numItem}</p>
       <div>${htmlItem}</div>
       <div>${raw('<strong>Trusted</strong> HTML')}</div>`,
  app,
);

sigItem.update('string with <strong>markup</strong>'); // stays escaped — renders as text

raw(source) parses its value through a detached <template> and mounts the resulting nodes with no wrapper element. It does not escape — only ever pass trusted HTML.

How parsing works (and why it is fast)

Every call site gets a random marker, @sig_<rand>. Interpolations are rendered into the template string as:

  • an attribute marker @sig_x for a Patch,
  • a comment marker <!--@sig_x--> for a View.
template.html
<div @sig_2734618> <!--@sig_2734618<!--@sig_2734618--> <!--@sig_2734618 <!--@sig_2734618--> </div>

Therefore parsing needs no regular expressions: Sigula walks the parsed fragment with a single TreeWalker, collects each marker node in order, and commits the matching item (commitPatch for elements, commitView for comments). The uniform format is also what makes the API extensible — id, on, attr, style are all just patch items, and you can write your own.

Two consequences worth knowing:

  1. One Patch per element. The marker is an attribute, so a second patch() on the same element cannot be located. Combine everything into a single patch(...) call — that is what its variadic form is for.
  2. Templates are cached per call site (a WeakMap on the TemplateStringsArray), and the cache key includes the mix of patch/view slots (a bitmask for up to 31 slots, a string beyond that). Repeated renders skip parsing entirely; a call site that changes its interpolation mix simply gets a fresh template.

The returned View is {node, children, boundary(), cleanBinds()} — see Boundaries.

Patching an element: patch

patch declares bindings to apply to one element. It accepts either a props object, or a list of command items, or both:

patch.ts
// Props form — desugared into commands
html`<input ${patch({id: 'name', val: name, placeholder: 'Your name'})} />`

// Command form
html`<input ${patch(val(name), attr('placeholder', placeholder))} />`

The props object handles id, val, class, style, styleProp, on; any other key becomes an attribute. A key whose value is undefined is skipped.

CommandWhat it does
id(source)Sets element.id.
val(source)Sets the value property (form controls).
attr(key, source)setAttribute(key, …) — boolean/ARIA/data attributes.
style(key, source)Sets a typed inline style property.
styleProp(key, source)style.setProperty — for --custom-properties.
toggleClass(token, source)Toggles one class from the truthiness of the value.
toggleClasses(tokens, source)Toggles several classes from one value.
on(type, listener, options?)addEventListener.
act(source, fn)Escape hatch: run arbitrary code with (element, value).

Every command takes a plain value (applied once at mount) or a Sig (applied at mount and re-applied on change):

patch-values.ts
const disabled = sig(false);
const label = 'Submit';

html`<button ${patch(attr('disabled', disabled), attr('aria-label', label))}>Go</button>`
//                     ↑ reactive                     ↑ static

Note that on registers the listener once at mount; the listener itself is not a reactive source. Drive updates by writing to a signal inside it.

Control flow

Sigula has exactly four control-flow helpers, all returning a View:

HelperUse it for
view(sig, viewFn)Swap one view for another when sig changes (conditional rendering).
repeat(sig, {key, view, eq?})Keyed list rendering with minimal DOM reuse/moves.
list(items, viewFn)A static array rendered once — no keying, no reconciliation.
frag(...views)Compose several views as flat siblings with no wrapper element.
control-flow.ts
// conditional
${view(isEmpty, (empty) => (empty ? text('empty') : listView))}

// keyed list
${repeat(todos, {
  key: (t) => t.id.toString(),
  view: (t) => html`<li>${text(t.text)}</li>`,
  eq: (a, b) => a.id === b.id && a.text === b.text, // optional, defaults to eq
})}

repeat matches items by key with a two-pointer walk, reusing, moving, creating, or removing as few nodes as possible, and uses moveBefore when available to preserve element state across moves. When nothing changed — same keys, same order, equal items — it bails out before touching the DOM at all. Use list instead when the array never changes shape.

Boundaries and teardown

A View occupies a contiguous range of sibling nodes, described by boundary(): {start, end} — this is how Sigula swaps or removes multi-node regions without a wrapper element or a virtual tree. The returned view is {node, children, boundary(), cleanBinds()}.

Teardown is explicit and recursive:

teardown.ts
const dispose = render(App(), app);
dispose();   // removeBoundary(view.boundary()) + view.cleanBinds()

cleanBinds() detaches the view's own bind and, recursively, all child binds. When a Sig loses its last bind it calls cleanup(), so a subtree that is removed stops receiving updates immediately — no manual effect cleanup, no leak by default.

The update queue

Writes never run synchronously. Every write pushes the signal's binds onto one global queue and schedules a single queueMicrotask.

  • Batched across signals — many writes, one flush.
  • Coalesced per binding — each binding runs once and reads the newest value.
  • Error-isolated — a throwing binding is logged and the rest of the queue still runs.
queue.ts
sig0.update(a);   // ┐
sig1.update(b);   // ├── one microtask
sig2.update(c);   // ┘

sig.update(1); sig.update(2); sig.update(3);
// → each dependent binding runs ONCE, against 3

What Sigula deliberately does not have

Not includedWhy
Virtual DOM / diffingUpdates are bound at mount time; there is nothing to diff.
A component instance or lifecycleA component is a function that returns a View, and it runs once.
A compiler / build stepTemplates are native tagged-template strings.
A router, store, or SSR runtimeOut of scope. Sigula is the rendering and reactivity layer; bring your own.
Proxy-based deep reactivityValues are compared, not wrapped. Mutate in place and call notify().
Automatic dependency trackingBindings are explicit (sig → cmd → target), which keeps the runtime at ~4.5KB.

API Cheat Sheet

All exports are named exports from sigula. This page is a quick map; the generated API reference has full signatures and TSDoc for every export.

ExportKindReturns
sig(v, opts?)stateSig<T>
compute(sig, fn) / compute(record, fn)derivedDerivedSig<T>
effect(sig, fn) / effect(record, fn)reactivitydisposer () => void
htmltemplateView
text(source)templateView (escaped text node)
raw(source)templateView (unescaped HTML)
patch(props | …items)bindingPatch
id, val, attr, style, styleProp, toggleClass, toggleClasses, on, actpatch commandsToPatchItem<T>
view(sig, viewFn)control flowView
repeat(sig, {key, view, eq?})control flowView
list(items, viewFn)control flowView (static)
frag(...views)compositionView
render(view | () => view, node)mountingdisposer () => void
createBind, removeBind, eq, toBoundary, walkBoundarylow-level—
Sig, DerivedSig, View, Patch, Reactive<T>, Eq<T>, Equatabletypes—

Errors

Runtime errors carry a short code in message instead of a sentence. Codes with arguments are colon-separated.

CodeThrown byMeaning
E1:<index>atArray index out of range.
E2toBoundaryCannot build a boundary from an empty fragment.
E3replaceWithNodeThe old boundary has no parentNode.
E4patchA keyed command (attr, style, styleProp, toggleClass) was given no key.
E5patchact was given no function.
E6patchon was given no event type.
E7repeatThe rendered items have no parent node.
E8repeatThe temporary start/end fences were removed mid-update.
E9repeatThere is no node after the fence to move before.
E10htmlThe template is empty.
E11:<expected>:<got>htmlInterpolation count does not match the template slots.
E12htmlUnmatched interpolation; patch() must be in attribute position.

How it compares

SigulaLitSolidReact
Update modelSignal → bind → DOM nodeProperty → render() → part commitSignal → compiled DOMComponent re-render → VDOM diff
Compiler requiredNoNoYes (JSX/babel)Yes (JSX)
Component re-runsNeverOn property changeNeverOn every state change
Approx. size~4.5KB min+gzip~5KB~7KB— (much larger runtime)
TemplatingNative tagged templatesTagged templatesJSXJSX
Standard Web ComponentsNo (any DOM node)YesNoNo

Size figures are each project's own published claim, measured with different tooling and feature sets — treat them as an order of magnitude, not a benchmark.

sigula — MIT License · zjh · GitHub