Port Recipes
Use a port for a browser service the platform does not
model. Each recipe below declares the data Roc sends and receives, supplies
a handler with a bounded lifetime, and has a spec that supplies fake answers.
The source is www/samples/port-recipes/. Its index.html mounts the compiled
app with ports.mjs; a camera preview is outside the engine’s mount root,
and the gauge draws inside its own shadow root.
The platform already models HTTP, storage, timers, history, focus, workers, files, cryptography, clipboard writes and observations of layout and media queries. Use those requests for those services. The examples here never bypass the engine’s routing or keep Roc values in JavaScript.
A gesture reaches the handler
A button posts a small marker to an outbox. Its effect site sends in that click’s turn, while the browser’s transient user activation is available. The shared call view samples the argument only when the marker is posted:
import pf.Engine
import pf.Html
import pf.Port
## A call posted in the button's turn, with a small marker and a send-time
## reading. Each instance owns its pending state and decodes its own port.
CallView := [].{
Props(ctx, input, output) : { label : Str, test_id : Str, port : Port.Call(input, output), argument : Engine.Signal(ctx, input), show : (output -> Str) }
view : Props(ctx, input, output) -> Engine.Elem(ctx)
view = |props| Engine.state(
{ sent: Engine.outbox({}), pending: False, text: "Not requested" },
|state| Html.div(
"recipe-call",
[
Html.button(props.label, [Html.disabled(state.signal().map(|s| s.pending))], state.update(|s| { ..s, sent: s.sent.post({}), pending: True, text: "Waiting…" })),
Engine.on_post_by(
state.signal().map(|s| s.sent),
props.argument.lift(),
|argument, _| [props.port.ask(argument)],
state.on_result(
|s, _, result| {
text = match result {
Ok(value) => (props.show)(value)
Err(error) => "Unavailable: ${Str.inspect(error)}"
}
{ ..s, pending: False, text }
},
),
),
Html.p_s(state.signal().map(|s| s.text), [Engine.test_id(props.test_id)]),
],
),
)
}
A permission prompt, share sheet or fullscreen request must begin directly
in the handler, before an await or another task loses the gesture. An
answer always arrives in a later turn. Sending from a timer or from a
previous call’s answer does not preserve the original click’s activation.
Browser permissions, secure-context requirements and an embedding page’s
permissions policy still apply. A rejected call becomes Port.Error.Threw;
a failed command goes to the mount’s onPortFault callback.
WebSocket and Server-Sent Events
One subscription owns one connection. It returns Opened, then numbered
Event messages. It takes the last sequence the app kept as after, so a
server can resume from that cursor. This sample expects SSE events whose
id is a decimal U64 and whose data is text. WebSocket text frames carry
JSON with a decimal-string seq and a text data. Both endpoints receive
after in the URL’s query string. A server must keep a bounded history or
report the gap when it cannot replay it; opening a new connection alone
cannot recover lost data.
Message : [Opened, Event({ seq : U64, data : Str, dropped : U64 })]
Input : { url : Str, after : U64 }
## The module's named ports, declared once and registered together.
Ports : {
## One scope is one connection. Every(16) preserves accepted messages;
## the handler's own bounded buffer reports any older readings it drops.
sse : Port.Subscription(Input, Message),
websocket : Port.Subscription(Input, Message),
## A closed connection drops this command. Use a call for acknowledged sends.
send : Port.Command({ connection : Str, data : Str }),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
sse: Port.subscription({ name: "example.org/recipes/sse", delivery: Every(16) }),
websocket: Port.subscription({ name: "example.org/recipes/websocket", delivery: Every(16) }),
send: Port.command({ name: "example.org/recipes/socket-send" }),
}
The handler closes an EventSource on its first error, disabling the
browser’s automatic reconnect, and ends the subscription with Threw.
A clean WebSocket close gives Closed; another close gives Threw.
Unsubscribe and abort remove listeners, stop the drain and close the socket.
A command to the named primary connection sends only while it is open;
otherwise it is dropped. Declare a call instead when the app needs an
acknowledgement, and make the server’s acknowledgement the answer.
The runtime keeps Every(16) messages; the handler has its own bounded
queue of at most 64 messages and 64 KiB, and reports a cumulative count
for that connection of older readings it drops when the queue fills. It retries
emit when the runtime says the queue is full. Neither layer retains an
unbounded backlog, and malformed frames end the connection rather than
being repaired.
// SSE uses a decimal U64 event id and text data. WebSocket text frames are
// JSON {seq: "decimal U64", data: "text"}. Reconnect policy belongs to Roc.
const NS = "example.org/recipes/";
const MAX_BYTES = 65536;
const MAX_U64 = (1n << 64n) - 1n;
const encoder = new TextEncoder();
function sequence(text) {
if (typeof text !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(text) || BigInt(text) > MAX_U64) {
throw new Error("The feed sequence must be a decimal U64 string");
}
return text;
}
// Check before encoding or parsing: one hostile frame cannot cause an
// unbounded copy in this handler. The browser itself already received it.
function boundedText(text) {
if (typeof text !== "string" || text.length > MAX_BYTES || !text.isWellFormed() || encoder.encode(text).length > MAX_BYTES) {
throw new Error("A feed frame exceeds 64 KiB or is not well-formed text");
}
return text;
}
export function socketPorts() {
let primary = null;
function connect(input, ctx, websocket) {
const url = new URL(input.url, location.href);
url.searchParams.set("after", sequence(input.after));
if (websocket) url.protocol = url.protocol === "https:" ? "wss:" : url.protocol === "http:" ? "ws:" : url.protocol;
if (websocket && primary) throw new Error("The primary WebSocket is already open");
const source = websocket ? new WebSocket(url) : new EventSource(url);
if (websocket) primary = source;
let ended = false, opened = false, frame = null, timer = null;
let bytes = 0, dropped = 0n;
const queue = [];
const unschedule = () => {
if (frame !== null) cancelAnimationFrame(frame);
if (timer !== null) clearTimeout(timer);
frame = timer = null;
};
const stop = () => {
if (ended) return;
ended = true;
unschedule();
ctx.signal.removeEventListener("abort", stop);
source.onopen = source.onmessage = source.onerror = source.onclose = null;
source.close();
if (primary === source) primary = null;
queue.length = 0;
bytes = 0;
};
const finish = (error) => { stop(); ctx.close(error); };
const schedule = () => {
if (ended || frame !== null || timer !== null) return;
// One fallback timer also makes progress when hidden tabs suspend frames.
frame = requestAnimationFrame(drain);
timer = setTimeout(drain, 100);
};
function drain() {
unschedule();
if (ended) return;
let sent = 0;
if (opened) {
if (!ctx.emit("Opened")) { schedule(); return; }
opened = false;
sent = 8;
}
while (queue.length && sent + queue[0].bytes <= MAX_BYTES) {
const next = queue[0];
if (!ctx.emit({ Event: { seq: next.seq, data: next.data, dropped: dropped.toString() } })) break;
queue.shift();
bytes -= next.bytes;
sent += next.bytes;
}
if (queue.length) schedule();
}
source.onopen = () => { opened = true; schedule(); };
source.onmessage = (event) => {
try {
const text = boundedText(event.data);
const value = websocket ? JSON.parse(text) : { seq: event.lastEventId, data: text };
const seq = sequence(value.seq);
const data = boundedText(value.data);
// Budget the complete outgoing JSON, including the largest drop count.
const size = encoder.encode(JSON.stringify({ Event: { seq, data, dropped: MAX_U64.toString() } })).length;
if (size > MAX_BYTES) throw new Error("The encoded feed message exceeds 64 KiB");
while (queue.length >= 64 || bytes + size > MAX_BYTES) {
bytes -= queue.shift().bytes;
if (dropped === MAX_U64) throw new Error("The feed drop counter is exhausted");
dropped += 1n;
}
queue.push({ seq, data, bytes: size });
bytes += size;
schedule();
} catch (error) { finish(error); }
};
// Closing first prevents EventSource's automatic reconnect from competing
// with the app's scoped backoff timer.
source.onerror = () => finish(new Error("The live connection failed"));
if (websocket) source.onclose = (event) => finish(event.wasClean ? undefined : new Error(`WebSocket closed with code ${event.code}`));
ctx.signal.addEventListener("abort", stop, { once: true });
if (ctx.signal.aborted) stop();
return stop;
}
return {
[`${NS}sse`]: { subscribe: (input, ctx) => connect(input, ctx, false) },
[`${NS}websocket`]: { subscribe: (input, ctx) => connect(input, ctx, true) },
[`${NS}socket-send`]: { command: ({ connection, data }) => {
if (connection !== "primary") throw new Error("Unknown connection name");
if (primary?.readyState === WebSocket.OPEN) {
const text = boundedText(data);
if (primary.bufferedAmount + encoder.encode(text).length > MAX_BYTES) throw new Error("The socket send buffer is full");
primary.send(text);
}
} },
};
}
Reconnect is an app decision in Roc. A pure generator seeded from
boot.seed chooses jitter up to a quarter of bases of 1, 2, 4, 8 and 16
seconds. After five failed retries the app gives up. A Waiting branch
owns a timer; leaving that branch cancels it. A refused timer gives up
instead of retrying into a full in-flight table.
## Failure chooses one bounded wait in Roc. A refusal never loops into
## a full in-flight table, and a fifth failed retry offers a manual start.
lost : Model -> Model
lost = |model| {
if model.attempt >= 5 {
return { ..model, retry: GaveUp, message: "Gave up after five retries" }
}
attempt = model.attempt + 1
random = Backoff.next(model.random)
delay = Backoff.delay({ attempt, random: random.value })
{ ..model, attempt, random: random.state, retry: Waiting(delay), message: "Reconnecting in ${delay.to_str()} ms (attempt ${attempt.to_str()})" }
}
waited : Model, Try(I64, [Refused]) -> Model
waited = |model, result| match result {
Ok(_) => { ..model, retry: Connecting, generation: model.generation + 1, resume: model.after, message: "Connecting" }
Err(Refused) => { ..model, retry: GaveUp, message: "Retry refused; reconnect manually" }
}
The connection input snapshots the resume cursor only when a connection opens. Receiving a new event changes the last-kept cursor without reopening the current connection. A forward jump reports the sequence gap as well as the handler’s drop count; these can describe the same missing readings and are not added together. The Status Page also disposes its connection and retry timer while hidden, and demonstrates bounded replay and counted gaps.
(test "The app reconnects after a lost feed and resumes the last kept sequence"
(setup (seed 7))
(steps
(click (role button :name "Connect event stream"))
(expect-port-subscriptions "example.org/recipes/sse" 1)
(expect-port-subscription-arg "example.org/recipes/sse" 1 "{\"after\":\"0\",\"url\":\"/events\"}")
(emit-port "example.org/recipes/sse" "\"Opened\"")
(expect-text (test-id "socket-result") "Connection opened; waiting for data")
(emit-port "example.org/recipes/sse" "{\"Event\":{\"data\":\"ready\",\"dropped\":\"0\",\"seq\":\"9\"}}")
(expect-text (test-id "socket-result") "ready (gap 8, dropped 0)")
(fail-port "example.org/recipes/sse" "lost")
(expect-port-subscriptions "example.org/recipes/sse" 0)
(run-effect 1)
(expect-port-subscriptions "example.org/recipes/sse" 1)
(expect-port-subscription-arg "example.org/recipes/sse" 1 "{\"after\":\"9\",\"url\":\"/events\"}")
(click (role button :name "Pause connection"))
(expect-port-subscriptions "example.org/recipes/sse" 0)
(click (role button :name "Connect WebSocket"))
(expect-port-subscriptions "example.org/recipes/websocket" 1)
(click (role button :name "Send greeting"))
(expect-port-sent "example.org/recipes/socket-send" 1 "{\"connection\":\"primary\",\"data\":\"hello\"}")
(close-port "example.org/recipes/websocket")
(expect-port-subscriptions "example.org/recipes/websocket" 0)
(click (role button :name "Pause connection"))
(expect-pending-effects 0)))
IndexedDB
The Ports guide contains the complete notes recipe:
typed declarations, its
IndexedDB handlers, and a
fake-store spec. The
Reading List adds cross-tab updates and shows
how optimistic commands and a Latest store subscription agree. Use a call
for a write whose failure the reader must hear; a command cannot acknowledge
that write.
Notifications
Permission is a gesture-driven call answering Granted, Denied or
Dismissed. Showing a notification is a command. An app that must report a
failure to show one should make that operation a call instead. The handler
keeps at most one permission request pending.
Permission : [Granted, Denied, Dismissed]
## The module's named ports, declared once and registered together.
Ports : {
## Ask from the click's turn; the browser's permission result is data.
permission : Port.Call({}, Permission),
## Showing a notification is a command. A failure reaches onPortFault,
## so an app that needs an acknowledgement instead declares a call.
show : Port.Command({ title : Str, body : Str }),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
permission: Port.call({ name: "example.org/recipes/notification-permission", timeout: Ms(60000) }),
show: Port.command({ name: "example.org/recipes/notification-show" }),
}
export function notificationPorts() {
let asking = false;
return {
"example.org/recipes/notification-permission": { call: async () => {
if (!("Notification" in globalThis)) throw new Error("Notifications are unavailable");
if (asking) throw new Error("Notification permission is already pending");
asking = true;
try {
const permission = await Notification.requestPermission();
switch (permission) {
case "granted": return "Granted";
case "denied": return "Denied";
case "default": return "Dismissed";
default: throw new Error("Unknown notification permission");
}
} finally { asking = false; }
} },
"example.org/recipes/notification-show": { command: ({ title, body }) => {
if (!("Notification" in globalThis) || Notification.permission !== "granted") throw new Error("Notification permission is not granted");
new Notification(title, { body });
} },
};
}
(test "Permission is a call; showing a notification is a command"
(steps
(click (role button :name "Allow notifications"))
(expect-port-call 1 "example.org/recipes/notification-permission" "{}")
(answer-port 1 reply "\"Denied\"")
(expect-text (test-id "notification-result") "Denied")
(click (role button :name "Allow notifications"))
(answer-port 2 reply "\"Granted\"")
(expect-text (test-id "notification-result") "Granted")
(click (role button :name "Show notification"))
(expect-port-sent "example.org/recipes/notification-show" 1 "{\"body\":\"The page asked for this notification.\",\"title\":\"Roc Signals\"}")))
Web Share
Start navigator.share in the click’s turn. User cancellation answers
Cancelled; successful completion answers Shared. Other rejections remain
port failures. The native sheet cannot be aborted, so the handler keeps one
pending operation until it settles and refuses a second. Aborting the call
stops delivery of its answer, rather than pretending to close the sheet.
Answer : [Shared, Cancelled]
## The module's named ports, declared once and registered together.
Ports : {
## The OS share sheet needs the user's gesture. Cancellation is an answer,
## while denial or an unavailable service remains a typed port failure.
share : Port.Call({ title : Str, text : Str, url : Str }, Answer),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
share: Port.call({ name: "example.org/recipes/share", timeout: Ms(60000) }),
}
// A timed-out OS sheet can still be pending in the browser. Keep one slot
// until it settles, so a new click cannot accumulate permission promises.
export function sharePorts() {
let sharing = false;
return {
"example.org/recipes/share": { call: async (message) => {
if (typeof navigator.share !== "function") throw new Error("Web Share is unavailable");
if (sharing) throw new Error("A share sheet is already pending");
sharing = true;
try { await navigator.share(message); return "Shared"; }
catch (error) { if (error?.name === "AbortError") return "Cancelled"; throw error; }
finally { sharing = false; }
} },
};
}
(test "A dismissed share sheet is a cancellation, not a shared answer"
(steps
(click (role button :name "Share"))
(expect-port-call 1 "example.org/recipes/share" "{\"text\":\"A pure engine and a browser host.\",\"title\":\"Roc Signals\",\"url\":\"https://lukewilliamboswell.github.io/roc-signals/\"}")
(answer-port 1 reply "\"Cancelled\"")
(expect-text (test-id "share-result") "Cancelled")
(click (role button :name "Share"))
(answer-port 2 reply "\"Shared\"")
(expect-text (test-id "share-result") "Shared")))
Reading the clipboard
Reading the clipboard needs permission and may need a gesture. It is a
call returning text or a port failure; the handler never keeps a second
pending read. Writing the clipboard uses the platform’s
Clipboard.text and Clipboard.html,
and text the user pastes arrives through Html.on_paste_text.
## The module's named ports, declared once and registered together.
Ports : {
## Reading needs browser permission. Writing uses the platform's Clipboard
## module instead; this port only reads what the user chooses to allow.
read : Port.Call({}, Str),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
read: Port.call({ name: "example.org/recipes/clipboard-read", timeout: Ms(15000) }),
}
// Writing the clipboard uses the platform's Clipboard module. A permission
// dialog cannot be cancelled; one pending browser read bounds that lifetime.
export function clipboardReadPorts() {
let reading = false;
return {
"example.org/recipes/clipboard-read": { call: async () => {
if (!navigator.clipboard?.readText) throw new Error("Clipboard reading is unavailable");
if (reading) throw new Error("A clipboard read is already pending");
reading = true;
try { return await navigator.clipboard.readText(); }
finally { reading = false; }
} },
};
}
(test "Clipboard text crosses only as the call answer"
(steps
(click (role button :name "Read clipboard"))
(expect-port-call 1 "example.org/recipes/clipboard-read" "{}")
(answer-port 1 reply "\"Text from the reader\"")
(expect-text (test-id "clipboard-result") "Text from the reader")
(click (role button :name "Read clipboard"))
(answer-port 2 throw "Permission denied")
(expect-text (test-id "clipboard-result") "Unavailable: Threw(\"Permission denied\")")))
Geolocation
A call asks for one fix; a Latest subscription follows the newest one.
Both handlers use a watch so abort and unsubscribe can call clearWatch.
The one-fix call clears its watch as soon as it answers or fails. The
subscription reports only plain coordinates and accuracy, never a browser
object. Permission denial ends it with Threw.
Position : { latitude : F64, longitude : F64, accuracy : F64 }
## The module's named ports, declared once and registered together.
Ports : {
## One location, cancelled through the handler's AbortSignal on timeout.
locate : Port.Call({}, Position),
## Current position is a value: only the newest waiting fix matters.
positions : Port.Subscription({}, Position),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
locate: Port.call({ name: "example.org/recipes/location", timeout: Ms(15000) }),
positions: Port.subscription({ name: "example.org/recipes/positions", delivery: Latest }),
}
function position(value) {
const { latitude, longitude, accuracy } = value.coords;
if (![latitude, longitude, accuracy].every(Number.isFinite)) throw new Error("Invalid geolocation coordinates");
return { latitude, longitude, accuracy };
}
function watch(ctx, receive, fail) {
if (!navigator.geolocation) throw new Error("Geolocation is unavailable");
let active = true;
let id = null;
const stop = () => {
active = false;
if (id !== null) navigator.geolocation.clearWatch(id);
id = null;
ctx.signal.removeEventListener("abort", stop);
};
ctx.signal.addEventListener("abort", stop, { once: true });
if (ctx.signal.aborted) { stop(); return stop; }
// A one-shot call also uses a watch, so abort can actually cancel it.
id = navigator.geolocation.watchPosition(
(value) => { if (active) { try { receive(position(value), stop); } catch (error) { stop(); fail(error); } } },
(error) => { if (active) { stop(); fail(new Error(error.message)); } },
{ maximumAge: 0 },
);
if (!active && id !== null) { navigator.geolocation.clearWatch(id); id = null; }
return stop;
}
export const geolocationPorts = {
"example.org/recipes/location": { call: (_, ctx) => new Promise((resolve, reject) => {
const aborted = () => reject(ctx.signal.reason ?? new DOMException("Cancelled", "AbortError"));
ctx.signal.addEventListener("abort", aborted, { once: true });
const done = (fn, value) => { ctx.signal.removeEventListener("abort", aborted); fn(value); };
if (ctx.signal.aborted) { done(reject, ctx.signal.reason); return; }
try { watch(ctx, (value, stop) => { stop(); done(resolve, value); }, (error) => done(reject, error)); }
catch (error) { done(reject, error); }
}) },
"example.org/recipes/positions": { subscribe: (_, ctx) => watch(ctx, (value) => ctx.emit(value), (error) => ctx.close(error)) },
};
(test "A position can be requested once or followed in a scoped subscription"
(steps
(click (role button :name "Find location"))
(expect-port-call 1 "example.org/recipes/location" "{}")
(answer-port 1 reply "{\"accuracy\":3,\"latitude\":1,\"longitude\":2}")
(expect-text (test-id "location-result") "1, 2 (±3 m)")
(click (role button :name "Toggle location watch"))
(expect-port-subscriptions "example.org/recipes/positions" 1)
(emit-port "example.org/recipes/positions" "{\"accuracy\":6,\"latitude\":4,\"longitude\":5}")
(expect-text (test-id "position-result") "4, 5 (±6 m)")
(click (role button :name "Toggle location watch"))
(expect-port-subscriptions "example.org/recipes/positions" 0)))
Media capture
A Latest subscription reports Starting, Active or Ended. The
recipe-camera custom element owns the stream and preview in its shadow
root. Roc receives only device state. Unsubscribe stops every track; if a
permission request completes after abort, its late stream is stopped too.
There is at most one pending device request and one live stream. Removing
the element also releases both its preview and any eventual late stream.
State : [Starting, Active, Ended]
## The module's named ports, declared once and registered together.
Ports : {
## Only device state crosses. The custom element owns its MediaStream and
## video, and unsubscribe stops its tracks; no browser object reaches Roc.
camera : Port.Subscription({}, State),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
camera: Port.subscription({ name: "example.org/recipes/camera", delivery: Latest }),
}
// This element owns the browser stream. Roc receives only Starting/Active/Ended.
export function registerCamera() {
if (customElements.get("recipe-camera")) return;
customElements.define("recipe-camera", class extends HTMLElement {
#pending = false;
#stop = null;
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
this.video = document.createElement("video");
this.video.autoplay = true;
this.video.muted = true;
this.video.playsInline = true;
this.video.style.maxWidth = "100%";
root.append(this.video);
}
subscribe(ctx) {
if (!navigator.mediaDevices?.getUserMedia) throw new Error("Camera capture is unavailable");
if (this.#pending || this.#stop) throw new Error("The camera already has an owner or a pending permission request");
let ended = false;
let stream = null;
const listeners = [];
const stop = () => {
if (ended) return;
ended = true;
ctx.signal.removeEventListener("abort", stop);
for (const [track, listener] of listeners) track.removeEventListener("ended", listener);
listeners.length = 0;
if (stream) for (const track of stream.getTracks()) track.stop();
this.video.srcObject = null;
if (this.#stop === stop) this.#stop = null;
};
this.#stop = stop;
ctx.signal.addEventListener("abort", stop, { once: true });
if (ctx.signal.aborted) { stop(); return stop; }
ctx.emit("Starting");
this.#pending = true;
// Browsers cannot cancel a permission dialog. Keep its single pending
// slot until it settles, and stop tracks from an answer that came late.
let permission;
try { permission = navigator.mediaDevices.getUserMedia({ video: true, audio: false }); }
catch (error) { this.#pending = false; stop(); throw error; }
Promise.resolve(permission).then((answer) => {
this.#pending = false;
if (ended) { for (const track of answer.getTracks()) track.stop(); return; }
stream = answer;
for (const track of stream.getTracks()) {
const listener = () => { stop(); ctx.emit("Ended"); ctx.close(); };
track.addEventListener("ended", listener, { once: true });
listeners.push([track, listener]);
}
this.video.srcObject = stream;
ctx.emit("Active");
}, (error) => {
this.#pending = false;
if (!ended) { stop(); ctx.close(error); }
});
return stop;
}
disconnectedCallback() { this.#stop?.(); }
});
}
export function mediaPorts(camera) {
return { "example.org/recipes/camera": { subscribe: (_, ctx) => camera.subscribe(ctx) } };
}
(test "A camera scope follows device state and disposes its subscription"
(steps
(click (role button :name "Toggle camera"))
(expect-port-subscriptions "example.org/recipes/camera" 1)
(emit-port "example.org/recipes/camera" "\"Starting\"")
(expect-text (test-id "camera-result") "Starting")
(emit-port "example.org/recipes/camera" "\"Active\"")
(expect-text (test-id "camera-result") "Active")
(click (role button :name "Toggle camera"))
(expect-port-subscriptions "example.org/recipes/camera" 0)))
Fullscreen and wake lock
Commands ask, state subscriptions report what the browser actually did. Request fullscreen in the click’s turn. Wake lock availability also depends on the browser, permission and visibility. A release is reported; this handler does not decide to reacquire it. The app must choose whether and when to send another command. One pending acquisition and one held sentinel bound the handler, and teardown releases it.
## The module's named ports, declared once and registered together.
Ports : {
## Browser state, not command acknowledgement. Both commands run in their
## buttons' turns; a failed command reaches onPortFault, not the app.
fullscreen : Port.Command({}),
fullscreen_state : Port.Subscription({}, Bool),
wake : Port.Command(Bool),
wake_state : Port.Subscription({}, Bool),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
fullscreen: Port.command({ name: "example.org/recipes/fullscreen" }),
fullscreen_state: Port.subscription({ name: "example.org/recipes/fullscreen-state", delivery: Latest }),
wake: Port.command({ name: "example.org/recipes/wake" }),
wake_state: Port.subscription({ name: "example.org/recipes/wake-state", delivery: Latest }),
}
// Commands request a change; subscriptions report the browser's actual state.
// A released wake lock is never reacquired here: that decision belongs to Roc.
export function displayPorts(target) {
let lock = null;
let acquiring = false;
let releasing = false;
let enteringFullscreen = false;
let generation = 0;
const observers = new Set();
const publish = () => { for (const ctx of observers) ctx.emit(lock !== null && !lock.released); };
const release = async () => {
generation += 1;
if (releasing) return;
const previous = lock;
if (previous) {
releasing = true;
try {
await previous.release();
previous.removeEventListener("release", released);
if (lock === previous) lock = null;
} finally { releasing = false; }
}
publish();
};
const released = (event) => {
const previous = event.currentTarget;
previous.removeEventListener("release", released);
if (lock === previous) { lock = null; publish(); }
};
return {
"example.org/recipes/fullscreen": { command: async () => {
if (!target.requestFullscreen) throw new Error("Fullscreen is unavailable");
if (enteringFullscreen) throw new Error("A fullscreen request is already pending");
enteringFullscreen = true;
try { await target.requestFullscreen(); }
finally { enteringFullscreen = false; }
} },
"example.org/recipes/fullscreen-state": { subscribe: (_, ctx) => {
const changed = () => ctx.emit(document.fullscreenElement === target);
const stop = () => {
document.removeEventListener("fullscreenchange", changed);
ctx.signal.removeEventListener("abort", stop);
};
document.addEventListener("fullscreenchange", changed);
ctx.signal.addEventListener("abort", stop, { once: true });
if (ctx.signal.aborted) stop(); else changed();
return stop;
} },
"example.org/recipes/wake": { command: async (wanted) => {
if (!wanted) { await release(); return; }
if (releasing) throw new Error("A wake-lock release is already pending");
if (lock && !lock.released) return;
if (acquiring) throw new Error("A wake-lock request is already pending");
if (!navigator.wakeLock?.request) throw new Error("Wake locks are unavailable");
const requested = generation;
acquiring = true;
try {
const answer = await navigator.wakeLock.request("screen");
if (requested !== generation || observers.size === 0) { await answer.release(); return; }
lock = answer;
lock.addEventListener("release", released);
publish();
} finally { acquiring = false; }
} },
"example.org/recipes/wake-state": { subscribe: (_, ctx) => {
// The sample mounts one observation. Runtime admission bounds this set
// by its program's in-flight limit; it retains no history of observers.
const stop = () => {
observers.delete(ctx);
ctx.signal.removeEventListener("abort", stop);
if (observers.size === 0) {
// Invalidate a permission answer that outlives its last observer.
release().catch((error) => console.error("Wake-lock cleanup failed", error));
}
};
observers.add(ctx);
ctx.signal.addEventListener("abort", stop, { once: true });
if (ctx.signal.aborted) stop(); else ctx.emit(lock !== null && !lock.released);
return stop;
} },
};
}
(test "Commands ask for fullscreen and wake while subscriptions report actual state"
(steps
(expect-port-subscriptions "example.org/recipes/fullscreen-state" 1)
(expect-port-subscriptions "example.org/recipes/wake-state" 1)
(click (role button :name "Enter fullscreen"))
(expect-port-sent "example.org/recipes/fullscreen" 1 "{}")
(expect-text (test-id "fullscreen-result") "Windowed")
(emit-port "example.org/recipes/fullscreen-state" "true")
(expect-text (test-id "fullscreen-result") "Fullscreen")
(click (role button :name "Toggle wake lock"))
(expect-port-sent "example.org/recipes/wake" 1 "true")
(expect-text (test-id "wake-result") "Wake lock released")
(emit-port "example.org/recipes/wake-state" "true")
(expect-text (test-id "wake-result") "Wake lock held")
(click (role button :name "Toggle wake lock"))
(expect-port-sent "example.org/recipes/wake" 2 "false")
(emit-port "example.org/recipes/wake-state" "false")
(expect-text (test-id "wake-result") "Wake lock released")))
Browser locale formatting
Simple date patterns can be pure Roc. When the app needs the browser’s CLDR
formatting, send a batch of instants, boot.languages and the chosen zone
through a call, and render the answered strings. No hole calls Intl
synchronously. This sample explicitly chooses UTC when boot has no zone
name; the handler never guesses a replacement for an invalid zone or locale.
I64 milliseconds cross as decimal strings. The handler checks the exact integer against the browser’s date range before converting it to a Number, and refuses a batch of more than 256 dates. A date outside that range is a failure, rather than a rounded or substituted instant.
Input : { languages : List(Str), zone : Str, instants : List(I64) }
## The module's named ports, declared once and registered together.
Ports : {
## Format one batch with browser CLDR data. Milliseconds cross as decimal
## strings; a date outside the browser's range is a failure, never rounded.
format : Port.Call(Input, List(Str)),
}
## The same values serve requests and the derived program catalogue.
ports : Ports
ports = {
format: Port.call({ name: "example.org/recipes/format-dates", timeout: Ms(5000) }),
}
const DATE_LIMIT = 8640000000000000n;
export function formatDates({ languages, zone, instants }) {
if (instants.length > 256) throw new RangeError("A date-formatting batch has at most 256 instants");
const format = new Intl.DateTimeFormat(languages, { timeZone: zone, dateStyle: "medium", timeStyle: "short" });
return instants.map((text) => {
if (typeof text !== "string" || !/^-?(0|[1-9][0-9]{0,18})$/.test(text)) throw new Error("Expected decimal I64 milliseconds");
const instant = BigInt(text);
// Every integer in the Date range is exactly representable as Number.
// Validate first, rather than rounding a large I64 before rejecting it.
if (instant < -DATE_LIMIT || instant > DATE_LIMIT) throw new RangeError("The date is outside the browser's range");
return format.format(Number(instant));
});
}
export const datePorts = { "example.org/recipes/format-dates": { call: formatDates } };
(test "Formatting receives boot facts and a batch of exact timestamps"
(setup (initial-time 1731200000000) (languages "en-AU") (time-zone "Australia/Brisbane" 600))
(steps
(click (role button :name "Format dates"))
(expect-port-call 1 "example.org/recipes/format-dates" "{\"instants\":[\"1731200000000\",\"0\"],\"languages\":[\"en-AU\"],\"zone\":\"Australia/Brisbane\"}")
(answer-port 1 reply "[\"10 Nov 2024\",\"1 Jan 1970\"]")
(expect-text (test-id "dates-result") "10 Nov 2024 | 1 Jan 1970")))
Canvas drawing belongs to an element
Canvas drawing needs no port. Roc renders a custom element with ordinary attributes; that element owns its canvas and animation frame. Disconnecting it cancels the frame. The app decides whether reduced motion disables the animation, using its declared boot media query. No per-frame callbacks enter Roc, and the JavaScript makes no reactive decisions.
## The element owns its canvas and drawing frame. Roc supplies a bounded
## value through an ordinary attribute, and decides the reduced-motion rule.
view : { reduced : Bool } -> Engine.Elem(ctx)
view = |props| Engine.state(
0.U32,
|state| Html.div(
"recipe",
[
Html.button("Increase gauge", [], state.update(|n| (n + 1) % 101)),
Engine.element("recipe-gauge", [Engine.test_id("gauge"), Engine.attr_s("data-value", state.signal().map(|n| n.to_str())), Engine.attr("data-animate", if (props.reduced) "false" else "true")], []),
],
),
)
// Canvas drawing is an element's business, rather than a port. The frame
// interpolates only a displayed value; Roc decides the gauge's target value.
export function registerGauge() {
if (customElements.get("recipe-gauge")) return;
customElements.define("recipe-gauge", class extends HTMLElement {
static observedAttributes = ["data-value", "data-animate"];
#frame = null;
#shown = 0;
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
this.canvas = document.createElement("canvas");
this.canvas.width = 240;
this.canvas.height = 140;
this.canvas.setAttribute("aria-label", "Gauge");
this.canvas.setAttribute("role", "img");
root.append(this.canvas);
}
connectedCallback() { this.draw(); }
attributeChangedCallback() { if (this.isConnected) this.draw(); }
disconnectedCallback() {
if (this.#frame !== null) cancelAnimationFrame(this.#frame);
this.#frame = null;
}
draw() {
if (this.#frame !== null) cancelAnimationFrame(this.#frame);
this.#frame = null;
const text = this.getAttribute("data-value") ?? "0";
const target = Number(text);
if (!/^(0|[1-9][0-9]*)$/.test(text) || !Number.isInteger(target) || target < 0 || target > 100) throw new Error("Gauge value must be an integer from 0 to 100");
const animate = this.getAttribute("data-animate") === "true";
this.#shown = animate ? this.#shown + (target - this.#shown) * 0.2 : target;
if (Math.abs(target - this.#shown) < 0.1) this.#shown = target;
const ctx = this.canvas.getContext("2d");
if (!ctx) throw new Error("Canvas drawing is unavailable");
ctx.clearRect(0, 0, 240, 140);
ctx.lineWidth = 12;
ctx.strokeStyle = "#e4e4e7";
ctx.beginPath(); ctx.arc(120, 120, 90, Math.PI, 2 * Math.PI); ctx.stroke();
ctx.strokeStyle = "#2563eb";
ctx.beginPath(); ctx.arc(120, 120, 90, Math.PI, Math.PI + this.#shown / 100 * Math.PI); ctx.stroke();
ctx.fillStyle = "#18181b";
ctx.font = "24px sans-serif";
ctx.textAlign = "center";
ctx.fillText(`${Math.round(this.#shown)}%`, 120, 110);
this.canvas.setAttribute("aria-label", `Gauge ${target}%`);
if (animate && this.#shown !== target) this.#frame = requestAnimationFrame(() => { this.#frame = null; if (this.isConnected) this.draw(); });
}
});
}
(test "A gauge receives attributes; drawing stays in its custom element"
(setup (initial-media "(prefers-reduced-motion: reduce)" true))
(steps
(expect-attr (test-id "gauge") "data-value" "0")
(expect-attr (test-id "gauge") "data-animate" "false")
(click (role button :name "Increase gauge"))
(expect-attr (test-id "gauge") "data-value" "1")))
What the specs prove
These specs use the same fake-port steps natively and in Chrome. They prove what the Roc app sends, how it handles answers, and when subscriptions go away. They do not exercise browser permission prompts or a real socket server. Test handlers against their actual services too; the recipe’s handler tests cover cleanup, bounded queues and late browser answers without showing permission prompts in the spec runner.