Created
July 24, 2015 17:23
-
-
Save z5h/c5d4a84b7f4a9dd6984b to your computer and use it in GitHub Desktop.
Elm rendering focus loss
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 (..) | |
type Action | |
= NoOp | |
| EditEntry Entry String | |
type alias Entry = | |
{ id : Int | |
, value : String | |
} | |
type alias Model = | |
{ entries : List Entry | |
, reverse : Bool | |
} | |
initialModel : Model | |
initialModel = | |
{ entries = [{id = 1, value = "first"}, {id = 2, value = "second"}] | |
, reverse = False | |
} | |
replaceList : List a -> a -> a -> List a | |
replaceList list old new = | |
let f item = | |
if | item == old -> new | |
| otherwise -> item | |
in List.map f list | |
-- Update our Model using a given Action | |
update : Action -> Model -> Model | |
update action model = | |
case action of | |
NoOp -> | |
model | |
EditEntry entry newValue -> | |
let newEntry = {entry | value <- newValue} | |
in | |
{ model | | |
entries <- replaceList model.entries entry newEntry, | |
reverse <- not model.reverse | |
} | |
view : Signal.Address Action -> Model -> Html | |
view actions model = | |
let entries = | |
if | model.reverse -> List.reverse model.entries | |
| otherwise -> model.entries | |
in | |
div [] (List.map ((viewEntry) actions) entries) | |
viewEntry : Signal.Address Action -> Entry -> Html | |
viewEntry actions entry = | |
div [key <| toString entry.id] [ | |
input | |
[ value entry.value | |
, on "input" targetValue (\string -> Signal.message actions <| EditEntry entry string ) | |
] [] | |
] | |
-- Wire the entire application together | |
main : Signal Html | |
main = | |
Signal.map (view actionMailbox.address) modelSignal | |
-- Manage the model of our application over time | |
modelSignal : Signal Model | |
modelSignal = | |
Signal.foldp update initialModel actionMailbox.signal | |
-- Actions from user input | |
actionMailbox : Signal.Mailbox Action | |
actionMailbox = | |
Signal.mailbox NoOp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment