Skip to content

EchoX ​

EchoX gives you Lit's templates, Solid's reactivity and D3's data joins — and no build step.

It works out of the box without the need for compilation or transpilation while still providing the following benefits:

  • Fine-grained reactivity
  • Readable templates
  • Native DOM, no virtual DOM

The philosophy for EchoX is UI = f(reactive, template), and APIs are designed around it: reactive declares reactive state, and html / svg turn markup into real DOM nodes.

js
import {reactive, html} from "echox";

function Counter({initial = 0} = {}) {
  return reactive()
    .state("count", initial)
    .computed("double", (d) => d.count * 2)
    .effect((d) => console.log(d.count, d.double))
    .view(
      (d) =>
        html`<div>
          <button ${{onclick: () => d.count++}}>👍</button>
          <button ${{onclick: () => d.count--}}>👎</button>
          <span>${() => d.count} doubled is ${() => d.double}</span>
        </div>`,
    );
}

document.body.append(Counter({initial: 3}));

One Shape for Every Component ​

A component is reactive(), any number of state, computed and effect declarations, and a terminating view that returns the DOM. Every callback in that chain receives the reactive scope as its first argument, conventionally named d, so the chain reads uniformly.

The shape is Vue 2's Options API: state, computed, effect and view stand where data, computed, watch and render stood, so a component's whole surface is readable in one pass. Unlike an options object, though, each one is a method call, so declarations group by concern rather than by kind — see Composing concerns. Declaration order never matters, and each declaration is tracked on its own, so a write re-runs only the bindings that read it instead of re-rendering the component.

js
reactive()
  .state("count", 0)
  .computed("double", (d) => d.count * 2)
  .effect((d) => console.log(d.count))
  .view((d) => html`<span>${() => d.double}</span>`);

view returns a native DOM node, so it can be appended anywhere — and interpolated straight into another template. Wrap the chain in a function to get a reusable component whose instances each hold their own state:

js
function Counter({initial = 0} = {}) {
  return reactive()
    .state("count", initial)
    .view((d) => html`<button ${{onclick: () => d.count++}}>${() => d.count}</button>`);
}

html`<div>${Counter({initial: 0})} ${Counter({initial: 10})}</div>`;

Props are ordinary function arguments, and a reactive prop is just a getter — so a piece of UI with no state of its own needs no reactive() at all:

js
function Toggle({label, onToggle}) {
  return html`<button ${{onclick: onToggle}}>${label}</button>`;
}

// The child tracks the parent's state through the getter it was handed.
Toggle({label: () => d.theme, onToggle: () => (d.theme = "dark")});

Composing Concerns ​

Because every declaration is a method call rather than a key in a fixed options object, a concern can be a plain function that takes the builder and adds whatever it needs — state, computed values and effects together, in one place:

js
function pagination(r, {size}) {
  return r
    .state("page", 0)
    .state("size", size)
    .computed("offset", (d) => d.page * d.size)
    .effect((d) => history.replaceState(null, "", `?page=${d.page}`));
}

function selection(r) {
  return r.state("selected", null).computed("hasSelection", (d) => d.selected !== null);
}

const table = selection(pagination(reactive(), {size: 10}))
  .state("rows", [])
  .view((d) => html`…`);

This is the part Vue 2's Options API could not do — a feature's data, computed and watch had to be split across three options — and the part Vue 3's Composition API bought by giving up the named structure. Keeping the names as methods gives both: state, computed and effect still say what each declaration is, while grouping is yours to choose.

Since declaration order never matters, a concern may read state that another concern declares, and a chain can be built in a loop or extended conditionally:

js
const r = reactive().state("count", 0);
if (debug) r.computed("label", (d) => `count=${d.count}`);
const node = r.view(render);

The one boundary is that declarations come before scope or view: the definitions are read once, when the scope is materialized, so one added afterwards would never be seen and throws instead.

Granular State Observation ​

State is observed per binding, so an update touches only the bindings that read the state that changed, never a whole subtree. (Similar to SolidJS.)

Any function in a template is a reactive binding. It is re-run when state it read changes. A function that reads no state collects no dependencies and simply runs once, which is why the same rule covers both reactive bindings and plain data callbacks.

js
html`<div ${{class: () => d.theme}}>
  <!-- reactive attribute -->
  Count: ${() => d.count}
  <!-- reactive text, anywhere in a text node -->
  ${() => (d.show ? html`<p>visible</p>` : null)}
  <!-- reactive children -->
</div>`;

