State and actions
The top-level script of a page or component is its state and behavior. A let is state; a function is an action when an event calls it and a derived value when a binding reads it. Assign the let and the runtime reapplies the bindings: no signals, no setState, no manual render.
A page's script
Every top-level let is state, read as $visitor in HTML; every top-level function is reachable from HTML too.
routes/examples/state/index.js
let visitor = ''const name = () => visitor.trim()const greeting = () => name() ? `Hello, ${name()}.` : 'Hello, whoever you are.'const anonymous = () => !name()function forget() { visitor = ''}
routes/examples/state/_snippets/page/usage.html
<div class="grid w-full max-w-sm gap-3"> <label class="grid gap-1.5"> <span class="label">Your name</span> <input class="h-10 border border-line-strong bg-sunken px-3" autocomplete="given-name" :model="$visitor"> </label> <p class="text-lg">{$greeting}</p> <div><button type="button" class="btn btn-small" @click="forget" :disabled="$anonymous">Forget</button></div></div>
Live result
Hello, whoever you are.
{$greeting} calls greeting() on every render, and @click="forget" calls forget(). A page writes its script as a <script> at the top of its .html, or as a .js with the same name; this page uses index.js because its .html is the whole article. A name in HTML that the script does not declare fails check with html/unknown-name.
Derived values are functions
Anything computed from state is a function, called again on every render, so there is nothing to keep in sync.
routes/examples/state/_components/split/split.html
<script> const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) let amount = 84.5 let people = 3 let tipPercent = '15' const bill = () => Math.max(amount ?? 0, 0) const headcount = () => Math.max(Math.round(people ?? 1), 1) const tip = () => bill() * Number(tipPercent) / 100 const total = () => bill() + tip() const tipLabel = () => money.format(tip()) const totalLabel = () => money.format(total()) const perPersonLabel = () => money.format(total() / headcount())</script><div class="grid w-full max-w-sm gap-4"> <div class="grid grid-cols-3 gap-3"> <label class="split-field"> <span class="label">Bill</span> <input class="split-input" type="number" min="0" step="0.01" inputmode="decimal" :model="$amount"> </label> <label class="split-field"> <span class="label">People</span> <input class="split-input" type="number" min="1" step="1" inputmode="numeric" :model="$people"> </label> <label class="split-field"> <span class="label">Tip %</span> <select class="split-input" :model="$tipPercent"> <option value="0">0</option> <option value="10">10</option> <option value="15">15</option> <option value="20">20</option> </select> </label> </div> <dl class="split-result"> <dt>tip</dt><dd>{$tipLabel}</dd> <dt>total</dt><dd>{$totalLabel}</dd> <dt>each</dt><dd class="text-accent">{$perPersonLabel}</dd> </dl></div><style> .split-field { display: grid; gap: 0.375rem; min-width: 0; } .split-input { width: 100%; height: 2.5rem; padding: 0 0.625rem; border: 1px solid var(--color-line-strong); background: var(--color-sunken); color: var(--color-ink); font-family: var(--font-mono); font-size: 0.875rem; font-variant-numeric: tabular-nums; caret-color: var(--color-accent); } .split-input:focus-visible { outline-offset: 0; border-color: var(--color-accent); } .split-result { display: grid; grid-template-columns: auto 1fr; gap: 0.5rem 1rem; padding: 1rem; border: 1px solid var(--color-line); background: var(--color-surface); font-family: var(--font-mono); font-size: 0.875rem; } .split-result dt { color: var(--color-faint); } .split-result dd { text-align: right; font-variant-numeric: tabular-nums; }</style>
Live result
- tip
- $12.68
- total
- $97.18
- each
- $32.39
HTML only reads paths, never formulas, so the template asks for $perPersonLabel and the script computes it. Inside the script you call them like any function: total() reads bill() and tip(). :model keeps the input's type: a number field writes a number, or null when it is empty. Never keep a derived copy in a let that actions update.
Actions take arguments
An event calls a function by name, and inside a <for> it passes the item: @change="toggle(job)".
routes/examples/state/_components/queue/queue.html
<script> const saveDelayMs = 900 let draft = '' let saving = false let savedAt = '' let jobs = [ { id: 'build', title: 'pragma build', done: true }, { id: 'check', title: 'pragma check --strict', done: false }, ] const pending = () => jobs.filter(job => !job.done).length const blank = () => !draft.trim() const saveText = () => saving ? 'Saving…' : 'Save' function add() { if (blank()) return jobs.push({ id: crypto.randomUUID(), title: draft.trim(), done: false }) draft = '' } function toggle(job) { job.done = !job.done } function remove(job) { jobs = jobs.filter(entry => entry.id !== job.id) } async function save() { saving = true await new Promise(resolve => setTimeout(resolve, saveDelayMs)) saving = false savedAt = new Date().toLocaleTimeString('en-GB') }</script><div class="grid w-full max-w-sm gap-3"> <form class="flex gap-2" notool @submit="add"> <input class="queue-input" aria-label="New job" placeholder="New job" :model="$draft"> <button class="btn btn-small" :disabled="$blank">Add</button> </form> <ul class="grid gap-1"> <for job in $jobs key=job.id> <li class="queue-row" .is-done="job.done"> <input type="checkbox" class="queue-check" :checked="job.done" aria-label="Done: {job.title}" @change="toggle(job)"> <span class="queue-title">{job.title}</span> <button type="button" class="queue-remove" aria-label="Remove {job.title}" @click="remove(job)"> <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" fill="none"></path></svg> </button> </li> </for> <empty> <li class="queue-empty">Queue is empty.</li> </empty> </ul> <div class="flex items-center justify-between gap-3"> <p class="font-mono text-xs text-faint">{$pending} of {$jobs.length} pending</p> <button type="button" class="btn btn-small btn-primary" @click="save" :disabled="$saving">{$saveText}</button> </div> <p class="font-mono text-xs text-faint" role="status" :show="$savedAt">saved at {$savedAt}</p></div><style> .queue-input { flex: 1; min-width: 0; height: 2rem; padding: 0 0.625rem; border: 1px solid var(--color-line-strong); background: var(--color-sunken); color: var(--color-ink); font-family: var(--font-mono); font-size: 0.8125rem; caret-color: var(--color-accent); } .queue-input::placeholder { color: var(--color-faint); } .queue-input:focus-visible { outline-offset: 0; border-color: var(--color-accent); } .queue-row { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0.25rem 0.5rem 0.75rem; border: 1px solid var(--color-line); background: var(--color-surface); } .queue-check { accent-color: var(--color-accent); } .queue-title { flex: 1; font-family: var(--font-mono); font-size: 0.8125rem; } .is-done .queue-title { color: var(--color-faint); text-decoration: line-through; } .queue-remove { display: grid; place-items: center; width: 2rem; height: 2rem; color: var(--color-faint); cursor: pointer; } .queue-remove:hover { color: var(--color-ink); } .queue-remove svg { width: 0.75rem; height: 0.75rem; } .queue-empty { padding: 0.75rem; color: var(--color-faint); font-size: 0.875rem; }</style>
Live result
- pragma build
- pragma check --strict
- Queue is empty.
1 of 2 pending
saved at
State is a deep proxy: job.done = true, jobs.push(…) and jobs = jobs.filter(…) all render. Arguments can be paths (job, $draft, data.x), simple literals, event or el, never expressions. An async action renders when its first part returns ("Saving…") and again after each await; renders are batched per microtask.
Props: export let, typed by the default
export let used = 0 declares a prop, and the default's type converts the attribute text.
routes/examples/state/_components/usage/usage.html
<script> export let label = '' export let used = 0 export let total = 100 export let critical = false const percent = () => Math.round(used / total * 100) const types = () => `used: ${typeof used} · total: ${typeof total} · critical: ${critical}`</script><figure .is-critical="$critical"> <figcaption class="usage-head"> <span>{$label}</span> <span class="tabular-nums">{$used} / {$total} · {$percent}%</span> </figcaption> <meter class="usage-meter" min="0" :max="$total" :value="$used" aria-label="{$label} usage"></meter> <p class="usage-types">{$types}</p></figure><style> [data-c="usage"] { display: grid; gap: 0.5rem; padding: 0.75rem 1rem; border: 1px solid var(--color-line); background: var(--color-surface); font-family: var(--font-mono); font-size: 0.75rem; } .usage-head { display: flex; justify-content: space-between; gap: 1rem; color: var(--color-ink); } .is-critical .usage-head { color: var(--color-danger-300); } .usage-meter { width: 100%; height: 0.5rem; } .usage-types { color: var(--color-faint); }</style>
routes/examples/state/_snippets/usage/usage.html
<div class="grid w-full max-w-sm gap-3"> <p-usage label="Disk" used="72" total="128" critical></p-usage> <p-usage label="Cache" used="9"></p-usage></div>
Live result
used: number · total: number · critical: true
used: number · total: number · critical: false
used="72" arrives as the number 72 because the default is a number; a bare critical is true and "false" is false; a missing prop keeps its default, so the second meter's total is 100. Props are read-only: assigning one fails check with js/prop-write, so copy it into a let to change it (let count = start). That goes deep: in dev, writing into an object prop (item.done = true) throws an error that names the prop; copy it first (let draft = { ...item }). A prop the script does not declare fails at the call site with html/unknown-prop. More in Components.
mount() and its cleanup
function mount() runs once after the first render and returns the cleanup.
routes/examples/state/_components/clock/clock.html
<script> const timeFormat = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) let now = Date.now() let width = 0 let resizes = 0 const time = () => timeFormat.format(now) function mount() { width = window.innerWidth const timer = setInterval(() => { now = Date.now() }, 1000) const measure = () => { width = window.innerWidth resizes += 1 } window.addEventListener('resize', measure) return () => { clearInterval(timer) window.removeEventListener('resize', measure) } }</script><dl> <div class="clock-cell"> <dt class="label">setInterval</dt> <dd class="clock-value">{$time}</dd> </div> <div class="clock-cell"> <dt class="label">window resize</dt> <dd class="clock-value">{$width}px</dd> </div> <div class="clock-cell"> <dt class="label">resize events</dt> <dd class="clock-value">{$resizes}</dd> </div></dl><style> [data-c="clock"] { display: grid; gap: 1px; width: 100%; max-width: 24rem; border: 1px solid var(--color-line); background: var(--color-line); } .clock-cell { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; padding: 0.875rem 1rem; background: var(--color-surface); } .clock-value { font-family: var(--font-mono); font-size: 1.125rem; font-variant-numeric: tabular-nums; }</style>
Live result
- setInterval
- 13:06:40
- window resize
- 0px
- resize events
- 0
It is only for external effects: timers, window or document listeners, observers. mount runs only in the browser, so it is also where browser-only reads belong: the clock reads window.innerWidth there, not at the top of the script, because on an SSR page the script also runs on the server. mount(el) receives the component's root element for an observer or a measurement; read from it, never write to it. The cleanup runs when the owner leaves the DOM; for a page, on navigation. An async function mount() works too: the runtime awaits it and uses the function it resolves to as the cleanup, even when the owner left before it resolved. Never fetch data in mount; that is what load is for.
Timers and promises just assign
A callback that runs later assigns the let like an action does, and the page renders.
routes/examples/state/_components/stopwatch/stopwatch.html
<script> const tickMs = 31 const pad = value => String(value).padStart(2, '0') let startedAt = 0 let elapsedBefore = 0 let now = 0 let timer = 0 let laps = [] let lapCount = 0 const running = () => timer !== 0 const elapsed = () => elapsedBefore + (running() ? now - startedAt : 0) const untouched = () => !running() && elapsed() === 0 const toggleText = () => running() ? 'Stop' : 'Start' const lapText = () => running() || untouched() ? 'Lap' : 'Reset' const display = () => { const centis = Math.floor(elapsed() / 10) const seconds = Math.floor(centis / 100) return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}.${pad(centis % 100)}` } function toggle() { if (running()) { clearInterval(timer) elapsedBefore = elapsed() timer = 0 return } startedAt = performance.now() now = startedAt timer = setInterval(() => { now = performance.now() }, tickMs) } function lapOrReset() { if (running()) { lapCount += 1 laps = [{ id: lapCount, time: display() }, ...laps].slice(0, 3) return } elapsedBefore = 0 lapCount = 0 laps = [] } function mount() { return () => clearInterval(timer) }</script><div class="grid w-full max-w-xs justify-items-center gap-4"> <output class="stopwatch-display">{$display}</output> <div class="flex gap-2"> <button type="button" class="btn btn-small" @click="lapOrReset" :disabled="$untouched">{$lapText}</button> <button type="button" class="btn btn-small btn-primary" @click="toggle">{$toggleText}</button> </div> <ol class="stopwatch-laps" aria-label="Laps"> <for lap in $laps key=lap.id> <li class="flex justify-between gap-6"><span>{lap.id}</span><span>{lap.time}</span></li> </for> </ol></div><style> .stopwatch-display { font-family: var(--font-mono); font-size: 2.25rem; font-stretch: 85%; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; } .stopwatch-laps { display: grid; gap: 0.25rem; min-width: 10rem; color: var(--color-muted); font-family: var(--font-mono); font-size: 0.75rem; font-variant-numeric: tabular-nums; }</style>
Live result
The action starts the interval and mount only returns the cleanup that stops it. Maps, Sets, Dates and class instances are not tracked: assign a new value instead of changing them in place.
event, el and services from 'pragma'
A handler without parentheses receives the DOM event: @keydown="inspectKey" calls inspectKey(event). With parentheses it receives only what it lists, and two names are always there: event and el, the element that has the directive. Everything else a script needs comes from import { … } from 'pragma'.
routes/examples/state/_components/probe/probe.html
<script> import { log } from 'pragma' const targets = [ { id: 'alpha', name: 'alpha' }, { id: 'beta', name: 'beta' }, ] let reading = [{ id: 'hint', field: 'arguments', value: 'click a button or type a key' }] function inspect(target, event, el) { reading = [ { id: 'target', field: 'target.name', value: target.name }, { id: 'type', field: 'event.type', value: event.type }, { id: 'clicked', field: 'event.target', value: '<' + event.target.localName + '>' }, { id: 'el', field: 'el', value: '<' + el.localName + '>' }, ] } function inspectKey(event) { reading = [ { id: 'type', field: 'event.type', value: event.type }, { id: 'key', field: 'event.key', value: event.key }, ] log.debug('probe key', { 'key.name': event.key }) }</script><div class="grid w-full max-w-sm gap-4"> <div class="flex flex-wrap gap-2"> <for target in $targets key=target.id> <button type="button" class="btn btn-small" @click="inspect(target, event, el)">run <strong>{target.name}</strong></button> </for> <input class="probe-input" aria-label="Type a key" placeholder="type a key" @keydown="inspectKey"> </div> <dl class="probe-reading"> <for row in $reading key=row.id> <div class="probe-row"> <dt>{row.field}</dt> <dd>{row.value}</dd> </div> </for> </dl></div><style> .probe-input { flex: 1; min-width: 7rem; height: 2rem; padding: 0 0.625rem; border: 1px solid var(--color-line-strong); background: var(--color-sunken); color: var(--color-ink); font-family: var(--font-mono); font-size: 0.75rem; caret-color: var(--color-accent); } .probe-input::placeholder { color: var(--color-faint); } .probe-input:focus-visible { outline-offset: 0; border-color: var(--color-accent); } .probe-reading { display: grid; border: 1px solid var(--color-line); background: var(--color-surface); font-family: var(--font-mono); font-size: 0.75rem; } .probe-row { display: flex; justify-content: space-between; gap: 1rem; padding: 0.5rem 0.75rem; } .probe-row + .probe-row { border-top: 1px solid var(--color-line); } .probe-row dt { color: var(--color-faint); } .probe-row dd { color: var(--color-accent); text-align: right; overflow-wrap: anywhere; }</style>
Live result
- arguments
- click a button or type a key
Use el instead of an id lookup or event.currentTarget, which is the root the runtime listens on, not your element. The services are shared (stores), data (the load result), params, query, page, log, call (server actions), navigate and open, close, confirm (overlays). Read data and the route inside functions, never at the top level of the script. Never write to the DOM: read event, change state and let the bindings follow.
Script mistakes that check catches
Four mistakes run without an error in the browser and show a wrong or stale value. pragma check stops each one and names the fix. This is real output for one page script:
pragma check --strict
routes/orders.html:4:16 error [js/top-level-data] `data` is read when the script starts, before the loader is done: read it inside a function (`const products = () => data.products`)
4 | let orders = data.orders
| ^
routes/orders.html:6:7 error [js/stale-derived] `label` reads `discount` once, when the script starts, and never updates: make it a function (`const label = () => discount + '% off'`) and use `$label` in HTML, `label()` in JS; or assign it in an action to change it
6 | let label = discount + '% off'
| ^
routes/orders.html:9:26 error [js/derived-call] `empty` is a function (a derived value): call it in JS: `empty()` (`$empty` without `()` is only for HTML)
9 | const summary = () => (empty ? 'No orders' : orders.length + ' orders')
| ^
routes/orders.html:12:5 error [js/dollar-in-script] `$orders` is HTML only; in <script> write `orders`
12 | $orders = []
| ^
4 error(s), 0 warning(s)
js/top-level-data:datais undefined until the loader ends, so read it in a function:const orders = () => data.orders.js/stale-derived: aletcomputed from anotherletor a prop is computed once. Make it a function, as in Derived values.js/derived-call: in JS a derived value is a call,empty();emptyalone is the function, which is always truthy.js/dollar-in-script:$is HTML only. In the script every name is plain.
Coming from state(ctx)
export const state = () => ({ count: 0 })is nowlet count = 0; getters are functions.export const actionsis now top-level functions, andctx.scope.itemis an argument:@click="remove(item)".ctx.update(fn)is gone: assign thelet.ctx.$.propisexport let prop.ctx.data,ctx.call,ctx.logand the rest come from'pragma';:textis{path}inside the element.
The old API fails check with js/legacy-api, and each message names the replacement.