Local State, Events, and Forms
Local state is what one piece of the view cares about: the fields of a form, whether a panel is open, the text of a draft. It is created with the piece of the view around it and goes with it. It needs no entry in the app’s store, and code that has no business with it cannot reach it.
Most of the snippets on this page come from one sign-up form,
www/samples/state.roc.
Introducing state
State(ctx, s) is a piece of state as one context sees it. It is read as a
signal and written with reducers. Engine.state makes a local one,
cell.state() gives a store cell as one, and a table view hands each drawn
row its row as one.
Engine.state(initial, body) creates local state and calls body with its
State. Everything body returns can read and write it; nothing outside can.
Each nested state introduces its own context:
signup : () -> Elem(Root)
signup = ||
Engine.state(
{ name: "", email: "", agreed: False, tried: False, sent: 0 },
|form| Engine.state(False, |compact| page(form.lift(), compact)),
)
Inside the inner state, the outer State is lifted with form.lift() so it
can be used in the inner context. Name the contexts once:
## One domain transition per event: everything a submit changes is in one
## record.
Signup : { name : Str, email : Str, agreed : Bool, tried : Bool, sent : U64 }
## A separate concern gets a separate state: toggling compact mode never
## wakes anything that reads only the form.
C1 : In(Root, Signup)
C2 : In(C1, Bool)
State inside a list row or a conditional branch is created per row or per branch, and released with it.
Handlers
A handler is how an event changes state. For local state it is built from
a State and attached to an element:
| Handler | The reducer receives |
|---|---|
st.update(f) | the state |
st.update_by(v, f) | the state and the value v reads when the event fires |
st.set_value(f) | the state and the event’s payload |
st.set_value_by(v, f) | the state, v’s value and the payload |
The handler’s declaration chooses its payload kind. Html.text_input and
textarea deliver the control’s text on input. Html.checkbox delivers
its Boolean checked state on change. Html.select delivers Chose(value)
from its current offered choices, or NotOffered when a removed or foreign
key arrives. Click helpers deliver Engine.Click, with modifiers and optional
nearest-link facts. A submit handler receives empty text. Raw text-kind
Engine.on("change", handler) retains its string payload; use on_checked
when attaching a Boolean handler to a checkbox or radio yourself.
HandlerOf(ctx, p) is the generic family: Handler(ctx) is its text
alias, and FilesHandler(ctx) takes the Received of a file event. The
same set_value, handle and also serve every payload kind; attaching a
handler through the wrong kind is a compile error.
update_by is the tool for “which one”: in a list row, update_by(row.key(), f)
passes the clicked row’s key.
A reducer receives the state’s value uniquely owned, so updating a record or a list in it happens in place. The state is not compared with what it held before: a reducer that returns an equal value still wakes the state’s readers, and they find nothing to change.
An element takes one handler per event type, whatever its kind or policies;
a second one for the same type is a
contract error. Two things that must both happen are one handler made with
also (see Shared State).
Declare browser policies with Engine.on_with(type, policy, handler).
Policy has prevent and stop, both false by default. prevent stops
the default action; stop hides a bubbling event from page listeners
above the mount root. For an event that does not bubble, stop does
nothing, so its target still receives it. Policies are static, chosen
before dispatch; a misspelt field does not compile. Event types are bare
names: retired :prevent and :files suffixes are contract errors.
Click handlers attached with Engine.on_click, on_click_with or a button
helper receive Engine.Click. Its modifier flags are ctrl, alt, shift and
meta. link is NoLink or Link({ href, target, download }), captured at
dispatch from the nearest HTML or SVG link inside the mount. The strings are
authored attribute text and download is presence. Use on_click_with to declare
synchronous prevention; a Roc handler cannot decide it after dispatch.
Engine.on("click", handler) remains available for a text payload. Checked
link destinations and imported HTML are described in Markup.
Keys and shortcuts
A key handler receives Engine.Key: key, physical code, ctrl, alt,
shift, meta, repeat, composing and heard. Attach it together with
a signal of the chords it hears:
Engine.on_key(
{ keymap: Engine.const(Engine.Keymap.prevent([Engine.Chord.plain("Escape")])) },
editor.update(|state| posted({ ..state, text: "Original" }, ApplyValue("editor"))),
),
Engine.on_key takes { keymap, on, stop }. Only keymap is required;
on defaults to Down and can be Up, and stop defaults to false.
Use the ordinary reducers, decisions and also at the Key payload type.
Text-event names are Engine.EventType values (also Web.EventType). Literals
are checked while compiling; computed nonempty names use from_str, and custom
events need no catalogue.
The old Html.on_keydown is removed; text handlers on keydown or keyup are
contract errors naming on_key.
Chord.plain builds a chord. with_ctrl, with_alt, with_shift and
with_meta add modifiers; primary gives Ctrl and Cmd alternatives.
Keymap.prevent(chords) hears and prevents those chords, while keep
hears them with their default intact. concat lists the left entries
first. An empty keymap hears nothing and costs no turns. An empty declared chord
is valid but cannot match a browser key.
Ctrl, Alt and Meta must match exactly. ASCII letters compare without case;
Shift must match too, except for a single punctuation or symbol character.
Thus ? works whether a layout needs Shift for it, while Shift+Tab remains
distinct from Tab. Punctuation and symbols use pinned Unicode 18.0.0 data
in both runners. Space, digits, other letters and named keys compare Shift.
For a shortcut naming an ASCII letter or digit, the physical code is a
fallback when the event’s key is not an ASCII letter or digit. Ctrl+K can
therefore work on a Cyrillic layout; Dvorak keeps its labelled ASCII key.
Exact matches anywhere in the list beat every fallback. Compare the
payload’s heard with your declared chord, rather than repeating these
rules in a handler. It is the original chord that matched.
Keymap.outside_text() restricts entries to targets outside text-entry
inputs, textarea, select and contenteditable. It is useful for plain-key
shortcuts such as /. Keymap.every catches anything no listed entry
matches, including composing keys, and prevents nothing. Named entries
never hear a composing event, so Enter cannot accidentally commit an IME
composition. Concatenation keeps one every, heard anywhere if either
side’s is.
An unmatched handler is passed over on the way to an ancestor. The nearest
matching local handler wins. on_document_key instead hears keys reaching
the document that no local handler of this mount dispatched, including
when focus is outside the root:
Engine.on_document_key(
{ keymap: Engine.const(Engine.Keymap.prevent(Engine.Chord.plain("k").primary())) },
editor.update(|state| posted(state, Focus("first"))),
),
The newest mounted matching document handler wins, so a modal can own
Escape and disposal restores the shell’s handler. A document handler
cannot compile under a list or table-view row, including within a state
nested in one: it requires the context’s OutsideRows evidence. There
can be at most 32 live document handlers per instance.
stop uses the ordinary propagation policy. At the root it blocks the
document; at the document it blocks window listeners. Other listeners on
the same document still run, in mount order across mounts. A queued event
keeps the keymap match made when it arrived, even if a later batch changes
the keymap before its turn. A handler still decides from its current state.
Browser-reserved chords cannot be prevented, including Chrome’s Ctrl/Cmd+N, T and W, and macOS Cmd+backquote and Cmd+Tab. macOS sends no keyup when a key is released while Cmd is held; Windows AltGr reports Ctrl+Alt.
A focus trap prevents just the two boundary chords and posts focus commands:
Engine.element(
"section",
[Engine.attr("role", "dialog"), Html.aria_label("Tab loop")],
[
Html.button(
"First",
[
Engine.ref("first"),
Engine.on_key(
{ keymap: Engine.const(Engine.Keymap.prevent([Engine.Chord.plain("Tab").with_shift()])) },
editor.update(|state| posted(state, Focus("last"))),
),
],
editor.update(|state| state),
),
Html.button(
"Last",
[
Engine.ref("last"),
Engine.on_key(
{ keymap: Engine.const(Engine.Keymap.prevent([Engine.Chord.plain("Tab")])) },
editor.update(|state| posted(state, Focus("first"))),
),
],
editor.update(|state| state),
),
],
),
The Spreadsheet demonstrates navigation, Shift+Arrow range selection, a changing grid keymap and document shortcuts.
One event, one transition
A reducer writes one state. If an event must change several things at once — a submit that marks the form as tried and counts a successful send — keep them in one record and write one reducer:
Problem : [NameMissing, EmailInvalid, NotAgreed]
problems : Signup -> List(Problem)
problems = |s|
[]
.concat(if (s.name.trim().is_empty()) [NameMissing] else [])
.concat(if (s.email.contains("@")) [] else [EmailInvalid])
.concat(if (s.agreed) [] else [NotAgreed])
message : Problem -> Str
message = |problem|
match problem {
NameMissing => "Enter your name."
EmailInvalid => "Enter an email address with an @."
NotAgreed => "Accept the terms to continue."
}
## A submit marks the form as tried, and counts it as sent when it is valid.
submit : Signup -> Signup
submit = |s| if (problems(s).is_empty()) { ..s, tried: True, sent: s.sent + 1 } else { ..s, tried: True }
The engine applies the whole reducer before anything observes the result, so the page never shows “tried” without the matching error messages.
Forms and validation
page : State(C2, Signup), State(C2, Bool) -> Elem(C2)
page = |form, compact| {
s = form.signal()
shown = |p| s.map(|v| v.tried and problems(v).contains(p))
Html.div_s(
compact.signal().map(|c| if (c) "signup compact" else "signup"),
[
Html.checkbox(Engine.const("Compact"), compact.signal(), [], compact.set_value(|_, v| v)),
Html.form(
"Sign up",
[Html.on_submit(form.update(submit))],
[
Html.text_input(Engine.const("Name"), "text", s.map(|v| v.name), [Html.aria_invalid(shown(NameMissing))], form.set_value(|v, text| { ..v, name: text })),
Html.text_input(Engine.const("Email"), "email", s.map(|v| v.email), [Html.aria_invalid(shown(EmailInvalid))], form.set_value(|v, text| { ..v, email: text })),
Html.checkbox(Engine.const("I accept the terms"), s.map(|v| v.agreed), [], form.set_value(|v, flag| { ..v, agreed: flag })),
Html.submit_button("Sign up", []),
],
),
Html.p_s(s.map(|v| if (v.tried) Str.join_with(problems(v).map(message), " ") else ""), [Engine.test_id("problems")]),
Html.p_s(s.map(|v| "Sent ${v.sent.to_str()} times"), [Engine.test_id("sent")]),
],
)
}
A few things to note:
- Validation is a pure function,
problems, and the messages are a second projection of the sameProblemtags. The view never inspects rendered text. aria_invalidmarks a field for assistive technology while its problem is shown.- The runtime prevents the default action of every
submit, so forms never navigate. A submit button’s click submits its form, as in any browser. - The compact toggle is a separate state, so toggling it re-evaluates only the class that reads it.
Dialogs and popovers
A dialog’s open state is a signal, and its close handler receives the
browser’s current open state as a Bool. Accept that value so Escape and
an authored close button agree:
## Accept the browser's close echo so Escape and the close button agree
## with the same signal. The helper owns the dialog's content scope.
settings : State(Ctx, Model) -> Elem(Ctx)
settings = |model| Html.dialog(
"Settings",
{ open: model.signal().map(|m| m.settings), on_close: model.set_value(|m, open| { ..m, settings: open }) },
[],
[
Html.h2("Settings", ""),
Html.button("Close settings", [], model.update(|m| { ..m, settings: False })),
],
)
Html.dialog(label, props, attrs, children) defaults to modal: Modal;
choose NonModal for an inline dialog. The element stays mounted while
closed, but its content has one scope that exists only while open. Closing
hides the dialog before disposing that content, so the browser can restore
focus to its opener. An open dialog removed with its row cannot restore
focus that way; post a focus command in the decision that removes it.
A modal initially focuses its autofocus descendant, otherwise its first
focusable descendant, otherwise the dialog itself. It makes background
controls inert. Html.on_cancel(handler) hears the text-kind cancel
event; use a preventing policy on Engine.on_with("cancel", ...) when the
app asks to refuse dismissal. Native cancellation is limited by user
activation: after one prevented request, another Escape can close without
a cancelable event until new activation. Use a preventing keymap when Escape
itself must be suppressed. Forms never navigate or close a dialog through
method="dialog": the runtime prevents every submit from mount onward.
A popover keeps its children mounted while hidden:
## An automatic popover accepts browser-driven hiding, including Escape
## and opening another unrelated automatic popover.
help : State(Ctx, Model) -> Elem(Ctx)
help = |model| Html.popover(
"Help",
{ open: model.signal().map(|m| m.help), on_toggle: model.set_value(|m, open| { ..m, help: open }) },
[],
[Engine.text("Choose settings to change your preferences.")],
)
Html.popover defaults to dismiss: Auto, accepting Escape, an outside
pointer press and release, and hiding caused by another unrelated auto
popover or a modal opening. Write the on_toggle value back to its cell or
local state. Choose Manual when unrelated popovers must stay shown
together, and provide the controls that hide them. Position either kind
with ordinary CSS, including anchor positioning.
Both handlers are required. If a handler ignores a browser close, the open signal is evaluated again and the control reopens, even when no state was written. Two unrelated auto popovers that both insist on staying open can keep dismissing each other; accept their toggles or make their desired states compatible. Test that decision as a pure function.
Native callbacks run in browser tasks and read live state at dispatch.
A delayed close after reopening can therefore carry True. Close and
toggle task sources have no promised relative arrival order: decisions
spanning them must work in either order. The helpers own their shown
properties and echo declarations. A controlled dialog rejects open,
popover and closedby attributes; a controlled popover owns its static
popover attribute. Both reject beforetoggle handlers. Extra declarations
are contract errors, including differently cased HTML attribute names.
Form Builder uses row settings dialogs, a page-level delete confirmation, and an automatic problem summary. Its invalid submit scrolls and focuses the first problem through named references (Scrolling and focus in place).
Controlled inputs
A text box’s value property is guarded, so the engine can rewrite it
without fighting the user:
- writing the value it already shows does nothing, so the caret stays put;
- a different value is held back while the box has focus or an IME composition is in progress, and applied when the box loses focus.
In practice: state written from a keystroke flows straight back, and a value
your app changes while the user is typing (clearing a draft after submit, for
example) appears when focus leaves the box. Checkboxes take checked as a
property, and a select re-applies its value when its options change.
For Escape-to-revert, post ApplyValue(reference) after restoring the
state. It applies the last rendered value while the control still has
focus, including when equality pruning emitted no new property write:
editor.update(|state| posted({ ..state, text: "Original" }, ApplyValue("editor"))),
The reference must name an input, textarea, select or option with an
explicit Prop.value (as Html controls provide). Otherwise it is a
contract error naming the reference and site. An absent reference counts
stale. During composition the command waits for compositionend, so it
does not cut an IME composition. Use it only when replacing the user’s draft
is the intended action; ordinary updates keep the guard.
A select’s choices are application values. Supply a selected-value signal,
an offered-list signal and Html.Choices(a) with stable key and label
functions. The helper owns ordinary keyed option rows; duplicate keys are
contract errors. An empty key is a real empty option value, not a sentinel.
On change it finds the key in the current offered list, in O(choices), and
returns that current value. Reusing a key with refreshed data delivers the
refreshed value. A missing key returns NotOffered without the raw text;
the decision explicitly chooses whether to write anything. A no-write arm
can leave the browser showing no choice until a later state write.
handler.from_payload_by(reading, convert) maps an arriving payload using
a signal read before that handler writes. In also, the second handler
reads after the first handler’s writes, as with handle_by. To share a
handler between controls with different payload types, bind a function that
returns it: one Roc value has one payload type.
Html controls set these properties for you. On a raw element use
Engine.prop or prop_s with Engine.Prop.value (text) or
Engine.Prop.checked (Bool). Properties prune equal values and work in
row templates. An attribute using a name claimed by a property row is a
contract error on that row’s elements. Elsewhere, such as on a custom
element, it is only an attribute. A property on an element its row does not allow, or declared
twice, is a contract error at mount. A value property on a file input is
rejected when applied, because its type can change through a signal.
Pointer input and dragging
A pointer handler receives Engine.Pointer: its id, kind (mouse, pen,
touch or other), changed button, held-button mask, modifiers, primary flag
and the zone beneath it. Use the ordinary handler constructors at this
payload type:
## Capture is declared on the press; moves are reports and cancellation is
## an ordinary typed handler that ends the same pointer's gesture.
view : {} -> Engine.Elem(Engine.Root)
view = |{}| Engine.state(
{ gesture: Idle, place: "Outside" },
|state| Html.div_attrs(
[Engine.attr("style", "display:flex;gap:24px;align-items:start")],
[
Engine.element(
"div",
[
Html.zone("grip"),
Html.aria_label("Drag handle"),
Engine.attr("style", "width:120px;height:120px;border:1px solid;touch-action:none;user-select:none"),
Html.on_pointer_down_capture(state.set_value(pressed)),
Html.on_pointer_move_paced(state.set_value(moved)),
Html.on_pointer_up(state.set_value(finished)),
Html.on_pointer_cancel(state.set_value(cancelled)),
],
[Engine.text("Drag from here")],
),
Engine.element("div", [Html.zone("target"), Html.aria_label("Drop zone"), Engine.attr("style", "width:160px;height:160px;border:1px solid")], [Engine.text("Move over this zone")]),
Html.p_s(state.signal().map(|model| model.place), [Engine.test_id("pointer-place")]),
],
),
)
| Attach function | What it does |
|---|---|
Engine.on_pointer(Down|Move|Up|Cancel, handler) | Deliver every event of that kind |
Engine.on_pointer_capture(handler) | Capture on pointerdown before its turn runs |
Engine.on_pointer_paced(handler) | Report the newest pointermove per pointer at the frame |
Html names the same choices on_pointer_down,
on_pointer_down_capture, on_pointer_move, on_pointer_move_paced,
on_pointer_up and on_pointer_cancel. Capture and pacing have their own
attach functions; they are not fields of Engine.Policy.
Html.zone(key) and zone_s(signal) set Engine.Prop.pointer_zone.
The nearest zone beneath the actual point gives pointer.at as
In({ zone, x, y }), with x and y in 1/10000 of its box: 5000 is
halfway. Outside the mount, over no zone or over a zone with no positive
area gives Outside; cancel also gives Outside. Empty text turns a
zone off. Capture changes the event’s target, while the zone still comes
from the point beneath it.
Interpret the key and fractions with a pure function:
## Zone keys stay application data. The platform reports them exactly; x and
## y are 0..10000 fractions of that zone, independently of capture routing.
place : Engine.Pointer -> Str
place = |pointer| match pointer.at {
Outside => "Outside"
In({ zone, x, y }) => "${zone}: ${x.to_str()}, ${y.to_str()}"
}
Zones provide fractions, so a drop target, splitter or swipe can be pure Roc logic and run in a native spec. They give no pixels, element sizes or drag ghost that follows the pointer. Only the nearest zone is reported.
Choose pacing for a drag whose newest position is all that matters; choose ordinary moves for a stroke that needs every sample. A waiting move is delivered before an up. The payload is captured when the event arrives, including its zone and fractions.
Start a drag only for the buttons the app accepts, update its target on
move, and end it on both up and cancel. Put touch-action:none on a touch
grip. If a result can dispose the grip during a drag, add up and cancel
handlers on a stable ancestor; the engine cannot know which state a lost
up should reset. The Kanban board keeps its
grip stable, decides the drop in Roc and preserves its Move buttons for
keyboard use. A drop that moves the pressed row ends without a click.
Capture is requested on the declaring element before dispatch. If the
browser refuses it, the handler still runs; the runtime monitor records
page.captureRefused and a pointer-capture-refused event. Pointer ids
identify active pointers; they are not persistent identities or values
whose numeric choice an app should interpret.
Derived values
map and map2 compute a value every time something it reads changes. When
the computation is expensive, or many holes read its result, cache it as a derived
signal with derive:
## `derive` caches a signal of its own. Its body re-runs only when
## the derived value changes, so readers of `count` do no work on a keystroke
## that leaves the count the same.
word_count : State(C2, Signup) -> Elem(C2)
word_count = |form|
Engine.derive(
form.signal().map(|v| v.name.split_on(" ").count_if(|w| !w.is_empty())),
|count| Html.p_s(count.map(|n| "${n.to_str()} words"), []),
)
derive evaluates its input once per change of what it reads. If the
result is equal to the last one, nothing below it runs. Holes that read only
the derived value do no work on a keystroke that leaves it unchanged.
Starting again
Local state lives as long as the piece of the view that declares it. Often that is exactly right: a branch that is switched away takes its state with it. Sometimes the piece stays but what it is about changes, and its state should not carry over. A draft belongs to the open message, and opening another message should start a new draft.
Engine.remount_on(key, body) builds body() and, whenever key changes to
an unequal value, disposes it and builds it again. Local state inside starts
again at its initial value:
Message : { id : Str, subject : Str }
inbox : List(Message)
inbox = [{ id: "m1", subject: "Welcome" }, { id: "m2", subject: "Invoice" }]
## Inside the state that holds the open message.
Mail : In(Root, Message)
program : Engine.Program
program = Engine.program(|| Engine.state({ id: "m1", subject: "Welcome" }, Replies.view))
## A button for each message, and the reply to the open one. The reply
## is built again whenever the open message's id changes.
view : State(Mail, Message) -> Elem(Mail)
view = |open|
Html.div(
"mail",
Replies.inbox
.map(|message| Html.button(message.subject, [], open.update(|_| message)))
.append(Engine.remount_on(open.signal().map(|message| message.id), || Replies.reply(open.signal()))),
)
The draft has its own state and knows nothing of the remount around it:
## The reply to the message `to`. The draft is the reply's own state: it
## is created with the reply and goes with it, so each message the
## reader opens gets a draft that starts empty.
reply : Signal(ctx, Message) -> Elem(ctx)
reply = |to|
Engine.state(
"",
|draft|
Html.div(
"reply",
[
Html.p_s(to.lift().map(|message| "Reply to ${message.subject}"), [Engine.test_id("to")]),
Html.textarea(Engine.const("Reply"), draft.signal(), [], draft.set_value(|_, typed| typed)),
Html.p_s(draft.signal().map(Replies.length), [Engine.test_id("length")]),
],
),
)
- The body takes no argument. It reads the key, if it needs it, like any other value.
- An equal key changes nothing: opening the open message again keeps its draft.
- The site keeps the key to compare it, so a key should be small, such as an id, not the record it identifies.
- Disposing the body follows the rules of every scope: its timers and subscriptions stop, and a request still in flight is delivered to the remount site, where its write to the state that has gone is skipped.
The sample’s spec pins the behaviour:
(test "a reply's draft starts again when another message is opened"
(steps
(expect-text (test-id "to") "Reply to Welcome")
(fill (label "Reply") "Thanks!")
(expect-text (test-id "length") "7 bytes")
; Opening the same message again changes nothing: the key is equal.
(click (role button :name "Welcome"))
(expect-value (label "Reply") "Thanks!")
; Another message: the reply is built again, with a draft of its own.
(mark-metrics)
(click (role button :name "Invoice"))
(expect-metric-delta scopes_disposed 1)
(expect-metric-delta scopes_created 1)
(expect-text (test-id "to") "Reply to Invoice")
(expect-value (label "Reply") "")
(expect-text (test-id "length") "0 bytes")
; Going back does not bring the first draft back: it went with its reply.
(click (role button :name "Welcome"))
(expect-value (label "Reply") "")))
When state stops being local
Local state is the right home until one of these becomes true:
- A second part of the app, somewhere else in the view, needs to read or
write it. Passing a
Statedown through every level between them is what the store is for. - It must outlive the piece of the view that shows it: a draft that should survive a change of page, a filter that should survive a branch switching.
- One event must change it together with shared state, and what each becomes depends on the same reading.
Then it is a cell of the app’s store, and Shared State is the next page.