Last active
April 21, 2017 06:58
-
-
Save kitop/e54b31fda3e987ee62fb6fcad0747ac5 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 LinkList exposing (..) | |
import Html exposing (Html, text, div, ul, li, a, input) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (onClick, onInput) | |
import List | |
type alias Link = | |
{ id : Int | |
, label : String | |
, url : String | |
} | |
type alias Model = | |
{ links : List Link | |
, uid : Int | |
} | |
type alias Flags = | |
{ links : List { label : String, url : String } } | |
type Msg | |
= Add | |
| Remove Int | |
| UpdateLabel Int String | |
| UpdateUrl Int String | |
newEntry : Int -> String -> String -> Link | |
newEntry id label url = | |
{ id = id | |
, label = label | |
, url = url | |
} | |
init : Flags -> ( Model, Cmd Msg ) | |
init flags = | |
let | |
model = | |
{ uid = List.length flags.links | |
, links = List.indexedMap (\i link -> (newEntry i link.label link.url)) flags.links | |
} | |
in | |
model ! [] | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
Add -> | |
let | |
newLink = | |
newEntry model.uid "" "" | |
in | |
( { model | |
| uid = model.uid + 1 | |
, links = model.links ++ [ newLink ] | |
} | |
, Cmd.none | |
) | |
Remove id -> | |
( { model | |
| links = List.filter (\link -> link.id /= id) model.links | |
} | |
, Cmd.none | |
) | |
UpdateLabel id string -> | |
let | |
updateLabel t = | |
if t.id == id then | |
{ t | label = string } | |
else | |
t | |
in | |
( { model | links = List.map updateLabel model.links } | |
, Cmd.none | |
) | |
UpdateUrl id string -> | |
let | |
updateUrl t = | |
if t.id == id then | |
{ t | url = string } | |
else | |
t | |
in | |
( { model | links = List.map updateUrl model.links } | |
, Cmd.none | |
) | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ ul [] | |
(List.map linkView model.links) | |
, a [ onClick Add ] [ text "Add" ] | |
] | |
textInput : String -> (String -> Msg) -> Html Msg | |
textInput inputValue msg = | |
input [ value inputValue, onInput msg, type_ "text", required True, class "fieldset" ] [] | |
linkView : Link -> Html Msg | |
linkView link = | |
li [] | |
[ div [ class "fieldset-row" ] | |
[ textInput link.label (UpdateLabel link.id) | |
, textInput link.url (UpdateUrl link.id) | |
, a [ onClick (Remove link.id) ] [ text "x" ] | |
] | |
] | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Sub.none | |
main : Program Flags Model Msg | |
main = | |
Html.programWithFlags | |
{ init = init | |
, update = update | |
, view = view | |
, subscriptions = subscriptions | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment