-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.elm
130 lines (93 loc) · 2.64 KB
/
Main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
-- MODEL
type alias Model =
{ votes : List String
, selectedChoice : String
, pollChoices : List Choice
}
type alias Choice =
{ choice : String, value : String, votes : Int }
init : Model
init =
let
model =
Model []
""
[ (Choice "Cake" "cake" 0), (Choice "Eclair" "eclair" 0), (Choice "Bread Pudding" "bread-pudding" 0), (Choice "Wareva" "wareva" 0) ]
in
model
-- UPDATE --
type Msg
= Vote
| Select String
update : Msg -> Model -> Model
update msg model =
case msg of
Vote ->
let
selectedChoice =
model.selectedChoice
updatedChoice =
List.map
(\pChoice ->
if pChoice.choice == selectedChoice then
{ pChoice | votes = pChoice.votes + 1 }
else
pChoice
)
model.pollChoices
in
{ model | pollChoices = updatedChoice }
Select option ->
{ model | selectedChoice = option }
-- VIEW
view : Model -> Html Msg
view model =
div [ class "container" ]
[ h1 [] [ text "Elm Opinion Poll" ]
, pollForm model
, pollFooter model
]
pollForm : Model -> Html Msg
pollForm model =
Html.form [ onSubmit Vote ]
[ div [] (List.map viewRadioButton <| List.map .choice model.pollChoices)
, button [ type_ "submit" ] [ text "Vote" ]
]
pollFooter : Model -> Html Msg
pollFooter model =
footer []
[ pollTotal model
, choiceList model
, div [] [ text (toString model) ]
]
pollTotal : Model -> Html Msg
pollTotal model =
let
totals =
List.sum <| List.map (\p -> p.votes) model.pollChoices
in
div []
[ text "Totals: ", text (toString totals) ]
choiceList : Model -> Html Msg
choiceList model =
model.pollChoices
|> List.map choice
|> ul []
choice : Choice -> Html Msg
choice choice =
li []
[ div [] [ text choice.choice, text ":", text (toString choice.votes) ]
]
viewRadioButton : String -> Html Msg
viewRadioButton msg =
label
[ style [ ( "padding", "5px" ) ] ]
[ input [ type_ "radio", name "dessert", onClick (Select msg) ] []
, text msg
]
main =
Html.beginnerProgram { model = init, view = view, update = update }