Created
April 23, 2016 02:24
-
-
Save chuck0523/6592b1eecd614b8beb8bc65575436253 to your computer and use it in GitHub Desktop.
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 TodoList where | |
import Todo | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (..) | |
-- model | |
type alias Model = | |
{ todos : List (ID, Todo.Model) | |
, nextID : ID | |
, addText : String | |
} | |
type alias ID = Todo.ID | |
init : Model | |
init = | |
{ todos = [] | |
, nextID = 0 | |
, addText = "" | |
} | |
-- action | |
type Action = Add | |
| InputText String | |
| Modify ID Todo.Action | |
update : Action -> Model -> Model | |
update action model = | |
case action of | |
Add -> | |
let newTodo = ( model.nextID, Todo.init model.nextID model.addText ) | |
newTodos = model.todos ++ [ newTodo ] | |
newModel = if model.addText == "" then model else { model | | |
todos = newTodos, | |
nextID = model.nextID + 1, | |
addText = "" | |
} | |
in | |
newModel | |
InputText str -> | |
{ model | | |
addText = str | |
} | |
Modify id todoAction -> | |
let updateTodo (todoId, todoModel) = | |
if todoId == id | |
then (todoId, Todo.update todoAction todoModel) | |
else (todoId, todoModel) | |
in | |
{ model | | |
todos = List.map updateTodo model.todos | |
} | |
-- view | |
view : Signal.Address Action -> Model -> Html | |
view address model = | |
let | |
todos = List.map (viewTodos address) model.todos | |
addButton = button ([onClick address Add] ++ getAddButtonAttr model.addText) [ text "Add" ] | |
in | |
div [ todosStyle ] | |
[ input | |
[ placeholder "enter todo" | |
, value model.addText | |
, on "input" targetValue ( Signal.message address << InputText) | |
] | |
[] | |
, addButton | |
, div | |
[] (todos) | |
] | |
viewTodos : Signal.Address Action -> (ID, Todo.Model) -> Html | |
viewTodos address (id, model) = | |
Todo.view (Signal.forwardTo address (Modify id)) model | |
getAddButtonAttr : String -> List Attribute | |
getAddButtonAttr addText = | |
let | |
isDisable = addText == "" | |
fontColor = if isDisable then "#999" else "#333" | |
in | |
[ style | |
[ ("color", fontColor) | |
] | |
, disabled isDisable | |
] | |
todosStyle : Attribute | |
todosStyle = | |
style | |
[ ("margin", "10px") | |
] | |
textareaStyle : Attribute | |
textareaStyle = | |
style | |
[ ("margin-right", "5px") | |
, ("height", "20px") | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment