aboutsummaryrefslogtreecommitdiff
path: root/test/example/main.gleam
blob: 21c406747a74303808dfc9fcf8db9ad2143494e9 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// IMPORTS ---------------------------------------------------------------------

import lustre
import lustre/cmd.{ Cmd }
import lustre/element.{ Element }

import example/application/counter

// 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.
    let assert Ok(dispatch) = lustre.start(program, selector)

    dispatch(Counter(counter.Incr))
    dispatch(Counter(counter.Incr))
    dispatch(Counter(counter.Incr))

    Nil
}

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

type State {
    State(
        counter: counter.State
    )
}

fn init () -> #(State, Cmd(Action)) {
    let #(counter, counter_cmds) = counter.init()
    let state = State(
        counter
    )

    #(state, cmd.map(counter_cmds, Counter))
}

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

type Action {
    Counter(counter.Action)
}

fn update (state: State, action: Action) -> #(State, Cmd(Action)) {
    case action {
        Counter(counter_action) -> {
            let #(counter, counter_cmds) = counter.update(state.counter, counter_action)
            let state = State(
                counter
            )

            #(state, cmd.map(counter_cmds, Counter))
        }
    }
}

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

fn render (state: State) -> Element(Action) {
    element.div([], [
        element.details([], [
            element.summary([], [ element.text("Counter") ]),
            counter.render(state.counter) 
                |> element.map(Counter)
        ])
    ])
}