Interfaces
In Mimic a user interface is a value. You write two pure functions:
view(state)describes the screen for a state.update(state, message)says how a message changes the state. A message is a click, a key press, or text typed into a box.
ui::run shows the interface in the browser. It keeps each tab's state, and after every message it sends only what changed. You never write HTML or JavaScript. You never change the screen yourself, and you never write async.
A counter
module main
type Msg = Inc | Dec
fn update(n: i64, m: Msg) -> i64 {
match m {
Inc => n + 1,
Dec => n - 1,
}
}
fn view(n: i64) -> ui::Node[Msg] {
ui::column(gap: 12, [
ui::text("Count: {n}", size: 24),
ui::row([ui::button("-", on_click: Dec), ui::button("+", on_click: Inc)]),
])
}
fn main() {
print(ui::run(0, view, update)) // open http://localhost:8080/
}
mimic run counter.mim
How it reads:
- The type of a screen.
ui::Node[Msg]is a screen whose buttons and boxes sendMsgvalues. - Elements are functions. Each takes its children as a list, and its settings (
gap,size, …) as named arguments. - Event handlers name messages.
on_click: Incmeans "when clicked, sendInc".updategets the message and returns the next state, thenviewruns again.
Screens are values
Because a screen is just a value, you can look at it without a browser. ui::html shows the HTML. ui::message tells which message a browser event stands for. ui::diff lists what changed between two screens:
module main
type Msg = Inc | Dec
fn view(n: i64) -> ui::Node[Msg] {
ui::row([ui::text("{n}"), ui::button("+", on_click: Inc)])
}
fn main() {
print(ui::html(view(1)))
print(ui::message(view(1), '{"p": "0.1", "e": "click", "v": ""}'))
print(json::encode(ui::diff(view(1), view(2), "0")))
}
<div data-p="0" style="display:flex;flex-direction:row;gap:8px;align-items:center"><span data-p="0.0">1</span><button data-p="0.1" type="button" data-e="click">+</button></div>
Some(Inc)
[{"op":"children","p":"0.0","html":"2","attrs":[],"at":0}]
Going from 1 to 2 changes only the text of one span, and that is all the browser receives.
A to-do list
Text boxes send what was typed. on_input: Typed uses the constructor Typed as a function, so typing "milk" sends Typed("milk"). A ui::form sends its message when Enter is pressed in one of its boxes:
module main
// A to-do list in the browser: `mimic run examples/todo/todo.mim`, then open
// http://localhost:8080/. Every tab has its own list.
type Todo = { id: i64, text: str, done: bool }
type State = { todos: [Todo], draft: str, next: i64 }
type Msg = Typed(str) | Add | Toggle(i64, bool) | Remove(i64) | ClearDone
fn update(s: State, m: Msg) -> State {
match m {
Typed(t) => { s with draft: t },
Add => if trim(s.draft) == "" { s } else { { s with todos: push(s.todos, Todo { id: s.next, text: trim(s.draft), done: false }), draft: "", next: s.next + 1 } },
Toggle(id, on) => { s with todos: s.todos ¨ (t => if t.id == id { { t with done: on } } else { t }) },
Remove(id) => { s with todos: s.todos ⌿ (s.todos ¨ (t => t.id != id)) },
ClearDone => { s with todos: s.todos ⌿ (s.todos ¨ (t => not t.done)) },
}
}
fn view(s: State) -> ui::Node[Msg] {
let left = (s.todos ¨ (t => if t.done { 0 } else { 1 })) ▷ +/
ui::column(gap: 16, [
ui::text("To do", size: 32, weight: "bold"),
ui::form(on_submit: Add, [
ui::input(s.draft, on_input: Typed, placeholder: "What needs doing?"),
ui::submit("Add"),
]),
ui::column(gap: 6, s.todos ¨ item),
ui::row([
ui::text("{left} left", color: "#888"),
ui::spacer(),
ui::button("Clear done", on_click: ClearDone),
]),
])
}
// keyed by id: removing a row touches only that row
fn item(t: Todo) -> ui::Node[Msg] {
ui::keyed("{t.id}", ui::row([
ui::checkbox(t.done, on_change: on => Toggle(t.id, on)),
ui::text(t.text, strike: t.done, color: if t.done { "#999" } else { "" }),
ui::spacer(),
ui::button("×", on_click: Remove(t.id)),
]))
}
fn main() {
print(ui::run(State { todos: [Todo { id: 0, text: "Try Mimic", done: true }], draft: "", next: 1 }, view, update, title: "To do"))
}
Things to notice:
- No loops. The list of rows is
s.todos ¨ item, built in parallel like any other¨, and the update maps over the todos the same way. - Messages name rows by id.
Toggle(t.id, on)still means the same todo after rows above it are added or removed. - Keyed rows.
ui::keyed("{t.id}", …)gives each row an identity, so removing one row from a long list sends just that change. - Rows that did not change are reused. With the rows made as
s.todos ¨ item(from each todo's own data, or a lambda whose captured values stay the same), a row whose todo is the same value as on the last screen is not built again, and comparing the screens skips it. That keeps a 10 000-row list fast. Making rows by position (⍳ ≢ s.todos ¨ (i => …)) builds every row each time. - One state per tab. Open the page in two tabs and each has its own list. Each tab is a task on the event loop, so thousands of tabs are cheap.
- Functions inside a screen must be pure.
on_input: t => { print(t); Typed(t) }is error E0605, because the screen may be rendered at any time and in parallel.
Slow work and things that happen by themselves
update is pure, so it cannot fetch a page or wait a second. Instead it returns a step: the next state, and maybe a job. A job is a function the runtime runs on its own, so the tab keeps working meanwhile. When the job finishes, the message it returns arrives like a click.
Use ui::run_live for this. Its update returns ui::stay(state) (nothing else to do) or ui::then(state, job). Subscriptions bring in messages nobody clicked: ui::every(1s, Tick) sends Tick every second, and ui::listen(receiver) sends whatever arrives through a channel (chapter 19).
module main
// A clock that ticks by itself, and a button that starts slow work without
// freezing the page: `mimic run examples/clock/clock.mim`.
type Msg = Tick | Roll | Rolled(i64)
type State = { now: i64, rolling: bool, rolls: [i64] }
fn slow_roll() -> i64 {
time::sleep(800ms) // stands for a slow request
random::int(1, 7)
}
fn update(s: State, m: Msg) -> ui::Step[State, Msg] {
match m {
Tick => ui::stay({ s with now: time::now() }),
Roll => ui::then({ s with rolling: true }, () => Rolled(slow_roll())),
Rolled(n) => ui::stay({ s with rolling: false, rolls: push(s.rolls, n) }),
}
}
fn view(s: State) -> ui::Node[Msg] {
ui::column(gap: 16, [
ui::text(time::format(s.now), size: 28, weight: "bold"),
ui::row([
ui::button("Roll a die", on_click: Roll),
ui::text(if s.rolling { "rolling…" } else { "" }, color: "#888"),
]),
ui::text("rolls: {s.rolls}"),
])
}
fn main() {
let init = State { now: time::now(), rolling: false, rolls: [] }
print(ui::run_live(init, view, update, subscriptions: [ui::every(1s, Tick)], title: "Clock"))
}
Click "Roll a die" and the clock keeps ticking while the roll takes its time. Jobs started together run in parallel, and every result comes back as a message in the tab's own order.
In a window
The same program can open a window of its own, with the system's real buttons, text boxes and check boxes, on macOS, Windows and Linux:
mimic run --window todo.mim
Nothing in the program changes. Clicks and typing reach update as messages, as they do in the browser. Closing the window ends ui::run. On Linux the window uses GTK 3, which most desktops already have (apt install libgtk-3-0 otherwise).
In a terminal
The same program can also draw itself as text:
mimic run --terminal todo.mim
To do
[What needs doing?] [ Add ]
[x] Try Mimic [ × ]
[ ] Buy milk [ × ]
1 left [ Clear done ]
Tab: next Enter or Space: press Esc: quit
Tab moves between the boxes and buttons. Typing fills the focused box, Enter presses, and Esc quits. To choose in code, write ui::run(…, show: "terminal").
As a web page
The same program can also run entirely inside the browser, with no server:
mimic run --web todo.mim # builds WebAssembly and opens it at http://localhost:8080/
mimic build --web todo.mim # writes todo-web/: index.html and app.wasm
The todo-web folder works on any static web host. Your view and update run in the visitor's browser, and nothing else changes in your code. Inside a page there is no network access. Jobs run straight after the message that started them, and print writes to the browser's console.
The full list of elements and settings is in the standard library reference.
Back to the index.
From docs/tutorial/20-interfaces.md in the Mimic repository.