Docs

Tutorial

This tutorial builds a to-do list. It uses each of the three places state lives (Thinking in Signals): a table of to-dos and two cells in the app’s store, and one piece of local state. Along the way it writes a decision and tests it, draws a table view, saves the list to local storage, and checks all of it with specs. The first checkpoint is a working app in a new directory, using the tool and platform matching these docs. Then you will explore its files, try each behavior and connect it to the code. The later snippets are named parts of that complete app; they are not separate programs to paste into an empty file.

You need the tools from Getting Started, but no repository checkout. The topic guides that follow teach each idea in full.

Create and run the app

If the Getting Started server is still running, stop it with Ctrl+C or open another terminal. Start in a working directory where you want a new my-todos app. Download the tool matching these docs and let it create the page, platform declaration and spec directory:

curl -fLO "https://github.com/lukewilliamboswell/roc-signals/releases/latest/download/signals.roc"
roc signals.roc init my-todos
cd my-todos

Add the complete Todos.roc module and its four specs. These commands fetch the same checked files this page shows:

todo_samples=https://lukewilliamboswell.github.io/roc-signals/samples/todos
curl -fL "$todo_samples/Todos.roc" -o Todos.roc
curl -fL "$todo_samples/specs/add-toggle-remove.scm" -o specs/add-toggle-remove.scm
curl -fL "$todo_samples/specs/duplicate-titles.scm" -o specs/duplicate-titles.scm
curl -fL "$todo_samples/specs/restore.scm" -o specs/restore.scm
curl -fL "$todo_samples/specs/show-open-and-done.scm" -o specs/show-open-and-done.scm
rm Counter.roc specs/counter.scm

The last command removes only the counter module and spec that init just wrote in this new app. Keep the generated signals.roc and index.html.

Open main.roc. Keep its complete first app [main] declaration, including its generated platform URL and the pf name. Replace the imports and main definition below that declaration with:

import pf.Engine
import Todos

## `roc build --target=wasm32` gives the browser module and
## `roc build --target=x64musl` its native spec runner.
main : Engine.Program
main = Todos.program

main.roc now imports the Todos.roc beside it and hands Todos.program to the platform. Keep the platform URL that init generated: the generic <package release URL here> shown in documentation examples is a placeholder, not a replacement for that URL.

Your app’s files are now:

my-todos/
  signals.roc
  main.roc              edited imports and main; generated platform URL kept
  index.html            generated browser page
  Todos.roc             downloaded module
  specs/
    add-toggle-remove.scm
    duplicate-titles.scm
    restore.scm
    show-open-and-done.scm

Run the module’s pure tests, the app’s four specs, and the development server:

roc test main.roc
roc signals.roc test
roc signals.roc serve --port 8080

Open the address the server prints, normally http://127.0.0.1:8080/. If that port is busy, use the different address it prints. Add “Water the plants” and “Buy milk”, mark one done, try the three filters and reload. The list survives. This is the first runnable checkpoint: all four specs pass, and the browser shows the to-do form and list.

As a first edit, change the page title in index.html from Counter to To-do List. Save it and watch the development server reload the page. Keep it running while you explore the module below; stop it with Ctrl+C when you need that terminal again.

Open the module

Todos.roc starts with these imports. They use the same pf platform name that main.roc declares:

import pf.Engine exposing [Elem, Signal, State, Table]
import pf.Html

The definitions that follow belong inside one type module:

