Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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.

Try itPutting one on a pageComing from Solid

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:

site/Demos/Counter.rocx
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:

  1. 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.
  2. Each hole runs once to show its first value, and the runtime notes what it read: the <output>'s text, the negative class and Reset's disabled all read count!.
  3. A click runs a handler. set_count!'s write applies when the handler ends, with any others it made.
  4. 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.

2 items left

What the runtime did, newest first

  1. Waking up…
The component: site/Demos/Todos.rocx
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:

site/Ui/Heading.rocx
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:

rocx
<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:

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.)

  1. 0: Roc
  2. 1: Solid
  3. 2: Elm
  1. 0: Roc
  2. 1: Solid
  3. 2: Elm

Three or fewer

First: Roc

text patched row moved row made part switched

What the runtime did, newest first

  1. Waking up…
site/Demos/Picks.rocx, in part
{ 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 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):

rocx
{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
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:

rocx
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>

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:

site/Demos/Picks.rocx, in part
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:

site/Demos/Tally.rocx, in part
view! = |{}| {
	{ picks!, set_picks!, next!, set_next! } = use_context!(Picks.picks_context)

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:

site/routes/components/+page.rocx, in part
<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

  1. 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

  1. Waking up…
The shelf and the bag: site/Demos/Shelf.rocx, site/Demos/Bag.rocx
site/Demos/Shelf.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>
}
site/Demos/Bag.rocx
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 €"

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:

WrittenWhat 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.filesThe files dropped, pasted or picked (drag and drop).

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:

web/test/app/Profile.rocx, in part
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.

Details: navigating, without a load.

Timers, sounds and the browser

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.

rocx
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 {
			{}
		},
)

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!().)

web/test/app/Profile.rocx, in part
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>
…
}
  1. Asking Five memos, five requests, all at once. The <Loading> shows its fallback until every one is in: one spinner, not five.
  2. 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.
  3. 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.

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
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>}

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:

web/test/app/Form.rocx, in part
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

  1. Waking up…
site/Demos/Planner.rocx, in part
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>

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.

A count shown ahead of the server
(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>

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:

site/Demos/PlannerDay.rocx, in part
<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!("")}>

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.

rocx
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>
}}

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.

test/e2e/app/routes/local/+page.rocx, in part
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>
}

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:

Solid 2.0
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>
  );
}
Roc Solid
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.0Roc 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 propsa 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.namestate.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 handlerBrowser.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-grouptransition={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:

Under the hood#

  1. 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.
  2. 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.
  3. 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.
  4. 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>.
What the server sends for the echo, in part (spaced out)
<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>
  • if and match in a hole, each part kept while its branch holds
  • .map by 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; reconcile and storePath
  • 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 .map row'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)