Docs

Conditionals and Lists

Dynamic structure is UI that appears, disappears or repeats. Each mechanism on this page creates scopes: a branch or a row owns everything mounted inside it and releases it when it goes. The snippets come from www/samples/structure.roc, a small mail view:

Tab : [Inbox, Archive]

Message : { id : Str, subject : Str, starred : Bool }

Model : { tab : Tab, messages : List(Message), selected : Str }

Ctx : In(Root, Model)

initial : Model
initial = { tab: Inbox, messages: [{ id: "m1", subject: "Welcome", starred: False }, { id: "m2", subject: "Invoice", starred: True }], selected: "" }

Deferred content

Use Html.placeholder when temporary static content should remain until a live body is ready and receives a browser-task opportunity. Its body then has an ordinary scope, with current state and normal disposal. See Startup and Deferred Content for the contract, readiness and a compiled example.

Conditionals

Engine.when takes a Signal(ctx, Bool) and two functions, and builds only the branch that is selected:

## `when` builds only the selected branch, and rebuilds it when the
## condition flips. State inside the departing branch is disposed.
empty_note : Signal(Ctx, List(Message)) -> Elem(Ctx)
empty_note = |messages|
	Engine.when(
		messages.map(|l| l.is_empty()),
		|| Html.p("No messages.", "empty"),
		|| Engine.text(""),
	)

When the condition flips, the departing branch is disposed (its nodes removed, its local state released, its timers cancelled) and the other branch is built. Use Engine.text("") for “nothing”.

Engine.switch selects among several branches by value. It takes the list of every case, so it knows what all of its branches read:

## `switch` lists every case it can select, so it knows everything its
## branches read. A value outside the list is a contract error.
tabs : State(Ctx, Model) -> Elem(Ctx)
tabs = |model|
	Engine.switch(
		model.signal().map(|m| m.tab),
		[Inbox, Archive],
		|tab|
			match tab {
				Inbox => Html.h2("Inbox", "tab-title")
				Archive => Html.h2("Archive", "tab-title")
			},
	)

A value that is not in the case list is a contract error. Because unselected branches are never built, a branch may contain the same function again: recursive UI, such as a tree, needs no special support.

Engine.remount_on(key, body) is the third of the family: one body, built again whenever its key changes. It is how local state that belongs to one key starts again, and Local State, Events, and Forms shows it.

Keyed lists

Engine.each(items, key, template) shows one row per item of a list that is a plain value:

## Rows are keyed by `id`. A surviving key keeps its DOM nodes and its row
## state when the list is reordered; a duplicate key is a contract error.
inbox : State(Ctx, Model) -> Elem(Ctx)
inbox = |model| {
	messages = model.signal().map(|m| m.messages)
	selected = Engine.keyed(model.signal().map(|m| m.selected), "selected", "")
	Html.ul(
		[],
		[
			Engine.each(
				messages,
				|m| m.id,
				|row| message_row(model, row, row.select(selected)),
			),
		],
	)
}

The key function gives each row its identity. Keys are compared as exact strings, and two items with the same key in one list are a contract error naming the key, never a silent merge. Choose a key from the domain (an id), not from the position.

The template runs once per list and receives a RowRef rather than an item:

Line : Row(Ctx, Message)

## The template runs once for the whole list. `row.field` reads the current
## row's item; `row.select` is "selected" for exactly one row, so changing the
## selection re-evaluates two rows, not all of them.
message_row : State(Ctx, Model), RowRef(Ctx, Message), Signal(Line, Str) -> Elem(Line)
message_row = |model0, row, is_selected| {
	model = model0.lift_row()
	id = row.key()
	Html.li(
		[Engine.class_s(is_selected)],
		[
			Html.button_s(row.field(|m| m.subject), [], model.update_by(id, |m, k| { ..m, selected: k })),
			Html.checkbox(row.field(|m| "Star ${m.subject}"), row.field(|m| m.starred), [], model.set_value_by(id, star)),
		],
	)
}

star : Model, Str, Bool -> Model
star = |m, id, flag| { ..m, messages: m.messages.map(|msg| if (msg.id == id) { ..msg, starred: flag } else msg) }

  • row.key() and row.field(f) are values in the row’s context. A hole that reads row.field(...) is re-evaluated only for rows whose item changed. row.item() is the whole item, for a handler that takes it as its reading: Engine.handle_by(row.item(), ...).
  • Handlers read the row they fired in: update_by(id, f) passes the clicked row’s key.
  • Outer values and local states are brought in with lift_row. Cells of the store need no lift.
  • A row template must produce a single element. It can declare a reference with Engine.ref_s, using a name built from the row’s key; see Focus. An empty name names nothing, and two live elements with one nonempty name are a contract error.

When the list changes, each compares the new list with the rows it drew: surviving rows keep their nodes and move if they must, and only added, removed or changed rows cost work on the page. The comparison itself is linear in the list. That suits a list that is small or computed, such as the options of a select, the items of an answer, or a few rows in local state as here. Rows the user edits by key, and anything sorted, filtered or long, belong in a table drawn through a table view, where a write names its row and nothing is compared: see Tables and Table Views.

Keyed selection

“Is this row the selected one?” read naively from the model would re-evaluate every row whenever the selection changes. Engine.keyed(selected, yes, no) and row.select(...) express it so the engine re-evaluates only the previously selected row and the newly selected one.

Row state

State created inside a row template belongs to that row:

## State declared inside a row template is per row: each message has its own
## "expanded" flag, kept while its key survives and dropped with its row.
expandable : RowRef(Ctx, Message) -> Elem(Line)
expandable = |row|
	Engine.state(
		False,
		|open| {
			subject = row.field(|m| m.subject).lift()
			Html.div(
				"message",
				[
					Html.button_s(open.signal().map(|o| if (o) "Hide" else "Show"), [], open.update(|o| !o)),
					Engine.when(open.signal(), || Html.p_s(subject, []), || Engine.text("")),
				],
			)
		},
	)

It survives reordering, filtering that keeps the key, and changes to the row’s item. It is released when the key leaves the list. Reinserting the key later starts a fresh row.

Lifetime rules

ChangeState and effectsDOM
Reorder a surviving keyKeptExisting nodes move
Insert or remove another keyUnaffected rows keptOnly affected rows change
Change a row’s item, same keyRow kept; holes reading the item re-evaluateOnly changed holes update
Remove a keyRow disposed; subscriptions and timers stop; requests in flight report to the listRow removed
Reinsert a removed keyA new rowNew nodes
Change an item’s keyThe old row ends, a new one startsRemove and insert
Flip a when or switchThe departing branch is disposedThe new branch is built
Change the key of a remount_onThe body is disposed; local state inside starts againThe body is built again
Hide with a class or attributeEverything stays liveNodes stay
Write a cell of the storeThe cell and everything mounted survive; its readers refreshOnly changed holes update

The rows of a table view follow the same rules, with one more way to go: leaving the table view’s window (Tables and Table Views).

State that must outlive a branch or a row — a draft that should survive switching tabs, say — belongs in the store: a cell, or a field of a table’s row. The engine never keeps a disposed scope alive for you.