Data-Driven Templates ​

EchoX has data-driven tagged template literals for HTML and SVG, so data, markup and mapping stay clearly connected in one place.

js
const chart = svg`<svg ${{width: 200, height: 100}}>
  <circle ${{
    data: circles,
    cx: (d) => d.x,
    cy: (d) => d.y,
    r: (d) => d.r,
  }} />
</svg>`;

The style is inspired by D3.js. D3 excels at dynamic, data-driven DOM updates with a rich API; these templates aim at the same mapping with a lighter syntax, and add reactivity on top.

Creating Elements ​

There are two tagged template literals for creating HTML and SVG elements: html and svg.

js
html`<h1>Hello, EchoX!</h1>`;

If multiple top-level nodes are given, the nodes are implicitly wrapped in a document fragment.

js
html`
  <h1>Hello A</h1>
  <h1>Hello B</h1>
  <h1>Hello C</h1>
`;

Markup is parsed with a template element, so fragments that an HTML parser would otherwise relocate — a bare <tr>, <td> or <option> — are preserved:

js
html`<tr>
  <td>1</td>
</tr>`; // a <tr> element, not a stray text node

Setting Attributes ​

You can set attributes (or styles, event listeners) by interpolating an object in place of attributes.

js
html`<h1 ${{id: "title", className: "heading1"}}></h1>`;

An interpolation must stand in for a whole attribute object; interpolating a single attribute's value throws, so the mistake is reported rather than rendered.

js
html`<h1 class="${name}"></h1>`; // throws
html`<h1 ${{class: name}}></h1>`; // do this

Anything else in that position that is not an attribute object throws too, so the mistake is never silently dropped. A falsy interpolation is allowed and adds nothing, which makes a conditional group of attributes read naturally:

js
html`<h1 ${{id: "title"}} ${active && {class: "active"}}></h1>`;

null, undefined and false unset an individual attribute, the same three values that skip a child. A callback that returns nothing therefore leaves the attribute off rather than writing the word undefined, and on && "active" leaves no class:

js
html`<div ${{class: () => on && "active"}}></div>`;

Kebab-case attributes are typically specified in snake_case:

js
html`<button ${{aria_label: "Close", aria_expanded: "false"}}></button>`;

But you can also specify them in kebab-case if you prefer:

js
html`<button ${{"aria-label": "Close", "aria-expanded": "false"}}></button>`;

Styles are typically specified with the prefix "style_" or "style-":

js
html`<div
  ${{
    style_background: "steelblue",
    style_width: "100px",
  }}
></div>`;

If an attribute starts with "on", it is treated as an event listener. Listeners receive (event, node, d, i, data), where the last three are undefined outside a data join. Listeners are not reactive; re-running one would only re-register it.

js
html`<button ${{onclick: () => alert("Hello, EchoX!")}}>Click me!</button>`;

If the value is a function, it is evaluated with (d, i, data, node) — the current datum, its index, the whole data array and the current node — and the result is used to set the attribute. Outside a data join the first three are undefined:

js
html`<div ${{id: (d, i, data, node) => node.tagName}}></div>`;

Appending Nodes ​

If an interpolated value is a node, it is inserted at that location.

js
html`<div>${svg`<svg></svg>`}</div>`;

You can interpolate multiple nodes at once by using an array:

js
html`<ul>
  ${[html`<li>Item 1</li>`, html`<li>Item 2</li>`]}
</ul>`;

null, undefined and false are skipped, and nested arrays are flattened. 0 is kept and rendered as text. Any other value is coerced to a string.

js
html`<ul>
  ${[[null, false], [html`<li>Item 1</li>`]]}
</ul>`;

Interpolations work anywhere in a text node, including several in one:

js
html`<p>${a} and ${b}</p>`;
html`<span>Count: ${count} items</span>`;

Binding Data ​

If a data attribute is specified, the data is mapped to a list of nodes and appended to the parent node. For other attributes, a constant gives every node the same value; a function is evaluated per node with (d, i, data, node).

js
const items = ["red", "green", "blue"];

svg`<svg>
  <circle ${{
    data: items,
    r: 10, // constant value
    fill: (d) => d, // function value
    cx: (d, i) => i * 100,
    cy: 50,
  }} />
</svg>`;

