Effects and the Browser
Apps never call JavaScript. Everything that reaches outside the page — a
request, a timer, the URL, local storage, focus — goes through an effect site.
An awaited request is an Engine.Ask(output, error): it carries the request
and the reader of its result together. Its reaction receives
Try(output, error) in a turn of its own. A result includes a timeout,
refusal or timer firing; an answer is one the other side produced, such as
an HTTP response, a job’s output or failure, or a port call’s return.
Most snippets come from www/samples/effects.roc, a search page with local state.
Effect sites
An effect site watches a signal and turns it into a list of typed asks:
Engine.watch(v, plan, reaction)issuesplan(value)at mount and again every timevchanges;Engine.watch_changes(v, plan, reaction)issues only on changes after mount.
The watched signal is any Signal: a local state’s, a cell’s, or a map of
several. The reaction says what a result writes. For local state it is a
reducer, built with st.on_result(f), which receives the state, the value
the request was issued for, and the result:
Results : [Idle, Loading, Loaded(Str), Failed(Engine.HttpError)]
## `url` is where the browser is; `nav` is an outbox of the places the app
## asks to go. They are separate so that following the back button does not
## push a new history entry. `saving` is an outbox of the searches the user
## asks to save, and `saved` those the server has kept.
Model : { query : Str, results : Results, url : Str, nav : Engine.Outbox(Str), saving : Engine.Outbox(Str), saved : List(Str), online : Bool, ticks : U64, drafts : Engine.Outbox({}), copies : Engine.Outbox({}), copy_status : Str, paste_status : Str, draft_status : Str }
Ctx : In(Root, Model)
## Issue a request whenever the query changes. The reaction receives the
## query the request was issued for, so a late answer to an old query is
## recognised and ignored.
search : State(Ctx, Model) -> Elem(Ctx)
search = |model|
Engine.watch_changes(
model.signal().map(|m| m.query),
|q| [Engine.http_body({ url: search_url.append_query_param("q", q).request_target(), timeout: Ms(5000) })],
model.on_result(
|m, q, res|
if q != m.query {
m
} else {
match res {
Ok(body) => { ..m, results: Loaded(body) }
Err(err) => { ..m, results: Failed(err) }
}
},
),
)
Passing the issued-for value is what makes out-of-order answers safe. If the user typed again before the first answer arrived, the reaction sees an old query and ignores the answer. Which answer wins is your decision, made in ordinary Roc.
Each ask keeps the reader chosen when it is issued. A result uses that
reader even if the signal has changed; a resource never runs its plan again
to interpret an answer. If a plan mixes different successes or errors, map
each ask into one application vocabulary with map_ok, map_err or map
before building the list. The File Tools sample does this for upload,
digest, preview and text reads.
A kept request moves its issued-for value and reader together to the nearest surviving owner on disposal. Cancellation, supersession, a terminal result or refusal releases its reader; subscription messages and progress retain it.
Because sites issue on change, two equal values in a row issue once. A request the user’s action asks for, which must be sent again for an equal value, is posted to an outbox instead.
Sending when the user acts
A save, an add or an order is asked for by a click, not by a value
changing. Keep an Engine.Outbox(item) in the state, made with
Engine.outbox({}); the handler posts to it with box.post(item), and
Engine.on_post(box, plan, reaction) issues plan(item) in the turn of the
post:
## The click posts the query to an outbox in the state, and the `on_post`
## site sends it in the same turn. Saving the same query twice is two
## requests, and each answer arrives with the query it was posted with.
save : State(Ctx, Model) -> List(Elem(Ctx))
save = |model| [
Html.button("Save search", [], model.update(|m| { ..m, saving: m.saving.post(m.query) })),
Engine.on_post(
model.signal().map(|m| m.saving),
|q| [Engine.http_body({ method: "POST", url: "/api/saved", body: q, timeout: Ms(5000) })],
model.on_result(
|m, q, res|
match res {
Ok(_) => { ..m, saved: m.saved.append(q) }
Err(_) => m
},
),
),
]
- Each post is sent, an item equal to the last one included: two outboxes are equal only when they hold the same post.
- The reaction is given the item it was posted with, so several posts can be in flight and each answer knows its own.
- Nothing is sent at mount, and nothing is ever cancelled for a later post,
as with
watch_changes. Disposing the site follows the usual rules: an HTTP request or a port call still completes, in the nearest surviving owner. - The reducer that changes the state posts in the same step, so an
expectsees both:box.last()isUnpostedorPosted(item). - Post at most once per turn to one outbox. A change that sends several
things posts a list (
Engine.Outbox(List(Note)), sent as|notes| notes.map(request)). A second post in the same turn would replace the first before the site saw it, so it is a contract error.
An outbox can be a cell of the store as well: a decision posts to it with
box_cell.update(|box| box.post(item)), as the shop below does.
Results that write the store
When a result changes shared state, the reaction is a decision: one pure
function from the result to a list of writes
(Shared State). Engine.react(decide)
gives decide the value the request was issued for and the result.
Engine.react_by(v, decide) also gives it the value v holds when the
result arrives, read once and before anything is written. This is the
shop’s order, from www/samples/shop/Shop.roc:
## What the server's answer to an order of `total` writes. An accepted
## order is counted and starts the basket again; a refused one leaves
## the basket as it was.
ordered : U64, Try(Str, Engine.HttpError) -> List(Engine.Write(_))
ordered = |total, res|
match res {
Ok(_) => [
Shop.cells.orders.update(|count| count + 1),
Shop.cells.basket.reset,
Shop.cells.notice.set("Order placed for ${total.to_str()}."),
]
Err(_) => [Shop.cells.notice.set("The order was not placed. Your cart is as it was.")]
}
## The site that sends each order posted, and decides what its answer
## writes.
ordering : {} -> Elem(ctx)
where [ctx.store : () -> Engine.Reach(ctx, _)]
ordering = |{}|
Engine.on_post(
Shop.cells.sending.signal(),
|total| [Engine.http_body({ method: "POST", url: "/api/orders", body: total.to_str(), timeout: Ms(5000) })],
Engine.react(Shop.ordered),
)
ordered is tested as a function, with no request made
(Shared State shows its expect),
and a spec stages the server’s answer:
(test "an accepted order is counted and starts the basket again; a refused one keeps it"
(steps
; Nothing in the cart: the decision returns no write and nothing is sent.
(click (role button :name "Check out"))
(expect-pending-effects 0)
(expect-text (test-id "notice") "Welcome.")
(click (role button :name "Add Tea"))
(click (role button :name "Add Jam"))
(click (role button :name "Cart (2)"))
(fill (label "Note for the courier") "Leave it by the door")
(expect-text (test-id "total") "Total 9")
; The server refuses the first order.
(click (role button :name "Check out"))
(expect-text (test-id "notice") "Sending your order.")
(expect-pending-effects 1)
(stub-http "refused" :url "/api/orders" :status 503 :body "")
(run-effect 1)
(expect-text (test-id "notice") "The order was not placed. Your cart is as it was.")
(expect-text (test-id "orders") "Orders placed: 0")
(expect-visible (role button :name "Cart (2)"))
; Sending the same total again is a second request, and it is accepted.
(click (role button :name "Check out"))
(stub-http "placed" :url "/api/orders" :status 201 :body "")
(run-effect 2)
(expect-text (test-id "notice") "Order placed for 9.")
(expect-text (test-id "orders") "Orders placed: 1")
(expect-visible (role button :name "Cart (0)"))
(expect-text (label "Tea in cart") "0 in cart")
; The note started again with the cart: one reset wrote both.
(expect-value (label "Note for the courier") "")))
first.also(second) makes one reaction of two, both run for one result: a
component’s own reducer, and the reaction its owner handed it.
Superseding sites
watch and watch_changes never cancel what they issued. When only the newest
value’s answer matters — a search box, the selected item — say so with a
superseding site instead of filtering answers in the reaction:
-
Engine.keep_current(v, plan, reaction)lets old work finish while accepting only the latest issuing step’s results. All requests from that step may answer, including progress. A changed value with an empty plan invalidates the earlier step too. Withheld answers count as delivered to the site, but run neither their reader nor reaction. After disposal, an eligible kept request must also match the signal read in its surviving ancestor. Usewatch_latestfor subscriptions. Keepwatchoron_postwhen every outcome matters, such as a mutation whose failures must all be shown. -
Engine.watch_latest(v, plan, reaction)issues likewatch, but before it issues for a new value it cancels everything it still has in flight for earlier ones: the fetch is aborted, a subscription stops, a timer is cleared, and a late answer never reaches the reaction. Aplanthat returns[]makes a change a pure cancel. -
Engine.resource(input, { init, pending, plan, resolve }, body)keeps the results in a signal thatbodyreads like a derived signal.pending(s, a)sets the signal when the input changes, in the same turn (a loading state that still holds the previous answer, say);resolve(s, a, res)sets it from each result for the current input. Readers below do no work when either returns an equal value.Worker.resourceandPort.resource(taught in Workers and Ports) are resources that follow one answer, held as anEngine.Remote. -
Engine.gather(asker, inputs, body)asks one request per input, all at once, and keeps the answers in anEngine.Gatheredsignal:jobs, each input’s job asWorking,Answered(output)orFailed(error), andall, anEngine.Remoteof the whole list in input order once no job is working (or the first failure).Worker.gatheris this for a task’s jobs; see Workers.
Both cancel only on a new value. Disposing them follows the same rules as any effect site: subscriptions and timers stop, and an admitted request still completes in the nearest surviving owner, where its write to the disposed resource is skipped.
A reaction that compares a serial, or the value it was issued for, with the
state to drop an old answer is asking for watch_latest: let the site cancel the
old request instead. Keep watch and such a check only where cancelling an
in-flight request would be wrong, such as a write the server must finish.
An Engine.Remote signal is read with remote.answered(), the latest answer
as a Try: ?? default shows a fallback, .map_ok(f) picks from it, and a
handler matches Ok(output). It keeps the answer while a newer request is
pending, and is Err(NoAnswer) before the first answer and after a
failure. To combine the answer with state outside the resource (the page a
list is on, say), lift that state in and map both:
v.lift().map2(r, |s, remote| ...).
Requests
Plans return typed asks. The reaction receives the listed value inside Ok,
or the ask’s typed failure inside Err.
| Ask | Success and failure |
|---|---|
Engine.http({ url, … }), file.upload({ url, … }) | A response with status, headers and text body, at every status; Network(message), Timeout or Refused |
Engine.http_body({ url, … }) | A 2xx text body; also classifies other statuses as Status(code) |
Engine.storage_get(key), Engine.session_get(key) | Text, including an empty string; Missing or Refused |
Engine.storage_changes(key) | Another document’s Set(text) or Removed, newest per frame; Refused |
Engine.storage_write_failures({}) | { store, key, reason }, where store is Local or Session and reason Quota or Unavailable; Refused |
Clipboard.text(text), Clipboard.html({ text, html }) | {}; NotAllowed, Unavailable or Refused |
Engine.timer(ms), Engine.interval(ms) | I64 wall-clock milliseconds, once or repeatedly; Refused |
Engine.popstate({}) | The URL on back or forward; Refused |
Engine.online_changes({}), Engine.visibility_changes({}), Engine.media_changes(query) | The corresponding boolean, newest per frame; Refused. A media query must be declared in ProgramProps.media |
task.ask(input) | The task’s output or Worker.Error(error); see Workers |
file.read_bytes(props), file.read_utf8(props) | Bytes or text; FileError, including refusal |
file.sha256(), file.object_url() | Digest bytes or a URL; FileError |
File.fetch({ url, … }) | A response with status, headers and a file body, at every status; Network(message), Timeout, TooLarge or Refused |
call.ask(input), subscription.ask(input) | The declared port output or message; Port.Error |
Engine.again({}) | {} in a follow-up turn |
Commands such as Title, Push, Replace, storage writes, focus, scrolling,
file saves and port sends await no result. Put one in a typed plan with
Engine.command(command). Cleanup plans still return List(Command).
Engine.ask_of(protocol, input) adapts a request/result protocol once, when
issuing it. Task and port request/result methods remain useful for pure
protocol tests and resource adapters. ask.sent() exposes the request for
such tests. Engine.raw(request) deliberately receives the whole
Engine.Result union; ordinary app reactions use the typed constructors.
Engine.http leaves HTTP status policy to the app. Use http_body when a
non-2xx response is a failure, or map the full response yourself when headers
or another policy matter. Public timeout props are Unlimited or Ms(ms);
the runtime caps an armed timeout at ten minutes.
To see where a worker job’s time goes and how busy the pool is, read the runtime’s monitor; see Monitoring Workers.
Building URLs
Build request URLs from decoded text with Url, as the search sample does.
A checked root-relative literal needs no invented origin. append_query_param
keeps a search value in one query pair, and request_target emits the path
and query HTTP sends, without a fragment or origin. Use to_str() when
passing an absolute URL to a browser request: its origin must be retained,
and a valid absolute path beginning // would otherwise be read as another host.
For a path name, handle the result of append_path_segments: an empty name,
. or .. has no safe target. To read a location, parse it once and use
path_segments and query_pairs; malformed escapes and escaped invalid UTF-8
are typed errors. Parsing normalizes dot segments and retains other empty
segments. The strict HTTP(S) subset rejects browser repairs and a root-relative
path whose normalized text begins //, which would mean an authority reference.
HTTP options
Build a request with Engine.http({ url }). Its HttpProps default to
method: "GET", empty headers and body, timeout: Unlimited,
cache: Default and credentials: SameOrigin. timeout: Ms(ms) is capped
at ten minutes. A finite timeout must be at least one millisecond: Ms(0)
is a contract error when Engine.http constructs the ask; use Unlimited
for no timeout. Cache modes are Default, NoStore, Reload, NoCache
and ForceCache, passed directly to the browser’s fetch policy. A polled
status endpoint can use NoStore; NoCache permits a stored response after
revalidation. Include credentials permit cross-origin cookies subject to
the browser’s cookie and CORS rules. There is no Omit, OnlyIfCached or
mode option.
File.fetch has the same cache and credentials options. file.upload
has credentials but no cache option. A mount’s own fetch receives these
options on every request, even when progress is requested.
Transfer progress
Attach a progress handler to the final-result reaction:
## Attaching this handler asks for sampled progress on the site's transfers.
## Reports update the caption; only the final result answers the request.
progress_search : {} -> Elem(ctx)
progress_search = |_| Engine.state(
{ sent: Engine.outbox({}), caption: "Not started" },
|state| Html.div(
"transfer",
[
Html.button("Download report", [], state.update(|s| { ..s, sent: s.sent.post({}), caption: "Starting…" })),
Engine.on_post(
state.signal().map(|s| s.sent),
|_| [Engine.http_body({ url: "/api/report", cache: NoStore, credentials: Include, timeout: Ms(30000) })],
state.on_result(
|s, _, result| {
..s,
caption: match result {
Ok(_) => "Report received"
Err(error) => "Report failed: ${Str.inspect(error)}"
},
},
).with_progress(
{ every_ms: 250 },
state.on_progress(
|s, _, transfer| {
..s,
caption: match transfer.total {
Known(total) => "Received ${transfer.done.to_str()} of ${total.to_str()} bytes"
Unknown => "Received ${transfer.done.to_str()} bytes"
},
},
),
),
),
Html.p_s(state.signal().map(|s| s.caption), []),
],
),
)
Transfer carries direction (Sending or Receiving), done: U64 and
total: Known(U64) or Unknown. The handler receives the value the request
was issued for, as the final reaction does. State.on_progress writes local
state; Engine.react_progress builds a pure decision over store cells.
Attaching it with reaction.with_progress(props, handler) asks for progress
on every HTTP, upload or fetch request that site issues. every_ms defaults
to 100 and has a floor of 16 milliseconds. Reaction.also composes progress
handlers in the same atomic order as final reactions, with the smaller
interval for the composed site. A later with_progress replaces its progress
attachment. resource and gather have no
reaction to attach it to; use a watch_latest site when progress matters.
A report does not answer or retire the request. One undelivered report per
request waits for a frame and newer counts replace it in place. The final
result drains earlier reports first; cancellation and timeout discard them.
Result gains no progress arm, so existing answer helpers keep their meaning.
A reparented request’s progress handler runs in the surviving ancestor’s
environment; writes to retired local state are skipped and counted.
Receiving an HTTP body is counted from its response stream. Its total is
unknown when the length is absent, encoded, or the runtime cannot establish
that the visible length describes the decoded body. Uploads and default-cache
file downloads that ask for progress use XMLHttpRequest, keeping the file
body in the browser. A cross-origin upload with progress sends a CORS
preflight: the server must answer OPTIONS, even when the same upload without
progress is a simple request.
A file download with both a non-default cache mode and progress uses a fetch
stream, holding the body in JavaScript memory up to maxFileBytes. A mount’s
own fetch is always honoured; it likewise counts received bytes from the
stream and reports sending complete once for an upload. Both transports
answer the same status and headers; a fetched file’s type is the response’s
Content-Type, or empty when absent. Progress is a courtesy, and may be coarse
when the transport cannot expose intermediate counts.
Cancelling or superseding a transfer aborts its fetch or XHR. Disposing its site keeps an admitted request running under the ordinary reparenting rule.
User activation
Requests and port commands posted by a click’s on_post or on_post_by site
are performed inside that click’s listener. A gesture-sensitive browser
operation must start in the handler before yielding. Starting it from a later
answer or timer turn has no guarantee of activation. See the
permission and share recipes.
Commands
Commands are emitted and forgotten, so their reaction is Engine.ignore({}):
## Commands are emitted and forgotten: the title follows the query, and the
## query is saved for the next visit.
commands : State(Ctx, Model) -> List(Elem(Ctx))
commands = |model| {
query = model.signal().map(|m| m.query)
[
Engine.watch(query, |q| [Engine.command(Title(if (q.is_empty()) "Search" else "Search: ${q}"))], Engine.ignore({})),
Engine.watch_changes(query, |q| [Engine.command(StorageSet("query", q))], Engine.ignore({})),
]
}
Animation
Ask for ViewTransition(types) from an effect site watching the value whose
change should animate. A result turn then animates just as a click does:
## A transition watches the value that changes the drawing. It starts
## after mount; each later change marks the complete batch for this call.
main : Engine.Program
main = Engine.program(
|| Engine.state(
False,
|show_details| Html.div(
"",
[
Html.button("Details", [], show_details.update(|visible| !visible)),
Engine.when(show_details.signal(), || Html.p("More about this book", ""), || Html.p("Book summary", "")),
Engine.watch_changes(show_details.signal(), |_| [Engine.command(ViewTransition(["shelf"]))], Engine.ignore({})),
long_exit({}),
],
),
),
)
It marks the complete batch of one host call, including its follow-up turns.
Several requests merge their types in first-issue order, removing duplicates.
The command awaits no result, occupies no in-flight slot, and never marks the
mount batch, even if a watch asks for it there. watch_changes expresses
that intention directly. Types are passed to the browser as supplied; use CSS
identifiers matched by :active-view-transition-type().
Style the browser’s snapshots with CSS. Give each independently moving row a
unique view-transition-name derived from its stable app key, with an identifier
prefix such as book-. A shared view-transition-class lets many uniquely
named rows share animation rules. Reading List demonstrates moves, entries
and removals, with different active types for shelf and book changes. Its CSS
lives with its Roc view, so every mount uses the same rules.
A transition captures at document scope and there is only one running per
document. A later one replaces the previous animation at its final state,
including animations from another mount. The browser’s capture cost follows
the page and its named elements, rather than how many rows changed. Name only
what should move independently. If your app is embedded in a page it does not
own, mount with viewTransitions: "off"; the default is "document".
The browser calls the update asynchronously. Until then the old page remains
and inputs queue; once the update runs, its DOM commands and node commands
such as focus run together, then queued inputs drain. An event for a removed
element is dropped. Effects that name no node, including saves, port commands,
HTTP and storage, run immediately when the call returns, preserving a click’s
user gesture. This deliberately puts them before focus and other node commands
in a marked batch, even if issued later. The API being absent, an actually
hidden document or the mount option "off" applies directly with the usual
DOM-before-effects order. A missing callback falls back after 1000 ms, and a
full queue while waiting forces the update sooner.
Input and reduced motion
::view-transition { pointer-events: none; } lets input reach uncaptured
parts of the page. Elements inside a captured subtree remain unavailable to
hit testing until their snapshots finish. Reading List sets the root’s
view-transition-name to none and captures book rows only: its form and
shelf buttons stay interactive, while controls inside a transitioning book
wait for its snapshots to finish. This is a browser cost the app’s capture
boundaries and animation duration must account for. See the browser’s
guide to groups of named elements.
Honor prefers-reduced-motion in the app’s CSS. For example, turn off the
snapshot animations:
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) { animation: none !important; }
}
An app that wants not to ask can also declare a media preference and gate its request plan. The runtime never guesses a motion preference. Duplicate live transition names can reject the animation; the update still applies and the monitor reports the rejection.
Entries and long exits
@starting-style supplies a newly inserted element’s initial CSS, including
on mount. A moved row uses insertBefore and can replay that entrance. Inside
a view transition, style entering snapshots through
::view-transition-new(...):only-child instead. Reading List limits its
@starting-style fallback to @supports not (view-transition-name: none).
Removing a row still removes its real DOM, routes, state and scoped requests in the ordinary turn. Its old snapshot can fade after removal; the runtime keeps no outgoing node. For a long exit that must keep real content on the page, model leaving in the app:
## The row stays in the app's list while leaving. Its own scope owns the
## timer, so disposing the row cancels it. CSS can animate `.leaving` for
## 1500 ms; the timer's result then removes the row from the list. At the
## in-flight bound, refusal removes it immediately rather than leaving it stuck.
long_exit : {} -> Engine.Elem(ctx)
long_exit = |_| Engine.state(
[{ id: "slow", title: "A slowly leaving book", leaving: False }],
|books| Engine.each(
books.signal(),
|book| book.id,
|row| Engine.element(
"article",
[Engine.class_s(row.item().map(|book| if (book.leaving) "leaving" else ""))],
[
Engine.text_s(row.item().map(|book| book.title)),
Html.button("Remove slowly", [], books.lift_row().update_by(row.key(), |current, id| current.map(|book| if (book.id == id) { ..book, leaving: True } else book))),
Engine.watch_changes(
row.item(),
|book| if (book.leaving) [Engine.timer(1500)] else [],
books.lift_row().on_result(
|current, issued, result| match result {
Ok(_) | Err(Refused) => current.keep_if(|book| book.id != issued.id)
},
),
),
],
),
),
)
Here the keyed row stays mounted with a leaving class while its row-scoped
1500 ms timer waits. CSS gives that class the matching exit animation. Both
Fired(_) and Refused remove it, so an exhausted in-flight allowance cannot
leave it stuck. Specs can assert this intermediate state in either runner.
No animation-frame subscription is needed. CSS transitions interpolate
progress between values written by an Interval; a countdown uses an
Interval directly. A custom canvas element can own its drawing frame loop
and read the latest state from an attribute, without making Roc compute a
turn for every frame.
Startup data
For a deterministic prerendered entry, request live facts after construction
with Engine.environment; see Startup and Deferred Content.
Its typed answer has the same fields described below. The existing boot-based
constructors remain available for pages whose first render intentionally reads
live facts.
Values a boot-based app needs before its first render come in the boot data.
Engine.program_boot declares the storage keys to read, and receives the URL,
those values, and whether the browser is online, the page visible and local
storage usable:
## Declared storage keys are read before mount and arrive in `Boot`, with the
## URL and whether the browser is online and the page visible.
main : Engine.Program
main = Engine.program_boot(
{ storage_keys: ["query"], session_keys: ["query.draft"], max_inflight: 32 },
|boot| Engine.state(initial(boot), page),
)
initial : Engine.Boot -> Model
initial = |boot| { query: Engine.boot_session(boot, "query.draft") ?? (Engine.boot_storage(boot, "query") ?? ""), results: Idle, url: boot.url, nav: Engine.outbox({}), saving: Engine.outbox({}), saved: [], online: boot.online, ticks: 0, drafts: Engine.outbox({}), copies: Engine.outbox({}), copy_status: "", paste_status: "", draft_status: if (boot.session_available) "" else "Drafts cannot survive a reload" }
When local storage is unavailable (disabled site data, a throwing
localStorage, or a declared key holding text Roc cannot hold, such as a
lone surrogate another script wrote), boot.storage_available is false and
boot.storage is empty. After boot, a read of a key whose value cannot be
read answers Missing, as a read of an absent key does.
Session storage has the same rule: declare session_keys, read them with
Engine.boot_session(boot, key), and check boot.session_available.
boot.session is empty when that service is unavailable. Each service is
independent, so one can work while the other cannot.
Engine.program_store takes the same configuration for an app with a store,
and hands the boot data both to the function that starts the store and to
the view (see Shared State).
Both functions accept defaulted ProgramProps: omit storage_keys and
session_keys for none, max_inflight for 32, media for no queries and zone_days for
366 days each side of mount, or pass {} for all defaults.
A page embedding an app can supply environment.online() and visible()
readers, called at boot and when the corresponding browser event answers a
live subscription. Both return booleans. environment.matchMedia(query)
is called for each declared query at boot and when a media subscription
starts. It returns an object with Boolean matches and addEventListener
and removeEventListener methods. The subscription retains that object
and reads matches when its change event arrives.
Omitted readers use the browser through the runtime’s window and document.
Report scheduling also reads visible() to choose a frame or the hidden
page’s microtask drain. Tests can supply fixed facts while exercising the
real subscription listeners.
Keep services in their own options: storage and sessionStorage provide
local and session reads and writes,
fetch performs HTTP requests and ports supplies port handlers. The URL
comes from the document’s location, and max… options cap deployment work.
Unknown environment keys, non-functions and failed boot reads refuse
mount; a reader that throws or returns the wrong type later stops the
instance with an executor fault.
Drafts and other tabs
Session storage survives a reload in the same tab. Use it for a draft, with local storage for the saved document. On boot, choose the draft before the saved document. The Markdown Editor demonstrates that choice. It keeps the draft even after Save, so a failed local write cannot discard the safety net. After a reload it treats a restored draft as unsaved until Save, without comparing two potentially large documents.
## The tab keeps its own draft. A failed write becomes a visible message;
## the failure subscription also hears refused writes to local storage.
drafts : State(Ctx, Model) -> List(Elem(Ctx))
drafts = |model| [
Engine.on_post_by(model.signal().map(|m| m.drafts), model.signal().map(|m| m.query), |query, _| [Engine.command(SessionStorageSet("query.draft", query))], Engine.ignore({})),
Engine.watch(
Engine.const({}),
|_| [Engine.storage_write_failures({})],
model.on_result(
|m, _, result| match result {
Ok({ store: _, key, reason: Quota }) => { ..m, draft_status: "Not kept: ${key} is over the storage quota" }
Ok({ store: _, key, reason: Unavailable }) => { ..m, draft_status: "Not kept: storage for ${key} is unavailable" }
Err(Refused) => { ..m, draft_status: "Storage failures cannot be reported" }
_ => m
},
),
),
Html.p_s(model.signal().map(|m| m.draft_status), []),
]
SessionStorageSet and SessionStorageRemove are commands, like their
local counterparts. A successful write adds no result turn. A write that
cannot persist warns in the console; mount StorageWriteFailures when the
app must tell its reader. Each failure arrives in a separate turn, one
task after its batch, as StorageFailed({ store, key, reason }). A full
store reports Quota; an unavailable one reports Unavailable. Handle
Refused too: that means the subscription could not take an in-flight slot,
so it will report no failed writes.
StorageChanges(key) subscribes to another document’s writes to a local
key. A storage event captures its newValue immediately, or Missing
for removal, clear() or a value Roc text cannot hold. These are reports: several waiting writes to
one subscription replace its queued value in place. A clear() reports
Missing to every subscription. This document’s own writes never echo,
and session storage has no cross-tab subscription.
The app decides what another tab’s value means. A clean editor can load it;
a dirty editor can ask whether to load theirs or keep its own. A report
can describe a value this tab has already replaced with a later write.
Local storage cannot order concurrent writes; use an app-level revision
when convergence matters. Another mount in the same document also raises
no storage event; use an app’s port over BroadcastChannel if those
mounts must communicate.
Warning before leaving
Engine.guard_leave(dirty) renders no DOM. While any mounted guard reads
true, the runtime asks the browser to confirm leaving the document:
## Pass the editor's dirty signal, usually a comparison of two revision
## numbers. Its live true guards jointly request one leave warning.
leave_warning : Engine.Signal(Ctx, Bool) -> Elem(Ctx)
leave_warning = |dirty| Engine.guard_leave(dirty)
The engine settles all guards once at the end of the turn. Replacing one true guard with another keeps the warning on, with no off/on gap. The site uses no in-flight slot and cannot be refused. False signals and disposal remove their contribution. Unmount and recovery remove the listener; a poisoned app keeps its last applied warning while its page remains visible.
This is a courtesy, with no custom message. Browsers require prior user
interaction and may skip the dialog, particularly on mobile. A same-origin
reload can preserve that interaction, so a restored dirty draft can still
ask before the reader leaves again. Keep a session draft as the safety net. In-app navigation is already the app’s own Push
decision, so this guard adds no in-app router callback.
Copying and pasting text
Clipboard.text(text) writes plain text. Clipboard.html({ html, text })
writes both representations in one item, so an app never relies on a
browser accepting two writes in one gesture. Post the request from the
button’s turn to keep that gesture’s activation:
## Post a small marker and read the text only when issuing its request.
## The site retains the marker, so it does not keep an old copy of the query.
## Issuing in the button's turn retains that gesture's activation.
copy_search : State(Ctx, Model) -> List(Elem(Ctx))
copy_search = |model| [
Html.button("Copy search", [], model.update(|m| { ..m, copies: m.copies.post({}) })),
Engine.on_post_by(
model.signal().map(|m| m.copies),
model.signal().map(|m| m.query),
|text, _| [Clipboard.text(text)],
model.on_result(
|m, _, result| {
copy_status = match result {
Ok(_) => "Copied"
Err(NotAllowed) => "Copy blocked by the browser"
Err(Unavailable) => "The clipboard is unavailable"
Err(Refused) => "Too many requests to copy now"
}
{ ..m, copy_status }
},
),
),
Html.p_s(model.signal().map(|m| m.copy_status), []),
]
on_post_by(box, reading, plan, reaction) keeps the posted marker as its
equality input.
It samples reading when the post issues and gives plan that reading and
the item. Changes to the reading alone issue nothing. This keeps a large
document in its source cell, rather than retaining it in an old outbox post.
The reaction still receives the posted item; put any identity the answer
needs in that item explicitly. A reader returned by the plan may capture
parts of the sampled reading; those captures remain live until its request
ends. A later sample cannot change an already-issued reader.
The clipboard ask delivers Ok({}) or Err(NotAllowed),
Err(Unavailable) or Err(Refused). NotAllowed covers denied permission, missing activation or
an unfocused page; Unavailable covers an absent clipboard service.
Outside a click’s turn Chrome usually permits a focused page, while
Firefox and Safari require activation. The write cannot be aborted, so its
request is kept when its site is disposed, like an HTTP request.
Html.on_paste_text(handler) receives Text(text) or TooLarge, and
prevents the paste’s default on that element:
## This focusable zone imports plain text and prevents the ordinary paste.
## Oversized text changes only the message, preserving the query.
paste_search : State(Ctx, Model) -> Elem(Ctx)
paste_search = |model| Html.div_attrs(
[
Engine.attr("tabindex", "0"),
Engine.attr("aria-label", "Paste a search"),
Html.on_paste_text(
model.set_value(
|m, pasted| match pasted {
Text(text) => { ..m, query: text, results: Loading, paste_status: "Search imported", draft_status: "", drafts: m.drafts.post({}) }
TooLarge => { ..m, paste_status: "Pasted text is too large" }
},
),
),
],
[Engine.text("Paste a search here"), Html.p_s(model.signal().map(|m| m.paste_status), [])],
)
The runtime reads plain text during dispatch. maxPasteBytes caps its UTF-8
size, 4 MiB by default; over the bound the app receives TooLarge. The
browser first provides the whole string; the limit then bounds validation,
UTF-8 copying and Wasm staging. Pasted text that is not well-formed
Unicode (a lone surrogate, which Roc text cannot hold) is not delivered at
all, nor is an input’s value that holds one; the runtime monitor counts
each in page.textRefused. A key event whose key or code holds one is heard
by no keymap. An element takes pasted text or pasted files, since it has one handler per
event type. An ordinary on("paste", ...) still receives its ordinary
empty text payload. Reading the clipboard on demand remains a port’s
business; the paste event covers text the user chooses to paste.
Time, randomness and locale
A boot-based first render receives boot.now_ms (I64 milliseconds since the
Unix epoch), boot.seed (U128), boot.languages in preference order and
boot.zone. A deterministic entry receives those fields from a later
Engine.environment request. Each returned value is an immutable sample;
request another when the app needs fresh facts. Engine.timer and Engine.interval
answer with an I64 wall-clock sample, in milliseconds since the Unix epoch,
when their callback ran.
Engine.timer accepts delays from 0 to 2,147,483,647 milliseconds;
Engine.interval accepts periods from 1 to that same browser limit.
A zero interval or a larger delay is a contract error when the site issues
it, before admission. A zero one-shot delay remains legal: it samples time
on the callback rather than imposing a timeout.
A clock for what is shown
Initialize a clock cell from boot and write each interval sample into it:
## The first paint uses the mount's sample. Ticks replace it with the
## callback's wall-clock time rather than counting elapsed intervals.
start : Engine.Boot -> Engine.Store(_, _)
start = |boot| TimeApp.store.with_initial(TimeApp.cells.clock, boot.now_ms).with_initial(TimeApp.cells.random, Time.seed_state(boot.seed))
clock_site : {} -> Engine.Elem(ctx)
where [ctx.store : () -> Engine.Reach(ctx, _)]
clock_site = |_props| Engine.watch(
Engine.const({}),
|_| [Engine.interval(30000)],
Engine.react(
|_, result| match result {
Ok(at_ms) => [TimeApp.cells.clock.set(at_ms)]
_ => []
},
),
)
Counting ticks drifts when the browser delays them. This cell is as old as its last sample; use it for relative ages such as “3 min ago”. Field Notes samples every thirty seconds, with a separate clock cell so only time-reading holes refresh. It also requests a fresh sample on returning visible.
A sample for an action
An action posts to an outbox; its site issues Engine.timer(0) and the reaction
uses that timer’s sample:
## Asking for an action's time posts a request. It does not mistake the
## displayed clock, which may be an old tick, for a fresh sample.
stamp : {} -> List(Engine.Write(_))
stamp = |_props| [TimeApp.cells.action.set(Waiting), TimeApp.cells.stamps.update(|outbox| outbox.post({}))]
stamp_site : {} -> Engine.Elem(ctx)
where [ctx.store : () -> Engine.Reach(ctx, _)]
stamp_site = |_props| Engine.on_post(
TimeApp.cells.stamps.signal(),
|_| [Engine.timer(0)],
Engine.react_by(
TimeApp.cells.clock.signal(),
|clock, _, result| match result {
Ok(at_ms) => [TimeApp.cells.action.set(Stamped(at_ms))]
Err(Refused) => [TimeApp.cells.action.set(Stamped(clock))]
_ => []
},
),
)
The sample arrives a task after the action, rather than inside its turn.
Background throttling can delay it by seconds or minutes, and suspension can
delay it further. The timer holds an in-flight slot until it answers; handle
Refused, here by using the last clock sample. The wall clock may jump
backwards. Field Notes then shows “just now” rather than a negative age.
Pure decisions take these values as data, so their tests need no real clock.
Self still answers bare Now, which carries no time.
Local dates and language
boot.zone is the user’s offsets in minutes east of UTC over an inclusive
span the browser measured, one to 128 of them. It is opaque: only checked boot/environment facts and
Engine.utc make one, so it is never malformed. zone.name() is its IANA
name ("" when the browser did not know one), and zone.offset_at(time)
the offset at a time, or OutsideZone beyond the span; handle it without
guessing an offset:
## A zone is a value with a stated span. A date outside it is an error the
## app handles, rather than using today's offset for a different instant.
local_time : { zone : Engine.Zone, at_ms : I64, language : Str } -> Str
local_time = |{ zone, at_ms, language }| match zone.offset_at(at_ms) {
Err(OutsideZone) => "Outside saved time zone"
Ok(offset_minutes) => match Time.clock_text({ at_ms, offset_minutes, language }) {
Ok(clock) => clock
Err(OutsideCalendar) => "Outside supported calendar"
}
}
Ask for the span in the program’s zone_days (366 by default, at most 7305
on each side of mount). The browser probes offsets daily and bisects changes
to the millisecond. If more changes than fit are found, the span is shortened
from both ends, still including mount time. Its returned bounds remain true.
The zone and languages stay as mounted until reload, even if the user’s
settings change while the page stays open.
Formatting belongs to the app. This sample’s pure civil-date conversion is:
## Gregorian civil date from days since 1970-01-01. Floor division gives
## days before the epoch their own date instead of truncating toward zero.
civil_date : I64 -> { year : I64, month : U8, day : U8 }
civil_date = |days| {
shifted = days.to_i128() + 719468
era = floor_div({ number: shifted, divisor: 146097 })
day_of_era = shifted - era * 146097
year_of_era = (day_of_era - day_of_era // 1460 + day_of_era // 36524 - day_of_era // 146096) // 365
year = year_of_era + era * 400
day_of_year = day_of_era - (365 * year_of_era + year_of_era // 4 - year_of_era // 100)
march_month = (5 * day_of_year + 2) // 153
day = day_of_year - (153 * march_month + 2) // 5 + 1
month = march_month + (if (march_month < 10) 3 else -9)
# Every I64 day has an I64 year; month and day are respectively
# 1..12 and 1..31. These narrowings cannot discard significant bits.
{ year: (year + (if (month <= 2) 1 else 0)).to_i64_wrap(), month: month.to_u8_wrap(), day: day.to_u8_wrap() }
}
## UTC text for an HTML time element. This example supports civil years
## 0001 through 9999 and reports an outside date instead of wrapping it.
utc_text : I64 -> Try(Str, [OutsideCalendar])
utc_text = |at_ms| {
parts = calendar_parts({ at_ms, offset_minutes: 0 })?
fraction = if (parts.millisecond == 0) "" else ".${pad({ number: parts.millisecond.to_u64(), width: 3 })}"
Ok("${pad({ number: parts.year.to_u64_wrap(), width: 4 })}-${pad({ number: parts.month.to_u64(), width: 2 })}-${pad({ number: parts.day.to_u64(), width: 2 })}T${pad({ number: parts.hour.to_u64(), width: 2 })}:${pad({ number: parts.minute.to_u64(), width: 2 })}:${pad({ number: parts.second.to_u64(), width: 2 })}${fraction}Z")
}
The app chooses its own pattern: Field Notes uses twelve hours for its first
language en-US, twenty-four otherwise. This is an app rule, not CLDR.
Browser CLDR formatting can use a batched port call; a hole never calls
Intl synchronously. The platform ships no calendar or formatting package.
Ids from the seed
Keep a generator’s state in a cell, or with the value whose parts must agree with it. The sample chooses a pure, non-cryptographic SplitMix64 stream and folds both halves of the boot seed into it:
## Fold the boot seed into the state of this app's SplitMix64 stream.
seed_state : U128 -> U64
seed_state = |seed| seed.to_u64_wrap().bitwise_xor(seed.shr_zf_wrap(64).to_u64_wrap())
## Take one value and the next state. Wrapping arithmetic is the generator's
## definition; it is never used to repair a timestamp or a date.
next : U64 -> { state : U64, value : U64 }
next = |state| {
advanced = state.plus_wrap(0x9e3779b97f4a7c15)
first = advanced.bitwise_xor(advanced.shr_zf_wrap(30)).times_wrap(0xbf58476d1ce4e5b9)
second = first.bitwise_xor(first.shr_zf_wrap(27)).times_wrap(0x94d049bb133111eb)
{ state: advanced, value: second.bitwise_xor(second.shr_zf_wrap(31)) }
}
## A fixed-width lowercase spelling keeps app ids independent of inspection.
hex : U64 -> Str
hex = |number| Str.join_with(
[60, 56, 52, 48, 44, 40, 36, 32, 28, 24, 20, 16, 12, 8, 4, 0].map(
|shift| {
index = number.shr_zf_wrap(shift).bitwise_and(15)
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"].get(index) ?? crash "Time.hex: a nibble is below sixteen"
},
),
"",
)
The platform provides entropy, not an id generator or a collision guarantee.
Field Notes chooses n- plus sixteen hex digits; Reading List chooses b-
and sends its database a whole book, including id and sampled time, minted
in Roc. The database port stores those values unchanged.
Readers and deterministic specs
environment.now() defaults to Date.now() and is read at mount and when
each timer or interval fires. It accepts a safe-integer Number or an I64
BigInt. seed() returns sixteen little-endian bytes as Uint8Array(16), defaulting to
crypto.getRandomValues; absence or failure refuses mount. languages()
defaults to the browser’s first sixteen language strings that fit 64 UTF-8
bytes each, or ["en-US"] when none remain. timeZone(days) returns the zone
table; timestamp fields accept safe integers or I64 BigInts. Injected readers
must already meet the bounds. An unavailable or overlong default browser
zone name becomes "", while malformed reader data refuses mount. A failing
now() after boot is an executor fault, never a fabricated timestamp.
Specs control these readers through their manual clock, seed, languages and zone (Testing). Advancing that clock fires nothing. Page JavaScript still has its real clock; a port must not mint these app timestamps. Workers get no boot or clock service: send any time or randomness a job needs in its ordinary input.
Cryptography and bytes in text
WebCrypto provides secure random bytes, PBKDF2 key derivation, AES-256-GCM
encryption and decryption, and SHA-256/384/512 digests. They are typed asks:
use them in ordinary effect sites, with the same in-flight bound, result
turns, cancellation and counters as other requests. They are scoped;
disposing their site or superseding its input discards the answer.
An encrypted project needs a fresh salt, an application-chosen KDF cost and an envelope containing that salt, the KDF parameters, IV and ciphertext. Those choices stay in Roc. The platform derives a non-extractable AES key from the exact UTF-8 password, without normalization, and generates a fresh 12-byte IV for every encryption. Applications cannot supply an encryption IV. Ciphertext includes its 16-byte authentication tag. Associated data, such as a project id, is authenticated without being encrypted or returned.
## These parameters are part of the saved envelope, chosen by the application.
## A deployment can cap the cost with maxCryptoIterations at mount.
derive : { password : Str, salt : List(U8) } -> Engine.Ask(WebCrypto.Key, WebCrypto.Error)
derive = |input| WebCrypto.derive_key({ password: input.password, salt: input.salt, iterations: 600000, hash: Sha256 })
## The platform generates a fresh 12-byte IV for every encryption. The project
## id is authenticated along with the ciphertext, without becoming plaintext.
seal : WebCrypto.Key, Str -> Engine.Ask(WebCrypto.Sealed, WebCrypto.Error)
seal = |key, message| WebCrypto.encrypt(key, { plaintext: message.to_utf8(), associated: "project-42".to_utf8() })
## Wrong passwords, changed ciphertext and changed associated data all answer
## NotAuthentic. No plaintext is returned until authentication succeeds.
open : WebCrypto.Key, WebCrypto.Sealed -> Engine.Ask(List(U8), WebCrypto.Error)
open = |key, envelope| WebCrypto.decrypt(key, { iv: envelope.iv, ciphertext: envelope.ciphertext, associated: "project-42".to_utf8() })
WebCrypto.random_bytes(16) generates a salt. It uses secure browser entropy
independently of boot.seed; there is no fallback to a pseudorandom stream.
WebCrypto.digest takes Sha256, Sha384 or Sha512 and bytes. For a file
already behind a handle, use File.sha256 to avoid reading it into Roc.
Keep WebCrypto.Key in the cell or local state that represents an unlocked
session. A key has no bytes accessor, export, port encoding or worker
encoding. Its lifetime follows Roc references, including any values that
still hold it after a cell is written; a key is neither a project name nor
a token the application must release. Dispose or supersede pending unlock
work when locking, so an earlier answer cannot unlock the session again.
## An application locks by writing its key-holding cell or state without the
## key. Once no value holds it, Roc releases the browser key automatically.
lock : Session -> Session
lock = |_session| Locked
The closed WebCrypto.Error distinguishes NotAuthentic (a wrong key,
modified ciphertext or wrong associated data; no plaintext is delivered),
InvalidParameters (salt shorter than 16 bytes, zero iterations, a non-12-byte
IV or ciphertext shorter than the tag), TooLarge (a deployment ceiling),
Refused (admission or key slots), Unavailable (secure browser cryptography
is absent) and Failed (another cryptographic service failure).
Mount options maxCryptoBytes (8 MiB by default, at most 64 MiB) and
maxCryptoIterations (1,000,000 by default, from 1 to 10,000,000) cap requests;
the byte ceiling may be zero, and the fixed digest output does not count.
The app still chooses its own salt, iteration count and envelope. The byte
ceiling counts password and salt together, plaintext and associated data
plus the 16-byte tag, ciphertext and associated data, a digest’s input, or
the number of random bytes requested. Each instance holds at most 64 keys.
The cryptographic executor admits at most 32 operations, counting those
awaiting execution and those already running. A canceled running operation
still counts until its browser promise settles. Another operation answers
Refused instead of waiting for capacity.
For binary data in a text-only place, such as local storage, use the pure
Base64 module. Its standard RFC 4648 encoding includes padding and no line
breaks. Decoding accepts only canonical base64 and answers NotBase64 for
whitespace, URL alphabet symbols, malformed padding or nonzero unused bits.
Base64 is an encoding; authenticate the decoded encrypted envelope before
using its plaintext.
## Keep a binary envelope in a text-only place, such as browser storage.
saved_envelope : Str
saved_envelope = Base64.encode([0, 255, 128, 1])
## A stored value is external input: handle malformed base64 before decoding
## the envelope itself. Base64 preserves bytes; it does not authenticate them.
read_envelope : Str -> Try(List(U8), [NotBase64])
read_envelope = |stored| Base64.decode(stored)
Both spec runners perform real PBKDF2, AES-GCM and SHA-2 on run-effect.
Their random bytes are the same deterministic test stream, independent of
the boot seed. Tests can therefore exercise lock/unlock and tampering without
replacing encryption with a fake. expect-keys checks live handles;
max-crypto-bytes and max-crypto-iterations in setup test deployment refusals.
Navigation
## Navigation is a pair of effects: `Push` when the app navigates, and a
## `Popstate` subscription for the back and forward buttons.
go : Model, Str -> Model
go = |m, url| { ..m, url, nav: m.nav.post(url) }
routing : State(Ctx, Model) -> List(Elem(Ctx))
routing = |model| [
Engine.on_post(model.signal().map(|m| m.nav), |url| [Engine.command(Push(url))], Engine.ignore({})),
Html.button("Settings", [], model.update(|m| go(m, "/settings"))),
Engine.watch(
Engine.const({}),
|_| [Engine.popstate({})],
model.on_result(
|m, _, res|
match res {
Ok(url) => { ..m, url }
_ => m
},
),
),
]
Keep the app’s navigation intent separate from the current location, so
that following the back button updates the location without pushing a new
entry: post each place the app asks to go to an outbox, and push what is
posted. Links inside the app should use a click handler with the prevent
policy (Engine.on_with("click", { prevent: True }, ...)) so the browser does not navigate on
its own.
In an app with several pages the location and the outbox are cells of the store, so a link anywhere asks to go somewhere with one write, and the move itself is one decision. Conduit is built this way.
Subscriptions and lifetime
Connectivity, visibility, media, other documents’ storage writes, a
port’s Latest messages and transfer progress report current state. They
wait for the next animation frame; a newer waiting report
from the same source replaces the earlier one in place. A visible
page given no frames drains within 100 ms, and a hidden page drains at the
end of the reporting task.
Clicks, key presses, interval ticks, final request results and a port’s
Every messages are occurrences. Each is delivered separately. An
occurrence first delivers reports queued ahead of it, so a click sees the
latest state reported before that click. Reports raised after it wait
behind it. An Every port message joins this order when its subscription’s
turn comes; reports raised while it waited in the port’s own queue come
first.
The runtime captures a report’s value when it arrives. Cancelling its
request or subscription drops waiting reports without delivering them. Use
hold-reports and release-reports in a spec
to state what a frame of reports should do.
Subscriptions (Interval, Popstate, OnlineChanges, VisibilityChanges,
MediaChanges, StorageChanges, StorageWriteFailures,
a port subscription), timers, operations on files on the page (ReadBytes,
ReadUtf8, Sha256, ObjectUrl) and worker jobs belong to their site.
Disposing the site — because its branch switched or its row left a list —
cancels them:
## Subscriptions deliver results until their site is disposed. This interval
## runs only while the page is online: going offline disposes the `when`
## branch, which cancels it.
subscriptions : State(Ctx, Model) -> List(Elem(Ctx))
subscriptions = |model| [
Engine.watch(
Engine.const({}),
|_| [Engine.online_changes({})],
model.on_result(
|m, _, res|
match res {
Ok(online) => { ..m, online }
_ => m
},
),
),
Engine.when(
model.signal().map(|m| m.online),
|| Engine.watch(Engine.const({}), |_| [Engine.interval(30000)], model.on_result(|m, _, _| { ..m, ticks: m.ticks + 1 })),
|| Engine.text(""),
),
]
Requests whose answer may matter after the site has gone are not cancelled
when it goes: Http, Upload, Fetch, StorageGet, SessionStorageGet,
ClipboardWrite, port calls, and the
jobs of a task that says on_dispose: Keep (see
Workers). They are handed to the nearest
surviving ancestor, and the reaction runs there when the answer arrives.
Writes to local states that were disposed with the site are skipped. Writes
to cells of the store are made as they would have been: the store is not
disposed with anything. Only unmounting the whole app abandons such a
request.
Focus
Focus is a command on a named reference. Mark the element with
Engine.ref(name) and ask for Focus(name), Blur(name) or
SelectText(name). The request is resolved at the end of the turn, so it can
target an element the same turn created:
## Focus is a command on a named reference. Here every change of the query
## keeps the search box focused.
search_box : State(Ctx, Model) -> List(Elem(Ctx))
search_box = |model| {
query = model.signal().map(|m| m.query)
[
Html.text_input(Engine.const("Search"), "search", query, [Engine.ref("search")], model.set_value(|m, q| { ..m, query: q, results: Loading, draft_status: "", drafts: m.drafts.post({}) })),
Engine.watch_changes(query, |_| [Engine.command(Focus("search"))], Engine.ignore({})),
]
}
Engine.ref_s(name_signal) lets the name follow a signal, including a row’s
key in an each or table view. A rename changes only the engine’s reference
map and writes nothing to the DOM. The empty name names nothing, so only a
selected row need hold a reference. A name is an address you build for a
command; the row’s identity remains its key.
Two live references may not hold the same nonempty name. The engine checks the names mounted or renamed at the end of the turn, before resolving focus, and reports a contract error naming the name and both construction sites. A departing row and an entering row can share a name during a turn as long as only one holds it when the turn ends.
A name that is no longer mounted is counted stale. It can leave in the
same turn that asks for it, so this is not a contract error. Focusing an
element that cannot take focus leaves focus where it was. Both spec runners
apply focus commands and let you assert the outcome with expect-focused
and expect-no-focus.
Scrolling and focus in place
FocusInPlace(name) moves focus with the browser’s scrolling prevented.
Pair it with an explicit scroll when revealing a validation problem:
## Explicit scroll commands run in stream order after the batch. Focus in
## place then moves keyboard focus without asking the browser to scroll.
reveal_problem : Engine.Signal(Ctx, Bool) -> Elem(Ctx)
reveal_problem = |invalid| Engine.watch_changes(
invalid,
|has_problem| if has_problem {
[Engine.command(Engine.scroll_into_view("problem", { block: Center, behavior: Instant })), Engine.command(FocusInPlace("problem"))]
} else {
[]
},
Engine.ignore({}),
)
## The narrow scroll tag also fits cleanup's command-only plan.
restore_scroll : Engine.Signal(Ctx, {}) -> Elem(Ctx)
restore_scroll = |signal| Engine.on_cleanup("restore page position", signal, |_| [Engine.scroll_into_view("search", {}), ScrollTo("search", { top: Start, left: Keep, behavior: Auto })])
Engine.scroll_into_view(name, props) defaults block and inline to
Nearest and behavior to Auto. Alignments are Start, Center, End
and Nearest; behavior is Auto, Instant or Smooth. Its narrow return
tag fits both a request plan and a cleanup’s command plan.
ScrollTo(name, { top, left, behavior }) scrolls the named element. Each
edge is Keep, Start, End or Px(U32). Left is distance from the
logical start edge, including RTL; the browser resolves End when
it performs the command. Both scroll commands run after the whole batch,
in order with focus and other node commands. A marked view-transition
batch starting a transition performs effects that name no node earlier,
before its DOM update. Both scroll commands use the same reference map and
stale-name count as focus, and await no result. Layout stays in the
browser. Specs assert the command performed with
expect-scroll.
Scrolling and layout
Layout arrives as reports that handlers write into ordinary state or cells.
import pf.Layout supplies three plain records:
| Attach function | Payload | Source |
|---|---|---|
Html.on_scroll(handler) | Layout.Scroll { top, left } | The element’s offsets when its scroll event is raised |
Html.on_size(handler) | Layout.Size { width, height } | The element’s content box, observed with ResizeObserver |
Html.on_seen(props, handler) | Layout.Seen { intersecting, ratio_permille } | IntersectionObserver entry and exit, with a ratio from 0 to 1000 |
## The box takes its size from CSS, independently of what its handler writes.
## Visibility and size registrations belong to this element's scope.
observations : {} -> Elem(ctx)
observations = |_args| Engine.state(
{ size: { width: 0.U32, height: 0.U32 }, seen: { intersecting: False, ratio_permille: 0.U16 } },
|facts| Engine.element(
"section",
[
Html.aria_label("Observed box"),
Engine.attr("style", "width:300px;height:150px;overflow:hidden"),
Html.on_size(facts.set_value(|before, size| { ..before, size })),
Html.on_seen({ ahead: True }, facts.set_value(|before, seen| { ..before, seen })),
],
[Html.p_s(facts.signal().map(|current| "${current.size.width.to_str()} × ${current.size.height.to_str()}, visible ${Str.inspect(current.seen.intersecting)}"), [])],
),
)
Offsets and dimensions are U32 rounded CSS pixels. Left is distance from
the container’s start edge, including RTL. Negative offsets, including
column-reverse and overscroll, clamp to zero. Seen defaults to observing
on-screen entry and exit. ahead: True also admits an element one screen
before it enters view, using both root and scroll margins; on browsers
without scroll-margin support a nested sentinel reports later, when seen.
Each is a report source: the newest value per element and handler (scroll) or element and kind (size/seen) waits for a frame. Size reports drain when the observer’s callback ends, before paint. Disposing a scope releases its observations; a row releases the observations on its template elements together. Observations take no awaited request slot and have no fixed row-count cap.
A scrolling table view writes its window from these reports. Its spacer
height must come from row count, independent of which rows are drawn, and
its scroller must set overflow-anchor: none. Drawing another window must
not move the scrollbar. Likewise, an observed box must take its size from
its container rather than from what its size handler draws. Otherwise the
app can keep creating a report each frame; the platform cannot infer which
CSS should change. Table windows
show the fixed-height pattern. Sizes and visibility are observations;
there is no on-demand measurement request or variable-height row model.
Media preferences
Declare each query in ProgramProps.media before boot reads it. There are
at most 32 distinct queries, each 1–256 UTF-8 bytes. Engine.boot_media
returns Ok(matches) or Err(Undeclared), so the first figure can already
use the preferred colors. MediaChanges(query) then reports changes:
color_query = "(prefers-color-scheme: dark)"
## Media is declared before mount so the first paint uses its boot value.
## The subscription follows later changes through the ordinary result turn.
main : Engine.Program
main = Engine.program_boot(
{ media: [color_query] },
|boot| {
initial = match Engine.boot_media(boot, color_query) {
Ok(matches) => matches
Err(Undeclared) => crash "the color query must be declared"
}
Engine.state(
initial,
|dark| Html.div(
"",
[
Html.p_s(dark.signal().map(|matches| if (matches) "Dark colors" else "Light colors"), []),
Engine.watch(
Engine.const({}),
|_| [Engine.media_changes(color_query)],
dark.on_result(
|before, _issued, result| match result {
Ok(matches) => matches
_ => before
},
),
),
observations({}),
],
),
)
},
)
An undeclared subscription is a contract error naming its query and site.
Subscriptions use the ordinary in-flight bound and can answer Refused.
A page’s environment.matchMedia reader defaults to the browser’s
window.matchMedia. Specs set this reader’s facts with initial-media and
set-media; they do not change the page’s own CSS media rules.
Log Explorer fits its viewer to the reported
height and colors its Roc-built timeline from a declared color-scheme query.
Cleanup
Engine.on_cleanup(name, v, plan) runs when its scope is disposed, in the
disposing turn, with the last value of v. Its plan returns a list of
Engine.Command: the requests that are emitted and forgotten, the last row
of the table under Requests. A request that awaits a result
would outlive its owner, and Command has no such tag, so a cleanup that
asks for one does not compile.
## A cleanup runs when its scope is disposed. Its plan returns commands, a
## list of `Engine.Command`: a request that awaits a result does not compile
## there.
leaving : State(Ctx, Model) -> Elem(Ctx)
leaving = |model| Engine.on_cleanup("restore title", model.signal(), |_| [Title("Search")])
A command written as a tag (Title("Search")) fits a list of commands and
a list of requests alike, and so does one built by File.save or by a port
command’s send. A function of your own that builds a command for a
cleanup returns Engine.Command, and a plan written as a named function
returns List(Engine.Command).
Specs can count cleanup runs by name with expect-cleanup;
Engine.cleanup(name) is a cleanup that only counts.
Third-party widgets
A JavaScript widget, such as a chart, is integrated as a standard custom
element. The app renders the element with an ordinary attribute holding the
widget’s input — Engine.element("plume-chart", [Engine.attr_s("data-figure", json)], []) — and a script on the page defines the element with
customElements.define, redrawing when the attribute changes and cleaning up
when it is removed. The engine and runtime see an ordinary element and an
ordinary attribute write, so nothing app-specific enters the platform. The
Status Page example draws its charts this way with
Plume, each setting the layout’s
ui_revision: Preserve(name) so a viewer’s zoom survives the redraws. Each
change of the attribute is a whole redraw: build the figure from page state the
app keeps bounded, and from a derive that changes only when the figure should.
A widget answers the way a form control does, because an event reaches the
app only as text: the element sets its own value and dispatches a bubbling
change event, and the app hears it with an ordinary handler such as
Html.on_change(st.set_value_by(answer, reducer)), which also reads a value
of the page (the answer the chart was drawn from) when the event fires. The
shared plume-chart element does this for a click on a point when it has
data-click="x": its value is the point’s x as Plotly gives it, on a date
axis a time such as 2026-11-11 12:05 (or the date alone at midnight). A
spec stands in for the widget with (change LOC "text"), which sets the
element’s value and fires change in both runners. The
Log Explorer opens its viewer at the minute a
click on its timeline names this way.
Bounds
- At most 32 awaited requests are in flight per app (set
max_inflightinprogram_bootorprogram_storeto change it). A request beyond the bound is not sent: its reaction receivesRefusedin a follow-up turn. - Follow-up turns (
Selfand refusals) may chain at most 64 deep per event: a follow-up whose reaction leads to another follow-up, and so on. A deeper chain is a feedback loop, such as retrying a refused request while the table is still full, and stops the app with a contract error. How many follow-ups one turn queues does not count: thousands of rows that each fetch at mount, nearly all of them refused, are fine. - As a backstop against a loop that multiplies, where each follow-up leads to two or more, one event runs at most 64 follow-up turns per in-flight slot (at least 4096) beyond those its own turn queued. More is a resource limit. The follow-ups the event’s own turn queued are never counted, so the bound is reached only by follow-ups that lead to follow-ups: a loop, or a reaction to a follow-up that itself mounts thousands of rows that fetch.
- An HTTP timeout is capped at 600 seconds.
- An outbox takes one post per turn; a second is a contract error.
- The runtime queues at most 4096 events while applying a batch. A drain
also delivers at most 4096 turns before returning to idle. Beyond either
bound the app stops with
resource_limit; the second catches a focus loop that raises only one further event at a time. The native runner applies the same turn bound to each step.