aboutsummaryrefslogtreecommitdiff
path: root/example/src/lustre_counter.gleam
diff options
context:
space:
mode:
authorFilip Figiel <figiel.filip@gmail.com>2022-05-23 20:36:17 +0200
committerGitHub <noreply@github.com>2022-05-23 19:36:17 +0100
commit03030ea62b59e859e068aa76eb1692dd1ef807f7 (patch)
tree5ae3914488446e52ebc27f341e9d10942ad01bb9 /example/src/lustre_counter.gleam
parentcb67e922d996077154dfdd05961071b2cc8cc7fc (diff)
downloadlustre-03030ea62b59e859e068aa76eb1692dd1ef807f7.tar.gz
lustre-03030ea62b59e859e068aa76eb1692dd1ef807f7.zip
🔀📝 add a fully-fledged example project (#2)
* docs: add a full-fledged example project * fix: use correct script path * docs: improve example readme commands * chore: ignore the dist folder * chore: cleanup the makefile
Diffstat (limited to 'example/src/lustre_counter.gleam')
-rw-r--r--example/src/lustre_counter.gleam95
1 files changed, 95 insertions, 0 deletions
diff --git a/example/src/lustre_counter.gleam b/example/src/lustre_counter.gleam
new file mode 100644
index 0000000..25872a4
--- /dev/null
+++ b/example/src/lustre_counter.gleam
@@ -0,0 +1,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")])]),
+ ],
+ )
+}