Docs

Tables and Table Views

A list the user edits is the place where “compare the old value with the new one” costs most: one changed row would mean looking at every row. So rows that are edited by key, and anything drawn sorted, filtered or long, are held in a table. Every write to a table names the rows it touches, and a table view draws part of the table from its changes, without ever comparing two lists.

The snippets on this page come from a league table, www/samples/scores/.

A table is a cell

Engine.table(start) describes a cell of the store that holds rows by key, starting at the table start:

	Player : { name : Str, team : [Red, Blue], points : I64 }

	## The players a league starts with, each under its key. A top-level
	## constant is evaluated while compiling, so a key written twice here is
	## a compile error naming it.
	roster : Table(U64, Player)
	roster = match Table.from_list([
		{ key: 1, row: { name: "Ada", team: Red, points: 30 } },
		{ key: 2, row: { name: "Ben", team: Blue, points: 25 } },
		{ key: 3, row: { name: "Cy", team: Red, points: 20 } },
		{ key: 4, row: { name: "Di", team: Blue, points: 15 } },
		{ key: 5, row: { name: "Eve", team: Red, points: 10 } },
		{ key: 6, row: { name: "Flo", team: Blue, points: 5 } },
	]) {
		Ok(table) => table
		Err(DuplicateKey(key)) => crash "Scores.roster lists the key ${key.to_str()} twice"
	}

	## What the board shows: which players, in which order. Plain data,
	## which a view compares to know when to build itself again.
	Listing : { show : [Everyone, Team([Red, Blue])], order : [Highest, Lowest] }

	## The store. `players` is a table. It and the key the next player
	## takes are one group, so one generated write starts both again.
	store = Engine.store(
		Scores.League,
		{
			league: {
				players: Engine.table(Scores.roster),
				next: Engine.cell(7.U64),
			}.Engine.Cells.with_reset(|described, reset| { players: described.players, next: described.next, reset }),
			listing: Engine.cell({ show: Everyone, order: Highest }),
			window: Engine.cell({ start: 0.U64, count: 3.U64 }),
			scroll_window: Engine.cell({ start: 0.U64, count: 3.U64 }),
			scrolled: Engine.cell(False),
		}.Engine.Cells,
	)

	## The store's cells.
	cells = Scores.store.cells()
	
  • The key is a typed value of your choosing, here a U64. A table finds a row through the key’s own equality and hash, and a key occurs once.
  • Table.from_list(rows) builds a table, or answers Err(DuplicateKey(key)) naming the first key two rows share. The roster is a top-level constant that matches on it and crashes on Err: the compiler evaluates a top-level constant, so a key written twice in the program’s own rows is a compile error naming the key, and the running app never meets it.
  • A table that starts empty starts at Table.empty({}).
  • A table has no order of its own. An order the user sees is worked out by a table view, from the rows’ fields.
  • The table is held in an ordinary cell, Scores.cells.league.players, read with signal() and written with update, like any other (Shared State).

The value in the cell is a Table(k, v), from the Table module. It changes only through its own operations, and that is how each write says which rows it touched:

OperationWhat it writes
table.insert(key, row)A row under a new key. A key the table holds leaves it unchanged: read contains first when the user must be told
table.put(key, row)The row at key, inserted or replaced
table.update(key, f), table.replace(key, row)The row at key. A key the table does not hold leaves it unchanged
table.remove(key)Removes the row at key. A missing key leaves the table unchanged
table.update_all(f)Every row: a whole rewrite
table.get(key), table.contains(key), table.len()Nothing: they read
table.fold(start, f), table.to_list()Nothing: they read every row, in no particular order. to_list gives each row with its key; sort the list before showing or comparing it

Draw a table view

A table view draws the rows a query keeps, in the query’s order, and of those only the rows inside a window. Engine.table_view(table, { query, plan, window }, template) is its site:

	## The board: three rows of the listing's order, from where the window
	## starts. The list's `data-count` says how many players the listing
	## keeps, however few the window draws.
	board : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	board = |{}|
		Html.ul(
			[Engine.test_id("board")],
			[
				Engine.table_view_counted(
					Scores.cells.league.players,
					{ query: Scores.cells.listing.signal(), plan: Scores.plan, window: Scores.cells.window.signal() },
					"data-count",
					|key, player| Scores.row(key, player),
				),
			],
		)
	

This board uses Engine.table_view_counted, a table view that also counts the rows its query keeps into an attribute of the list (Counting the rows kept); Engine.table_view takes the same arguments without the name.

The table view keeps the place of every row the query keeps. When a row is written, it works out that row’s place again and touches only that row on the page: its text changes, it moves, or it enters or leaves the window. What a write costs depends on the rows written, not on the size of the table.

The query is data

query is a value the site can compare: the filter and the order the user chose, the kind of thing a URL or a saved setting holds. plan turns it into a QueryPlan(k, v, s), the three functions a table view needs:

	## Order by points in the chosen direction, with keys breaking ties.
	plan : Listing -> Engine.QueryPlan(U64, Player, (Order.Direction(I64), U64))
	plan = |{ show, order }| Engine.sort_by({
		keep: |_, player| match show {
			Everyone => True
			Team(team) => player.team == team
		},
		sort: |_, player| Order.directed(player.points, order == Highest),
	})
	

Engine.sort_by takes keep, which selects rows, and sort, which gives a row’s sort value. It compares that value by its type’s order_relative_to, then breaks a tie by the key’s own order. A table has no insertion order for ties to keep. The key’s order must agree with its equality: Same exactly when the keys are equal.

Order.asc, Order.desc and Order.directed(value, descending) keep both directions in one type. Order.pair(first, second) compares two priorities; nest pairs for more. Order.utf8(text) gives identifiers an explicit UTF-8 byte order, with no allocation during comparison. It is not a reader’s language-sensitive order: uppercase ASCII precedes lowercase, and different normalization forms stay different. Normalize at input when the app requires it, and give names an application-defined order when byte order is unsuitable. A nominal sort value can provide its own order_relative_to, just like a number does.

The primitive QueryPlan also accepts an explicit compare, like List.sort_with beside List.sort_by. Use it for a key without its own order, such as Str. Its order must be total: Same identifies only a row’s own sort value. Include the key wherever the sorted field can tie. Two rows can tie between the keyed writes of one event even when they do not tie before or after it; two different rows comparing Same are a contract error.

The query is data rather than the functions themselves because functions cannot be compared: given a record of functions, the site could not tell a new query from the same one. When the query changes to an unequal value the table view builds itself again, with a pass over the table.

The window

window is { start, count }: the table view creates rows on the page only for the count rows from position start of its order. Scrolling or paging is a write of the window, and costs the rows that leave and enter. A window that reaches past the last row draws the rows there are.

Engine.every_row is the window that draws every row the query keeps, however many they come to: window: Engine.const(Engine.every_row). Use it for a list that is short by nature, such as the cards of a column. A long list wants a window of its own: with every row drawn, one row that enters, leaves or moves costs a comparison across all of them.

Here the listing and the window are cells, so buttons change them. Either could as well be local state or a constant: each is just a Signal.

Following a scrollbar

A fixed-height list can write the same window from a scroll report instead of a paging button:

	## This second board follows its scrollbar. The spacer uses the table's
	## whole row count, so changing the drawn window never moves the scrollbar.
	scroll_board : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	scroll_board = |_args| Engine.element(
		"div",
		[
			Html.aria_label("Scrolled scores"),
			Engine.attr("style", "height:84px;overflow:auto;overflow-anchor:none;position:relative"),
			Html.on_scroll(Engine.handle(|position| [Scores.cells.scroll_window.set({ start: position.top.to_u64() // 28, count: 3 })])),
		],
		[
			Engine.element(
				"div",
				[Engine.attr_s("style", Scores.cells.league.players.signal().map(|table| "height:${(table.len() * 28).to_str()}px;position:relative"))],
				[
					Engine.element(
						"div",
						[Engine.attr_s("style", Scores.cells.scroll_window.signal().map(|window| "position:absolute;top:${(window.start * 28).to_str()}px;width:100%"))],
						[
							Engine.table_view(
								Scores.cells.league.players,
								{ query: Engine.const({ show: Everyone, order: Highest }), plan: Scores.plan, window: Scores.cells.scroll_window.signal() },
								|_key, player| Html.p_s(player.signal().map(|held| "Scrolled ${held.name} ${held.points.to_str()}"), [Engine.attr("style", "height:28px;line-height:28px;margin:0")]),
							),
						],
					),
				],
			),
		],
	)
	

The scroller’s CSS fixes its height, and every row uses the height the window calculation assumes. A spacer keeps the full row count’s height; only the drawn rows change with the window. Set overflow-anchor: none and keep the spacer independent of drawn rows, so a window write cannot move the scrollbar and produce another scroll report. A size report can also change the window’s count as its container grows or shrinks. Both writes use the ordinary turn and preserve rows kept by the final window.

This model assumes fixed-height rows. Measuring each row, page scrolling and variable-height virtualization are outside the platform’s layout vocabulary. Scrolling and layout describes size/seen observations and their lifetimes.

Counting the rows kept

A window draws a few rows, and the page sometimes needs to know how many the query keeps in all: to size a scroller for every row, or to say “3 of 1,200”. Engine.table_view_counted(table, props, name, template) is a table view that sets the attribute name of its parent element to that number, in decimal. The board above sets data-count on its list: 6 at first, 3 once only the red team is shown, 4 when a red player joins. The attribute is written when the view mounts and again in each turn that changes the number; the view already holds the number, so counting costs nothing per row. A reader of the table that counted the rows itself would filter the whole table on every write.

The view must be placed directly inside an element of your view, outside the rows of an each or another table view, so it has a parent to write to. Placed anywhere else, it stops the app when it mounts, with an error naming the site. The attribute is the view’s: do not set it on the element as well, or the two overwrite each other. A spec reads it with expect-attr.

A drawn row is handed its row

The template runs once for the whole table view, not once per row. It receives the row’s key, fixed for the drawn row’s lifetime, and a State of the row:

	## One row of the board. `player` is a `State` of this row: reading it
	## reads the row at this key, and writing it writes that row and no
	## other. Removing the row is a write of the table, so it is a decision
	## over the table's cell.
	row : Signal(r, U64), State(r, Player) -> Elem(r)
		where [r.store : () -> Engine.Reach(r, _)]
	row = |key, player| {
		name = player.signal().map(|held| held.name)
		# How often this row was cheered: state of the row on the page, which
		# the table knows nothing of.
		cheer = Engine.state(
			0.U64,
			|cheers| Html.button_s(
				cheers.signal().map2(name.lift(), |count, who| "Cheer ${who} (${count.to_str()})"),
				[],
				cheers.update(|count| count + 1),
			),
		)
		Html.li(
			[],
			[
				Html.span_s(player.signal().map(|held| "${held.name} ${held.points.to_str()}"), []),
				Html.button_s(name.map(|who| "Point to ${who}"), [], player.update(|held| { ..held, points: held.points + 1 })),
				Html.button_s(name.map(|who| "Remove ${who}"), [], Engine.handle_by(key, |id, _| [Scores.cells.league.players.update(|table| table.remove(id))])),
				cheer,
			],
		)
	}
	
  • player.signal() reads the row at this key. player.update(f) and the other State reducers write that row and no other, so a row’s own handlers cannot name the wrong row or the wrong table.
  • Any other write (removing the row, inserting one, writing several) changes the table itself, so it is a decision over the table’s cell.
  • A function written over a State draws a table’s row unchanged, as it draws a local state or a cell.
  • The template must return a single element. Values from outside the row enter with lift_row; cells need no lift.

Write the table

Writes to a table stand in a decision’s list beside its other writes:

	## What "Add player" writes, given the key the next player takes: the
	## new row, and the key after it.
	joined : U64 -> List(Engine.Write(_))
	joined = |key| [
		Scores.cells.league.players.update(|table| table.insert(key, { name: "Player ${key.to_str()}", team: Red, points: 0 })),
		Scores.cells.league.next.set(key + 1),
	]

	## A point to each of `keys`, as that many keyed writes in one event. A
	## fold over the keys rather than a `while` loop over a `var` holding
	## the table, which copies the table on every iteration in optimised
	## builds (roc-lang/roc#12971).
	awarded : Table(U64, Player), List(U64) -> Table(U64, Player)
	awarded = |table, keys| keys.fold(table, |held, key| held.update(key, |player| { ..player, points: player.points + 1 }))

	## What choosing who is shown writes: the listing, and the window back at
	## the top of the new order.
	shown : [Everyone, Team([Red, Blue])] -> List(Engine.Write(_))
	shown = |show| [
		Scores.cells.listing.update(|listing| { ..listing, show }),
		Scores.cells.window.update(|window| { ..window, start: 0 }),
	]
	
  • joined writes two cells that must agree, the table and the next key, in one decision.
  • awarded makes several keyed writes in one event. Every table view absorbs each of them from the table’s changes.
  • shown changes the query and puts the window back at the top: a change of what is shown is a transition like any other.

The toolbar attaches them, with the two kinds of whole rewrite:

	## The buttons. Each one's handler is a decision over the store's cells:
	## the listing, the window, or the table itself. A transition that needs
	## nothing from the event is a list of writes (`Engine.does`).
	toolbar : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	toolbar = |{}| {
		players = Scores.cells.league.players
		window = Scores.cells.window
		Html.div(
			"toolbar",
			[
				Html.button("Everyone", [], Engine.does(Scores.shown(Everyone))),
				Html.button("Red team", [], Engine.does(Scores.shown(Team(Red)))),
				Html.button("Lowest first", [], Engine.does([Scores.cells.listing.update(|listing| { ..listing, order: Lowest })])),
				Html.button("Next three", [], Engine.does([window.update(|at| { ..at, start: at.start + 3 })])),
				Html.button("First three", [], Engine.does([window.update(|at| { ..at, start: 0 })])),
				Html.button("Add player", [], Engine.handle_by(Scores.cells.league.next.signal(), |key, _| Scores.joined(key))),
				Html.button("Point to the first three", [], Engine.does([players.update(|table| Scores.awarded(table, [1, 2, 3]))])),
				Html.button("Clear the points", [], Engine.does([players.update(|table| table.update_all(|_, player| { ..player, points: 0 }))])),
				Html.button("New season", [], Engine.does([Scores.cells.league.reset])),
				Html.button("Show scrolled scores", [], Engine.does([Scores.cells.scrolled.set(True)])),
			],
		)
	}
	

Write a table with update, never with a set of a table built from a reading of the cell: that copies the table.

Rows from outside

Rows that arrive at run time (a server’s answer, storage, a file) enter through Table.from_list, in the decision that receives them. On Ok the decision sets the table into its cell; on Err(DuplicateKey(key)) it writes a state of the app’s own instead, which the page shows like any other failure of what arrived. The Reading List example refuses a shelf with two books under one id this way, and names the id.

Whole rewrites

update_all, a set of a new table (Table.from_list(rows)) and a generated reset replace every row. They do not record each key: every table view of the table builds itself again, with a pass over the table and a sort. Rows that are in the window before and after are kept, not created again.

The league group’s reset puts the table back to the rows it was described with. A table described as Engine.table(Table.empty({})) and filled later, with with_initial or a set, resets to empty.

Several table views, and plain readers

Any number of table views can draw one table, each with its own query and window. They all follow the same writes:

	## The three players with the most points, whatever the board shows: a
	## second view of the same table, with a query and a window that never
	## change.
	podium : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	podium = |{}|
		Engine.element(
			"p",
			[Engine.test_id("podium")],
			[
				Engine.table_view(
					Scores.cells.league.players,
					{ query: Engine.const({ show: Everyone, order: Highest }), plan: Scores.plan, window: Engine.const({ start: 0, count: 3 }) },
					|_key, player| Html.span_s(player.signal().map(|held| "${held.name} "), []),
				),
			],
		)
	

A value that reads the table’s cell without a table view is an ordinary reader:

	## How many players the league has: a plain reader of the table's cell,
	## evaluated on every write of the table.
	size : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	size = |{}| Html.p_s(Scores.cells.league.players.signal().map(|table| "${table.len().to_str()} players"), [Engine.test_id("size")])
	

It is evaluated on every write to the table, and pruned if its result is equal. That is fine for a count or one row by key. Only a row of a table view wakes for its own row alone.

A drawn row’s own state

State declared inside the template belongs to the drawn row, not to the table:

		# How often this row was cheered: state of the row on the page, which
		# the table knows nothing of.
		cheer = Engine.state(
			0.U64,
			|cheers| Html.button_s(
				cheers.signal().map2(name.lift(), |count, who| "Cheer ${who} (${count.to_str()})"),
				[],
				cheers.update(|count| count + 1),
			),
		)
		

It moves with the drawn row when the row’s place changes. It goes when the drawn row leaves the window, whether by a scroll, a change of query or a move past the window’s edge, and a drawn row that comes back starts fresh. State that must outlive that is a field of the row in the table.

ChangeThe drawn rowIts own state
Its row in the table is writtenKept; holes that read the row re-evaluateKept
Its place in the order changes, inside the windowMoved, with its nodesKept
It leaves the window, or its key is removedRemovedGone
It enters the windowCreatedStarts fresh
The query changes, or the table is rewritten wholeKept if it is in the window before and afterKept with it
One event writes the table, the query and the window togetherKept if it is in the window before the event and after itKept with it

An event changes the rows a table view draws once, from the window before it to the window after it, whatever it wrote on the way. A decision that inserts a row above the window and moves the window down by one leaves every row on the page where it was. Rows that enter in one event are created from the first to the last, as the rows of a new table view are, so a request each row issues when it is created goes out in the table view’s order.

Testing

A transition over a table is tested like any decision, by reading the table of the store it leaves:

## A new player takes the next key, and the key after it becomes the next.
expect {
	after = Scores.store.after(Scores.joined(7))
	league = Scores.cells.league

	actual =
		\\players: ${after.read(league.players).len().to_str()}
		\\new: ${Str.inspect(after.read(league.players).get(7).map_ok(|player| player.name))}
		\\next: ${after.read(league.next).to_str()}
	expected =
		\\players: 7
		\\new: Ok("Player 7")
		\\next: 8
	actual == expected
}

## A new season starts the league again at the roster it was described
## with, whatever was added or scored.
expect {
	league = Scores.cells.league
	played = Scores.store.after(Scores.joined(7)).after([league.players.update(|table| Scores.awarded(table, [1, 7]))])
	again = played.after([league.reset])

	actual =
		\\played: ${played.read(league.players).len().to_str()} players, Ada on ${Str.inspect(played.read(league.players).get(1).map_ok(|player| player.points))}
		\\again: ${again.read(league.players).len().to_str()} players, Ada on ${Str.inspect(again.read(league.players).get(1).map_ok(|player| player.points))}, next ${again.read(league.next).to_str()}
	expected =
		\\played: 7 players, Ada on Ok(31)
		\\again: 6 players, Ada on Ok(30), next 7
	actual == expected
}

The table of that store keeps the changes, so a test can also ask which rows a transition wrote: table.inverse() is one write for each, and table.changes() each written key with its row as it was.

A spec pins what a write does on the page, and how much:

(test "a point writes one row, and the row moves when its place changes"
  (steps
    (expect-text (test-id "podium") "Ada Ben Cy ")
    (expect-visible (text "Cy 20"))
    (expect-absent (text "Di 15") :never-drawn)
    ; One point to Cy leaves it third: its text changes and nothing else does.
    (mark-metrics)
    (click (role button :name "Point to Cy"))
    (expect-visible (text "Cy 21"))
    (expect-metric-delta set_text 1)
    (expect-metric-delta rows_moved 0)
    (expect-metric-delta rows_created 0)
    (expect-metric-delta rows_removed 0)
    (click (role button :name "Point to Cy"))
    (click (role button :name "Point to Cy"))
    (click (role button :name "Point to Cy"))
    (click (role button :name "Point to Cy"))
    (expect-text (test-id "podium") "Ada Ben Cy ")
    ; The sixth takes Cy past Ben. Each view moves the row it already drew:
    ; no row is created or removed in either.
    (mark-metrics)
    (click (role button :name "Point to Cy"))
    (expect-visible (text "Cy 26"))
    (expect-text (test-id "podium") "Ada Cy Ben ")
    (expect-metric-delta rows_moved 2)
    (expect-metric-delta rows_created 0)
    (expect-metric-delta rows_removed 0)))

Four metrics say what a write did to the rows drawn: rows_created, rows_removed, rows_moved, and rows_updated, the drawn rows a table view kept whose row was written (Testing).

A table or a list?

Engine.each (Conditionals and Lists) draws a list that is a plain value, by comparing the new list with the rows it drew. That comparison is linear in the list, which is right for a list that is small or computed: the options of a select, the items of an answer, a few rows in local state. Reach for a table when rows are edited by key, when the list is sorted or filtered on the page, or when it is long.

Costs and limits

  • A keyed write costs each table view of the table a search for the row’s place, and each plain reader of the table one evaluation.
  • A change of query, a whole rewrite and the mount of a table view each cost a pass over the table and a sort of the rows kept. So does an event that writes a large share of the table’s rows by key, more than about an eighth of them: the table view builds itself again, since that then costs less than placing each row. How few rows the table view keeps does not matter: a table view of ten rows of a large table follows a write of all ten row by row.
  • A move costs the rows the table view draws, so keep a window on a long list.
  • An event that writes several of a table view’s table, query and window settles them together. A query or window derived from local state follows that state before the table view reads it. The table view compares the drawn rows before the event with the final window once, preserving every drawn row that remains in it.
  • A write to a key the table does not hold writes nothing and reports nothing: an earlier write of the same event may have removed the row. An insert of a key it holds writes nothing too.
  • A row read after its key left the table in the same event is a contract error.
  • Table.changes retains the last turn that wrote this table, including across unrelated turns. The next writing turn clears it before its first modifier runs; further writes in that event keep the first earlier row per key. A signal can read these changes like any other part of the cell.
  • Table.inverse gives writes that undo those retained changes, and Table.apply applies them. A later event’s decision can read the inverse before its writes begin and use it to undo the last writing turn. Inside a modifier the inverse describes that event’s writes instead. Keep an inverse in a history cell if it must survive the next write of the table. Earlier rows are held until that next write or disposal of their holder; there is no time bound, and no earlier whole table is kept. The next writing turn pays for freeing those earlier rows, so a single keyed write can also pay cleanup proportional to the previous turn’s recorded keys.

Two compiler defects touch tables today, each with its upstream issue:

  • Many writes to a table in one event are a fold over the keys, as awarded is, not a while loop over a var that holds the table: the loop copies the table on every pass in an optimised build (roc-lang/roc#12971).
  • A shipping build copies a table’s rows on every keyed write (roc-lang/roc#12957); a development build writes them in place. A write of one element of a list in a store cell is in place in both, while a local state’s value is copied on every write in every build (roc-lang/roc#13012). Until that is fixed, keep a large or often-edited value, such as a long list or a document, in a store cell rather than in local state. An allocation guard (tests/runtime/write-scaling.mjs) runs on a development and a --opt=size build: it fails if a write that is in place starts to copy, and prints each that copies, so the fix shows when it lands. The platform is designed for the fix, and nothing in an app changes when it lands.