aboutsummaryrefslogtreecommitdiff
path: root/test/example/application/counter.gleam
blob: 0433c1e2d3b1ca116de6eb710a45a569aacb8642 (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 gleam/int
import lustre
import lustre/attribute.{ style }
import lustre/element.{ button, div, p, text }
import lustre/event.{ dispatch, on_click }

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

pub fn main () -> Nil {
    let selector = "[data-lustre-container]"
    let program  = lustre.application(init(), update, render)

    // `lustre.start` can return an `Error` if no DOM element is found that matches
    // the selector. This is a fatal error for our examples, so we panic if that 
    // happens.
    assert Ok(_) = lustre.start(program, selector)

    Nil
}

// STATE -----------------------------------------------------------------------

pub type State 
    = Int

pub fn init () -> State {
    0
}

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

pub type Action {
    Incr
    Decr
}

pub fn update (state, action) {
    case action {
        Incr ->
            state + 1

        Decr ->
            state - 1
    }
}

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

pub fn render (state) {
    div([ style([ #("display", "flex") ]) ], [
        button([ on_click(dispatch(Decr)) ], [ text("-") ]),
        p([], [ int.to_string(state) |> text ]),
        button([ on_click(dispatch(Incr)) ], [ text("+") ])
    ])
}