Todos := [TodoList].{
	

Its closing brace is near the end of the file, before the top-level expects. Todos.TodoList is the module’s tag; it gives this store its own identity. Keep this module opening and the imports when editing the sections below.

The store

Start with the data. A to-do has a title and is open or done. The app holds its to-dos, the key the next one takes, and the title being typed:

	Todo : { title : Str, status : [Open, Done] }

	## The app's store. Its to-dos are a table: rows by key, here a number
	## the app hands out. `next` is the key the next to-do takes, and
	## `draft` the title being typed.
	store = Engine.store(
		Todos.TodoList,
		{
			todos: Engine.table(Table.empty({})),
			next: Engine.cell(0.U64),
			draft: Engine.cell(""),
		}.Engine.Cells,
	)

	## The store's cells.
	cells = Todos.store.cells()
	
  • The store is the app’s shared state, described once. Each field is a cell, and Todos.cells holds each cell, which the rest of the app reads and writes through.
  • The to-dos are a table: a cell that holds rows by key. The user changes them one at a time (checks one off, removes one), and a table’s writes say which row they touch, so the list on the page follows a change by touching that row, however long the list is.
  • The key is a number the app hands out, not the title. next is the number the next to-do gets.

Adding a to-do: one decision

Submitting the form changes three things that must agree: the table gains a row, the next key moves on, and the draft is cleared. Or it changes nothing, when the title is blank or the list has it already. One pure function decides which, and returns every write:

	## What the form reads when it is submitted: the title typed, whether
	## the list has it already, and the key the next to-do takes.
	Adding : { title : Str, listed : [Listed, Unlisted], next : U64 }

	## The form's reading: three cells read together, and mapped to the
	## three small things the decision needs.
	adding : {} -> Signal(ctx, Adding)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	adding = |{}|
		{
			draft: Todos.cells.draft.signal(),
			table: Todos.cells.todos.signal(),
			next: Todos.cells.next.signal(),
		}.Signal.map(|{ draft, table, next }| { title: draft.trim(), listed: Todos.presence(table, draft.trim()), next })

	## Whether `table` has a to-do called `title`.
	presence : Table(U64, Todo), Str -> [Listed, Unlisted]
	presence = |table, title| table.fold(Unlisted, |found, _, todo| if (todo.title == title) Listed else found)

	## What submitting the form writes. A blank title, or one the list has
	## already, writes nothing. Any other writes the new row, the key after
	## it and an empty draft, together.
	added : Adding -> List(Engine.Write(_))
	added = |{ title, listed, next }|
		if title.is_empty() or listed == Listed {
			[]
		} else {
			[
				Todos.cells.todos.update(|table| table.insert(next, { title, status: Open })),
				Todos.cells.next.set(next + 1),
				Todos.cells.draft.set(""),
			]
		}
	
  • added is a decision: a function from a reading to a list of writes. cell.set(value) and cell.update(f) are values that say what to write; the engine applies the list when the form is submitted.
  • adding is the reading. Three values are combined into one with Roc’s record builder ({ ... }.Signal), and mapped down to the three small things the decision needs. It is read once, when the form is submitted and before anything is written. The decision is handed whether the title is listed, not the table, so it holds nothing large while it decides.
  • The table is changed with update and one of its own operations, insert. That is how the table knows which row was written.
  • The draft is a cell, not local state of the form, because this decision must clear it or keep it from the same reading that decides the rest.

Because a decision is an ordinary function, it is tested with no engine and no browser. store.after(writes) applies a list to the store, and read reads a cell of the result:

## A new title is added under the next key, and the next key and the draft
## move on with it.
expect {
	typed = Todos.store.after([Todos.cells.draft.set("Buy milk")])
	after = typed.after(Todos.added({ title: "Buy milk", listed: Unlisted, next: 0 }))

	actual =
		\\row 0: ${Str.inspect(after.read(Todos.cells.todos).get(0))}
		\\next: ${after.read(Todos.cells.next).to_str()}
		\\draft: "${after.read(Todos.cells.draft)}"
	expected =
		\\row 0: Ok({ status: Open, title: "Buy milk" })
		\\next: 1
		\\draft: ""
	actual == expected
}

## A blank title and a title already on the list write nothing.
expect {
	blank = Todos.added({ title: "", listed: Unlisted, next: 3 })
	again = Todos.added({ title: "Buy milk", listed: Listed, next: 3 })
	blank.is_empty() and again.is_empty()
}

Run them with roc test main.roc in my-todos/. In the browser, try a blank title and then add the same title twice. The second submission keeps the draft and adds no row, just as the decision says.

The list: a table view

A table has no order of its own. A table view draws the rows a query keeps, in the query’s order. The query is plain data, here which to-dos to show, and plan turns it into the three functions a table view needs:

	## Which to-dos the list shows.
	Showing : [All, Open, Done]

	## How a choice of `Showing` selects and orders rows: the rows it
	## keeps, in the order they were added, which is the order of their
	## keys.
	plan : Showing -> Engine.QueryPlan(U64, Todo, (U64, U64))
	plan = |showing| Engine.sort_by({
		keep: |_, todo| match showing {
			All => True
			Open => todo.status == Open
			Done => todo.status == Done
		},
		sort: |key, _| key,
	})
	

keep chooses the rows and sort gives the value a row is ordered by. Engine.sort_by uses that value’s own order and then the key’s order for a tie. Keys are handed out in order, so sorting by key is the order the to-dos were added in.

	## The list: three buttons that choose what it shows, and a view of the
	## table. The choice is the list's own state, since nothing else in the
	## app reads it.
	list : {} -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, _)]
	list = |{}|
		Engine.state(
			All,
			|showing| Html.div(
				"list",
				[
					Html.button("Show all", [], showing.update(|_| All)),
					Html.button("Show open", [], showing.update(|_| Open)),
					Html.button("Show done", [], showing.update(|_| Done)),
					Html.ul(
						[],
						[
							Engine.table_view(
								Todos.cells.todos,
								{ query: showing.signal(), plan: Todos.plan, window: Engine.const(Engine.every_row) },
								|key, todo| Todos.row(key, todo),
							),
						],
					),
				],
			),
		)
	
  • Engine.table_view draws the table view. When a row of the table is written, the table view places that row again and touches only it on the page.
  • showing is local state: Engine.state(All, ...) creates it for this piece of the view. Nothing else in the app reads which to-dos the list shows, so it does not belong in the store. Its buttons write it with a reducer, showing.update(...).
  • A table view draws a window of its rows. A to-do list is short, so it draws every row: Engine.every_row.

One row

The row template runs once for the whole table view, not once per row. It is handed the row’s key and a State of the row:

	## One row. `todo` is a `State` of this row of the table: the checkbox
	## reads and writes this to-do and no other. Removing a row changes the
	## table itself, so it is a decision over the table's cell.
	row : Signal(r, U64), State(r, Todo) -> Elem(r)
		where [r.store : () -> Engine.Reach(r, _)]
	row = |key, todo| {
		title = todo.signal().map(|held| held.title)
		Html.li(
			[],
			[
				Html.checkbox(
					title.map(|text| "Done: ${text}"),
					todo.signal().map(|held| held.status == Done),
					[],
					todo.set_value(|held, checked| { ..held, status: if (checked) Done else Open }),
				),
				Engine.text_s(title),
				Html.icon_button(
					"x",
					title.map(|text| "Remove ${text}"),
					"remove",
					Engine.handle_by(key, |id, _| [Todos.cells.todos.update(|table| table.remove(id))]),
				),
			],
		)
	}
	

The checkbox delivers a Boolean checked state and reads and writes its own row through todo: it cannot touch another row. Removing a row changes the table itself, so the button’s handler is a decision over the table’s cell, given the row’s key when it is pressed. Each control’s accessible name includes the title, which is how assistive technology, and the specs, tell the rows apart.

The page

	## The page: the form, the list, a note while there is nothing to do,
	## the count of open to-dos, and the effect that saves the list.
	view : {} -> Elem(Engine.StoreRoot(_))
	view = |{}| {
		todos = Todos.cells.todos.signal()
		Html.div(
			"todos",
			[
				Html.form(
					"New todo",
					[Html.on_submit(Engine.handle_by(Todos.adding({}), |at, _| Todos.added(at)))],
					[
						Html.text_input(Engine.const("Title"), "text", Todos.cells.draft.signal(), [], Engine.handle(|typed| [Todos.cells.draft.set(typed)])),
						Html.submit_button("Add", []),
					],
				),
				Todos.list({}),
				Engine.when(todos.map(|table| table.len() == 0), || Html.p("Nothing to do.", "empty"), || Engine.text("")),
				Html.span_s(todos.map(Todos.remaining), [Engine.test_id("remaining")]),
				Engine.watch_changes(todos.map(Todos.encode), |text| [Engine.command(StorageSet("todos", text))], Engine.ignore({})),
			],
		)
	}
	

Going through it:

  • The form’s submit runs the decision. Engine.handle_by(reading, decide) makes a handler of it. The runtime prevents the browser’s default for every form, so submitting never reloads the page.
  • The text box shows the draft, and each keystroke puts the box’s new text in the draft’s cell. Engine.handle gives a decision the event’s payload.
  • todos is the table’s value, read here without a table view by the empty note, the counter and the storage effect. Such a reader is evaluated on every write to the table, which is fine for a count.
  • Engine.when shows “Nothing to do.” only while the table is empty.
  • Nothing is passed down to Todos.list or to a row. Every part of the view reaches the store’s cells directly.

Saving to local storage

Two pieces make the list survive a reload. The program declares the storage key it reads at startup and starts the store from it, and the view saves the list whenever it changes:

	## The saved list: one to-do per line in the order they were added, `+`
	## for done and `-` for open.
	encode : Table(U64, Todo) -> Str
	encode = |table| {
		rows = table.fold([], |found, key, todo| found.append({ key, todo })).sort_by(|held| held.key)
		Str.join_with(rows.map(|{ todo, .. }| "${if (todo.status == Done) "+" else "-"}${todo.title}"), "\n")
	}

	## The to-dos a saved text holds, in its order. A line that starts with
	## neither sign is skipped.
	decode : Str -> List(Todo)
	decode = |text|
		text.split_on("\n").keep_oks(
			|line|
				if line.starts_with("+") {
					Ok({ title: line.drop_prefix("+"), status: Done })
				} else if line.starts_with("-") {
					Ok({ title: line.drop_prefix("-"), status: Open })
				} else {
					Err(Blank)
				},
		)

	## The store a visit starts with: the saved to-dos under the keys 0, 1,
	## 2 and so on, and the key after the last as the next. A to-do's place
	## in the saved text is its key, and no place repeats.
	start : Engine.Boot -> Engine.Store(_, _)
	start = |boot| {
		saved = Todos.decode(Engine.boot_storage(boot, "todos") ?? "")
		match Table.from_list(saved.map_with_index(|todo, index| { key: index, row: todo })) {
			Ok(todos) =>
				Todos.store
					.with_initial(Todos.cells.todos, todos)
					.with_initial(Todos.cells.next, saved.len())
			Err(DuplicateKey(place)) => crash "Todos.start: the saved place ${place.to_str()} repeats"
		}
	}

	program : Engine.Program
	program = Engine.program_store({ storage_keys: ["todos"], max_inflight: 32 }, Todos.start, |_boot| Todos.view({}))
	

Engine.program_store is the program of an app with a store. The runtime reads each declared key before mounting and passes the values in Boot, and store.with_initial(cell, value) starts a cell at a value that depends on them. The saving half is the last child of the view:

				Engine.watch_changes(todos.map(Todos.encode), |text| [Engine.command(StorageSet("todos", text))], Engine.ignore({})),
				

watch_changes issues its requests each time the watched value changes after mount. StorageSet is a command, so there is no result to react to and the reaction is Engine.ignore. Effects and the Browser covers requests that do return results.

The format is a pair of pure functions, so one more expect pins it:

## The saved text reads back as the same to-dos, in the order they were added.
expect {
	todos = [{ title: "Water the plants", status: Open }, { title: "Buy milk", status: Done }]
	table = Table.from_list(todos.map_with_index(|todo, index| { key: index, row: todo }))?
	Todos.encode(table) == "-Water the plants\n+Buy milk" and Todos.decode(Todos.encode(table)) == todos
}

Specs

The four files already downloaded into my-todos/specs/ are also available individually: add-toggle-remove.scm , duplicate-titles.scm , restore.scm and show-open-and-done.scm .

The expects test the logic. Specs test what a user sees and does. The first walks through the main path:

(test "add, complete and remove todos"
  (steps
    (expect-visible (text "Nothing to do."))
    (fill (label "Title") "Water the plants")
    (submit (role form :name "New todo"))
    (fill (label "Title") "Buy milk")
    (submit (role form :name "New todo"))
    (expect-absent (text "Nothing to do."))
    (blur (label "Title"))
    (expect-value (label "Title") "")
    (expect-text (test-id "remaining") "2 items left")
    (check (label "Done: Buy milk"))
    (expect-text (test-id "remaining") "1 item left")
    (expect-local-storage "todos" "-Water the plants\n+Buy milk")
    (click (role button :name "Remove Water the plants"))
    (expect-text (test-id "remaining") "0 items left")))

Two details are worth noticing. The box keeps the text the user typed while it has focus, even after the decision clears the draft: the runtime never overwrites a focused control, so a value written while the user is typing cannot move their caret. The blur step lets the cleared draft through. And expect-local-storage checks the exact text the effect saved.

The duplicate rule and the restore path get their own specs:

(test "a title already on the list is not added again"
  (steps
    (fill (label "Title") "Buy milk")
    (submit (role form :name "New todo"))
    (fill (label "Title") "Buy milk")
    (submit (role form :name "New todo"))
    (expect-text (test-id "remaining") "1 item left")
    (expect-value (label "Title") "Buy milk")))
(test "the list is restored from local storage"
  (setup (local-storage "todos" "+Buy milk\n-Call home"))
  (steps
    (expect-checked (label "Done: Buy milk") true)
    (expect-text (test-id "remaining") "1 item left")))

The last one checks the view, and how much work a change does: checking a to-do off while only open ones are shown removes one row and builds none.

(test "the list shows all, open or done todos"
  (setup (local-storage "todos" "+Buy milk\n-Call home"))
  (steps
    (expect-visible (label "Done: Buy milk"))
    (expect-visible (label "Done: Call home"))
    (click (role button :name "Show open"))
    (expect-absent (label "Done: Buy milk"))
    (expect-visible (label "Done: Call home"))
    ; Checking a todo off takes its row out of the open ones, so the step is
    ; a click: `check` would look for the box afterwards. The row was
    ; written, not the list compared: one row is removed and none is built.
    (mark-metrics)
    (click (label "Done: Call home"))
    (expect-absent (label "Done: Call home"))
    (expect-metric-delta rows_removed 1)
    (expect-metric-delta rows_created 0)
    (expect-text (test-id "remaining") "0 items left")
    (click (role button :name "Show done"))
    (expect-checked (label "Done: Buy milk") true)
    (expect-checked (label "Done: Call home") true)
    (click (role button :name "Show all"))
    (expect-local-storage "todos" "+Buy milk\n+Call home")))

blueprint run check builds this sample and runs these specs natively and in Chrome, so the code on this page is known to work.

Check and build your app

After an edit, run both kinds of tests from my-todos/:

roc test main.roc
roc signals.roc test
roc signals.roc build

The first command checks the module’s pure decisions and storage format; the second checks all four .scm files against the app. build writes a deployable dist/ with the browser module, page and matching runtime. Serve that directory over HTTP to deploy it; Getting Started explains what to keep together.

You have a running app, its editable source and a test suite. As you make it your own, use the specs to state what should stay true about adding, checking, filtering and restoring a to-do.

Where to go next