Components
Values that change, and values that are on their way
Components are a page's interactive parts, on SolidJS 2.0's model, in Roc: a component runs once, and each hole in its markup runs again when a value it reads changes. Server data is a plain value, and boundaries say what shows while it loads.
At a glance#
A component is a function from props to markup (Html), written in a .rocx file: Roc with markup wherever an expression can stand (see the syntax page). The file has import pf.Html; its module defines view or view!. The front page's counter, the smallest component with state:
view! = |{ start_value }| {
(count!, set_count!) = create_signal!(start_value)
<div class="counter" class:negative={count!() < 0}>
<button type="button" on:click={|| set_count!(count!() - 1)} aria-label="One less">−</button>
<output>{count!().to_str()}</output>
<button type="button" on:click={|| set_count!(count!() + 1)} aria-label="One more">+</button>
…
</div>
}The component runs once
view! runs once, where the component is rendered: it makes the signal count!, builds the markup, and never runs again.
Holes run again
Each {…} or attribute that reads count!() reruns when the count changes, and patches its own node. No virtual DOM, no diffing.
Server data is a plain value
A memo that reads an endpoint gives a Str or a record, never a loading state. <Loading> and <Errored> say what shows while it waits.
Rendered on the server
The server renders the page with every answer in it. The browser takes over the server's nodes (hydration) and asks for nothing again.
Know SolidJS? Coming from Solid maps each of its functions to its name here.
Signals, holes and memos#
The functions come from the platform's Solid module:
import pf.Solid exposing [create_signal!, create_memo!, untrack!]A signal
(count!, set_count!) =
create_signal!(0)A value that changes, as two functions: an accessor, count!, reads it (count!()) and tracks the read; a setter, set_count!, writes a new one. Its type is fixed when it is made. Given a value == the one it has, the setter tells no one, so its value is data; for one that holds a function (a timer's clear!), create_signal_with! takes Solid's equals.
A hole
<output>
{count!().to_str()}
</output>A computation in the markup. The runtime notes which signals it reads and reruns it when one changes, patching its own node.
A handler
<button on:click={||
set_count!(count!() + 1)}>What an event runs, and where signals are written. Its writes apply together when it ends.
A memo
doubled! = create_memo!(||
count!() * 2)A value computed from others, again when they change; read it like a signal. Computed again to a value == the last, it tells no one, so its value is data: not a function or markup.
These names end in ! because Roc marks every function that has an effect, and the compiler checks the mark. Reading a signal is an effect: the read is tracked. Signals, memos and changing props are all read through an accessor.
What runs, and when
In the counter above:
- The body runs once.
view!makes the signal and builds the markup; each hole is a closure it doesn't run. As in Solid, the body's own reads aren't tracked. - Each hole runs once to show its first value, and the runtime notes what it read: the
<output>'s text, thenegativeclass and Reset'sdisabledall readcount!. - A click runs a handler.
set_count!'s write applies when the handler ends, with any others it made. - Those three holes run again and patch their nodes. Nothing else runs, so the signal keeps its value.
Attributes are holes too (disabled?={count!() == 0}, class:negative={count!() < 0}, style:--size={…}). A hole that calls nothing ending in ! can't change, so rocx writes it once, with no computation ({label}, a pure component's prop). A hole that ran and read nothing that changes (a prop given a constant) is static too: plain text from the server, nothing kept in the browser.
A signal's write isn't compared with the old value: writing the same count again reruns every hole that reads it (one whose text comes out the same patches nothing). Memos and store selections do compare, with ==.
Writing from the value
Since writes apply when the handler ends, a read in it gives the old value: set_count!(count!() + 1) twice adds one, as in Solid 2.0. update! (Solid's setCount((c) => c + 1)) writes from the value the handler's writes so far leave, so two updates add two. Only update! sees a pending write; a plain read still gives the old value.
import pf.Solid exposing [create_signal!, update!]
(count!, set_count!) = create_signal!(0)
add! = |n| update!(count!, set_count!, |c| c + n)
<button on:click={|| {
add!(1)
add!(1)
}}>Two more</button>It also takes an optimistic value's accessor and setter. A store's setter already takes a function and composes the same way.
Memos and the server
A memo starts computing when it is made. One that reads an endpoint (Api.get_user({}).read!(), see talking to the server) is async: five such memos send five requests at once, and a hole that reads one waits (waiting and failing). refresh!(user!) asks the server again; the old value stays on screen, and is_pending!(user!) says it is on its way out. Roc can't compare functions, so refresh! finds the memos by running the accessor once and noting what it reads.
A read in the body is read once
doubled = count!() * 2 in the body is the starting count times two, for good. To follow the count, read it in the hole ({(count!() * 2).to_str()}) or a memo. This is the one mistake the model invites, so a dev build (rocx dev) warns in the browser's console, once per place, as Solid 2.0's does:
rocx: Ui/Chart.rocx:44:39 reads a value that changes (a signal, a memo or a prop) in a component's body, once, as the component runs: what it shows won't follow it. Read it where it is used (in markup, a memo, an effect's compute or a handler), or, if one read is what you want, say so: untrack!(|| …)When one read is meant (a start value), untrack! (Solid's untrack) reads without tracking and silences the warning: create_signal!(untrack!(|| start)). In a memo or hole, create_memo!(|| count!() + untrack!(|| base!())) reruns when count! changes, not base!. A hole whose reads are all untracked is static. The warning misses reads inside a helper function.
Try it: a to-do list#
The server rendered this list. Add an item, tick one, filter, or press Escape in the field. The panel says what the runtime did: a key typed patches the field's value and Add's disabled; removing an item drops its row and touches nothing else. The state is four signals, and each hole reads only what it needs.
What the runtime did, newest first
- Waking up…
The component: site/Demos/Todos.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
## A to-do list: a form, rows that come and go (each kept by its id: moved, never rewritten),
## checkboxes, a key, and filters. Its state is four signals; each hole reads the ones it needs.
Todos := [].{
Item : { id : U64, text : Str, done : Bool }
Filter : [All, Active, Completed]
view! : { first : List({ text : Str, done : Bool }) } => Html
view! = |{ first }| {
(items!, set_items!) = create_signal!(first.map_with_index(|item, index| { id: index, text: item.text, done: item.done }))
(draft!, set_draft!) = create_signal!("")
(filter!, set_filter!) = create_signal!(everything)
(next!, set_next!) = create_signal!(first.len())
add! = || {
text = draft!().trim()
if (text.is_empty()) {} else {
set_items!(items!().append({ id: next!(), text, done: Bool.False }))
set_next!(next!() + 1)
set_draft!("")
}
}
tick! = |id, done| set_items!(items!().map(|item| if (item.id == id) { ..item, done: done } else item))
remove! = |id| set_items!(items!().drop_if(|item| item.id == id))
<div class="todos">
<form on:submit={add!}>
<input
type="text"
placeholder="What needs doing?"
aria-label="New item"
value={draft!()}
on:input.value={set_draft!}
on:keydown.Escape={|| set_draft!("")}
/>
<button type="submit" disabled?={draft!().trim().is_empty()}>Add</button>
</form>
<ul>
{...shown(items!(), filter!()).map(|item|
<li key={item.id} class:done={item.done}>
<label>
<input type="checkbox" checked?={item.done} on:change.checked={|done| tick!(item.id, done)} />
{item.text}
</label>
<button type="button" class="remove" aria-label={"Remove ${item.text}"} on:click={|| remove!(item.id)}>×</button>
</li>
)}
</ul>
<footer>
<span class="left">{left(items!())}</span>
<span class="filters">
<button type="button" class:selected={filter!() == All} on:click={|| set_filter!(All)}>All</button>
<button type="button" class:selected={filter!() == Active} on:click={|| set_filter!(Active)}>Active</button>
<button type="button" class:selected={filter!() == Completed} on:click={|| set_filter!(Completed)}>Done</button>
</span>
{if items!().any(|item| item.done) {
<button type="button" class="clear" on:click={|| set_items!(items!().drop_if(|item| item.done))}>Clear done</button>
}}
</footer>
</div>
}
<style>
.todos form {
display: flex;
gap: var(--space-2);
}
.todos form input {
flex: 1;
}
button[type="submit"] {
background: var(--accent);
color: var(--accent-text);
}
button[type="submit"]:hover:not(:disabled) {
background: var(--accent-strong);
}
ul {
margin: var(--space-4) 0;
padding: 0;
list-style: none;
}
li {
display: flex;
align-items: center;
padding: var(--space-2) 0;
border-bottom: 1px solid var(--rule);
}
label {
flex: 1;
display: flex;
align-items: center;
gap: var(--space-2);
cursor: pointer;
}
.done label {
color: var(--text-faint);
text-decoration: line-through;
}
.remove,
.remove:hover:not(:disabled) {
padding: 0 var(--space-2);
background: none;
color: var(--text-faint);
font-size: var(--size-lg);
line-height: 1;
}
.remove:hover:not(:disabled) {
color: var(--bad);
}
footer {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
color: var(--text-muted);
font-size: var(--size-sm);
}
.filters {
display: inline-flex;
gap: var(--space-1);
}
.filters button {
padding: var(--space-1) var(--space-3);
background: none;
color: var(--text-muted);
}
.filters .selected,
.filters .selected:hover:not(:disabled) {
background: var(--accent-soft);
color: var(--accent);
}
.clear {
margin-left: auto;
padding: var(--space-1) var(--space-3);
font-size: var(--size-sm);
}
</style>
}
everything : Todos.Filter
everything = All
## The items the filter shows.
shown : List(Todos.Item), Todos.Filter -> List(Todos.Item)
shown = |items, filter|
items.keep_if(
|item|
match filter {
All => Bool.True
Active => !item.done
Completed => item.done
},
)
left : List(Todos.Item) -> Str
left = |items| {
count = items.count_if(|item| !item.done)
"${count.to_str()} ${if (count == 1) "item" else "items"} left"
}
expect left([{ id: 0, text: "a", done: Bool.False }, { id: 1, text: "b", done: Bool.True }]) == "1 item left"
expect shown([{ id: 0, text: "a", done: Bool.True }], Active) == []Pure and effectful components#
Components use Roc's ! mark too: a function without one can't call one with one. A component's module defines either view (pure) or view! (effectful). The counter above is effectful; this site's section heading is pure:
import pf.Html
## A section's heading, with a link to it.
Heading := [].{
view : { id : Str, children : List(Html) } -> Html
view = |{ id, children }| <h2 id={id}>{...children}<a class="anchor" href={"#${id}"} aria-label="Link to this section">#</a></h2>
<story name="Section">
<Heading id="parts">Three parts</Heading>
<p>The text under it: the anchor beside the heading links here.</p>
</story>
<story name="Long title">
<Heading id="long">A heading that is long enough to wrap onto a second line on a narrow screen</Heading>
</story>
<style>
.anchor {
margin-left: var(--space-2);
color: var(--magenta);
text-decoration: none;
opacity: 0;
transition: opacity 0.15s;
}
h2:hover .anchor,
.anchor:focus {
opacity: 1;
}
</style>
}view: pure
Makes markup from its props, which are plain values. It can't make a signal, read a context or call the server: the compiler refuses. It is called where it is written, like any function: <Heading id="why">…</Heading> becomes Heading.view({ id: "why", children: […] }).
view!: effectful
May make signals and memos, read a context, and read endpoints. It runs once, where it is rendered, like a Solid component: <Counter start_value={3} /> becomes Html.component(|| Counter.view!({ start_value: || 3 })), which the runtime calls at its place in the tree, under the contexts above it. Its props are getters (props that change).
You don't mark the call: rocx writes the one that fits, so a component can switch kinds without its callers changing. Start with view; add the ! when the component needs its own state, a context or the server. Solid can't tell the two apart, since any JavaScript function may do anything. Roc can, so a pure component is guaranteed to keep no state, and costs no more than a function call.
A pure component can still show changing values. Given one (<Badge count={unread!()} />), its call becomes a hole: when the value changes, the component is called again and its markup replaced. It has no state to lose, but its elements are new, so the focus or text typed in them goes. To keep them, pass an accessor for its holes to read (<Badge count!={unread!()} />, typed count! : () => U64), or make it a view!. This is on purpose: a pure component stays a function of values, so a test or an email's HTML (Html.to_str) can call it with plain values.
Props that change#
An effectful component runs once, so a changing prop must be read where it is used. Like Solid's compiler, rocx passes each value prop of a view! as a getter, a function that computes it, and the child (written with a plain text : Str) calls it wherever it says text:
<Heading text={user!().name} level={2} />
# Html.component(|| Heading.view!({ text: || user!().name, level: || 2 }))
view! = |{ text, level }| <h2 class={level.to_str()}>{text}</h2>
# |{ text: text!, level: level! }| … class: || level!().to_str() … || text!()Where the child reads a prop decides what follows it:
- In a hole, an attribute, a memo or an effect's
compute: read again when the value changes, patching only that place. The component and its signals stay. - In a handler: the value when the handler runs.
- In the component's body: read once (
first = textkeeps the first value). Fine for a start value, withuntrack!; otherwise the dev build warns (a read in the body is read once), and rocx warns at a call given amatcharm's name or a row's item (if, match and .map). - In a pure function the component calls (
items.keep_if(|item| item.owner == me)): a value. A pure function can't call a getter, so the hole or memo around the call reads the prop and passes the value in.
So destructuring is safe. In Solid, const { text } = props loses reactivity; here |{ text }| means props.text, because rocx rewrites every read of text. A prop given a constant (level={2}) is static, and the dev warning ignores it.
Accessor props. A prop named with !, text!={user!().name}, is the same getter written by hand: the child types it (text! : () => Str) and calls it (text!()). It lets a pure component follow a changing value and keep its elements (above). To let a child write, pass the setter; it is already a handler, so on:input.value={set_draft!} needs no wrapper. children is markup, whose holes are already live.
Passing props on. |{ kind, ..rest }| takes kind out and keeps the rest (Solid's omit); <Base {...rest} size={3} /> passes them on, still getters (Solid's merge: the last of a name wins). With the view's props annotated, rocx writes the fields out one by one (label: rest.label), and other attributes can add or replace some. Without, it writes Roc's record update ({ ..rest, size: || 3 }), so Base's props must be exactly that type, and only one such record can be spread on a tag.
Button := [].{
view! : { kind : Str, label : Str, on_press! : () => {} } => Html
view! = |{ kind, ..rest }| <span class={kind}><Base {...rest} size={3} /></span>
}
# Base.view!({ label: rest.label, on_press!: rest.on_press!, size: || 3 })if, match and .map#
Branches and lists are Roc's own if, match and .map in a hole: no <Show>, <Switch> or <For> to learn. When they read something that changes, each branch and row is a part, as in Solid 2.0: made once, then kept, moved or dropped, never rebuilt just to compare.
Below, the same picks are listed by id (left) and by position (right). Click the buttons: a ring marks each node that changed, coloured by what happened. (The picks come from a context the tally further down reads too.)
- 0: Roc
- 1: Solid
- 2: Elm
- 0: Roc
- 1: Solid
- 2: Elm
Three or fewer
First: Roc
text patched row moved row made part switched
What the runtime did, newest first
- Waking up…
- Reverse moves the rows by key (the same elements, reordered) and patches their indexes. The rows by position stay put; their names are patched.
- Shout changes every name but no id: every row stays, and only its name is patched.
- Add makes one row in each list; the fourth pick switches the
ifunder them. Clear drops every row and shows theifthat says there are none.
{ picks!, set_picks!, next!, set_next! } = use_context!(picks_context)
…
<div class="picks-lists">
{# A row per id: kept while its id is there, moved with it. }
<ol class="keyed" aria-label="By key">
{...picks!().map_with_index(|pick, index| <li key={pick.id}>{index.to_str()}: {pick.name}</li>)}
{if (picks!().is_empty()) <li class="none">None</li>}
</ol>
{# A row per place: the pick in it changes. }
<ol class="unkeyed" aria-label="By position">
{...picks!().map_with_index(|pick, index| <li key={index}>{index.to_str()}: {pick.name}</li>)}
</ol>
</div>
<div class="picks-shows">
{if picks!().len() > 3 {
<p class="many">More than three</p>
} else {
<p class="few">Three or fewer</p>
}}
{match picks!().first() {
Ok(first) => <p class="first">First: {first.name}</p>
Err(_) => <></>
}}
</div>A row per key: .map
{...todos!().map(|todo| <li key={todo.id}>{todo.title}</li>)} is Solid's <For>. Each row is kept by the key on its root: made once, moved when its key moves, dropped when its key goes. todo is a getter for the current item, so an edit that keeps the id keeps the row's elements, focus and typing.
- A key is required when the list changes; rocx refuses a row without one, at its line. Roc's values have no identity, so Solid's default (a row per object) can't work. A key can be any value: a string as is, anything else as
Str.inspectwrites it. - The key goes on the row's root, an element or a component (where it is never a prop). A row that is an
ifputs a key on each branch. - A row is told only when its item changed, compared by
==: toggling one todo of a thousand runs that row's holes alone. So an item must be data (records, tags, lists, text, numbers), not a function or markup. - A row runs once, like a component (Solid's
mapArray): what it reads at its top is read once; its holes, and the props it gives components, follow the item. It may hold another.map, anif, or plain markup. - A list that reads nothing that changes (a constant, or one in a
<NoHydration>) is built once and needs no keys.
A row per position. .map_with_index(|pick, i| <li key={i}>…</li>) is Solid's <For keyed={false}> (formerly <Index>): rows stay put, and the item at each position changes (the right list). With any other key, it is a row per key whose index is a getter too (the left list). A key computed from the index is refused: write key={i} alone.
A part per branch: if
{if (count!() > 3) <Timer />} shows its part while the condition holds (no else needed). The part is remade only when a different branch holds, so the <Timer> keeps its signals as the count goes from 4 to 5; holes inside still follow what they read. An if whose branches are all text, {if (on!()) "On" else "Off"}, is an ordinary text hole.
A part per arm: match
One part per arm: Solid's <Switch>, and its <Show> narrowing a value that may be missing (in Roc, a Try):
{match tab!() {
Inbox => <Inbox />
Card(card) => <CardView title={card.title} />
Nothing => <p>Nothing to show</p>
}}An arm's names (card in Card(card)) are getters for the newest value: the part stays, and <CardView title={card.title} /> follows it. For a part remade per value (Solid's keyed <Show>), .map a list of one, keyed by the value or its id: {...[card!()].map(|card| <Editor key={card.id} card={card} />)}.
A component that reads such a name or a row's item once, in its body (shown = card), keeps the first value: a bug. rocx warns at the call, and rocx check exits with 2. The ways out: read the prop where it is used, write untrack!(|| card) if one read is meant, or key the part by the value as above.
When parts are made
A part (a branch, an arm or a row) is made like a component: once, where it is rendered, its own reads untracked, and again each time it reappears. So a value prop inside, <Podium players={game!().players} />, is read where the component reads it, while the part shows. A signal made inside a part goes with it.
Rows by index: Repeat
<Repeat count!={n!()} from!={first!()}>{|index| …}</Repeat> (import pf.Repeat, Solid 2.0's <Repeat>) makes a row per index from from! (default 0) up to, not including, from! + count!, with no list behind them. When the range moves, only rows entering it are made; fallback={…} shows while the count is 0. With on:viewport it becomes a virtual list: packages/virtual renders a million rows as the twenty that show.
The whole component: site/Demos/Picks.rocx
import pf.Html
import pf.Solid exposing [create_signal!, use_context!]
import pf.Context
## Picks you can reverse, add to, shout and clear: a .map's rows (Solid's <For>), by key and
## by position, and an if and a match. The picks are a store: what is under a
## <PicksContext> reads and writes the same ones (the docs' tally does).
Picks := [].{
Pick : { id : U64, name : Str }
## The picks and the next id, as accessors and setters.
Store : {
picks! : () => List(Pick),
set_picks! : List(Pick) => {},
next! : () => U64,
set_next! : U64 => {},
}
picks_context : Context(Store)
picks_context = create_context()
## A store with three picks in it.
store! : {} => Store
store! = |{}| {
(picks!, set_picks!) = create_signal!([
{ id: 1, name: "Roc" },
{ id: 2, name: "Solid" },
{ id: 3, name: "Elm" },
])
(next!, set_next!) = create_signal!(4.U64)
{ picks!: picks!, set_picks!: set_picks!, next!: next!, set_next!: set_next! }
}
view! : {} => Html
view! = |{}| {
{ picks!, set_picks!, next!, set_next! } = use_context!(picks_context)
reverse! = || set_picks!(picks!().rev())
add! = || {
set_picks!(picks!().append({ id: next!(), name: "Gleam" }))
set_next!(next!() + 1)
}
shout! = || set_picks!(picks!().map(loud))
<section class="picks">
<div class="picks-buttons">
<button class="reverse" on:click={reverse!}>Reverse</button>
<button class="add" on:click={add!}>Add</button>
<button class="shout" on:click={shout!}>Shout</button>
<button class="clear" on:click={|| set_picks!([])}>Clear</button>
</div>
<div class="picks-lists">
{# A row per id: kept while its id is there, moved with it. }
<ol class="keyed" aria-label="By key">
{...picks!().map_with_index(|pick, index| <li key={pick.id}>{index.to_str()}: {pick.name}</li>)}
{if (picks!().is_empty()) <li class="none">None</li>}
</ol>
{# A row per place: the pick in it changes. }
<ol class="unkeyed" aria-label="By position">
{...picks!().map_with_index(|pick, index| <li key={index}>{index.to_str()}: {pick.name}</li>)}
</ol>
</div>
<div class="picks-shows">
{if picks!().len() > 3 {
<p class="many">More than three</p>
} else {
<p class="few">Three or fewer</p>
}}
{match picks!().first() {
Ok(first) => <p class="first">First: {first.name}</p>
Err(_) => <></>
}}
</div>
</section>
}
<style>
.picks {
display: grid;
gap: var(--space-4);
}
.picks-buttons {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.picks-lists {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: var(--space-3);
}
ol {
display: grid;
align-content: start;
gap: var(--space-2);
margin: 0;
padding: var(--space-3);
border-radius: var(--radius);
background: var(--bg-sunken);
list-style: none;
}
ol::before {
content: attr(aria-label);
color: var(--magenta);
font: 600 var(--size-2xs) var(--mono);
letter-spacing: 0.06em;
text-transform: uppercase;
}
li {
padding: var(--space-1) var(--space-2);
border-radius: var(--radius-sm);
background: var(--bg-raised);
font: var(--size-sm) / 1.4 var(--mono);
}
.none {
background: none;
color: var(--text-faint);
}
.picks-shows {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.picks-shows p {
margin: 0;
padding: var(--space-1) var(--space-3);
border-radius: var(--pill);
background: var(--accent-soft);
color: var(--accent);
font-size: var(--size-sm);
font-weight: 600;
}
</style>
}
## A pick, shouted: its id is the same, so its row is too.
loud : Picks.Pick -> Picks.Pick
loud = |pick| { ..pick, name: pick.name.with_ascii_uppercased() }Stores#
A store (Solid 2.0's createStore) holds many parts in one value, each read on its own. Use one where a single signal would rerun every reader on every change: a board, a big form, a filtered list. Roc has no proxies, so a read selects a part with a function, tracked by the value selected:
import pf.Solid exposing [create_store!]
(todos, set_todos!) = create_store!({ items: [], filter: All })
<p>{Filter.name(todos.get!(|s| s.filter))}</p>
<ul>{...todos.get!(|s| s.items).map(|todo| <li key={todo.id} class:done={todo.done}>{todo.title}</li>)}</ul>
<button on:click={|| set_todos!(|s| { ..s, filter: Done })}>Done</button>- A part's readers rerun only when it changes. Each write recomputes every selection and compares it with its last value by
==: clicking Done reruns the filter's hole alone. So a part must be data (a type of your own needs anis_eq), not a function or markup. - A write is a function of the state (Solid 2.0's draft setter, with Roc's record update as the draft). Two writes in one handler compose.
- A read outside a computation (a handler, a component's body,
untrack!) selects once, untracked. Store.of(board!)(import pf.Store) reads any accessor by parts: an endpoint's answer, a memo, a prop. It has no setter. In a hole or an effect'scompute,Store.of(user!).get!(|u| u.id)reruns only when the id changes.
The cost: each write runs every live selection of its store (four hundred take about half a millisecond). Solid's store touches only the paths written.
Selectors#
When one row of a list is picked (selected, open), every row reading a plain signal reruns on each pick. A selector (Solid's createSelector) answers whether a key is the picked one and tracks each key on its own: a pick reruns only the row it leaves and the row it comes to.
import pf.Solid exposing [create_selector!, create_signal!]
(picked!, set_picked!) = create_signal!(0)
is_picked! = create_selector!(picked!)
<ul>
{...rows!().map(|row|
<li key={row.id} class:picked={is_picked!(row.id)} on:click={|| set_picked!(row.id)}>{row.label}</li>
)}
</ul>Its source is any accessor (a signal, a memo, a store's part), and keys have its type. On the server it is computed once, like a memo.
Contexts#
A context (Solid's createContext, useContext) gives a value to every component under its provider, however deep. The picks above and the tally below read their list and setter from one. Here is the context (no default) and the record of accessors and setters it provides:
Store : {
picks! : () => List(Pick),
set_picks! : List(Pick) => {},
next! : () => U64,
set_next! : U64 => {},
}
…
picks_context : Context(Store)
picks_context = create_context()
…
store! : {} => Store
store! = |{}| {
(picks!, set_picks!) = create_signal!([
{ id: 1, name: "Roc" },
{ id: 2, name: "Solid" },
{ id: 3, name: "Elm" },
])
(next!, set_next!) = create_signal!(4.U64)
{ picks!: picks!, set_picks!: set_picks!, next!: next!, set_next!: set_next! }
}Its provider is a tag named after it (picks_context gives <PicksContext value={…}>). Under it, use_context! reads the value:
view! = |{}| {
{ picks!, set_picks!, next!, set_next! } = use_context!(Picks.picks_context)- Defining one.
name = create_context()must be provided;create_context("light")has a default. Either is a module's definition, in a file importingpf.Context. rocx names each after its module and definition:Context.required("Demos/Picks.picks_context")(orContext.define, with a default).create_contexthas no!: it makes nothing until provided. - Providing it. The tag (the name in PascalCase) works in the context's module or any module importing it, in a file importing
pf.Context. It takesvalue={…}and children. A layout can provide one for every page under it. - Nothing above? A context with a default gives it; one without fails, and the nearest
<Errored>says so. - Read it in a component's body or a computation, and keep what it gives for your handlers, as the tally does. A component sees what is above where it is rendered, because rocx defers each component's call (
Html.component(|| …)) until the runtime builds that place.
One page, one tree#
A page is one tree: its layouts, the page, and their components. A component goes on a page as in another component, by its tag. Nothing to register, no islands.
The server renders the whole tree, and the browser hydrates the whole document, binding each hole and handler to the server's nodes. So components far apart share state through a context above both. This page puts one <PicksContext> around the picks and this tally, prose and all, and one <BagContext> around the shelf and the bag further down:
<PicksContext value={Picks.store!({})}>
<Demo inspect="picks" legend>
<div data-demo="picks" data-flash="yes"><Picks /></div>
</Demo>
…
<Demo inspect="tally">
<div data-demo="tally" data-flash="yes"><Tally /></div>
…
</Demo>
</PicksContext>
…
<BagContext value={Bag.store!({})}>
<Demo inspect="bag" title="What the bag did, newest first" stacked pair>
<div data-demo="shelf"><Shelf /></div>
<div data-demo="bag"><Bag /></div>
</Demo>
</BagContext>Add Zig here, then look at the picks. Clear the picks, and the tally says so.
A component of its own, reading the same picks as the lists in if, match and .map.
What the runtime did, newest first
- Waking up…
Below, a shelf and a bag share a context. The shelf's stock and the reader's name come from GET endpoints (/api/shelf, /api/reader). The server read both while rendering this page and put the answers in it, so the browser asked for neither.
- Roc bird sticker 2 €
- rocx mug 9 €
- Lambda pin 3 €
Ada's bag
Nothing yet.
0 things · 0 €
What the bag did, newest first
- Waking up…
The shelf and the bag: site/Demos/Shelf.rocx, site/Demos/Bag.rocx
import pf.Html
import pf.Solid exposing [create_memo!, use_context!]
import pf.Loading
import Bag
import ../Generated/Api
## A shelf of things to put in the bag: what is on it is a GET endpoint's answer
## (`routes/api/shelf/+server.roc`), which the server renders the shelf with; what is in the bag is
## the store the shelf and the bag share: a thing put in it shows in the bag, the bag emptied shows here.
Shelf := [].{
## What is on the shelf: `GET /api/shelf`, read as a plain value.
stock! : {} => List(Bag.Thing)
stock! = |{}| Api.get_api_shelf({}).read!()
view! : {} => Html
view! = |{}| {
{ things!, set_things! } = use_context!(Bag.bag_context)
shelved! = create_memo!(|| stock!({}))
taken! = |thing| things!().any(|in_bag| in_bag.name == thing.name)
put! = |thing| if (taken!(thing)) {} else set_things!(things!().append(thing))
<div class="shelf">
<Loading fallback={<p class="shelf-note">Fetching the shelf…</p>}>
<ul>
{...shelved!().map(|thing|
<li key={thing.name} class:taken={taken!(thing)}>
<span class="shelf-name">{thing.name}</span>
<span class="shelf-price">{thing.price.to_str()} €</span>
<button type="button" on:click={|| put!(thing)} disabled?={taken!(thing)}>
{if (taken!(thing)) "In the bag" else "Put in the bag"}
</button>
</li>
)}
</ul>
</Loading>
</div>
}
<style>
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) 0;
border-bottom: 1px solid var(--rule);
}
.shelf-name {
flex: 1;
}
.shelf-price {
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.taken .shelf-name {
color: var(--text-faint);
}
button {
padding: var(--space-1) var(--space-3);
font-size: var(--size-sm);
white-space: nowrap;
}
.shelf-note {
margin: var(--space-2) 0;
color: var(--text-muted);
}
</style>
}import pf.Html
import pf.Solid exposing [create_signal!, use_context!]
import pf.Context
import ../Generated/Api
## The bag the shelf puts things in, and a component that shows it. The bag is a store: signals in
## a context, which the page provides around both (`<BagContext>`), so the shelf and the bag, apart
## on the page, read and write the same one.
Bag := [].{
Thing : { name : Str, price : U64 }
## What is in the bag, as an accessor and a setter.
Store : { things! : () => List(Thing), set_things! : List(Thing) => {} }
bag_context : Context(Store)
bag_context = create_context()
## An empty bag.
store! : {} => Store
store! = |{}| {
(things!, set_things!) = create_signal!([])
{ things!: things!, set_things!: set_things! }
}
## Who is reading: `GET /api/reader`, what a session would say on the server (here, always Ada).
## The server renders the bag with it, and puts the answer in the page, so the browser doesn't ask
## again.
reader! : {} => Str
reader! = |{}| Api.get_api_reader({}).read!()
view! : {} => Html
view! = |{}| {
{ things!, set_things! } = use_context!(bag_context)
<div class="bag">
<p class="bag-title">{reader!({})}'s bag</p>
{if !things!().is_empty() {
<ul>
{...things!().map(|thing|
<li key={thing.name}>{thing.name}</li>
)}
</ul>
} else {
<p class="bag-empty">Nothing yet.</p>
}}
<p class="bag-total">{total(things!())}</p>
<button type="button" on:click={|| set_things!([])} disabled?={things!().is_empty()}>Empty the bag</button>
</div>
}
<style>
.bag {
padding: var(--space-3) var(--space-4);
border-radius: var(--radius);
background: var(--bg-sunken);
}
.bag-title {
margin: 0 0 var(--space-2);
font-weight: 600;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
padding: 0.15rem 0;
}
.bag-empty {
margin: var(--space-2) 0;
color: var(--text-muted);
}
.bag-total {
margin: var(--space-2) 0;
color: var(--text-muted);
font-size: var(--size-sm);
}
button {
padding: var(--space-1) var(--space-3);
font-size: var(--size-sm);
white-space: nowrap;
}
</style>
}
## How many things, and what they cost.
total : List(Bag.Thing) -> Str
total = |things| {
count = things.len()
price = things.fold(0, |sum, thing| sum + thing.price)
"${count.to_str()} ${if (count == 1) "thing" else "things"} · ${price.to_str()} €"
}
expect total([]) == "0 things · 0 €"
expect total([{ name: "mug", price: 9 }]) == "1 thing · 9 €"- Sharing a context is sharing its signals: a write in one component patches what reads it in the other.
- Per request, by construction. Roc has no module-level state for requests to share; each renders its own tree. This page makes the picks as it runs (
Picks.store!({})): per request on the server, and once in the browser as it hydrates. - Only the page's tree runs: without the shelf, its endpoint isn't read. The answers go at the end of the page, beside
/rocx/start.js, which loads the app's wasm (the engine in it) and hydrates. Every page loads the same wasm, with every page's components. - What never changes in the browser goes in a
<NoHydration>: prose, listings. It stays plain HTML; the browser's copy is an empty placeholder, so none of it is in the wasm, and hydration skips it. No handler can go inside, and reads inside aren't sent with the page. This page's prose is in them. - Browser extensions are passed over. An element one adds straight in
<html>,<head>or<body>(a password manager's popup) is left where it is. A page that still doesn't match what the app renders (the parser repaired broken markup, an extension's node inside the app's own elements) has its<body>rendered again from the same answers. The console names the node (expected <circle>, found <rect> in body > svg.dot), and the document gets arocx:mismatchevent for an app's error reporting. The<head>and<NoHydration>regions keep the server's nodes. To make a mismatch throw in your own browser, runlocalStorage.setItem("rocx:strict", "1")and reload.
Handlers#
A handler is the function an event runs, written on the element: on:click={|| set_count!(count!() + 1)}. Its writes apply when it ends, and each computation that read them runs once then. A dotted name after the event gives the handler what the event carries, or narrows which events it runs for:
| Written | What the handler gets |
|---|---|
on:click={|| …} | Runs on the event, given nothing. Any DOM event works: on:input, on:focus, on:dragstart… |
on:input.value={|text| …} | The field's value. |
on:change.checked={|on| …} | Whether the box is ticked. |
on:keydown.key={|key| …} | The key's name, as the browser has it: "k", "Enter", "ArrowUp". |
on:keydown.keys={|keys| …} | The key and the modifier keys held, a record (Html.Keys): if keys.mod and keys.key == "s" { save!() }. |
on:keydown.Escape={…} | Runs for that key only, with no modifier key held. |
on:keydown.Shift+Enter={…}, on:keydown.Mod+K={…} | Runs with exactly those modifier keys held. Mod is ⌘ on macOS and Ctrl elsewhere. |
on:click.prevent={…} | The browser's default is prevented first: a link's click goes where the handler says, not to its href. |
on:frame.ms={|ms| …} | Runs every animation frame while the element is on the page, given the milliseconds since the last frame (at most 100). |
on:viewport={|view| …} | The part of the element's content that shows (Html.Viewport: top, left, width, height), once it is on the page, then on each scroll or resize, at most once a frame. A virtual list renders by it. |
on:pointermove.point={|point| …} | Where the pointer is over the element, as fractions of its width and height from 0 to 1 (Html.Point), at most once a frame. Live cursors send this. |
on:drop.files, on:paste.files, on:change.files | The files dropped, pasted or picked (drag and drop). |
- Keys with modifiers run only with exactly the modifiers named (Shift+Enter isn't Enter), and the browser's own action is prevented: an arrow key a game takes doesn't scroll, and ⌘K doesn't focus the browser's search.
- The whole document. A page-wide handler (⌘K anywhere, Escape to close a panel) goes on
<Document on:keydown.Mod+K={open!} />. It renders nothing and listens while its part is on the page, so anifaround it turns it on and off.<Document on:visibilitychange.visible={|shown| …} />is told whether the page shows (false while its tab is hidden);<Window on:resize={…} />listens to the window. - A form's
on:submitruns instead of a page load (the runtime prevents the default). A form that posts to an endpoint is different (forms and submissions).
Asking the server from a handler
A handler can send an endpoint and use its answer. While it waits, that run's writes are dropped; once the answer is in, the handler runs again with it, so the request is sent once. Here a rename is sent, then the user read again:
rename! = || {
_ = Api.rename!(draft!())
refresh!(user!)
}To send without waiting, use an action (actions and optimistic values); a form has its submission (forms).
Going to another page
A click on a link to another of the app's pages renders that page in place, without a load.
navigate!(Paths.blog_slug({ slug }))(import pf.Router exposing [navigate!], Solid Router'suseNavigate) goes there once the handler ends;navigate_with!(to, { replace, scroll })takes Solid Router's options. A handler that waits and runs again navigates once. Navigating while rendering fails.Router.location!({})andRouter.is_routing!({})say where the page is and whether a navigation is on its way.use_search_params!({})reads and changes the query in place.use_before_leave!may stop a navigation (an unsaved draft).- A component that must redirect as it renders renders
<Navigate href={…} />. - Every link to the page gets
aria-current="page", and one to a page above itaria-current="true": style them by that. data-rocx-reloadon a link, or around it, leaves it to the browser: a load.
Details: navigating, without a load.
Timers, sounds and the browser
- Timers.
set_interval!(ms, tick!)runstick!everymsmilliseconds;set_timeout!(ms, done!)runsdone!once afterms. Each returns aclear!, and stops by itself when what started it goes (effects, cleanups and timers). - The time.
Time.now_millis!({})andTime.now_nanos!({})(import pf.Time, as on the server) read the clock in a handler, an effect'sapplyor a timer's tick. Never while rendering: the markup would differ from the server's. - Sounds.
Audio.play!("/sounds/eat.wav")plays any sound file the browser can, with nothing prepared (Audio.play_with!sets volume and rate). It comes from the packages/audio plugin; the showcase's games use it. - The page's own JavaScript. For what the platform has no module for (vibration, the clipboard),
Browser.call!("vibrate", { ms: 50 })(import pf.Browser) calls the function the page gave the runtime asvibrate(Engine.load(wasm, { effects })), with the argument as parsed JSON, like Elm's ports.Browser.focus!("card-title")focuses the element with that id. Both run after the handler and the page's patch; in an effect,on_settled!(|| Browser.focus!("card-title"))focuses a field as its part shows. - A question for the page.
Browser.ask!("local.get", { key: "theme" })asks the page's function at once, anywhere, and reads its answer as a typed value (D-159):Err(Unanswered)where nothing answers, and always in the server's render. On a phone the shell answers by the same name. packages/local keeps signals on the device with it:Local.signal!("rack.games", []).
Effects, cleanups and timers#
An effect is what a component does outside its markup: listen to a stream, run a timer, focus a field, call the browser. As in Solid 2.0, create_effect!(compute, apply) has two halves: compute reads, tracked; apply acts on its result once the markup is on the page. When a read changes, compute reruns, then the last apply's cleanups, then apply.
import pf.Solid exposing [create_signal!, create_effect!, on_cleanup!, set_interval!]
(heard!, set_heard!) = create_signal!(0.U64)
create_effect!(
|| room!(),
|room| {
# the room's stream, while this is on the page; another when the room changes
Endpoint.listen!(Api.events_room({ room }), |_| set_heard!(heard!() + 1))
on_cleanup!(|| set_heard!(0))
},
)
(seconds!, set_seconds!) = create_signal!(0.U64)
create_effect!(
|| running!(),
# a tick a second while running: the next apply's cleanups stop it
|running|
if running {
_ = set_interval!(1000, || set_seconds!(seconds!() + 1))
{}
} else {
{}
},
)applyruns like a handler: untracked, its writes applied when it ends. Every run ofcomputeruns it, uncompared; to act only on a real change, read through a selection:create_effect!(|| Store.of(user!).get!(|u| u.id), |id| …).- An effect goes with what made it (an
ifswitching branch, a row going), running its cleanups. on_cleanup!(|| …)(Solid'sonCleanup) runs when what is running now is done: a component, when it goes; a computation, before it reruns; an effect'sapply, before the next. What a part owns goes first, then its own cleanups, last one first. In an event handler it fails, since nothing would run it.- A listen started in an effect stops with it: the request is aborted. One started in a click's handler runs to the stream's end.
- Timers clean up too, as if their starter had called
on_cleanup!(clear!). A component's timer stops when the component goes; an effect's, before its nextapplyand when the effect goes; an event handler's, when its element goes. The server starts none. The showcase has a stopwatch, a search that waits for a pause in typing, and a clock that goes with itsif. on_settled!(|| …)runs once, in the browser, once the component is on the page (Solid 2.0'sonSettled, formerlyonMount). Anon_cleanup!inside runs when the component goes. Browser-only work goes there: reading what the page kept, focusing a field, measuring.- A render effect applies at once.
create_render_effect!(|| query!(), |_| set_page!(1))(Solid 2.0'screateRenderEffect) applies right aftercompute, during the render: in a component, before its markup is built; in an update, before other effects apply. It keeps a value in step with the render, with no frame between; anything that reads the page wantscreate_effect!. - An effect can handle its own failure.
create_effect_with!(compute, { apply, error })is Solid 2.0'screateEffect(compute, { effect, error }). Whencomputefails (a failed read, a missing context),errorgets why after the update, instead of an<Errored>showing. It answersOk({}), orErr(why)to pass it on to the nearest<Errored>after all (Solid's rethrow: log it, or note it, and still show the boundary). Whencomputesucceeds again,applyruns. - On the server, no effect runs. The browser hydrates the page as it was before any effect, then runs them. (Solid's server runs both halves of a render effect; here, its first
apply's writes are patched in during hydration.)
Waiting and failing#
A hole that reads an endpoint waits for its answer. Meanwhile <Loading> shows a fallback until the first values come, and <Errored> one when something fails (import pf.Loading, import pf.Errored).
The design came from this component in the browser platform's tests: five answers (you, your posts, friends, likes and notifications), one spinner until all are in. Posts and friends can each fail alone; anything else fails the whole. (Api.current_user!({}) and the others each read a GET endpoint with its read!().)
view! = |{}| {
# Made first, so every request starts at once; read as plain values.
user! = create_memo!(|| Api.current_user!({}))
posts! = create_memo!(|| Api.posts_of!(user!().id))
…
(count!, set_count!) = create_signal!(0.U64)
…
<Errored fallback={|problem, retry|
<p class="page-problem">
The page failed: {problem} <button on:click={retry}>Again</button>
</p>
}>
<Loading fallback={<p class="spinner">Loading…</p>}>
<Heading text!={user!().name} />
…
<button class="count" on:click={|| set_count!(count!() + 1)}>
Clicked {count!().to_str()} times
</button>
…
<section class="posts">
<Errored fallback={|problem, retry|
<p class="problem">
No posts: {problem} <button on:click={retry}>Again</button>
</p>
}>
<ul>
{...posts!().map(|post|
…
)}
</ul>
</Errored>
</section>
…
</Loading>
</Errored>
…
}- Asking Five memos, five requests, all at once. The
<Loading>shows its fallback until every one is in: one spinner, not five. - In Everything appears at once. A later change that waits, such as a rename, keeps what is shown until its answer is in: no spinner again.
- Posts fail Their
<Errored>shows its fallback, with an Again button, and the rest stays. Anything else failing fails the whole, which can try again too.
<Loading fallback={…}>shows its fallback until everything inside has its first values. Later waits keep what is shown;is_pending!can flag them.<Errored fallback={|problem, retry| …}>shows its fallback when something inside fails: a refused read, a request with no answer, a context nothing provides. It gets why (aStr) andretry, a handler that asks again for what failed (and the failed reads it came from, even ones nothing inside reads), then renders the children again.- A failure no
<Errored>of yours catches reaches the app's root one, which rocx writes: the page answers with its error page (+error.rocx), with the endpoint's status for a 4xx refusal, else 500 (where no page is).
On the server nothing waits: endpoint reads are answered in-process, and the browser reads the answers from the page. Talking to the server follows one read from the server's render to a click in the browser.
The whole component: web/test/app/Profile.rocx
import pf.Html
import pf.Solid exposing [create_signal!, create_memo!, refresh!]
import pf.Loading
import pf.Errored
import pf.Context
import Api
import Picks
## A profile that needs five answers from the server: who you are, your posts
## (which need who you are), your friends, your likes and your notifications.
## One spinner until they are all in; posts and friends fail on their own, and
## anything else failing fails the page.
Profile := [].{
view! : {} => Html
view! = |{}| {
# Made first, so every request starts at once; read as plain values.
user! = create_memo!(|| Api.current_user!({}))
posts! = create_memo!(|| Api.posts_of!(user!().id))
friends! = create_memo!(|| Api.friends!({}))
likes! = create_memo!(|| Api.likes!({}))
notifications! = create_memo!(|| Api.notifications!({}))
(count!, set_count!) = create_signal!(0.U64)
(draft!, set_draft!) = create_signal!("")
rename! = || {
_ = Api.rename!(draft!())
refresh!(user!)
}
<main>
<Errored fallback={|problem, retry|
<p class="page-problem">
The page failed: {problem} <button on:click={retry}>Again</button>
</p>
}>
<Loading fallback={<p class="spinner">Loading…</p>}>
<Heading text!={user!().name} />
<Stats likes!={likes!} notifications!={notifications!} />
<button class="count" on:click={|| set_count!(count!() + 1)}>
Clicked {count!().to_str()} times
</button>
<form class="rename" on:submit={rename!}>
<input name="name" on:input.value={set_draft!} />
<button type="submit">Rename</button>
</form>
<section class="posts">
<Errored fallback={|problem, retry|
<p class="problem">
No posts: {problem} <button on:click={retry}>Again</button>
</p>
}>
<ul>
{...posts!().map(|post|
<li key={post.title}>{post.title}</li>
)}
</ul>
</Errored>
</section>
<section class="friends">
<Errored fallback={|problem, retry|
<p class="problem">
No friends: {problem} <button on:click={retry}>Again</button>
</p>
}>
<ul>
{...friends!().map(|friend|
<li key={friend}>{friend}</li>
)}
</ul>
</Errored>
</section>
</Loading>
</Errored>
<PicksContext value={Picks.store!({})}><Picks /></PicksContext>
</main>
}
}
## The likes and notifications. It is given their accessors, so it reads them
## (and is patched when they change), and can't write them; a signal's
## accessor, a memo's or any `|| …` would do.
stats! : { likes! : () => U64, notifications! : () => U64 } => Html
stats! = |{ likes!, notifications! }|
<p class="stats">
{likes!().to_str()} likes · {notifications!().to_str()} new
</p>
## The page's heading. `text!={user!().name}` gives it an accessor, as Solid's
## compiler makes a prop a getter: it reads the name in its hole, and only that
## text is patched when the user changes.
heading! : { text! : () => Str } => Html
heading! = |{ text! }| <h1>{text!()}</h1>Loading again: is_pending!#
A memo reading again (after a refresh!, or because its URL changed) keeps showing the old value, with no spinner. is_pending! (Solid 2.0's isPending) tells the reader it is about to change. The first load is <Loading>'s job; loading again is is_pending!'s.
import pf.Solid exposing [create_signal!, create_memo!, refresh!, is_pending!]
(page!, set_page!) = create_signal!(1.U64)
posts! = create_memo!(|| Api.get_posts({}).with_query("page=${page!().to_str()}").read!())
<Loading fallback={<p>Loading…</p>}>
<ul class:stale={is_pending!(posts!)}>
{...posts!().map(|post| <li key={post.id}>{post.title}</li>)}
</ul>
</Loading>
<button on:click={|| refresh!(posts!)}>Refresh</button>
<button on:click={|| set_page!(page!() + 1)}>Next page</button>
{if (is_pending!(posts!)) <p>Updating…</p>}- True while a memo the accessor reads has a value and waits for a new one, from the update the click started until the answer is in. A memo that reads a pending memo is pending too:
is_pending!(count!)is true whilecount!, which countsposts!(), waits with it. - False on the first load (
<Loading>'s job), for a failed read (<Errored>'s), and on the server, which renders final values, so hydration sees false too. - Several at once:
is_pending!(|| (user!(), posts!()))is true while any of them is. - It never waits or fails, and doesn't make its caller depend on the values it reads: its caller reruns only when its answer changes. The
class:staleabove is patched twice a refresh, on and off.
latest!(posts!) (Solid 2.0's latest) is the last value a memo settled at. Every read here gives that already, since nothing holds writes back as Solid's transitions do; it exists for code written the Solid way.
No live demo here: this site's static copy answers reads from files at once, so there would be nothing to see. A form's submission.pending!() is different: whether a submission is on its way (forms).
Forms and submissions#
A form posts to an endpoint, which reads its fields as a record. use_submission!(endpoint) (import pf.Router exposing [use_submission!], Solid Router's useSubmission) is the latest submission to it: pending!(), input!() (what was typed, as the endpoint reads it), field!(name), result!(), error!(), and clear!() and retry!() for a handler. The runtime sends a form posting to one of the app's endpoints with fetch, so only the page changes:
- A form whose submission a component reads gets its result or refusal there. A result reads the page's data again, and a
<NoHydration>that read data as the server rendered it is taken again from the page's document. A redirect is followed in place, and the layouts it keeps read again what they read, so a sign-in shows in the header. - A form nothing reads is answered as a plain form, in place: back to the page with the flash (below), or to the endpoint's redirect. Brought back to the page it is on, the page is kept (its signals, scroll and focus), and what it read follows the server. An answer that isn't a page to go to (a crash, a middleware's refusal, no answer) shows in the nearest
<Errored>around the form, with a retry. - A form that succeeded starts empty, as after a plain post, and
field!gives "" (data-rocx-keepon the form or around it keeps it). After a refusal,field!gives what was typed, to put it back. data-rocx-reloadon a form, its button or an element around them leaves it to the browser: a plain post and a load (data-rocx-reload="off"takes it back inside).
view! = |{}| {
submission = use_submission!(Form.join)
…
<form class="join" method="post" action={Endpoint.url_of(Form.join)}>
<input name="name" value={submission.field!("name")} />
<button type="submit" disabled?={submission.pending!()}>{if (submission.pending!()) "Joining…" else "Join"}</button>
</form>
…
{match submission.result!() { Ok(welcome) => <p class="welcome">{welcome}</p>, Err(_) => <></> }}
{match submission.error!() { Ok(problem) => <p class="problem">{Server.explain(problem)}</p>, Err(_) => <></> }}
<button class="clear" on:click={|| submission.clear!()}>Clear</button>Without the runtime (before it loads, or with JavaScript off), the form posts like any HTML form, and the endpoint sends the browser back with a flash: what was typed and the result or refusal, kept on the server for a minute under an id in a cookie, and read once. The page's submission is then the flash, so the page looks as it would with the runtime and hydrates as rendered. A password field is never filled in again. Server.flash!({}) reads it directly: Ok({ url, fields, status, body }) or Err(NoFlash). The endpoint's side and redirects: talking to the server.
Actions and optimistic values#
use_action!(endpoint) (Solid Router's useAction) gives a function a handler calls with the endpoint's arg, without a form or waiting: each call is a submission, sent as JSON when the handler ends. A form posting to the same endpoint sends fields, read into the same type (a number from its text, an unticked box as false). use_submissions!(endpoint) (useSubmissions) lists every submission: whether on its way, what it sent, its result or refusal.
An optimistic value is the server's data with the pending submissions applied, shown before the server confirms. Drag a plan to another day: it moves at once, though the server takes 800 ms and refuses a full day or the dentist.
Monday
- Team stand-up
- Release notes
Tuesday
- Review the parser
Wednesday
- Dentist, 9:30
Thursday
- Demo day prep
- Groceries
Every move is in.
What the runtime did, newest first
- Waking up…
moves = use_submissions!(Api.post_api_planner_move({}))
move! = use_action!(Api.post_api_planner_move({}))
…
week = Api.get_api_planner({})
plans! = create_memo!(
|| {
server = week.read!()
moves.pending_inputs!().fold(server, PlannerDay.moved)
},
)
…
{...moves.all!().keep_if(|sent| sent.error.is_ok()).map(|sent|
…
<span>{Planner.why(sent.error)}</span>
<button type="button" on:click={|| moves.clear!(sent.id)}>Dismiss</button>- It shows at once. The memo reads the server's week and the moves on their way (
pending_inputs!()); a drop adds one, so the plan shows where it was dropped. - It gives way without a flicker. A result has every endpoint the page read read again (Solid Router's revalidation), and the submission stays on its way until they are in; then the server's week and the move's end show together. Meanwhile
is_pending!(plans!)is true, and the week dims. - A refusal puts it back and says why: its
erroris the refusal (Refused(409, why)) untilmoves.clear!(id). - Several can be on their way, each answered on its own. Apply a value (a plan's day), not a step (one more): the server's data, read again, may already include a pending move.
- Nothing optimistic exists on the server: the browser hydrates the week with no submissions. Submissions are kept by the endpoint's URL, so what varies goes in the body, not the path.
Or the other way round, as in Solid 2.0: create_optimistic!(|| board.read!()) is a signal holding the server's value until a handler writes it. The write shows at once and holds until that handler's submissions are done and the page's reads are in again; then it is undone in the same update, with no flicker. A refusal undoes it at once, as does a write whose handler sent nothing. Use it for a value the handler knows; use the memo above for many pending moves on the latest data.
(count!, set_count!) = create_optimistic!(|| Api.get_count({}).read!())
add! = use_action!(Api.post_add({}))
<button on:click={|| {
set_count!(count!() + 1)
add!({ by: 1 })
}}>{count!().to_str()}</button>- What a result reads again is the endpoint's call (Solid Router's revalidate keys):
Router.revalidate!([Endpoint.url_of(Api.get_board({}))])in its handler limits it to that URL and those under it (after/or?);[]means none. In a browser handler, it reads them again at once. - Retrying:
submission.retry!()ormoves.retry!(id)resends what was sent, pending again. - A form's fields given ahead of time (Solid Router's
action.with):Endpoint.url_of(Endpoint.with_fields(toggle, { id: todo.id }))is the form'saction, its fields in the URL (/todos/toggle?id=7), read before the form's own, with or without JavaScript. An action binds values with a closure instead. - Files: a form with an
<input type="file">(enctype="multipart/form-data") is sent as the browser sends it, as is an action whose arg holds a file's URL (dropped, pasted or picked). The endpoint reads the field as the file's name, and its bytes withServer.file(request, "photo").
Drag and drop#
Drag and drop are plain events: on:dragstart and on:dragend on what is dragged (with draggable="true"), on:dragenter, on:dragleave and on:drop where it goes. Keep what is dragged in a signal: dragstart sets it, drop reads it, as the planner above does:
<section class="day" data-day={day.id} class:over={over!() == day.id} on:dragenter={|| set_over!(day.id)} on:dragleave={|| if (over!() == day.id) set_over!("") else {}} on:drop={dropped!}>
…
{...here!().map(|plan|
<li class="plan" key={plan.id} draggable="true" class:dragged={dragging!() == plan.id} transition:move={Transition.glide.ms(320)} on:dragstart={|| set_dragging!(plan.id)} on:dragend={|| set_dragging!("")}>- Only an element with a drop handler is a drop target: the runtime accepts a drag over it as a move (preventing
dragover's default) and keeps a dropped link or file from opening in the tab. - Its dragenter and dragleave are its own, like mouseenter and mouseleave: a child fires neither, and a drop or the drag's end counts as leaving. So a lit day stays lit over its plans.
- It works in every browser, Firefox included (the runtime adds the data Firefox needs to start a drag).
on:drop.valuegives text dropped from elsewhere: a link, a word from another program. - By touch and pen too. Holding a finger still on a draggable element for a quarter second starts the runtime's own drag, firing the same events; swipes still scroll and taps still click. A copy follows the finger, and a scrolling list scrolls near its edge. A mouse keeps the browser's drag, which can reach other windows. Give keyboard users another way, as the planner's menus do.
- What a drag carries for other pages:
drag:data={[("text/uri-list", url), ("text/plain", title)]}puts each piece on the drag by type, so a link dropped in another tab opens. A drop target gets every piece withon:drop.data={|items| …}.drag:image={id}shows a copy of the element with that id (hidden or not), held where the dragged one was grabbed. - Files dropped, pasted or picked come to
on:drop.files,on:paste.filesor a file input'son:change.files, each with its name, type, size and ablob:URL to show it by (<img src={file.url}>) while the element is on the page. An action sends one as a field of its arg.
Transitions#
A row or part can animate as it comes and goes, with the transition written on the element as in Svelte (import pf.Transition). A leaving element stays in place, inert, until its animation ends. The browser plays the animations, so they cost Roc nothing per frame.
import pf.Transition
{...todos!().map(|todo|
<li key={todo.id} transition={Transition.fade}>{todo.text}</li>
)}
{if open!() {
<div class="panel"
transition:in={Transition.fly({ x: 0.0, y: -8.0 })}
transition:out={Transition.fade.ms(120)}
>…</div>
}}transition={…}plays both ways;transition:in={…}andtransition:out={…}one each.- A transition is a Roc value:
Transition.fade,Transition.fly({ x, y }),Transition.scale(0.5),Transition.grow(Bottom), or your own hidden style, animated to and from the element's own:Transition.style([("opacity", "0"), ("translate", "0 8px")])..ms(…)(default 200),.delay(…),.easing(…)and.origin(…)adjust it;.plus(…)plays two at once. A style value with anything but letters, digits, spaces and.,%#()-+is dropped, so data can't write CSS. - They play when a row or part comes or goes, on that row's or part's own elements only (Svelte's local transitions): a list inside a leaving part stays as it is. Nothing plays during hydration.
- A transition that reads a signal is computed like any attribute, and the one current when the element goes plays. Chart bars shrink into the axis, up or down by their value: give a bar chart new data and watch.
- Moves:
transition:move={Transition.glide}. When a change moves the element (reordered, or pushed by one coming or going), it glides from its old place to its new one (the FLIP technique: measured before and after). With akey={…}, an element is the same anywhere on the page: leaving one list as it enters another, it glides between them, with no in or out transition. Moving between scrolling boxes (a card into another column), it glides above the page, unclipped, growing or shrinking to its new size. The planner's plans glide from day to day. - With
prefers-reduced-motion, none plays: what goes, goes at once, and what moves lands in place.
Solid's core has no transitions (the community's solid-transition-group uses classes and a callback). Roc Solid takes Svelte's form, because a transition on the element is a value the compiler checks.
The document's head#
<Title> (import pf.Title, as in @solidjs/meta) sets the document's title from anywhere in the page, its holes live. The last one rendered that is still on the page wins: a page's over its layouts'; one in an if's part while that part shows. With none, the root layout's own <title> stands.
import pf.Html
import pf.Title
import pf.Solid exposing [create_signal!]
meta = { title: "Local" }
## A page with components of its own, defined below it: one that may make signals, and a pure one.
## They see the file's own definitions, as the page does (`shown`).
view! = |_| {
(count!, set_count!) = create_signal!(0.U64)
<section class="local">
<Title>Local {count!().to_str()}</Title>
<Board count!={count!} />
<Tag text="its own" />
<button class="bump" type="button" on:click={|| set_count!(count!() + 1)}>Bump</button>
</section>
}
## A count, as the page shows it.
shown : U64 -> Str
shown = |count| count.to_str()
## The count, as a board shows it.
Board := [].{
view! : { count! : () => U64 } => Html
view! = |{ count! }| <p class="board">{shown(count!())}</p>
<style>
.board { font-weight: bold }
</style>
}
Tag := [].{
view : { text : Str } -> Html
view = |{ text }| <span class="tag">{text}</span>
}- On the server, it goes first in the
<head>, as a<title data-rocx>before the layout's own, since browsers take the first. The layout's<head>is rendered as written, and hydration passes over the platform's element. - In the browser, the runtime keeps
document.titlein step: a changed<Title>changes it, and one that goes hands the title back to the one before it, or to the layout's.
The other @solidjs/meta elements need no import: <Meta name="description" content={post!().summary} />, <Link rel="canonical" href={…} /> and <Style>p { … }</Style>, written like their lowercase tags, anywhere in the page. The server puts them just before </head>, in render order, and the browser keeps them there, following their holes. A later <Meta> with the same name (or property, http-equiv, charset) replaces an earlier one, so a page can replace its layout's default description. Hydration keeps the server's elements, so a stylesheet isn't loaded twice.
Coming from Solid#
Solid 2.0's primitives, control flow and boundaries, with Roc's names. The same component in both:
function Friends() {
const [shown, setShown] = createSignal(3);
const friends = createMemo(() => getFriends());
return (
<Loading fallback={<p>Loading…</p>}>
<ul>
<For each={friends().slice(0, shown())} keyed={(f) => f.id}>
{(friend) => <li>{friend().name}</li>}
</For>
</ul>
<Show when={friends().length > shown()}>
<button onClick={() => setShown(shown() + 3)}>More</button>
</Show>
</Loading>
);
}view! = |{}| {
(shown!, set_shown!) = create_signal!(3.U64)
friends! = create_memo!(|| Api.get_friends({}).read!())
<Loading fallback={<p>Loading…</p>}>
<ul>
{...friends!().take_first(shown!()).map(|friend| <li key={friend.id}>{friend.name}</li>)}
</ul>
{if friends!().len() > shown!() {
<button on:click={|| set_shown!(shown!() + 3)}>More</button>
}}
</Loading>
}| Solid 2.0 | Roc Solid |
|---|---|
const [n, setN] = createSignal(0) | (n!, set_n!) = create_signal!(0) |
createSignal(timer, { equals: false }) | create_signal_with!(timer, { equals: |_, _| Bool.False }) |
setN((n) => n + 1) | update!(n!, set_n!, |n| n + 1), in a handler |
const user = createMemo(() => …) | user! = create_memo!(|| …) |
refresh(user) | refresh!(user!) |
isPending(() => user()) | is_pending!(user!) |
latest(() => user()) | latest!(user!), which every read already is |
untrack(() => base()) | untrack!(|| base!()) |
<Heading text={user().name} /> | <Heading text={user!().name} />, a getter as in Solid; or text!={user!().name}, an accessor the child calls |
| a component that only renders its props | a pure one: view, no !, called where it is written |
omit(props, "kind"), <Base {...rest} /> | |{ kind, ..rest }|, <Base {...rest} /> |
merge(rest, { size: 3 }) | <Base {...rest} size={3} />: the last of a name wins |
<Show when={…} fallback={…}> | {if … { … } else { … }} |
<Show when={…} keyed>{(v) => …}</Show> | a .map over a list of one, keyed by the value |
<Switch fallback={…}><Match when={…}>…</Match></Switch> | {match … { … => …, _ => … }} |
<For each={…} keyed={(t) => t.id}> | {...ts!().map(|t| <li key={t.id}>…</li>)} |
<For each={…} keyed={false}> | {...ts!().map_with_index(|t, i| <li key={i}>…</li>)} |
<Repeat count={n()}>{(i) => …}</Repeat> | <Repeat count!={n!()}>{|i| …}</Repeat> |
const [state, setState] = createStore(init) | (state, set_state!) = create_store!(init) |
state.user.name | state.get!(|s| s.user.name) |
setState((s) => { s.filter = "done" }) | set_state!(|s| { ..s, filter: Done }) |
const isPicked = createSelector(picked), isPicked(row.id) | is_picked! = create_selector!(picked!), is_picked!(row.id) |
const PicksContext = createContext() | picks_context = create_context() |
<PicksContext value={store}> | the same |
useContext(PicksContext) | use_context!(picks_context) |
createEffect(() => room(), (room) => { …; return () => … }) | create_effect!(|| room!(), |room| { …; on_cleanup!(|| …) }) |
createRenderEffect(() => q(), () => setPage(1)) | create_render_effect!(|| q!(), |_| set_page!(1)) |
createEffect(() => room(), { effect, error }) | create_effect_with!(|| room!(), { apply, error }) |
onCleanup(() => …) | on_cleanup!(|| …) |
onSettled(() => …) (onMount before 2.0) | on_settled!(|| …) |
const id = setInterval(tick, 1000), onCleanup(() => clearInterval(id)) | clear! = set_interval!(1000, tick!), cleared with what started it |
setTimeout(done, 400), clearTimeout(id) | clear! = set_timeout!(400, done!), clear!() |
onClick={(e) => { e.preventDefault(); go() }} | on:click.prevent={go!} |
makeEventListener(document, "keydown", …) (Solid Primitives) | <Document on:keydown.Mod+K={open!} /> |
new Audio(url).play() | Audio.play!(url) (import audio.Audio) |
| any other browser API, called in a handler | Browser.call!("vibrate", arg), the page's own function |
makePersisted(createSignal(games), { name: "games" }) (Solid Primitives) | Local.signal!("games", games) (import local.Local) |
<Loading>, <Errored> | the same |
<form action={join} method="post">, useSubmission(join) (Solid Router) | <form action={Endpoint.url_of(join)} method="post">, use_submission!(join) |
const move = useAction(moveAction); move(card, day) | move! = use_action!(Api.post_move({})), move!({ card, day }), in a handler |
useSubmissions(moveAction) | moves = use_submissions!(Api.post_move({})), moves.all!() as records |
const [cards, setCards] = createOptimistic(() => board()), written in the action | (cards!, set_cards!) = create_optimistic!(|| board.read!()), written in the handler that sends it; or derived: create_memo!(|| moves.pending_inputs!().fold(board.read!(), moved)) |
<form action={toggle.with(todo.id)} method="post"> | <form action={Endpoint.url_of(Endpoint.with_fields(toggle, { id: todo.id }))} method="post"> |
submission.retry() | submission.retry!(), moves.retry!(id) |
return json(card, { revalidate: getBoard.key }) | Router.revalidate!([Endpoint.url_of(Api.get_board({}))]), in the endpoint's handler |
const navigate = useNavigate(); navigate("/blog/hello", { replace: true }) | navigate_with!(Paths.blog_slug({ slug: "hello" }), { replace: Bool.True, scroll: Bool.True }), in a handler; a plain <a href> navigates in place, as Solid Router's does |
useIsRouting(), useLocation() | Router.is_routing!({}), Router.location!({}), both tracked |
const [params, set] = useSearchParams(); set({ days: 30 }) | search = use_search_params!({}), search.set!([("days", "30")]), in a handler |
<A href="/lists/7" activeClass="current" end> | <a href={Paths.lists_id({ id })}>, styled by a[aria-current="page"] (at its path) or a[aria-current] (under it too): every link is marked |
<Navigate href="/login" /> | <Navigate href={Paths.login} /> |
useBeforeLeave((e) => { if (dirty()) e.preventDefault() }) | use_before_leave!(|leave| if dirty!() { leave.prevent!() }) |
<HttpStatusCode code={404} /> (SolidStart) | the same (import pf.HttpStatusCode) |
<Title>{post().title}</Title> (@solidjs/meta) | <Title>{post!().title}</Title> (import pf.Title) |
<Meta name="description" content={…} />, <Link …/>, <Style> (@solidjs/meta) | the same, with nothing to import |
<TransitionGroup>, from solid-transition-group | transition={Transition.fade} on the element, as Svelte writes it |
animate:flip, crossfade (Svelte) | transition:move={Transition.glide}, with key={…} across lists |
<NoHydration> | the same |
| islands (SolidStart, Astro) | none: a page is one tree, hydrated whole, with what stays the server's in a <NoHydration> |
Where they differ, Roc is the reason:
- Names end in
!: reading or making a signal and rendering a component are effects to Roc (count!(),create_signal!,Picks.view!). - A pair is a tuple (
(count!, set_count!) = …): Roc's list patterns can't take a list apart into names. - Props are getters, and destructuring keeps them: props can only be named by a Roc pattern, so
|{ text }|reads likeprops.text(props that change). - A row says its key: Solid keys a row by its object's identity, and Roc's values have none.
- Branches are Roc's
ifandmatch, not components. Amatchnarrows aTrywhere<Show>narrows what isn't null. rocx reads the branches before the compiler, as Svelte reads{#if}. - rocx names a context after its module and definition, since values have no identity.
create_contexthas no!, so it can be a module's constant. - An effect's
applycallson_cleanup!instead of returning a cleanup: a Roc function can't return "nothing" when it has none. Neither half gets the previous value. - A submission's fields are methods (
submission.pending!()), and a form'sactionis the endpoint's URL: Roc can't turn an endpoint into a string by itself. - A setter takes a value. A Roc function takes one type of argument, so Solid's function form is
update!(count!, set_count!, |c| c + 1), given the accessor since Roc can't tell which signal a setter writes. - Signals don't compare. A signal may hold functions, which Roc can't compare, so a write always runs its readers (Solid skips an equal one). Memos and store selections compare with
==. Keep state nothing shows (the snake's time since its last move) in a signal nothing reads.
Under the hood#
- A component runs once, where it is rendered and returns markup whose holes are Roc closures. The runtime, in JavaScript, keeps them as boxes and runs them as needed, running the components inside as it builds.
- A read that has to wait stops its hole It throws, in JavaScript, through the Roc code that made it. The runtime restores Roc's stack pointer and reruns the hole when the value is in. No JSPI needed.
- On the server, nothing waits Reads are answered in-process; comments mark the holes. The answers go at the page's end, with the script that starts the browser's side.
- In the browser, nothing is made twice The runtime walks the document, binding each computation to its node with the answers from the page, and skips every
<NoHydration>.
<div data-demo="echo" data-flash="yes">
<form class="echo">
<button type="button" aria-pressed="true">the page, …</button>
<button type="button" aria-pressed="false">hello</button>
<button type="button" aria-pressed="false">this site, as files</button>
<!--errored--><!--loading-->
<output class="echo-answer">
<!--x-->Echo: the page, rendered on the server<!--/x-->
</output>
<!--/loading--><!--/errored-->
</form>
</div>
…
<script type="application/json" class="rocx-answers">
[["GET /api/facts", "", "…"],
["GET /api/echo/the%20page%2C%20…", "", "{\"status\":200,\"body\":\"\\\"Echo: the page, …\\\"\"}"],
["GET /api/echo/hello", "", "{\"status\":200,\"body\":\"\\\"Echo: hello\\\"\"}"],
["GET /api/echo/this%20site%2C%20as%20files", "", "{\"status\":200,\"body\":\"\\\"Echo: this site, as files\\\"\"}"]]
</script>
<script type="module" data-rocx src="/rocx/start.js"></script>The browser platform has the rest: the wasm, its host, the runtime, and the numbers. The platform reference types every function in the modules used here (Solid, Store, Html, Router and the rest).
Roadmap#
Solid 2.0 is the roadmap: what it has, Roc Solid should have, unless Roc says otherwise.
Works now
- Signals and
update!, memos compared by==,refresh!,is_pending!,latest!,untrack! - Holes in text, attributes, classes and styles; static when nothing they read changes
- Pure and effectful components; getter and accessor props;
{...rest} - Warnings for a value read once in a body, an arm or a row
- Contexts; components that run where they are rendered
- One tree per page, hydrated whole, browser extensions passed over;
<NoHydration> ifandmatchin a hole, each part kept while its branch holds.mapby key and by position;<Repeat>by index- Stores tracked by part; selectors; rows told only when their item changed
<Loading>,<Errored>, retry- Handlers that wait for the server; modifier keys; frames;
on:viewport; document and window events - Effects split as in Solid 2.0; render effects; error handlers;
on_cleanup!,on_settled! - Timers, cleared by
clear!or with their part - Forms sent by the runtime, or answered in place as plain forms; emptied after a success; a flash without JavaScript
- Actions, submissions, optimistic values,
retry!, revalidate keys, fields ahead of time, files - Drag and drop by mouse, touch and pen; drag data and image; dropped files
- Transitions in and out; moves, keyed across lists
<Title>,<Meta>,<Link>,<Style>- Navigating without a load: links,
navigate!, back and forward, the query in place, prefetch,use_before_leave! - Sound files (
Audio.play!) and the page's own functions (Browser.call!)
Not yet
- Derived stores and projections (
createStore(fn, seed),createProjection); a memo does for now createOptimisticStore;reconcileandstorePath- Store writes that touch only the paths written (each write runs every live selection)
- Finer reads within a row (a changed item reruns all its row's holes)
- A dev warning for a value read once in a helper function or at a
.maprow's top - Dragging by keyboard (offer another way, as the planner's menus do)
- Loading only a page's own components (every page loads one wasm with all of them)