Last active
December 5, 2016 01:34
-
-
Save mgadda/404086c806ddf7715c37d5d692c084fb to your computer and use it in GitHub Desktop.
Conditional event handlers for key presses
This file contains hidden or 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 Util exposing (..) | |
| import Html.Events exposing (on, keyCode) | |
| import Html exposing (Attribute) | |
| import Json.Decode as Json | |
| import Dict exposing (Dict) | |
| {-| Conditionally emit msg defined by `tagger` if the | |
| key pressed was the enter key. Cannot be used with onEscape. | |
| -} | |
| onEnter : msg -> Attribute msg | |
| onEnter = | |
| onKeyDown <| (==) 13 | |
| {-| Conditionally emit msg defined by `tagger` if the | |
| key pressed was the escape key. Cannot be used with onEnter. | |
| -} | |
| onEscape : msg -> Attribute msg | |
| onEscape = | |
| onKeyDown <| (==) 27 | |
| {-| Because apparently elm does not support attaching | |
| multiple event handlers for the same event! | |
| -} | |
| onKeyDownMap : List ( Int, msg ) -> Attribute msg | |
| onKeyDownMap keyList = | |
| let | |
| keyMap : Dict Int msg | |
| keyMap = | |
| Dict.fromList keyList | |
| pred : Int -> Maybe msg | |
| pred key = | |
| Dict.get key keyMap | |
| in | |
| on "keydown" | |
| (keyCode | |
| |> Json.map pred | |
| |> Json.andThen | |
| (\maybeTagger -> | |
| case maybeTagger of | |
| Just tagger -> | |
| Json.succeed tagger | |
| Nothing -> | |
| Json.fail "" | |
| ) | |
| ) | |
| {-| Conditionally emit msg defined by `tagger` based | |
| on return value of `pred`. | |
| -} | |
| onKeyDown : (Int -> Bool) -> msg -> Attribute msg | |
| onKeyDown pred tagger = | |
| on "keydown" | |
| (keyCode | |
| |> Json.map pred | |
| |> Json.andThen | |
| (\result -> | |
| if result then | |
| Json.succeed tagger | |
| else | |
| Json.fail "" | |
| ) | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment