Elm - How to determine the current focus

How do you get the current focus in Elm? I know how to set focus with Elm, but I cannot find any function to find that it currently has focus.

+4
source share
1 answer

The elm-lang / dom package allows you to set focus on the element specified by the identifier, but it does not allow you to retrieve the current focused element. He hints that you can use document.activeElement. You will have to use ports for this.

Here is a contrived example. Let's say you have Modelone that contains the currently selected identifier and a list of all the identifiers of some text fields that we will create soon.

type alias Model =
    { selected : Maybe String
    , ids : List String
    }

Msgs, , , Dom :

type Msg
    = NoOp
    | FetchFocused
    | FocusedFetched (Maybe String)
    | Focus (Maybe String)

:

port focusedFetched : (Maybe String -> msg) -> Sub msg

port fetchFocused : () -> Cmd msg

javascript, , document.activeElement:

var app = Elm.Main.fullscreen()
app.ports.fetchFocused.subscribe(function() {
  var id = document.activeElement ? document.activeElement.id : null;
  app.ports.focusedFetched.send(id);
});

, , .

view : Model -> Html Msg
view model =
    div []
        [ div [] [ text ("Currently selected: " ++ toString model.selected) ]
        , div [] (List.map viewButton model.ids)
        , div [] (List.map viewInput model.ids)
        ]


viewButton : String -> Html Msg
viewButton id =
    button [ onClick (Focus (Just id)) ] [ text id ]


viewInput : String -> Html Msg
viewInput idstr =
    div [] [ input [ id idstr, placeholder idstr, onFocus FetchFocused ] [] ]

update :

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            model ! []

        FetchFocused ->
            model ! [ fetchFocused () ]

        FocusedFetched selected ->
            { model | selected = selected } ! []

        Focus (Just selected) ->
            model ! [ Task.attempt (always NoOp) (Dom.focus selected), fetchFocused () ]

        Focus Nothing ->
            { model | selected = Nothing } ! [ fetchFocused () ]

ellie-app.com.

+8

Source: https://habr.com/ru/post/1676972/


All Articles