Runtime API
The @qatjs/core package (the runtime; qat is the command) is what compiled .qx code calls. You can also use it directly from plain
JavaScript. Every js example below is executed by scripts/test/docs.test.ts; check(a, b)
there throws if a !== b. The @qatjs/core/sync example needs a relay and is not run.
Entry points: @qatjs/core (the core: 4,194 B gzip, under its 4.2 kB budget) and, for code that needs them, /deep,
/deep/collections, /boundary, /transition, /element, /props, /portal, /dynamic,
/style, /keep, /schedule, /events, /collections/delta, /cold, /live and /invariant.
In .qx files you never import these: the compiler adds the imports for the syntax you use. You
import the others yourself: /collections, /i18n, /version, /version/live, /sync,
/live/ws, /secret, /scenario. The whole package, every entry point, is 6.49 kB (pnpm size;
its limit 6.5 kB).
Reactivity
signal(initial)
A value you can read (s()), replace (s.set(v)) or update (s.update(fn)). set/update can
be passed around on their own; set returns the value it was given, as an assignment does.
import { signal } from '@qatjs/core'
const count = signal(0)
count.set(1)
count.update((n) => n + 1)
check(count(), 2)count statecomputed(fn)
Derived value: lazy (computed on first read), cached, recomputed at most once per change.
import { computed, signal } from '@qatjs/core'
const price = signal(10)
const withTax = computed(() => price() * 1.2)
price.set(20)
check(withTax(), 24)price statewithTax derivedeffect(fn)
Runs fn now (or after mount, inside a component) and whenever what it read changes. A returned
function is the cleanup, run before each re-run and on dispose. Returns a disposer.
import { effect, signal } from '@qatjs/core'
const title = signal('Home')
const seen = []
const stop = effect(() => {
seen.push(title())
return () => seen.push('cleanup')
})
title.set('About')
stop()
check(seen.join(), 'Home,cleanup,About,cleanup')title statewatch(src, fn)
Calls fn(now, before) when src() changes to a different value. Never runs initially.
import { signal, watch } from '@qatjs/core'
const page = signal(1)
let log = ''
watch(page, (now, before) => (log += `${before}→${now} `))
page.set(2)
page.set(2)
page.set(3)
check(log, '1→2 2→3 ')page statebatch(fn)
Group writes; effects run once at the end.
import { batch, effect, signal } from '@qatjs/core'
const first = signal('Ada')
const last = signal('Lovelace')
let runs = 0
effect(() => (first(), last(), runs++))
batch(() => {
first.set('Grace')
last.set('Hopper')
})
check(runs, 2)first statelast stateu(value) · SIG
Read a value that may or may not be reactive: signals and computeds (which carry the SIG tag) are
called and tracked, anything else is returned unchanged. Compiled .qx code wraps identifiers it
did not declare itself (imports, parameters) in u(), so no type information is needed.
import { SIG, computed, signal, u } from '@qatjs/core'
const theme = signal('dark')
check(u(theme), 'dark')
check(u('light'), 'light')
check(typeof computed(() => 1)[SIG], 'object')theme stateuntrack(fn)
Read without subscribing.
import { effect, signal, untrack } from '@qatjs/core'
const a = signal(1)
const b = signal(1)
let runs = 0
effect(() => (a(), untrack(b), runs++))
b.set(2)
check(runs, 1)a stateb stateroot(fn)
An ownership scope: everything created inside is disposed by the dispose it receives. A root
outlives the scope it was created in, but sees that scope's context.
import { effect, root, signal } from '@qatjs/core'
const s = signal(0)
let runs = 0
const dispose = root((d) => {
effect(() => (s(), runs++))
return d
})
dispose()
s.set(1)
check(runs, 1)s stateonMount(fn) / onCleanup(fn)
Compiled from mount(…) / unmount(…). onMount runs after the component's DOM is in the
document; a returned function becomes a cleanup. onCleanup runs when the owner is disposed.
import { component, onCleanup, onMount, render, template } from '@qatjs/core'
const tpl = template('<input>')
const log = []
function Search() {
const input = tpl()
onMount(() => log.push('focused:' + input.isConnected))
onCleanup(() => log.push('gone'))
return input
}
const unmount = render(() => component(Search, {}), document.body)
unmount()
check(log.join(), 'focused:true,gone')provide(token, value) / inject(token, fallback?)
Context through the owner tree. Tokens are any value; symbols are typical.
import { component, inject, provide, render } from '@qatjs/core'
const Theme = Symbol('theme')
let seen
const Button = () => ((seen = inject(Theme, 'light')), document.createElement('button'))
const App = () => (provide(Theme, 'dark'), component(Button, {}))
render(() => component(App, {}), document.body)
check(seen, 'dark')onError(handler)
Errors that no {try} boundary catches — including errors thrown by event handlers and rejected
promises returned by async ones — reach the handler, then console.error. render(fn, root, { onError }) installs a handler for one app.
import { effect, onError, signal } from '@qatjs/core'
const seen = []
onError((e) => seen.push(e.message))
const log = console.error
console.error = () => {}
const n = signal(0)
effect(() => {
if (n() === 1) throw new Error('bad state')
})
n.set(1)
console.error = log
onError(() => {})
check(seen.join(), 'bad state')n statereport(error)
Routes an error the way an uncaught one goes — to the onError handler, then console.error — for
code that catches errors itself. Event handlers and store actions use it for rejected promises.
import { onError, report } from '@qatjs/core'
const seen = []
onError((e) => seen.push(e))
const log = console.error
console.error = () => {}
report('lost connection')
console.error = log
onError(() => {})
check(seen.join(), 'lost connection')getOwner() / runWithOwner(owner, fn)
Resume ownership after an await, so effects and cleanups created later still belong to the
component.
import { getOwner, onCleanup, root, runWithOwner } from '@qatjs/core'
let cleaned = false
const dispose = root((d) => {
const owner = getOwner()
queueMicrotask(() => runWithOwner(owner, () => onCleanup(() => (cleaned = true))))
return d
})
await Promise.resolve()
dispose()
check(cleaned, true)selector(src)
is(key) is true for the one key equal to src(). Changing src re-runs only the observers of
the old and the new key — O(1) "select one of N".
When you need it: many rows (or cells, tabs, options) each compare themselves against one shared
value — row.id === selectedId. Written as a plain comparison, every change of selectedId re-runs
the comparison in every row; with selector, only two rows update. With a few dozen rows the plain
comparison is fine; reach for selector in lists of hundreds or more.
import { effect, selector, signal } from '@qatjs/core'
const selected = signal(1)
const isSelected = selector(selected)
let runs = 0
for (const id of [1, 2, 3]) effect(() => (isSelected(id), runs++))
selected.set(2)
check(runs, 5) // 3 initial runs + ids 1 and 2selected stateComponents
component(Comp, props)
Compiled from <Comp … />. Runs setup once, untracked, in its own owner. Reactive props are
getters.
import { component, insert, render, signal, template } from '@qatjs/core'
const tpl = template('<h1> </h1>')
function Hello(props) {
const h1 = tpl()
insert(h1, () => 'Hello ' + props.name)
return h1
}
const name = signal('Ada')
render(() => component(Hello, { get name() { return name() } }), document.body)
name.set('Grace')
check(document.body.textContent, 'Hello Grace')name staterender(fn, container)
Mounts content into a container; returns unmount.
import { render } from '@qatjs/core'
const unmount = render(() => 'hi', document.body)
check(document.body.textContent, 'hi')
unmount()
check(document.body.textContent, '')Templates and bindings
template(html, svg?)
Parse once, clone many times. Compiled from the static parts of JSX and hoisted to module scope.
import { template } from '@qatjs/core'
const card = template('<div class="card"><b></b></div>')
check(card().outerHTML, '<div class="card"><b></b></div>')attr(el, name, fn) · prop(el, name, fn) · toggleClass(el, name, fn) · style(el, name, fn)
One reactive binding per node; the DOM is written only when the value changes. For attr,
null/false remove the attribute and true sets it empty. flag(el, name, fn) is attr for
an attribute that is there or is not — disabled, hidden, open, required, … (the compiler
picks it): 0, '' and NaN are "not" too, so disabled={errors.length} is what it reads as;
a word stays a word (hidden="until-found"). For prop, a className that is null,
undefined or false is no class, and a field's value that is null or undefined is an
empty field. A child that is an object and no node — a Date, a record — is shown as its text.
import { attr, insert, prop, signal, style, template, toggleClass } from '@qatjs/core'
const el = template('<a> </a>')()
const done = signal(false)
insert(el, () => (done() ? 'Done' : 'Todo'))
attr(el, 'aria-pressed', done)
prop(el, 'title', () => 'state: ' + done())
toggleClass(el, 'done', done)
style(el, 'color', () => (done() ? 'green' : null))
done.set(true)
check(el.textContent, 'Done')
check(el.getAttribute('aria-pressed'), '')
check(el.title, 'state: true')
check(el.className, 'done')
check(el.style.color, 'green')done stateon(el, event, fn, options?)
Delegated for bubbling UI events (one document listener per type); attached directly for others
and whenever options (capture, passive) are given. Modifiers like |prevent are compiled into
fn; |debounce, |throttle and the gestures come from @qatjs/core/events (events).
import { on, template } from '@qatjs/core'
const button = template('<button></button>')()
document.body.append(button)
let clicks = 0
on(button, 'click', () => clicks++)
button.click()
check(clicks, 1)insert(parent, value, marker?) · dynamic(fn)
Content: a function is reactive (text updates in place; nodes and arrays replace the previous
content), anything else is inserted once. Without marker, a reactive value is the parent's whole
content; with it, the content goes before the marker (a template placeholder). dynamic returns
reactive content as a fragment, for positions without a parent element (component roots).
A component may have several roots: elements, blocks, and an expression in braces, read again
when what it reads changes, as among an element's children. The expression may be the first of
them where the roots stand in the result's parentheses and a root follows it — return ( {children} <footer /> ); alone, or anywhere else, braces in parentheses are an object. A comment
between the roots, in braces or not, is nothing:
export default function List({ title, items }) {
let count = derived(items.length)
return (
<h1>{title}</h1>
{/* the count, then the list */}
{count}
{for (const x of items)}<p key={x.id}>{x.name}</p>{/for}
)
}count derivedexpose(…) may also stand in the component's mount(): mount(() => expose(el)) gives a parent's
ref the element itself, once it is there.
import { dynamic, insert, render, signal, template } from '@qatjs/core'
const who = signal('world')
const h1 = template('<h1></h1>')()
insert(h1, () => 'Hello, ' + who())
render(() => [h1, dynamic(() => who().length)], document.body)
who.set('Qat')
check(document.body.textContent, 'Hello, Qat3')who stateBlocks
branch(select, branches)
Compiled from {if}/{else if}/{else} and {switch}. select() returns the branch index (or
-1). A branch is rebuilt only when the index changes.
import { branch, render, signal } from '@qatjs/core'
const user = signal(null)
render(() => branch(() => (user() ? 0 : 1), [() => 'Hi ' + user(), () => 'Sign in']), document.body)
user.set('Ada')
check(document.body.textContent, 'Hi Ada')user statelist(each, map, key?)
Compiled from {for}. Keyed reconciliation with minimal moves (prefix/suffix, end swaps, longest
increasing subsequence). Without key, map gets the item; with key, an accessor that updates
when a new item arrives under the same key. Declare a second parameter to get a reactive index.
import { list, render, signal } from '@qatjs/core'
const todos = signal([{ id: 1, text: 'milk' }, { id: 2, text: 'eggs' }])
render(() => list(todos, (todo, i) => () => `${i() + 1}. ${todo().text} `, (t) => t.id), document.body)
todos.set([{ id: 2, text: 'eggs' }, { id: 1, text: 'oat milk' }])
check(document.body.textContent, '1. eggs 2. oat milk ')todos statekeepBranch(select, branches) — @qatjs/core/keep
Like branch, but switched-away branches stay alive and come back with their state, form values
and scroll position. Used by the router's keep and by tabs.
import { component, render, signal, template } from '@qatjs/core'
import { keepBranch } from '@qatjs/core/keep'
const tab = signal(0)
const tpl = template('<input>')
let input
render(() => keepBranch(tab, [() => (input = tpl()), () => 'settings']), document.body)
input.value = 'draft'
tab.set(1)
tab.set(0)
check(document.querySelector('input').value, 'draft')tab statehold(fn) · defer · chunked — @qatjs/core/schedule
hold builds detached: mount hooks and effects wait for commit(). (defer, chunked: Large lists.)
import { component, onMount, root, template } from '@qatjs/core'
import { hold } from '@qatjs/core/schedule'
let log = ''
const [node, commit] = root(() => hold(() => component(() => (onMount(() => (log = 'mount')), template('<p>')()), {})))
document.body.append(node)
check(log, '')
commit()
check(log, 'mount')tryCatch(tryFn, catchFn) — @qatjs/core/boundary
Compiled from {try}…{catch (err, retry)}…{/try}. Errors thrown while building tryFn, or later by
its effects, watches, mount hooks and derived values, replace it with catchFn(err, retry); err
is an accessor, retry() rebuilds the content. Event-handler errors are not caught here (they go
to onError); an error thrown by the catch content goes to the next boundary out.
import { render } from '@qatjs/core'
import { tryCatch } from '@qatjs/core/boundary'
render(
() => tryCatch(() => JSON.parse('{oops'), (err) => 'Could not load: ' + err().name),
document.body,
)
check(document.body.textContent, 'Could not load: SyntaxError')Deep state — @qatjs/core/deep
deep(value) / raw(value)
deep is compiled from state(init): plain objects and arrays become deep-reactive proxies
(cached per object); anything else is returned as is. Maps and Sets are deep once
@qatjs/core/deep/collections is loaded — the compiler imports it when a state initializer is a Map/Set,
plain JS imports it explicitly. raw returns the object behind a
proxy — pass it to structuredClone, postMessage and libraries that mutate. See
reactivity.md for the rules.
import { effect } from '@qatjs/core'
import { deep, raw } from '@qatjs/core/deep'
import '@qatjs/core/deep/collections' // Map/Set support; .qx files get it automatically
const cart = deep({ items: [], tags: new Set() })
let count = 0
effect(() => (count = cart.items.length + cart.tags.size))
cart.items.push({ sku: 'A1' })
cart.tags.add('gift')
check(count, 2)
check(structuredClone(raw(cart)).items[0].sku, 'A1')Transitions — @qatjs/core/transition
transition(el, fn, params?) · fade · slide
Compiled from transition:fade / transition:slide={{ … }}. Animates in after insertion; a block
removing the element waits for the reverse animation. Uses the Web Animations API (immediate
without it).
import { branch, render, signal, template } from '@qatjs/core'
import { fade, transition } from '@qatjs/core/transition'
const tpl = template('<p>saved</p>')
const show = signal(true)
render(() => branch(() => (show() ? 0 : -1), [() => {
const p = tpl()
transition(p, fade, { duration: 150 })
return p
}]), document.body)
check(document.body.textContent, 'saved')show stateCustom elements — @qatjs/core/element
define(tag, Comp, { shadow?, props? })
Registers a component as a Custom Element. Props ↔ properties and kebab-case attributes (from
Comp.props, which the compiler sets, or props). The component's events (emit in .qx, the
props['on:name'] call in plain JS) dispatch a composed CustomEvent('name'), bubbling only when
emitted with { bubbles: true }; expose({…}) members become element methods and getters; initial
light-DOM children become children and slots (projected once). Light DOM unless shadow: true.
import { insert, on, template } from '@qatjs/core'
import { define } from '@qatjs/core/element'
const tpl = template('<button> </button>')
function LikeButton(props) {
const b = tpl()
insert(b, () => '♥ ' + props.label)
// what `emit('like', { label }, { bubbles: true })` compiles to
on(b, 'click', () => props['on:like']?.apply({ bubbles: true }, [{ label: props.label }]))
return b
}
define('like-button', LikeButton, { props: ['label'] })
document.body.innerHTML = '<like-button label="Qat"></like-button>'
let liked
document.body.addEventListener('like', (e) => (liked = e.detail.label))
document.querySelector('like-button button').click()
check(liked, 'Qat')Renderer
setRenderer(renderer) · dom
Every DOM mutation goes through the active renderer, so a string or server renderer can be swapped
in without changing compiled output. dom is the default.
import { dom, insert, setRenderer, signal, template } from '@qatjs/core'
const writes = []
setRenderer({ ...dom, setText: (node, value) => (writes.push(value), dom.setText(node, value)) })
const label = signal('draft')
insert(template('<i> </i>')(), label)
label.set('sent')
setRenderer(dom)
check(writes.join(), 'draft,sent')label stateProps — @qatjs/core/props
mergeProps(...sources) · splitProps(props, keys)
Lazy props objects: getters are forwarded, not evaluated, so reactivity survives. mergeProps is
compiled from <C {...a} b={1} /> (later sources win); splitProps from a ...rest in a props
pattern, and is handy in wrapper components.
import { signal } from '@qatjs/core'
import { mergeProps, splitProps } from '@qatjs/core/props'
const title = signal('a')
const merged = mergeProps({ id: 1, title: 'x' }, { get title() { return title() } })
title.set('b')
const [own, rest] = splitProps(merged, ['id'])
check(merged.title + own.id + Object.keys(rest).join(), 'b1title')title stateSpread onto an element — @qatjs/core/spread
spread(el, props, skip?)
Compiled from <button {...rest}>: a wrapper component passing on what it was given. Each key is
the binding it would be if it were written out — on:click (and onClick) a listener, class and
style, ref, children (when the markup gave the element none), value/checked as
properties, anything else an attribute — and its value stays live. An attribute written after the
spread wins (skip names those); one written before it gives way. The keys are those the object
has when the element is made.
import { signal } from '@qatjs/core'
import { spread } from '@qatjs/core/spread'
const pressed = signal(false)
const b = document.createElement('button')
spread(b, { title: 'Save', get 'aria-pressed'() { return pressed() }, type: 'submit' }, ['type'])
pressed.set(true)
check(b.title + b.getAttribute('aria-pressed') + b.hasAttribute('type'), 'Savetruefalse')pressed stateBuilt-in components — @qatjs/core/portal, @qatjs/core/dynamic
Portal
Compiled from <Portal to={target}>. Renders its children into to (selector or element, default
document.body) while keeping the owner tree (inject, {try}, disposal). DOM events bubble
through the DOM tree only.
import { component, render, template } from '@qatjs/core'
import { Portal } from '@qatjs/core/portal'
const box = template('<div id="modals"></div>')()
document.body.append(box)
render(() => component(Portal, { to: '#modals', children: () => 'hello' }), document.body)
check(box.textContent, 'hello')Dynamic
Compiled from <Dynamic component={X} /> or <Dynamic tag="h2">. Renders a component or tag that
may change; the previous instance is disposed.
import { component, render, signal } from '@qatjs/core'
import { Dynamic } from '@qatjs/core/dynamic'
const tag = signal('h2')
render(() => component(Dynamic, { get tag() { return tag() }, children: () => 'Title' }), document.body)
tag.set('h3')
check(document.body.innerHTML.replace(/<!---->/g, ''), '<h3>Title</h3>')tag statetoNodes
A piece of content as its nodes, made now: a string is a text node, a function reactive content, a node itself. The compiler writes it, in a build whose pages resume, around each string and value among several pieces of content, so that each is made in its place (server.md); you do not call it.
import { toNodes } from '@qatjs/core/dynamic'
const [text] = toNodes('Total')
check(text.nodeType, 3)Versions — @qatjs/core/version
outdated · check()
A newer deploy, seen from an open page (399 B). outdated() is null until dist/versions.json
names a newer build than the page's, then that file. check() reads it; it is also read at each
navigation and when the tab comes back. See Deploying.
import { check as read, outdated } from '@qatjs/core/version'
await read() // (a page with no build named in it: nothing to compare)
check(outdated(), null)@qatjs/core/version/live: status · refusal(versions) · into(versions, base, running)
A newer deploy switched into the open page when it is provably safe (opt-in, 2.4 kB; see
Switching in place). status is where the switch
stands (running, newest, state: running, waiting, switched or kept, and reason), as
__qat.explain('version') shows it. refusal(v) gives the reason a versions.json cannot be switched
into this page, or null; refusal(v, running) asks it for another running build. into(v, base, running) switches a build in at a quiet moment, with its files under base, and resolves with the
refusal or null. The page's own switch uses it, and so does
@qatjs/federate/live for each remote.
hot is what a live build's compiled code calls (each component's wrapper, each state by name); an
app does not call it.
import { status } from '@qatjs/core/version/live'
check(status.state, 'running') // (until a newer build is seen)Shared documents — @qatjs/core/sync
shared(initial, { room }) · room(doc)
A deep store that everyone in room shares, through the app's relay, and that merges after time
offline (opt-in, 2.85 kB with its CRDT, pnpm size). room(doc) gives its status, its pending writes, and
presence (present, others, me). replica(initial) is the CRDT on its own: a document's
replica, applying operations in any order (for tests and tools). The guide:
Collaboration.
import { room, shared } from '@qatjs/core/sync'
const todos = shared([], { room: 'todos' })
todos.push({ text: 'Milk', done: false })
room(todos).status() // 'connecting', then 'open'Live loads — @qatjs/core/live
live(createLoad, fn, options) · stale · @qatjs/core/live/ws
What load(fn, { live: true, key }) compiles to (opt-in, 499 B): the load, subscribed through the
page's one session with the server (/__qat/live, @qatjs/server/live) to options.key. A push
becomes its data. stale is true while the page has no session. import '@qatjs/core/live/ws' (160 B)
uses a WebSocket instead of Server-Sent Events. The guide: Collaboration.
import { stale } from '@qatjs/core/live'
check(stale(), false) // (no session lost yet)Secrets — @qatjs/core/secret
secret(value) · reveal(s)
A value that must not leave its view (198 B): the compiler follows it and reports each sink it would
reach. reveal is the only exit. The guide: Secrets.
import { reveal, secret } from '@qatjs/core/secret'
const t = secret('abc')
check(JSON.stringify({ t }), '{"t":"[secret]"}')
check(reveal(t), 'abc')Scenarios — @qatjs/core/scenario
scenario({ name }) · scoped(x) · within(s, render) · Compare
A branch of the page's state, to try a change before making it (opt-in, 1.7 kB). s.of(x, name)
is x as the branch sees it, copy on write. s.mutate(target, apply, commit) applies now and
queues its request. s.diff() lists the changes; s.commit() commits them in order and reports a
conflict or the step that failed; s.discard() drops the branch. scoped(x) is the current
scenario's view of x. <App scope={s} /> compiles to within(s, …), and Compare
(<Compare scope={s}>) renders both sides. The guide: Collaboration.
import { deep } from '@qatjs/core/deep'
import { scenario } from '@qatjs/core/scenario'
const orders = deep([{ id: '7', status: 'New' }])
const s = scenario({ name: 'Try' })
s.of(orders, 'orders')[0].status = 'On the way'
check(orders[0].status, 'New')
check(s.diff()[0].path, 'orders[7].status')Styles — @qatjs/core/style
css(id, text)
Compiled from a .qx file's <style>: adds the scoped CSS once as a constructed stylesheet.
import { css } from '@qatjs/core/style'
css('q-demo01', '.title[q-demo01] { color: red }')
check(document.adoptedStyleSheets.length > 0, true)