Skip to content

Instantly share code, notes, and snippets.

@note89
Forked from manuscrypt/KeyDown-Event-Decoder
Created July 10, 2016 20:33
Show Gist options
  • Save note89/aaa12f6faf7e583530916a137286b804 to your computer and use it in GitHub Desktop.
Save note89/aaa12f6faf7e583530916a137286b804 to your computer and use it in GitHub Desktop.
onKeyUp : Json.Decoder Msg
onKeyUp =
Json.oneOf
[ logged "keyDecoder" keyDecoder
-- , charCodeDecoder -- only on keypress
, logged "keyCodeDecoder" keyCodeDecoder
, logged "whichDecoder" whichDecoder
, logged "keyIdentifierDecoder" keyIdentifierDecoder
, logged "charDecoder" charDecoder
]
`andThen` (\kc -> Json.succeed (OnKey kc))
logged : String -> Json.Decoder a -> Json.Decoder a
logged message decoder =
decoder `andThen` (\value -> Json.succeed <| Debug.log message value)
keyDecoder : Json.Decoder Int
keyDecoder =
"key" := Json.string `andThen` succeedIfNot "Unidentified"
keyCodeDecoder : Json.Decoder Int
keyCodeDecoder =
"keyCode" := Json.int `andThen` validCode
charCodeDecoder : Json.Decoder Int
charCodeDecoder =
"charCode" := Json.int `andThen` validCode
keyIdentifierDecoder : Json.Decoder Int
keyIdentifierDecoder =
"keyIdentifier" := Json.int `andThen` validCode
whichDecoder : Json.Decoder Int
whichDecoder =
"which" := Json.int `andThen` validCode
charDecoder : Json.Decoder Int
charDecoder =
"char" := Json.string `andThen` succeedIfNot ""
succeedIfNot : String -> String -> Json.Decoder Int
succeedIfNot s dontBeThat =
if s == dontBeThat then
Json.fail s
else
fromString s
validCode : Int -> Json.Decoder Int
validCode s =
if s == 0 then
Json.fail "0"
else
Json.succeed s
fromString : String -> Json.Decoder Int
fromString s =
case String.uncons s of
Nothing ->
Json.fail "invalid string"
Just ( c, s' ) ->
Json.succeed <| Char.toCode c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment