From 24d2f31a7e8e14daa9933e5af13de771216e0ba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=ABl=20Quenneville?= Date: Wed, 5 Jul 2017 11:43:24 -0400 Subject: [PATCH] Focus search input when opening dropdown This uses a combination of `Dom.focus` and `Task.attempt` to create a Cmd that will focus the DOM node with the given id. Since all Cmds trigger a Msg when they are done but we just want to fire and forget, we create a Noop Msg to deal with the situation. --- Main.elm | 19 ++++++++++++++++--- elm-package.json | 1 + 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Main.elm b/Main.elm index 9c0dfcf..79c1c11 100644 --- a/Main.elm +++ b/Main.elm @@ -2,6 +2,9 @@ module Main exposing (main) import Html exposing (..) import Html.Events exposing (onClick, onInput) +import Html.Attributes exposing (id) +import Dom +import Task main = @@ -28,7 +31,7 @@ type alias Model = initialModel : Model initialModel = - { state = Open + { state = Closed , values = fruits , selected = Nothing , query = "" @@ -59,7 +62,7 @@ viewOpen : Model -> Html Msg viewOpen model = div [] [ dropdownHead model.selected CloseSelect - , input [ onInput SearchInput ] [] + , input [ id "search-box", onInput SearchInput ] [] , ul [] (List.map dropdownItem (filteredValues model)) ] @@ -101,13 +104,17 @@ type Msg | CloseSelect | ItemSelected String | SearchInput String + | Noop update : Msg -> Model -> ( Model, Cmd Msg ) update msg model = case msg of + Noop -> + ( model, Cmd.none ) + OpenSelect -> - ( { model | state = Open }, Cmd.none ) + ( { model | state = Open }, focus ) CloseSelect -> ( { model | state = Closed }, Cmd.none ) @@ -119,3 +126,9 @@ update msg model = SearchInput query -> ( { model | query = query }, Cmd.none ) + + +focus : Cmd Msg +focus = + Dom.focus "search-box" + |> Task.attempt (always Noop) diff --git a/elm-package.json b/elm-package.json index f5ba1c5..272bcb2 100644 --- a/elm-package.json +++ b/elm-package.json @@ -9,6 +9,7 @@ "exposed-modules": [], "dependencies": { "elm-lang/core": "5.1.1 <= v < 6.0.0", + "elm-lang/dom": "1.1.1 <= v < 2.0.0", "elm-lang/html": "2.0.0 <= v < 3.0.0" }, "elm-version": "0.18.0 <= v < 0.19.0"