JavaScript API
The elements cover most documents. For charts, simulations and anything custom, the same reactive variables are available from JavaScript.
A first script
Here, the HTML declares two variables, g and years, and an empty .bars element. A
script draws one bar per year, and the button resets both numbers:
Growing by
Step by step:
- Find the variables. A page can have more than one set of variables: one page-wide
set, plus one for each
<t-scope>. Every example in these docs sits in its own<t-scope>, so thisyearscan't clash with ayearselsewhere on the page.scopeOf(element)returns the set thatelementbelongs to, which is why it needs an element. Here that'sroot, the<t-scope id="growth">, found by its id. Any element inside it works too:scopeOf(bars)returns the same scope. - Read them in an effect.
scope.effect(fn)runsfnstraight away. While it runs, eachs.get("…")returns the current value and records thatfndepends on it. Here that'sgandyears. - Re-run when they change. When the reader drags
goryears,fnruns again and rebuilds the bars. Each bar's height is a percentage of the tallest one. - Set them from anywhere. The button calls
scope.setValues. The numbers in the text update, and so do the bars, because the effect depends on both values.
On a page without any <t-scope>, everything is page-wide. There, use scopeOf(document)
and skip the id:
const scope = scopeOf(document);
scope.effect((s) => console.log(s.get("years")));
An effect finds its dependencies by running, so you never list them. If an if skips a
s.get, that variable isn't watched until a later run reads it.
Updating a chart builds a bigger example, and covers canvas and chart
libraries.
Importing
Import from the same URL as your <script type="module"> tag. The
browser loads a module once per URL, so /tangle.js and /tangle.js?v=2 would be
two separate copies with separate variables.
import { scopeOf, registerFunction, registerFormat, tangleCall, configure, TangleElement } from "/tangle.js";
Scopes
scopeOf(element) returns the scope an element belongs to: its nearest
<t-scope>, or the page-wide scope. Call
scopeOf(document) for the page-wide scope directly.
| Method | Description |
|---|---|
get(name) | The current value. Inside an effect, also subscribes to it. |
peek(name) | The current value, without subscribing. |
set(name, value) | Sets a value. Everything that depends on it updates. |
setValues({ a: 1, b: 2 }) | Sets several values in one go. |
preview(name, value) | Sets a live value during a drag, edit or menu browse without committing it yet (so previous waits). |
commit(name) | Finishes an active preview, committing the current value. |
revert(name) | Cancels an active preview, restoring the value from before it started. |
define(name, fn) | Defines a computed variable, like <t-let>. fn receives the scope: (s) => s.get("w") * s.get("h"). An expression string also works: define("area", "w * h"). |
eval(expr) | Evaluates an expression against the scope. |
effect(fn) | Runs fn(scope) now, and again whenever a variable it read changes. Returns a function that stops it. |
meta(name) | The variable's settings: { min, max, step, format, color, label, pixelsPerStep }. |
setMeta(name, patch) | Changes some of those settings. |
inspectScope(scope) | Not a method: an export that lists the scope's variables as data, with what each reads and what reads it. See <t-debug>. |
setPending(name, on) | Marks a variable as waiting on a new value, as <t-fetch> does while it reloads. Elements that show it, directly or through other variables, get the class is-stale until setPending(name, false). |
Timing
Effects don't run synchronously on set. They're batched and run in a microtask, so setting
ten variables in a row redraws once. If you need the updated DOM right after a set,
wait a microtask first:
scope.set("years", 12);
await Promise.resolve();
// outputs, formulas and effects are now up to date
Your own elements
TangleElement is the base class of the built-in elements. Extend it to write your own:
// <t-stars expr="rating"></t-stars>
customElements.define("t-stars", class extends TangleElement {
connectedCallback() {
this.watch((s) => (this.textContent = "★".repeat(s.eval(this.getAttribute("expr")))));
}
});
It adds this.scope, this.watch(fn), this.declare(name, initial) and
this.makeDraggable(name). See Your own elements for examples.
Formula DAGs
formulaDag(spec) checks a <t-formula-dag> spec and works out its
layout, without drawing it. It throws an Error that says what's wrong, or returns:
| Key | Description |
|---|---|
formulas | One entry per formula, in spec order: name, symbol, label, uses (the formulas it uses), color (or null), value, format. |
edges | [producer, consumer] pairs, once each. |
layers | The rows, top to bottom. Each lists formula names, plus ids starting with ! for the gaps kept free for long arrows. |
routes | One [producer, …gaps, consumer] chain per edge. |
notes, params | The notes and \tangle{} numbers, with their settings. |
The element itself has el.edges, el.upstream(name) and el.downstream(name). The last two
list every formula that name uses, or that uses it, directly or not.
Signals
The reactive core is exported too, for state that doesn't belong in a scope:
import { signal, computed, effect, untracked } from "/tangle.js";
const count = signal(1);
const double = computed(() => count.value * 2);
const stop = effect(() => console.log(double.value)); // logs 2
count.value = 5; // logs 10, in a microtask
untracked(() => count.value); // read without subscribing
stop();
Functions and formats
| Export | Description |
|---|---|
registerFunction(name, fn) | Makes fn callable by name from every expression. Expressions that already ran re-run. See Your own functions. |
registerFormat(name, fn) | Adds a named format. fn(value) returns a string. |
formatValue(value, format, step) | Formats a value the way the elements do. |
formats | The registry of named formats, as a plain object. |
Function calls
| Export | Description |
|---|---|
tangleCall(fn, { name, params }) | Builds a <t-call> with one argument per parameter of fn, typed by its default. |
parseParams(fn) | Reads a function's parameters and evaluates their defaults: [{ name, value, hasDefault }]. |
Code cells
| Export | Description |
|---|---|
registerEngine(lang, factory) | Lets <t-codecell lang="…"> run another language. Cells waiting on it run once it's registered. |
Configuration
configure(options) changes global defaults. Call it in the same module that imports
tangle.js, before the first formula loads KaTeX, the first <t-vega> loads Vega, or the first
<t-obsplot> loads Plot.
| Option | Default | Description |
|---|---|---|
katexUrl | jsDelivr, KaTeX 0.19.0 | The KaTeX ES module to import. |
katexCssUrl | jsDelivr, KaTeX 0.19.0 | The KaTeX stylesheet, added if the page has none. |
vegaUrl, vegaLiteUrl, vegaEmbedUrl | jsDelivr: Vega 6.4.0, Vega-Lite 6.4.3, vega-embed 7.3.0 | The three Vega scripts, loaded in order. Each is skipped if its global (vega, vegaLite, vegaEmbed) already exists. |
d3Url, plotUrl | jsDelivr: d3 7.9.0, Observable Plot 0.6.17 | The two Plot scripts, loaded in order. <t-graph> loads only d3. Each is skipped if its global (d3, Plot) already exists. |
jsxgraphUrl | jsDelivr, JSXGraph 1.14.0 | The JSXGraph script, skipped if JXG already exists. |
codemirrorUrl, codemirrorViewUrl, codemirrorJsUrl, codemirrorLanguageUrl, lezerHighlightUrl | esm.sh: codemirror 6.0.2, @codemirror/view 6.43.15, @codemirror/lang-javascript 6.2.5, @codemirror/language 6.13.1, @lezer/highlight 1.2.5 | The ES modules of the <t-codecell> editor. They must share one copy of @codemirror/state and @codemirror/view. |
pixelsPerStep | 5 | The default drag sensitivity. |