Created
May 3, 2018 14:02
-
-
Save jayantbh/1c361611ad80507d262d51afdad6d656 to your computer and use it in GitHub Desktop.
The most basic Todo code in Elm
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
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (..) | |
import List | |
main = Html.beginnerProgram { model = model, view = view, update = update } | |
type alias Todo = { text: String } | |
type alias Model = { todos: List Todo, newTodo: String } | |
model : Model | |
model = { todos = [], newTodo = "" } | |
type Msg = AddTodo | |
| RemoveTodo Int | |
| AddText String | |
update : Msg -> Model -> Model | |
update msg model = | |
case msg of | |
AddTodo -> | |
let | |
todos = model.todos ++ [ { text = model.newTodo } ] | |
in | |
{- reset text only when a new todo is added -} | |
{ model | todos = todos, newTodo = "" } | |
RemoveTodo index -> | |
let | |
todos = removeTodo index model.todos | |
in | |
{ model | todos = todos } | |
AddText text -> | |
{ model | newTodo = text } | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ h1 [] [ text "Todos!" ] | |
, div [] [ text ("Items present: " ++ (toString (List.length model.todos)))] | |
, div [] [ text ("NewTodo String Length: " ++ (toString (String.length model.newTodo)))] | |
, input [ onInput AddText, value model.newTodo ] [] | |
, button [ onClick AddTodo ] [ text "Add Todo" ] | |
, div [] [ viewTodo model.todos ] | |
] | |
viewTodo : List Todo -> Html Msg | |
viewTodo todos = | |
todos | |
|> List.indexedMap (\i todo -> li [] | |
[ span [] [ text todo.text ] | |
, button [ onClick ( RemoveTodo i ) ] [ text "X" ] | |
]) | |
|> ul [] | |
removeTodo : Int -> List Todo -> List Todo | |
removeTodo i todos = | |
(List.take i todos) ++ (List.drop (i+1) todos) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment