Docs

Components

Roc organises code around types: a module defines a type and the functions on it. A component is that kind of module with a view added. It is not a special construct of the engine, which mounts the elements a view returns and knows nothing else about it.

The snippets come from the cart of the shop in Shared State, www/samples/shop/Cart.roc.

The smallest component

A function over what it is handed is already a component. This one is handed a State:

## The smallest component is a function over what it is handed: here a
## `State` of the rating, which it reads and writes. It cannot tell whose
## state that is, so the same function draws a local state of its caller's,
## a row of a table or a cell of the app's store (`cell.state()`).
stars : State(ctx, U8) -> Elem(ctx)
stars = |rating|
	Html.div(
		"stars",
		[
			Html.button_s(rating.signal().map(|n| "${n.to_str()} of 5"), [], rating.update(|_| 5)),
			Html.button("Clear", [], rating.update(|_| 0)),
		],
	)

The caller decides whose state it is: a local state (Engine.state(3, stars)), a row of a table, which a table view hands out as a State, or a cell of the store (cell.state()).

A type and its operations

A component with state of its own starts as an ordinary type module. The type is the component’s state, and every change to it is a pure function on the type:

## A shopping cart: what is in it, and how many of each. The type, its pure
## operations and its view are this one module.
Cart :: { lines : List(Line) }.{

	is_eq : _

	## One thing a shop sells.
	Product : { name : Str, price : U64 }

	## One product in the cart, and how many of it.
	Line : { product : Product, count : U64 }

	empty : Cart
	empty = { lines: [] }

	## The cart with one more of `product`.
	add : Cart, Product -> Cart
	add = |cart, product|
		if cart.lines.any(|line| line.product.name == product.name) {
			{ lines: cart.lines.map(|line| if (line.product.name == product.name) { ..line, count: line.count + 1 } else line) }
		} else {
			{ lines: cart.lines.append({ product, count: 1 }) }
		}

	## The cart without the product called `name`.
	remove : Cart, Str -> Cart
	remove = |cart, name| { lines: cart.lines.drop_if(|line| line.product.name == name) }

	## How many of the product called `name` the cart holds.
	quantity : Cart, Str -> U64
	quantity = |cart, name| cart.lines.keep_if(|line| line.product.name == name).fold(0, |sum, line| sum + line.count)

	## How many things the cart holds.
	size : Cart -> U64
	size = |cart| cart.lines.fold(0, |sum, line| sum + line.count)

	## What the cart costs.
	total : Cart -> U64
	total = |cart| cart.lines.fold(0, |sum, line| sum + line.count * line.product.price)
	

:: makes the type opaque: other modules hold a Cart and call its functions, and cannot build one or take one apart by hand. The operations are tested where they are written, with no engine and no browser:

## Adding a product twice makes one line of two, and the total follows.
expect {
	tea = { name: "Tea", price: 4 }
	cart = Cart.empty.add(tea).add({ name: "Bread", price: 3 }).add(tea)

	actual =
		\\size: ${cart.size().to_str()}
		\\tea: ${cart.quantity("Tea").to_str()}
		\\total: ${cart.total().to_str()}
		\\without tea: ${cart.remove("Tea").total().to_str()}
	expected =
		\\size: 3
		\\tea: 2
		\\total: 11
		\\without tea: 3
	actual == expected
}

One thing to know when naming things in a type module: its own functions are in scope throughout its block, and Roc does not allow shadowing. A parameter or a local that reuses the name of a function defined above it is reported as a duplicate definition. That is why the cart’s row function below is line_row: line stays free for the lambdas that walk the lines.

The view is handed its cells

Shared state reaches a component as a props record of cells. The record says exactly which shared state the component reads and writes:

	## What the view is drawn over, in a store whose storage is `st`: the
	## cart, and a note for whoever delivers it.
	Props(st) : { cart : Cell(st, Cart), note : Cell(st, Str) }

	## What an app's store holds for a cart: its cells, and
	## the write that starts every one of them again.
	Basket(st) : { cells : Props(st), reset : Engine.Write(st) }

	## The cart's cells, for an app to nest in its store. `reset` is
	## generated from this description, so a cell added here later is
	## started again with the rest.
	cells : {} -> Engine.Cells(whole, _, Basket(whole))
	cells = |{}| {
		cart: Engine.cell(Cart.empty),
		note: Engine.cell(""),
	}.Engine.Cells.with_reset(|described, reset| { cells: described, reset })
	

The view takes that record and is generic twice over: in st, the type of whichever store holds the cells, and in ctx, the context it is drawn in.

	## Whether the cart's panel is open.
	Panel : [Open, Closed]

	## The cart, drawn over its cells. Whether the panel is open is the
	## view's own state: no one else reads it, so it is not in the store.
	view : Props(st) -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, st)]
	view = |props|
		Engine.state(
			Closed,
			|panel| Html.section(
				"Cart",
				"cart",
				[
					Html.button_s(props.cart.signal().map(|cart| "Cart (${cart.size().to_str()})"), [], panel.update(toggled)),
					Engine.when(panel.signal().map(|shown| shown == Open), || Cart.contents(props, panel), || Engine.text("")),
				],
			),
		)
	

Because the view names no store and no fixed context, it works at any depth, in a row, and in another app. Props(st) takes the store’s type as a parameter because a type alias cannot leave it to the compiler with _.

Private state stays local

What only the component cares about is local state in its view. The cart’s panel is open or closed, and no one else reads that, so it is an Engine.state and not a cell. It needs no entry in the store, cannot be reached by code that has no business with it, and starts again by itself when the cart’s piece of the view is disposed.

Inside, the component writes its cells with decisions, from any depth, and composes them with its local writes:

	## The open panel: the cart's lines, its total, the note, and a button
	## that empties the cart.
	contents : Props(st), State(ctx, Panel) -> Elem(ctx)
		where [ctx.store : () -> Engine.Reach(ctx, st)]
	contents = |props, panel| {
		held = props.cart.signal()
		# One click, two writes: the panel closes, which is the view's own
		# state, and the cart is emptied, which is the store's.
		emptied = panel.update(|_| Closed).also(Engine.does([props.cart.set(Cart.empty)]))
		Html.div(
			"lines",
			[
				Html.ul([], [Engine.each(held.map(|cart| cart.lines), |line| line.product.name, |row| Cart.line_row(props, row))]),
				Html.p_s(held.map(|cart| "Total ${cart.total().to_str()}"), [Engine.test_id("total")]),
				note_box("Note for the courier", props.note.state()),
				Html.button("Empty cart", [], emptied),
			],
		)
	}

	## One line of the cart, in a row of its list. The row writes the cart's
	## cell with no `lift`.
	line_row : Props(st), RowRef(ctx, Line) -> Elem(Row(ctx, Line))
		where [ctx.store : () -> Engine.Reach(ctx, st)]
	line_row = |props, row| {
		name = row.key()
		Html.li(
			[],
			[
				Engine.text_s(row.field(|held| "${held.count.to_str()} × ${held.product.name}")),
				Html.button_s(name.map(|product| "Remove ${product}"), [], Engine.handle_by(name, |product, _| [props.cart.update(|cart| cart.remove(product))])),
			],
		)
	}
	

A feature describes its own cells

Cart.cells({}) above is the description of the cells a cart needs, with a reset where they should start again. The app nests it in its store as one field, and gets back the cells in the shape the component chose. A cell the component gains later appears in the app’s store, and in the reset, with no change to the app.

Only the composing module imports the store

The store’s description names the component’s type, so the module that builds the store imports the component. A component that imported the store back would make the two import each other. So a third party hands the component its cells: the module that composes, a page or the app’s root.

	## The page. It hands the cart its cells: this module knows the store
	## and the cart, and the cart knows neither the store nor this module.
	view : {} -> Elem(Engine.StoreRoot(_))
	view = |{}| {
		basket = Shop.cells.basket.cells
		check_out = Html.button("Check out", [], Engine.handle_by(basket.cart.signal(), |cart, _| Shop.checked_out(cart)))
		Html.div(
			"shop",
			[
				Html.p_s(Shop.cells.notice.signal(), [Engine.test_id("notice")]),
				Html.p_s(Shop.cells.orders.signal().map(|count| "Orders placed: ${count.to_str()}"), [Engine.test_id("orders")]),
				Html.ul([], [Engine.each(Engine.const(Shop.shelf), |item| item.name, |row| Shop.product_row(row))]),
				Cart.view(basket),
				check_out,
				Shop.ordering({}),
			],
		)
	}
	

In this small app the root both builds the store and composes. In a larger one the store has a module of its own, each page composes its components, and the components import neither. Passing is one level deep: a cell needs nothing to reach a nested context, so a component hands a cell to a child directly and nothing is threaded through the contexts between.

Nothing is sent upward

There is no action type and no channel from a component to its owner. A component that must tell the rest of the app something does one of two things:

  • It writes a cell it was handed, in the same decision as its own change. The cart’s rows write the cart’s cell, and the shop’s product rows and its check-out read it.
  • It runs a handler or a reaction it was handed, composed with its own by also. A menu that closes itself, which is its own state, and then runs the handler its owner gave it is open.update(...).also(chosen).

What a component needs from above arrives as ordinary values in its props: values, cells, an element to place, a handler.

What the types do not catch

A component handed the wrong cell of the right type compiles: two Cell(st, Str) are the same to the type checker. A spec, or a pure test of the transition, is what tells them apart. Keep a component’s props to the cells it uses, and name them for what they hold.

Code size

A view that is generic over its context is compiled once for each kind of context it is drawn in. That is what lets one view read the store and be drawn in a row with no ceremony. Its price is code size: a large view drawn under several kinds of context is in the module once for each.