-
Notifications
You must be signed in to change notification settings - Fork 11
/
2-counter-list.elm
97 lines (66 loc) · 1.54 KB
/
2-counter-list.elm
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
96
97
module Main exposing (..)
import Counter
import Html exposing (..)
import Html.App as App
import Html.Events exposing (..)
main : Program Never
main =
App.beginnerProgram
{ model = init
, update = update
, view = view
}
-- MODEL
type alias Model =
{ counters : List ( ID, Counter.Model )
, nextID : ID
}
type alias ID =
Int
init : Model
init =
{ counters = []
, nextID = 0
}
-- UPDATE
type Msg
= Insert
| Remove
| Modify ID Counter.Msg
update : Msg -> Model -> Model
update msg model =
case msg of
Insert ->
let
newCounter =
( model.nextID, Counter.init 0 )
newCounters =
model.counters ++ [ newCounter ]
in
Model newCounters (model.nextID + 1)
Remove ->
{ model | counters = List.drop 1 model.counters }
Modify id counterMsg ->
let
updateCounter ( counterID, counterModel ) =
if counterID == id then
( counterID, Counter.update counterMsg counterModel |> Tuple.first )
else
( counterID, counterModel )
in
{ model | counters = List.map updateCounter model.counters }
-- VIEW
view : Model -> Html Msg
view model =
let
remove =
button [ onClick Remove ] [ text "Remove" ]
insert =
button [ onClick Insert ] [ text "Add" ]
counters =
List.map viewCounter model.counters
in
div [] ([ remove, insert ] ++ counters)
viewCounter : ( ID, Counter.Model ) -> Html Msg
viewCounter ( id, model ) =
Counter.view (Modify id) model