Add Select.V4 with optional id for select in config (#153)

* add Select.V4 with optional id for select in config

* add to exposed

* address comments
This commit is contained in:
Luke Westby 2018-10-31 08:43:23 -07:00 committed by GitHub
parent 5710d2732c
commit 6e5bf2f058
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 82 additions and 0 deletions

View File

@ -56,6 +56,7 @@
"Nri.Ui.Select.V1",
"Nri.Ui.Select.V2",
"Nri.Ui.Select.V3",
"Nri.Ui.Select.V4",
"Nri.Ui.Styles.V1",
"Nri.Ui.Table.V1",
"Nri.Ui.Table.V2",

81
src/Nri/Ui/Select/V4.elm Normal file
View File

@ -0,0 +1,81 @@
module Nri.Ui.Select.V4 exposing (Config, view)
{-| Build a select input.
@docs Config, view
-}
import Css
import Dict
import Html.Styled as Html exposing (..)
import Html.Styled.Attributes as Attributes exposing (..)
import Html.Styled.Events exposing (..)
import Json.Decode exposing (Decoder, andThen, succeed)
import Nri.Ui
import Nri.Ui.Colors.V1
import Nri.Ui.Util
{-| Configure a Select
-}
type alias Config a =
{ choices : List { label : String, value : a }
, current : a
, id : Maybe String
}
{-| TODO: Consider moving this to Nri.Ui.Util once the non-0.19-approved `toString` is removed
-}
niceId : String -> a -> String
niceId prefix x =
prefix ++ "-" ++ Nri.Ui.Util.dashify (Nri.Ui.Util.removePunctuation (toString x))
{-| A select dropdown
-}
view : Config a -> Html a
view config =
let
valueLookup =
-- TODO: probably worth using Lazy here, since choices won't change often
config.choices
|> List.map (\x -> ( niceId "nri-select" x.value, x.value ))
|> Dict.fromList
decodeValue string =
Dict.get string valueLookup
|> Maybe.map Json.Decode.succeed
|> Maybe.withDefault (Json.Decode.fail ("Nri.Select: could not decode the value: " ++ toString string ++ "\nexpected one of: " ++ toString (Dict.keys valueLookup)))
onSelectHandler =
on "change" (targetValue |> andThen decodeValue)
viewChoice choice =
Html.option
[ Attributes.id (niceId "nri-select" choice.value)
, Attributes.value (niceId "nri-select" choice.value)
, Attributes.selected (choice.value == config.current)
]
[ Html.text choice.label ]
extraAttrs =
config.id
|> Maybe.map (\id -> [ Attributes.id id ])
|> Maybe.withDefault []
in
config.choices
|> List.map viewChoice
|> Nri.Ui.styled Html.select
"nri-select-menu"
[ Css.backgroundColor Nri.Ui.Colors.V1.white
, Css.border3 (Css.px 1) Css.solid Nri.Ui.Colors.V1.gray75
, Css.borderRadius (Css.px 8)
, Css.color Nri.Ui.Colors.V1.gray20
, Css.cursor Css.pointer
, Css.fontSize (Css.px 15)
, Css.height (Css.px 45)
, Css.width (Css.pct 100)
]
([ onSelectHandler ] ++ extraAttrs)