Skip to content

Instantly share code, notes, and snippets.

@markhamburg
Created October 17, 2016 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhamburg/b17b6d0ecb19d73ab10f015f693c4a6b to your computer and use it in GitHub Desktop.
Save markhamburg/b17b6d0ecb19d73ab10f015f693c4a6b to your computer and use it in GitHub Desktop.
A demonstration of how to achieve identity continuity using Html.Keyed in Elm
import Html exposing (div, input, text, fieldset, label)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onInput, onClick)
import Html.Attributes exposing (value, type', style, name)
import Html.Keyed
type alias Model =
{ text : String
, items : List String
, position : BeforeAfter
}
type BeforeAfter
= Before
| After
| AfterWithKeys
init =
{ text = ""
, items = []
, position = Before
}
type Msg
= NewText String
| SetPosition BeforeAfter
update : Msg -> Model -> Model
update msg model =
case msg of
NewText string ->
{ model | text = string, items = string :: model.items }
SetPosition position ->
{ model | position = position }
view : Model -> Html.Html Msg
view model =
let
buttons =
fieldset []
[ radio "Before" "position" (SetPosition Before)
, radio "After" "position" (SetPosition After)
, radio "After With Keys" "position" (SetPosition AfterWithKeys)
]
items =
List.map (\str -> div [] [ text str ]) model.items
textField =
input [ value model.text, onInput NewText ] []
ordered =
case model.position of
Before ->
div [] (textField :: items)
After ->
div [] <| List.reverse <| textField :: items
AfterWithKeys ->
let
n =
List.length items
keyedItems =
List.indexedMap (\idx elem -> (toString (n - idx), elem)) items
withInput =
("input", textField) :: keyedItems
reversed =
List.reverse withInput
in
Html.Keyed.node "div" [] reversed
in
div []
[ buttons
, ordered
]
radio : String -> String -> msg -> Html.Html msg
radio value groupName msg =
label
[ style [ ( "padding", "20px" ) ] ]
[ input [ type' "radio", name groupName, onClick msg ] []
, text value
]
main =
beginnerProgram { model = init, view = view, update = update }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment