-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCalories.elm
106 lines (77 loc) · 1.91 KB
/
Calories.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
{----}
module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (type', value)
import Html.Events exposing (onClick, onInput)
import Html.App as App
import String
main : Program Never
main =
App.beginnerProgram
{ model = initialModel
, update = update
, view = view
}
-- MODEL
type alias Model =
{ calories : Int
, input : Int
, error : Maybe String
}
initialModel : Model
initialModel =
{ calories = 0
, input = 0
, error = Nothing
}
-- UPDATE
type Msg
= Add
| Clear
| ChangeInput String
update : Msg -> Model -> Model
update msg model =
case msg of
Add ->
{ model | calories = model.calories + model.input, input = 0 }
Clear ->
initialModel
ChangeInput input ->
case String.toInt input of
Ok val ->
{ model | input = val, error = Nothing }
Err err ->
{ model | input = 0, error = Just err }
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h3 []
[ text <| "Total Calories " ++ (toString model.calories) ]
, div []
[ input
[ type' "text"
, onInput ChangeInput
, value
(if model.input == 0 then
""
else
toString model.input
)
]
[]
, text <| Maybe.withDefault "OK" model.error
]
, div
[]
[ button [ type' "button", onClick Add ] [ text "Add" ]
, button [ type' "button", onClick Clear ] [ text "Clear" ]
]
, viewDebug model
]
viewDebug : Model -> Html Msg
viewDebug model =
div []
[ hr [] []
, text <| toString model
]