Created
May 15, 2017 10:05
-
-
Save Ahrengot/212ef3a686d104a63f2717e6246d980b 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 View.Repeater exposing (viewRepeater, update, Msg) | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (..) | |
import Html.Keyed as Keyed | |
import Dom exposing (focus) | |
import Task | |
import Array | |
type alias Agency = | |
{ name : String | |
} | |
type alias KeyedAgency = | |
{ index : Int | |
, name : String | |
} | |
type alias Model = | |
List { name : String } | |
type Msg | |
= Add | |
| Remove Int | |
| Update Int String | |
| OnFocus (Result Dom.Error ()) | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
Add -> | |
( model ++ [ Agency "" ] | |
, focus (getInputId (List.length model)) | |
|> Task.attempt OnFocus | |
) | |
Remove index -> | |
( model | |
|> indexAgencyList | |
|> List.filter (\a -> a.index /= index) | |
|> List.map (\a -> Agency a.name) | |
, Cmd.none | |
) | |
Update index val -> | |
( model | |
|> Array.fromList | |
|> Array.set index (Agency val) | |
|> Array.toList | |
, Cmd.none | |
) | |
OnFocus _ -> | |
( model, Cmd.none ) | |
getInputId : Int -> String | |
getInputId index = | |
"repeater-input-" ++ toString index | |
indexAgencyList : List Agency -> List KeyedAgency | |
indexAgencyList agencyList = | |
List.map .name agencyList | |
|> List.indexedMap KeyedAgency | |
viewAddBtn : Html Msg | |
viewAddBtn = | |
button | |
[ type_ "button" | |
, class "circular-btn add-item-btn" | |
, title "Tilføj ny" | |
, onClick Add | |
] | |
[ span [ class "sr-only" ] [ text "Tilføj ny" ] ] | |
viewItem : KeyedAgency -> Html Msg | |
viewItem { index, name } = | |
li [ class "repeater-item" ] | |
[ input | |
[ type_ "text" | |
, id <| getInputId index | |
, class "form-control" | |
, onInput (Update index) | |
, placeholder "Indtast bureaunavn" | |
, value name | |
] | |
[] | |
, button | |
[ type_ "button" | |
, class "circular-btn delete-item-btn" | |
, onClick (Remove index) | |
, title "Slet" | |
] | |
[ span [ class "sr-only" ] [ text "Slet" ] ] | |
] | |
viewKeyedItem : KeyedAgency -> ( String, Html Msg ) | |
viewKeyedItem keyedAgency = | |
( toString keyedAgency.index, viewItem keyedAgency ) | |
viewRepeater : Model -> Html Msg | |
viewRepeater agencies = | |
div [ class "input-repeater" ] | |
[ List.map viewKeyedItem (indexAgencyList agencies) | |
|> Keyed.ul [ class "repeater-list" ] | |
, viewAddBtn | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment