The Elm Architecture, from scratch, in Nim 2.4
There are not TEA (The Elm Architecture) in Nim? From this it seems so https://tea.rinn7e.com/ make a better search. Now that we have better sum types with Nim 2.4 we should be able to make a small PoC that explained the TEA concepts from scratch
The Elm Architecture (TEA) writes an interactive program as a loop. A Msg says what happened, update turns it into the next Model, and view draws the model. Two things make this worth it. Because update is a plain function, you can test a program by feeding it messages, without a browser. And because every change goes through update, the list of messages is the whole history of the program. This page looks for TEA in Nim, then builds it from scratch with Nim 2.4's new sum types. Its three demos run in your browser, compiled from the Nim you read.
- What exists: a catalog of TEA frameworks lists 100 in 27 languages, none in Nim. Nim has one TEA library for terminals (bobabrew, new this year), and older Karax examples. Nothing for the browser with commands and subscriptions.
- Nim 2.4 sum types fit TEA's messages exactly: no enum to declare,
SetStep(step: 5)builds a message, acasemust handle every message, and a field can only be read in its own branch. - The PoC: the HTML, the effects (
Cmd) and the event sources (Sub) are sum types too. A runtime of 242 lines runs three apps (150 lines): a counter, dice and a stopwatch. - Rough edges in Nim 2.4.2: three small ones, each shown with the compiler's own error.
Is there TEA in Nim?
TEA Ecosystem is a catalog that grades TEA frameworks against Elm, part by part (Model, Msg, update, view, Cmd, Sub, and ports, Elm's typed channels to JavaScript). As of 23 Nov 2026 its data has 100 entries in 27 languages and none in Nim. Searching nimble, GitHub and the Nim forum finds this ("core" is Model, Msg, update and view):
| TEA in Nim, 24 Nov 2026 | |||
|---|---|---|---|
| core | Cmd | Sub | |
| bobabrew 2026 | โ | โ | as a Cmd |
| KaraxExamples 2017 | update in place | โ | โ |
| forum gists 2018 | โ | โ | โ |
| redux.nim 2017 | a reducer | outside | โ |
| Karax | by hand | โ | โ |
The only full TEA in Nim is bobabrew, a port of Bubble Tea (Go's TEA framework for terminal apps), new enough that the catalog has not found it. On the web, Nim has Model, Msg, update and view written by hand on top of Karax, but nobody wrote the other half: commands (update returns the effects it wants instead of doing them) and subscriptions (the model says what to listen to, the runtime starts and stops it).
Each project, and how I searched
- bobabrew (Aug 2026): TEA for terminal UIs. As of
24 Nov 2026 it has all 62 Bubble Tea examples ported and one commit, and is not on nimble.
Commands (
Batch,Tick,Every) are there, subscriptions are commands that reschedule themselves (as in Bubble Tea), and messages are an open type hierarchy (msg of KeyPressMsg), not a closed sum type. - KaraxExamples (2017): two demos "going in the direction of the Elm architecture", with an enum for messages and an update that changes the model in place.
- The forum asked "Are there examples of the 'Elm architecture' for Nim?" in July 2018. Araq answered: "if you use a clean Model+Update distinction and only use the update part in Karax's event handlers, you get the Elm architecture with Karax", and two gists followed (one uses the patty macros for sum types). Since then TEA comes up only in passing: in the "Wishlist: Ideal UI library for Nim" thread, Nerve (28 Feb 2024) pointed to Rust's Iced for its GPU-drawn widgets, adding "maybe we don't have to exactly adopt the Elm functional-reactive application model".
- redux.nim (2017) and redux-nim (2022): Redux stores, where effects run outside the reducer. The catalog calls these TEA-adjacent.
- Karax, Nim's virtual-DOM framework, is not TEA (handlers change any state, then Karax redraws), but TEA can be written on top of it.
- Not TEA: owlkettle (GTK) and Fidget are declarative views over mutable state; loom (NimTui, 2026) uses signals.
- Searched: nimble's
packages.json(elm, tea, redux, mvu, elmish, karax), GitHub repositories in Nim mentioning Elm or Bubble Tea, and the forum search (elm, elm architecture, bubbletea, redux).
TEA in one loop
In Elm's guide the architecture is Model, update and view; a real program
adds commands and subscriptions. Here is the loop, with the Nim signatures this page builds:
- MsgSetStep(step: 5)a value saying what happened: a click, a timer tick, the result of an effect
- updateproc update(msg: Msg, model: Model): (Model, Cmd[Msg])the next model, and the effects it asks for (a
Cmd) - ModelModel(count: 7, step: 5)the whole state of the program, one plain value
- viewproc view(model: Model): Html[Msg]the page as data, with a message on each button
- the runtimedispatch(msg)turns a click in the view, the result of a
Cmdor a tick of aSubinto the next Msg
Nim 2.4's sum types, the right shape for Msg
TEA asks for a closed set of messages, some carrying data. Nim always had this as case objects,
with an enum to declare and a kind field to switch on. Nim 2.4 (28 Oct 2026; 2.4.2
on 13 Nov) adds a shorter form: the branch names come from the type itself.
type
Msg = object
case
of Increment, Decrement, Reset: discard
of SetStep:
step: int
proc describe(msg: Msg): string =
case msg
of Increment: "plus one step"
of Decrement: "minus one step"
of Reset: "back to zero"
# the pattern binds the field to s
of SetStep(s): "steps of " & $s
for msg in [Increment(), SetStep(step: 5), Reset()]:
echo msg, ": ", describe(msg)
Increment(): plus one step SetStep(step: 5): steps of 5 Reset(): back to zero
Four things here are exactly what TEA needs. The branch name is the constructor
(SetStep(step: 5)). The field of a branch is read by a pattern, of SetStep(s). $ prints a
message the way you would write it, which is all a message log needs. And the compiler catches the
two classic mistakes. These snippets are compiled when the page is built, and the errors are what
Nim 2.4.2 printed:
type Msg = object
case
of Increment: discard
of SetStep:
step: int
proc update(msg: Msg, count: int): int =
# forgot SetStep
case msg
of Increment: count + 1snippet.nim(9, 3) Error: not all cases are covered; missing: {SetStep}
type Msg = object
case
of Increment: discard
of SetStep:
step: int
let msg = Increment()
# the wrong branch's field
echo msg.stepsnippet.nim(9, 10) Error: field 'step' can only be accessed in a pattern matching `case` branch
With classic case objects the second one compiles and, by default, fails at run time with a
FieldDefect (field checks are off with -d:danger). Here it cannot happen at all.
Step 1: Model, Msg, update, view
The first program is a counter with a step. Its model is two ints and its messages are the four above:
apps/counter.nimtype
Model* = object
count*, step*: int
Msg* = object
case
of Increment, Decrement, Reset: discard
of SetStep:
step*: intupdate makes the next model. It also returns a Cmd, the effects it wants, and here it wants
none: none() is a helper for NoCmd(), the empty command (Step 2 is about commands).
apps/counter.nimproc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Increment: m.count += m.step
of Decrement: m.count -= m.step
of Reset: m.count = 0
of SetStep(s): m.step = s
(m, none())view does not touch the DOM. It returns an Html[Msg], built with small helpers: el for an
element, text, cls for a class, and onClick Increment(), which puts a message on a
button. onInput takes a proc that makes a message from what was typed (parseStep here).
apps/counter.nimproc parseStep(s: string): Msg =
try: SetStep(step: parseInt(s))
except ValueError: SetStep(step: 1)
proc view*(m: Model): Html[Msg] =
el("div", [cls "app"],
el("p", [cls "big"], text $m.count),
el("div", [cls "row"],
el("button", [onClick Decrement()], text "โ" & $m.step),
el("button", [onClick Increment()], text "+" & $m.step),
el("button", [onClick Reset()], text "reset")),
el("label", [cls "row"], text "step ",
el("input", [prop("type", "number"), prop("value", $m.step),
onInput(parseStep)])))Html is another sum type: a Text, or an Elem with a tag, attributes and children. An
attribute is a property, or an event with the message it sends. From
tea/core.nim:
tea/core.nimtype
Attr*[M] = object
## what you can put on an element
case
of Prop:
name*, value*: string
of OnClick:
## a click sends this message
msg*: M
of OnInput:
## typing sends toMsg(the new text)
toMsg*: proc (s: string): M
type
Html*[M] = object
## the view returns data, not DOM
case
of Text:
s*: string
of Elem:
tag*: string
attrs*: seq[Attr[M]]
kids*: seq[Html[M]]Since update and view are plain functions, this page runs them at build time, natively,
before anything reaches a browser. Feed a list of messages to update, starting from the initial
model:
var (model, _) = counter.init()
for msg in [Increment(), Increment(), SetStep(step: 5), Increment(), Decrement()]:
(model, _) = counter.update(msg, model)
echo msg, " โ ", model
Increment() โ (count: 1, step: 1) Increment() โ (count: 2, step: 1) SetStep(step: 5) โ (count: 2, step: 5) Increment() โ (count: 7, step: 5) Decrement() โ (count: 2, step: 5)
And render turns the last model's view into an HTML string (one line per element here):
let html = render(counter.view(model))
<div class="app"> <p class="big">2</p> <div class="row"> <button onclick="Decrement()">โ5</button> <button onclick="Increment()">+5</button> <button onclick="Reset()">reset</button> </div> <label class="row">step <input type="number" value="5" oninput="โฆ"> </input> </label> </div>
Here is the same file compiled to JavaScript, running. Every message you send appears in the log with the model it produced. Type a step, then press the buttons.
apps/counter.nim 46 lines
## 1. A counter: Model, Msg, update, view. No effects yet.
import std/strutils
import ../tea/core
type
Model* = object
count*, step*: int
Msg* = object
case
of Increment, Decrement, Reset: discard
of SetStep:
step*: int
htmlFor(Msg)
proc init*(): (Model, Cmd[Msg]) = (Model(count: 0, step: 1), none())
proc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Increment: m.count += m.step
of Decrement: m.count -= m.step
of Reset: m.count = 0
of SetStep(s): m.step = s
(m, none())
proc parseStep(s: string): Msg =
try: SetStep(step: parseInt(s))
except ValueError: SetStep(step: 1)
proc view*(m: Model): Html[Msg] =
el("div", [cls "app"],
el("p", [cls "big"], text $m.count),
el("div", [cls "row"],
el("button", [onClick Decrement()], text "โ" & $m.step),
el("button", [onClick Increment()], text "+" & $m.step),
el("button", [onClick Reset()], text "reset")),
el("label", [cls "row"], text "step ",
el("input", [prop("type", "number"), prop("value", $m.step),
onInput(parseStep)])))
proc subscriptions*(m: Model): seq[Sub[Msg]] = @[]
let program* = Program[Model, Msg](init: init, update: update, view: view,
subscriptions: subscriptions)Step 2: commands, effects as data
A die cannot be rolled by a pure function: update would give a different answer for the same
message. In TEA, update asks for a random number by returning a command, and the runtime
sends the result back as a new message. Cmd is one more sum type:
tea/core.nimtype
Cmd*[M] = object
## effects as data: update asks, the runtime does
case
of NoCmd: discard
of Batch:
cmds*: seq[Cmd[M]]
of RandomInt:
lo*, hi*: int
## how the result comes back
gotInt*: proc (n: int): M
of Now:
gotTime*: proc (t: float): MThe dice model counts how often each face came up, and rolling counts the rolls asked for whose
answer has not come back yet. Roll asks for one number, RollMany asks for many in one Batch,
and Rolled is the answer:
apps/dice.nimproc rollCmd(): Cmd[Msg] =
RandomInt(lo: 1, hi: 6, gotInt: proc (n: int): Msg = Rolled(value: n))
proc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Roll:
inc m.rolling
(m, rollCmd())
of RollMany(n):
m.rolling += n
var cmds: seq[Cmd[Msg]]
for i in 1 .. n: cmds.add rollCmd()
(m, Batch(cmds: cmds))
of Rolled(v):
m.face = v
inc m.counts[v]
dec m.rolling
(m, none())Now testing is the interesting part. Without a runtime, Roll gives a command we can look at,
and we can play the runtime's role ourselves, with a die that always shows 4:
let (asked, cmd) = dice.update(Roll(), dice.init()[0])
echo "after Roll:\n ", asked
echo "command:\n ", cmd
case cmd
of RandomInt(lo, hi, gotInt):
# the runtime would pick rand(lo..hi)
let back = (gotInt)(4)
echo "the runtime sends:\n ", back
echo "after it:\n ", dice.update(back, asked)[0]
else: discard
echo "RollMany(n: 60) asks for:\n ", dice.update(RollMany(n: 60), dice.Model())[1]
after Roll: (face: 0, counts: [0, 0, 0, 0, 0, 0], rolling: 1) command: RandomInt(lo: 1, hi: 6, gotInt: โฆ) the runtime sends: Rolled(value: 4) after it: (face: 4, counts: [0, 0, 0, 1, 0, 0], rolling: 0) RollMany(n: 60) asks for: Batch(60 cmds)
Press roll 60 and look at the log: one RollMany(n: 60), then sixty Rolled messages, each
a step of the same pure update. The bars are the model's counts, drawn by view.
apps/dice.nim 65 lines
## 2. Dice: update cannot roll a die (that is an effect), so it returns a command.
import ../tea/core
type
Model* = object
# 0: not rolled yet
face*: int
counts*: array[1..6, int]
# rolls asked for and not back yet
rolling*: int
Msg* = object
case
of Roll: discard
of RollMany:
n*: int
of Rolled:
value*: int
htmlFor(Msg)
proc init*(): (Model, Cmd[Msg]) = (Model(), none())
proc rollCmd(): Cmd[Msg] =
RandomInt(lo: 1, hi: 6, gotInt: proc (n: int): Msg = Rolled(value: n))
proc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Roll:
inc m.rolling
(m, rollCmd())
of RollMany(n):
m.rolling += n
var cmds: seq[Cmd[Msg]]
for i in 1 .. n: cmds.add rollCmd()
(m, Batch(cmds: cmds))
of Rolled(v):
m.face = v
inc m.counts[v]
dec m.rolling
(m, none())
const pips = ["ยท", "โ", "โ", "โ", "โ", "โ", "โ
"]
proc view*(m: Model): Html[Msg] =
var bars: seq[Html[Msg]]
var most = 1
for c in m.counts: most = max(most, c)
for f in 1 .. 6:
bars.add el("div", [cls "bar"],
el("span", text pips[f]),
el("span", [cls "fill", prop("style", "width:" & $(m.counts[f] * 100 div most) & "%")]),
el("span", [cls "n"], text $m.counts[f]))
el("div", [cls "app"],
el("p", [cls "big"], text pips[m.face]),
el("div", [cls "row"],
el("button", [onClick Roll()], text "roll"),
el("button", [onClick RollMany(n: 60)], text "roll 60")),
el("div", [cls "bars"], bars))
proc subscriptions*(m: Model): seq[Sub[Msg]] = @[]
let program* = Program[Model, Msg](init: init, update: update, view: view,
subscriptions: subscriptions)Step 3: subscriptions, a function of the model
A stopwatch needs a clock that ticks while it runs, and only then. In TEA you do not start and
stop timers in update. A Sub says what to listen to:
tea/core.nimtype
Sub*[M] = object
## what the program wants to listen to, given its model
case
of Every:
every*: int
tick*: proc (t: float): Mand the program's subscriptions(model) says which ones it wants given this model. After
every message the runtime compares the answer with what is running: it starts the new
subscriptions and stops the ones that are gone.
apps/stopwatch.nimproc subscriptions*(m: Model): seq[Sub[Msg]] =
if m.running: @[Every(every: 100, tick: proc (t: float): Msg = Tick(t: t))]
else: @[]let stopped = stopwatch.Model()
let running = stopwatch.Model(running: true)
echo "stopped wants ", stopwatch.subscriptions(stopped).len, " subscriptions"
echo "running wants ", stopwatch.subscriptions(running).len, ": every ",
(case stopwatch.subscriptions(running)[0]
of Every(ms, _): $ms & " ms"), " a Tick"
stopped wants 0 subscriptions running wants 1: every 100 ms a Tick
Start needs the time, and reading the clock is an effect too, so Start returns
Now(gotTime: โฆ) and the runtime answers with Started(at: โฆ):
apps/stopwatch.nimproc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Start:
# update may not read the clock: it asks the runtime for the time
return (m, Now(gotTime: proc (t: float): Msg = Started(at: t)))
of Started(t):
m.running = true
m.since = t
m.now = t
of Tick(t): m.now = t
of Stop:
m.elapsed = m.shown
m.running = false
of Lap: m.laps.insert(m.shown, 0)
of Reset: m = Model()
(m, none())Press start, then stop, and the Tick messages stop with it: nothing in update stopped the
timer, the runtime did, because subscriptions stopped asking for it.
apps/stopwatch.nim 68 lines
## 3. A stopwatch: the clock is a subscription, and it exists only while the watch runs.
import std/[strformat, math]
import ../tea/core
type
Model* = object
running*: bool
# ms counted before the current run
elapsed*: float
# when the current run started, last tick
since*, now*: float
laps*: seq[float]
Msg* = object
case
of Start, Stop, Lap, Reset: discard
of Started:
at*: float
of Tick:
t*: float
htmlFor(Msg)
proc init*(): (Model, Cmd[Msg]) = (Model(), none())
proc shown*(m: Model): float =
if m.running: m.elapsed + (m.now - m.since) else: m.elapsed
proc update*(msg: Msg, model: Model): (Model, Cmd[Msg]) =
var m = model
case msg
of Start:
# update may not read the clock: it asks the runtime for the time
return (m, Now(gotTime: proc (t: float): Msg = Started(at: t)))
of Started(t):
m.running = true
m.since = t
m.now = t
of Tick(t): m.now = t
of Stop:
m.elapsed = m.shown
m.running = false
of Lap: m.laps.insert(m.shown, 0)
of Reset: m = Model()
(m, none())
proc fmtMs(ms: float): string =
let s = ms / 1000
&"{int(s) div 60:02}:{floorMod(s, 60.0):04.1f}"
proc view*(m: Model): Html[Msg] =
var laps: seq[Html[Msg]]
for i, l in m.laps: laps.add el("li", text &"lap {m.laps.len - i}: {fmtMs(l)}")
el("div", [cls "app"],
el("p", [cls "big"], text fmtMs(m.shown)),
el("div", [cls "row"],
if m.running: el("button", [onClick Stop()], text "stop")
else: el("button", [onClick Start()], text "start"),
el("button", [onClick Lap()], text "lap"),
el("button", [onClick Reset()], text "reset")),
el("ol", [cls "laps"], laps))
proc subscriptions*(m: Model): seq[Sub[Msg]] =
if m.running: @[Every(every: 100, tick: proc (t: float): Msg = Tick(t: t))]
else: @[]
let program* = Program[Model, Msg](init: init, update: update, view: view,
subscriptions: subscriptions)The runtime
All the impure code is one module, tea/browser.nim (158 lines), compiled
only for the JS backend. dispatch is the loop of the diagram:
tea/browser.nimproc dispatch[Model, M](rt: Runtime[Model, M], msg: M) =
let (model, cmd) = rt.program.update(msg, rt.model)
rt.model = model
# the log under each demo
rt.logLine($msg)
# view, then patch the DOM where it changed
rt.render()
# RandomInt, Now, Batch: their results come back through dispatch
rt.perform(cmd)
# start and stop timers to match subscriptions(model)
rt.syncSubs()render walks the old and the new Html together and changes only the DOM nodes that differ
(it matches children by position: no keys, which is the first thing a real library would add).
Event attributes are set again on every render, so a button always sends the message of the
latest view. perform runs each command and dispatches its result; syncSubs keeps one
setInterval per period that subscriptions asks for.
The two modules, whole. tea/core.nim (84 lines) compiles on both backends, which is
what let this page run the apps natively above.
tea/core.nim 93 lines
## The Elm Architecture, from scratch: the part that does not know about the browser.
## Every type here is a Nim 2.4 sum type, so `case` must cover every branch and a field
## can only be read in the branch that has it.
import std/strutils
type
Attr*[M] = object
## what you can put on an element
case
of Prop:
name*, value*: string
of OnClick:
## a click sends this message
msg*: M
of OnInput:
## typing sends toMsg(the new text)
toMsg*: proc (s: string): M
Html*[M] = object
## the view returns data, not DOM
case
of Text:
s*: string
of Elem:
tag*: string
attrs*: seq[Attr[M]]
kids*: seq[Html[M]]
Cmd*[M] = object
## effects as data: update asks, the runtime does
case
of NoCmd: discard
of Batch:
cmds*: seq[Cmd[M]]
of RandomInt:
lo*, hi*: int
## how the result comes back
gotInt*: proc (n: int): M
of Now:
gotTime*: proc (t: float): M
Sub*[M] = object
## what the program wants to listen to, given its model
case
of Every:
every*: int
tick*: proc (t: float): M
Program*[Model, M] = object
init*: proc (): (Model, Cmd[M])
update*: proc (msg: M, model: Model): (Model, Cmd[M])
view*: proc (model: Model): Html[M]
subscriptions*: proc (model: Model): seq[Sub[M]]
template htmlFor*(M: typedesc) =
## Nim cannot infer `M` of `Html[M]` from the expected type of a generic proc, so the
## helpers are stamped out for the program's own message type.
proc text(s: string): Html[M] {.used.} = Text(s: s)
proc el(tag: string, attrs: openArray[Attr[M]], kids: varargs[Html[M]]): Html[M] {.used.} =
Elem(tag: tag, attrs: @attrs, kids: @kids)
proc el(tag: string, kids: varargs[Html[M]]): Html[M] {.used.} =
Elem(tag: tag, attrs: @[], kids: @kids)
proc cls(c: string): Attr[M] {.used.} = Prop(name: "class", value: c)
proc prop(n, v: string): Attr[M] {.used.} = Prop(name: n, value: v)
proc onClick(m: M): Attr[M] {.used.} = OnClick(msg: m)
proc onInput(f: proc (s: string): M): Attr[M] {.used.} = OnInput(toMsg: f)
# no effect
proc none(): Cmd[M] {.used.} = NoCmd()
func esc(s: string): string =
s.multiReplace(("&", "&"), ("<", "<"), (">", ">"), ("\"", """))
proc render*[M](h: Html[M]): string =
## The same view, as an HTML string: handy to look at it outside a browser.
case h
of Text(s): esc(s)
of Elem(tag, attrs, kids):
var r = "<" & tag
for a in attrs:
case a
of Prop(n, v): r.add " " & n & "=\"" & esc(v) & "\""
of OnClick(m): r.add " onclick=\"" & esc($m) & "\""
of OnInput(_): r.add " oninput=\"โฆ\""
r.add ">"
for k in kids: r.add render(k)
r & "</" & tag & ">"
proc `$`*[M](c: Cmd[M]): string =
case c
of NoCmd: "NoCmd()"
of Batch(cs): "Batch(" & $cs.len & " cmds)"
of RandomInt(lo, hi, _): "RandomInt(lo: " & $lo & ", hi: " & $hi & ", gotInt: โฆ)"
of Now(_): "Now(gotTime: โฆ)"tea/browser.nim 171 lines
## The runtime: the only impure part. It keeps the model, turns events into messages, runs
## update, patches the DOM, performs the commands and starts and stops the subscriptions.
import std/[dom, random, tables, sequtils]
import core
export core
proc dateNow(): float {.importjs: "Date.now()".}
proc setProp(n: Node, k: cstring, v: cstring) {.importjs: "#[#] = #".}
proc getProp(n: Node, k: cstring): cstring {.importjs: "#[#]".}
proc setHandler(n: Node, k: cstring, f: proc (ev: Event)) {.importjs: "#[#] = #".}
proc clearHandler(n: Node, k: cstring) {.importjs: "#[#] = null".}
type Runtime[Model, M] = ref object
program: Program[Model, M]
model: Model
root: Element
dom: Node # what is on screen
vdom: Html[M] # the Html it came from
subs: Table[int, Interval] # running subscriptions, by period
ticks: Table[int, Sub[M]] # the latest Sub for each period
log: Element
count: int
proc dispatch[Model, M](rt: Runtime[Model, M], msg: M)
proc setAttrs[Model, M](rt: Runtime[Model, M], n: Node, attrs: seq[Attr[M]]) =
let e = Element(n)
n.clearHandler("onclick")
n.clearHandler("oninput")
for a in attrs:
case a
of Prop(k, v):
if k == "value":
if $n.getProp("value") != v: n.setProp("value", v.cstring)
elif e.getAttribute(k.cstring) != v.cstring:
e.setAttribute(k.cstring, v.cstring)
of OnClick(m):
n.setHandler("onclick", proc (ev: Event) = rt.dispatch(m))
of OnInput(f):
let toMsg = f
n.setHandler("oninput", proc (ev: Event) = rt.dispatch(toMsg($n.getProp("value"))))
proc create[Model, M](rt: Runtime[Model, M], h: Html[M]): Node =
case h
of Text(s): document.createTextNode(s.cstring)
of Elem(tag, attrs, kids):
let n = document.createElement(tag.cstring)
rt.setAttrs(n, attrs)
for k in kids: n.appendChild(rt.create(k))
n
proc sameShape[M](a, b: Html[M]): bool =
case a
of Text(_):
case b
of Text(_): true
of Elem(_, _, _): false
of Elem(t1, _, _):
case b
of Text(_): false
of Elem(t2, _, _): t1 == t2
proc patch[Model, M](rt: Runtime[Model, M], n: Node, old, new: Html[M]): Node =
## Change the DOM node `n` (drawn from `old`) so it shows `new`. Returns the node now there.
if not sameShape(old, new):
let fresh = rt.create(new)
n.parentNode.replaceChild(fresh, n)
return fresh
case new
of Text(s):
if $n.nodeValue != s: n.nodeValue = s.cstring
of Elem(_, attrs, kids):
var oldKids: seq[Html[M]]
case old
of Elem(_, oldAttrs, ok):
oldKids = ok
for a in oldAttrs: # drop attributes that are gone
case a
of Prop(k, _):
var still = false
for b in attrs:
case b
of Prop(k2, _): still = still or k2 == k
else: discard
if not still: Element(n).removeAttribute(k.cstring)
else: discard
of Text(_): discard
rt.setAttrs(n, attrs)
var domKids: seq[Node]
for c in n.childNodes: domKids.add c
for i, k in kids:
if i < oldKids.len: discard rt.patch(domKids[i], oldKids[i], k)
else: n.appendChild(rt.create(k))
for i in kids.len ..< oldKids.len: n.removeChild(domKids[i])
n
proc perform[Model, M](rt: Runtime[Model, M], cmd: Cmd[M]) =
case cmd
of NoCmd: discard
of Batch(cs):
for c in cs: rt.perform(c)
of RandomInt(lo, hi, f):
let n = rand(lo .. hi)
let toMsg = f # a binding is a template: calling it needs a real proc value
discard setTimeout(proc () = rt.dispatch(toMsg(n)), 0)
of Now(f):
let toMsg = f
discard setTimeout(proc () = rt.dispatch(toMsg(dateNow())), 0)
proc syncSubs[Model, M](rt: Runtime[Model, M]) =
## Start what subscriptions(model) asks for and is not running, stop what it no longer asks for.
var wanted: Table[int, Sub[M]]
for s in rt.program.subscriptions(rt.model):
case s
of Every(ms, _): wanted[ms] = s
for ms in toSeq(rt.subs.keys):
if ms notin wanted:
clearInterval(rt.subs[ms])
rt.subs.del ms
rt.ticks = wanted
for ms in wanted.keys:
if ms notin rt.subs:
let period = ms
rt.subs[ms] = setInterval(proc () =
if period in rt.ticks:
case rt.ticks[period]
of Every(_, f):
let toMsg = f
rt.dispatch(toMsg(dateNow())),
ms)
proc logLine[Model, M](rt: Runtime[Model, M], msg: string) =
if rt.log == nil: return
inc rt.count
let li = document.createElement("li")
li.textContent = (msg & " โ " & $rt.model).cstring
rt.log.insertBefore(li, rt.log.firstChild)
while rt.log.childNodes.len > 30: rt.log.removeChild(rt.log.lastChild)
let total = document.getElementById(($rt.root.id & "-count").cstring)
if total != nil: total.textContent = ($rt.count & (if rt.count == 1: " message" else: " messages")).cstring
proc render[Model, M](rt: Runtime[Model, M]) =
let next = rt.program.view(rt.model)
rt.dom = rt.patch(rt.dom, rt.vdom, next)
rt.vdom = next
proc dispatch[Model, M](rt: Runtime[Model, M], msg: M) =
let (model, cmd) = rt.program.update(msg, rt.model)
rt.model = model
# the log under each demo
rt.logLine($msg)
# view, then patch the DOM where it changed
rt.render()
# RandomInt, Now, Batch: their results come back through dispatch
rt.perform(cmd)
# start and stop timers to match subscriptions(model)
rt.syncSubs()
proc mount*[Model, M](id: string, program: Program[Model, M]) =
## Run `program` inside the element with this id; messages are listed in `id & "-log"`.
randomize()
let rt = Runtime[Model, M](program: program, root: document.getElementById(id.cstring))
rt.log = document.getElementById((id & "-log").cstring)
let (model, cmd) = program.init()
rt.model = model
rt.vdom = program.view(model)
rt.dom = rt.create(rt.vdom)
rt.root.appendChild(rt.dom)
rt.logLine("init")
rt.perform(cmd)
rt.syncSubs()Rough edges in Nim 2.4.2
Three things got in the way while writing this, plus a small one. Each was checked again while building this page; open a fold to see the code and the compiler's error.
A generic proc cannot learn its type from the expected type. A helper
proc text[M](s: string): Html[M] cannot be called as text "+" inside a view that returns
Html[Msg], because nothing in its arguments says what M is. Elm infers this, Nim does not,
even with {.experimental: "inferGenericTypes".}. The PoC works around it with a template,
htmlFor(Msg), that writes non-generic helpers (text, el, onClick, cls, ...) for each
app's own message type. One line per app; a real library would want a macro DSL here anyway.
The code, and the error
type
Html[M] = object
case
of Text:
s: string
of Elem:
tag: string
kids: seq[Html[M]]
Msg = object
case
of Increment: discard
proc text[M](s: string): Html[M] = Text(s: s)
proc button[M](kids: seq[Html[M]]): Html[M] =
Elem(tag: "button", kids: kids)
let v: Html[Msg] = button(@[text("+")])snippet.nim(13, 11) Error: cannot instantiate: 'M' snippet.nim(17, 33) template/generic instantiation of `text` from here
A proc field bound by a pattern cannot be called directly. In of RandomInt(lo, hi, gotInt),
gotInt is bound as a template (that is how bindings become views into the object), so
gotInt(4) is read as a template call with an extra argument. (gotInt)(4) works, and so does
let f = gotInt first (the runtime does this, since it calls the proc later, from a timer).
The code, and the error
type Cmd = object
case
of RandomInt:
gotInt: proc (n: int): string
of NoCmd: discard
let cmd = RandomInt(
gotInt: proc (n: int): string = "rolled " & $n)
case cmd
of RandomInt(gotInt): echo gotInt(4)
of NoCmd: discardsnippet.nim(10, 34) Error: type mismatch Expression: gotInt(4) [1] 4: int literal(4) Expected one of (first mismatch at [position]): [1] template gotInt(): untyped extra argument given
No == for sum types. Increment() == Increment() does not compile, as for classic case
objects ("parallel 'fields' iterator does not work for 'case' objects"). Elm compares messages
and models structurally for free; in Nim a library would generate == with a macro.
How the PoC grades, and what a real library needs
On the catalog's rubric, as I read it: Model, Msg, update, view native (one value, a closed
sum type checked for exhaustiveness, a pure update that returns its effects, a pure view);
Cmd native (effects as data, performed by the runtime, results as messages); Sub native
(subscriptions(model), started and stopped by the runtime); ports missing, which the
catalog does not require. That is the shape of "full TEA", in 242 lines of
runtime and 150 lines for the three apps. It is a PoC, not a library. The next steps,
roughly in order:
- keyed children in the DOM patch, so lists can reorder without redrawing;
- a macro DSL for views (Karax's
buildHtmlstyle), which also replaceshtmlFor; - more commands (HTTP, local storage, focus) and subscriptions (keys, animation frames, window size), and ports for JavaScript interop;
- a generated
==for models, soviewcan be skipped when nothing changed; - nested programs (a child's model in the parent's model, as Elm does).
Two follow-ups are outside this page: bobabrew would probably qualify for the catalog (it grades like Bubble Tea, which is there), and the proc-field binding above looks worth a Nim issue.
Built on 24 Nov 2026 with Nim 2.4.2 and nimib. The page's sources: tea.nim (this page),
tea/core.nim, tea/browser.nim, apps/*.nim. The demos are compiled from the same apps
files that ran natively above.