1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
import gleam/int
import lustre
import lustre/element.{button, div, p, span, text}
import lustre/event.{dispatch, on_click}
import lustre/cmd
import gleam/map.{Map}
import gleam/list
import gleam/option
pub fn main() {
let app = lustre.application(#(init_state(), cmd.none()), update, render)
lustre.start(app, "#app")
}
type State {
State(ctr: Int, counters: Map(Int, Int))
}
fn init_state() {
State(ctr: 2, counters: map.from_list([#(1, 0)]))
}
pub type Action {
Add
Remove(id: Int)
Increment(id: Int)
Decrement(id: Int)
}
fn update(state, action) {
case action {
Add -> #(
State(
..state,
ctr: state.ctr + 1,
counters: state.counters
|> map.insert(state.ctr, 0),
),
cmd.none(),
)
Remove(id) -> #(
State(
..state,
counters: state.counters
|> map.delete(id),
),
cmd.none(),
)
Increment(id) -> #(
State(
..state,
counters: state.counters
|> map.update(id, fn(opt_ctr) { option.unwrap(opt_ctr, 0) + 1 }),
),
cmd.none(),
)
Decrement(id) -> #(
State(
..state,
counters: state.counters
|> map.update(id, fn(opt_ctr) { option.unwrap(opt_ctr, 0) - 1 }),
),
cmd.none(),
)
}
}
fn render(state) {
let render_counter = fn(pair) {
let #(id, value) = pair
p(
[],
[
button([on_click(dispatch(Decrement(id)))], [text("-")]),
span([], [text(" "), text(int.to_string(value)), text(" ")]),
button([on_click(dispatch(Increment(id)))], [text("+")]),
span([], [text(" ")]),
button([on_click(dispatch(Remove(id)))], [text("remove")]),
],
)
}
div(
[],
[
div(
[],
state.counters
|> map.to_list
|> list.map(render_counter),
),
p([], [button([on_click(dispatch(Add))], [text("add")])]),
],
)
}
|