Created
August 30, 2016 07:36
-
-
Save pdamoc/4f6cfc7ff5f69aeb527c3fff52550fd2 to your computer and use it in GitHub Desktop.
CounterList Example without nesting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
import Html exposing (..) | |
import Html.App as App | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (..) | |
main = | |
App.beginnerProgram | |
{ model = init | |
, update = update | |
, view = view | |
} | |
-- MODEL | |
type alias Model = | |
{ counters : List IndexedCounter | |
, uid : Int | |
} | |
type alias IndexedCounter = | |
{ id : Int | |
, model : Int | |
} | |
init : Model | |
init = | |
{ counters = [] | |
, uid = 0 | |
} | |
-- UPDATE | |
type Msg | |
= Insert | |
| Remove | |
| Modify Int Int | |
-- ID DELTA | |
update : Msg -> Model -> Model | |
update message ({ counters, uid } as model) = | |
case message of | |
Insert -> | |
{ model | |
| counters = counters ++ [ IndexedCounter uid 0 ] | |
, uid = uid + 1 | |
} | |
Remove -> | |
{ model | counters = List.drop 1 counters } | |
Modify id delta -> | |
{ model | counters = List.map (updateHelp id delta) counters } | |
updateHelp : Int -> Int -> IndexedCounter -> IndexedCounter | |
updateHelp targetId delta { id, model } = | |
IndexedCounter id | |
(if targetId == id then | |
model + delta | |
else | |
model | |
) | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
let | |
remove = | |
button [ onClick Remove ] [ text "Remove" ] | |
insert = | |
button [ onClick Insert ] [ text "Add" ] | |
counters = | |
List.map viewIndexedCounter model.counters | |
in | |
div [] ([ remove, insert ] ++ counters) | |
viewIndexedCounter : IndexedCounter -> Html Msg | |
viewIndexedCounter { id, model } = | |
counter (Modify id 1) (Modify id -1) model | |
-- COUNTER | |
counter : msg -> msg -> Int -> Html msg | |
counter inc dec val = | |
div [] | |
[ button [ onClick dec ] [ text "-" ] | |
, div [ countStyle ] [ text (toString val) ] | |
, button [ onClick inc ] [ text "+" ] | |
] | |
countStyle : Attribute msg | |
countStyle = | |
style | |
[ ( "font-size", "20px" ) | |
, ( "font-family", "monospace" ) | |
, ( "display", "inline-block" ) | |
, ( "width", "50px" ) | |
, ( "text-align", "center" ) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment