aboutsummaryrefslogtreecommitdiff
path: root/test/nested.gleam
blob: b32a5a367a8c93dce03aef3e6f961aba2f16eeb0 (plain)
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
// IMPORTS ---------------------------------------------------------------------

import counter
import gleam/list
import gleam/map.{Map}
import gleam/pair
import lustre
import lustre/element.{Element}
import lustre/html.{div}

// MAIN ------------------------------------------------------------------------

pub fn main() {
  // A `simple` lustre application doesn't produce `Cmd`s. These are best to 
  // start with if you're just getting started with lustre or you know you don't
  // need the runtime to manage any side effects.
  let app = lustre.simple(init, update, render)
  let assert Ok(_) = lustre.start(app, "body")

  Nil
}

// MODEL -----------------------------------------------------------------------

type Model =
  Map(Int, counter.Model)

fn init() -> Model {
  use counters, id <- list.fold(list.range(1, 10), map.new())

  map.insert(counters, id, counter.init())
}

// UPDATE ----------------------------------------------------------------------

type Msg =
  #(Int, counter.Msg)

fn update(model: Model, msg: Msg) -> Model {
  let #(id, counter_msg) = msg
  let assert Ok(counter) = map.get(model, id)

  map.insert(model, id, counter.update(counter, counter_msg))
}

// RENDER ----------------------------------------------------------------------

fn render(model: Model) -> Element(Msg) {
  let counters = {
    use rest, id, counter <- map.fold(model, [])
    let el = element.map(counter.render(counter), pair.new(id, _))

    [el, ..rest]
  }

  div([], counters)
}