abadi199 / elm-input-extra

🔢 Commonly used Html element with extra functionality
http://package.elm-lang.org/packages/abadi199/elm-input-extra/latest
MIT License
51 stars 12 forks source link

Special handling of onEnter? #2

Closed desmond-dsouza closed 7 years ago

desmond-dsouza commented 7 years ago

Is it possible to configure a different Msg when user hits Enter key, to distinguish "Done with input" from "still editing input"?

abadi199 commented 7 years ago

Currently, there's no way to configure onEnter, I'm considering adding that in the future since it's pretty common use case. For now, you can try using this function.

onEnter : msg -> Html.Attribute msg
onKey tagger =
    let
        options =
            { stopPropagation = False, preventDefault = True }

        decoder =
            (Html.Events.keyCode
                |> Decode.andThen
                    (\k ->
                        if k == 13 then
                            Decode.succeed (tagger k)
                        else
                            Decode.fail "not an enter"
                    )
            )
    in
        Html.Events.onWithOptions "keypress"
            options
            decoder

and then add that event handler to your input attributes:

type Msg = OnEnterMsg

view model =
    ...
    input options [ onEnter OnEnterMsg, ... ] ...
    ...

I can't guarantee that this will work since I haven't try it myself, but give it a try and let me know if it works or not.

desmond-dsouza commented 7 years ago

That worked, thank you!

I changed tagger k to just tagger. Wonder if it might be nicer to capture the current field value:

onEnter : (Int -> msg) -> Html.Attribute msg