This is equivalent to the following, but with a more concise structure:

js
svg`<svg>${items.map((d, i) => svg`<circle ${{r: 10, fill: d, cx: i * 100, cy: 50}} />`)}</svg>`;

A child node can access its ancestor's data through function attributes.

js
svg`<svg>
  <g ${{data: items, transform: (d, i) => `translate(0, ${i * 100})`}}>
    <circle ${{r: 10, fill: (d) => d}} />
  </g>
</svg>`;

A child can also be a function, evaluated for each node with the same parameters.

js
svg`<svg>
  <g ${{data: items}}>${(d, i) => svg`<circle ${{r: 10, fill: d}} />`}</g>
</svg>`;

If the child's data is itself a function, it is evaluated per parent node, which is useful for nested data such as a table.

js
const table = [
  [11975, 5871, 8916],
  [1951, 10048, 2060],
];

html`<table>
  <tbody>
    <tr ${{data: table}}>
      <td ${{data: (d) => d, textContent: (d) => d}} />
    </tr>
  </tbody>
</table>`;

When data is a function, the join becomes reactive: changing the state it reads rebuilds the nodes.

js
reactive()
  .state("items", ["a", "b"])
  .view(
    (d) =>
      html`<ul>
        <li ${{data: () => d.items, textContent: (v) => v}} />
      </ul>`,
  );

A callback that takes the datum can read reactive state too, so each datum updates independently:

js
svg`<circle ${{data: () => d.points, r: (p) => p.r * d.scale}} />`;

Getting Started ​

Installing from a Package Manager ​

sh
$ npm add -S echox
sh
$ pnpm add -S echox
sh
$ yarn add -S echox
js
import {html} from "echox";

document.body.append(html`<span>hello world</span>`);

Imported as an ES Module ​

html
<script type="module">
  import {html} from "https://cdn.jsdelivr.net/npm/echox/+esm";

  document.body.append(html`<span>hello world</span>`);
</script>

UMD Bundle ​

html
<script src="https://cdn.jsdelivr.net/npm/echox"></script>
<script>
  document.body.append(ex.html`<span>hello world</span>`);
</script>

API Index ​

reactive() ​

Returns a builder used to declare state and effects. Chain state, computed and effect in any order, then end with view to render the DOM, or with scope for the scope alone. The builder collects definitions; nothing is materialized until one of those runs.

js
reactive()
  .state("n", 0)
  .computed("double", (d) => d.n * 2);

Because the builder and the scope are separate objects, method names are not reserved — state, effect and view are all usable as state names.

The definitions are read once, when the scope is materialized, so declaring after that throws: a state added later would be a plain property of the scope rather than a reactive one, and an effect added later would never run.

reactive.state(key, value) ​

Declares a state named key with initial value. Inside view, computed and effect, the scope exposes key as a readable and assignable property; assigning to it schedules an update of every binding, computed and effect that read it. Updates are batched, so several writes in one turn produce one update.

js
reactive().state("count", 0).state("label", "go");

reactive.computed(key, define) ​

Declares a derived state under key. define is (scope) => value and may read other fields on the scope. Computed values resolve on first read and recompute when their dependencies change, so declaration order does not matter.

js
reactive()
  .state("x", 2)
  .computed("area", (d) => d.x * d.x);

Computed state is brought up to date before any effect or binding that reads it runs, so a value derived from a state is never observed one write behind the state itself — not even through a chain of computeds. An effect reading both count and a double derived from it therefore sees one consistent pair per write, and runs once:

js
const d = reactive()
  .state("count", 1)
  .computed("double", (d) => d.count * 2)
  .effect((d) => console.log(d.count, d.double)) // Logs 1 2.
  .scope();

d.count = 3; // Logs 3 6, and only that — never 3 2 first.

A computed whose own value never settles is a circular dependency like any other: updates are abandoned after a thousand passes and the reason is logged. The effects waiting on it keep the last value they saw rather than running on a moving one.

A computed key is the define's to write, so assigning to one from outside throws: the write would otherwise replace the derived value with a constant and the key would quietly stop deriving. Write the state it derives from instead. A define that throws leaves the key unresolved rather than resolved to undefined, so the next read runs it again.

reactive.effect(effect) ​

Registers a side effect. Effects run once when scope or view is called — after every definition is registered — and again whenever state they read changes. If effect(scope) returns a function, it is treated as a cleanup: it runs before the effect re-runs, and once more when the view is disposed.

js
reactive()
  .state("n", 0)
  .effect((d) => {
    const id = setInterval(() => console.log(d.n), 1000);
    return () => clearInterval(id);
  });

An effect may write state it also reads, which is how a value is normalized as it changes. Its own write re-runs it, so the write has to settle — write the same value the second time, and the effect stops there:

js
reactive()
  .state("page", 1)
  .state("pages", 10)
  .effect((d) => (d.page = Math.min(Math.max(d.page, 1), d.pages)));

One that never settles, such as d.n++, is a circular dependency: updates are abandoned after a thousand passes and the reason is logged.

reactive.scope() ​

Materializes the scope, runs the effects and returns the scope. Use it for state that is not tied to one view — a store several views read, or state driven from outside a template.

js
const store = reactive().state("theme", "light").scope();

html`<span>${() => store.theme}</span>`;
html`<button ${{onclick: () => (store.theme = "dark")}}>dark</button>`;

scope is idempotent, and view calls it internally, so calling both is safe: the scope is created and the effects run exactly once.

js
const rx = reactive().state("n", 0);
const d = rx.scope();
const node = rx.view(() => html`<span>${() => d.n}</span>`);

Nothing is mounted, so nothing disposes a scope made this way on its own — call dispose when you are done with it.

reactive.view(render) ​

Calls scope, then render(scope), and returns the node it produced.

The node is rendered under the builder's owner, which is what ties its bindings to the builder: dispose stops them. Removing the node from the document does not, because echox hands you real nodes and does not own the page, so it cannot know whether a node is gone for good or on its way somewhere else. Lifetime is yours to end.

js
const rx = reactive().state("n", 0);
const node = rx.view((d) => html`<button ${{onclick: () => d.n++}}>${() => d.n}</button>`);

document.body.append(node);

node.remove();
rx.dispose(); // bindings stop, effect cleanups run

You rarely need this. A component that lives as long as the page needs no teardown at all, and a component created inside another's render is disposed with its parent, because its owner nests under that parent's. One dispose at the point where you appended covers everything below it:

js
const app = reactive().state("route", "home");
document.body.append(app.view(() => html`<main>${Counter()} ${Todo()}</main>`));

app.dispose(); // reaches Counter and Todo as well

The same nesting is why nothing leaks inside a data join: a join disposes the bindings and components of the rows it replaces each time its data changes.

reactive.dispose() ​

Stops every binding and effect under the builder and runs the effect cleanups. It reaches everything created inside its views, nested components included, since each nests under the builder's owner.

Disposing is final: scope and view throw afterwards, rather than handing back a scope whose effects are quietly dead.

js
const rx = reactive()
  .state("n", 0)
  .effect((d) => {
    const id = setInterval(() => d.n++, 1000);
    return () => clearInterval(id);
  });

rx.scope();
rx.dispose(); // the interval is cleared

dispose lives on the builder rather than the scope, so dispose stays usable as a state name.

html`<markup>` ​

Renders the specified markup as HTML and returns the node, or a document fragment if there are several top-level nodes. See Creating Elements.

js
const h1 = html`<h1>Hello, EchoX!</h1>`;

svg`<markup>` ​

Renders the specified markup as SVG and returns the node, or a document fragment if there are several top-level nodes.

js
const chart = svg`<svg ${{width: 100, height: 100}}></svg>`;

track(effect) ​

Runs effect immediately and re-runs it whenever state it read changes. Templates use this for every function binding, which is why any function in a template is reactive. It is exported for reactive work whose result is not a DOM attribute or child — a document title, storage, a canvas, another library.

js
const node = reactive()
  .state("count", 0)
  .view((d) => (track(() => (document.title = `Count: ${d.count}`)), html`<span />`));

Give each call a function of its own. An effect's dependencies and its owner are kept on the function itself, so tracking one function twice would make a single effect that only the first owner could dispose; track throws rather than let that pass.

effect is track with a lifetime: it belongs to the chain that declared it, so it is disposed with the view and may return a cleanup. A track call inside view or scope — as above — is owned the same way. One made outside either belongs to nobody, and keeps running for as long as the state it read exists, so prefer effect wherever there is a chain to put it on.

Released under the MIT License.