Skip to content

Instantly share code, notes, and snippets.

@mrvicadai
Forked from owanturist/Main.elm
Created May 9, 2017 20:15
Show Gist options
  • Save mrvicadai/c3f5a471dcfa329d6936b1584d488b4d to your computer and use it in GitHub Desktop.
Save mrvicadai/c3f5a471dcfa329d6936b1584d488b4d to your computer and use it in GitHub Desktop.
Simple elm-app with normalized store
module Main exposing (main)
import Html.App
import Html exposing (Html, div, ul, li, form, input, button, strong, text)
import Html.Events exposing (onSubmit, onInput)
import Html.Attributes exposing (type', value)
import Dict exposing (Dict)
-- MODEL
type alias Todo =
{ id : Int
, title : String
}
type alias Model =
{ ids : Int
, nextTodo : String
, data : Dict String (Dict Int Todo)
, list : List Int
}
-- UPDATE
type Msg
= CreateTodo
| ChangeNextTodo String
update : Msg -> Model -> Model
update msg ({ ids, nextTodo, data, list } as model) =
case msg of
CreateTodo ->
let
newTodo =
Todo ids nextTodo
foo maybeTodos =
Just
<| case maybeTodos of
Just todos ->
Dict.insert ids newTodo todos
Nothing ->
Dict.fromList [ ( ids, newTodo ) ]
newData =
Dict.update "todos" foo data
in
{ model
| ids = ids + 1
, nextTodo = ""
, data = newData
, list = list ++ [ ids ]
}
ChangeNextTodo newNextTodo ->
{ model | nextTodo = newNextTodo }
-- VIEW
buildTodosList : Model -> List Todo
buildTodosList { data, list } =
let
todosStore =
Maybe.withDefault Dict.empty (Dict.get "todos" data)
in
List.foldl
(\todoId acc ->
case (Dict.get todoId todosStore) of
Just todo ->
acc ++ [ todo ]
Nothing ->
acc
)
[]
list
view : Model -> Html Msg
view model =
div []
[ form
[ onSubmit CreateTodo
]
[ input
[ type' "text"
, value model.nextTodo
, onInput ChangeNextTodo
]
[]
, button [ type' "submit" ] [ text "Add Todo" ]
]
, ul [] (List.map viewTodo (buildTodosList model))
]
viewTodo : Todo -> Html Msg
viewTodo { id, title } =
li []
[ strong [] [ text (toString id) ]
, text (" " ++ title)
]
-- MAIN
main : Program Never
main =
Html.App.beginnerProgram
{ model = Model 0 "" Dict.empty []
, view = view
, update = update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment