{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Miso.Event.Decoder
(
Decoder (..)
, DecodeTarget (..)
, at
, emptyDecoder
, keycodeDecoder
, keyInfoDecoder
, checkedDecoder
, valueDecoder
)
where
import Data.Aeson.Types
import Control.Applicative
import GHCJS.Marshal (ToJSVal, toJSVal)
import Miso.Event.Types
import Miso.String
data DecodeTarget
= DecodeTarget [MisoString]
| DecodeTargets [[MisoString]]
instance ToJSVal DecodeTarget where
toJSVal (DecodeTarget xs) = toJSVal xs
toJSVal (DecodeTargets xs) = toJSVal xs
data Decoder a = Decoder {
decoder :: Value -> Parser a
, decodeAt :: DecodeTarget
}
at :: [MisoString] -> (Value -> Parser a) -> Decoder a
at decodeAt decoder = Decoder {decodeAt = DecodeTarget decodeAt, ..}
emptyDecoder :: Decoder ()
emptyDecoder = mempty `at` go
where
go = withObject "emptyDecoder" $ \_ -> pure ()
keycodeDecoder :: Decoder KeyCode
keycodeDecoder = Decoder {..}
where
decodeAt = DecodeTarget mempty
decoder = withObject "event" $ \o ->
KeyCode <$> (o .: "keyCode" <|> o .: "which" <|> o .: "charCode")
keyInfoDecoder :: Decoder KeyInfo
keyInfoDecoder = Decoder {..}
where
decodeAt = DecodeTarget mempty
decoder =
withObject "event" $ \o ->
KeyInfo <$> (o .: "keyCode" <|> o .: "which" <|> o .: "charCode")
<*> o .: "shiftKey"
<*> o .: "metaKey"
<*> o .: "ctrlKey"
<*> o .: "altKey"
valueDecoder :: Decoder MisoString
valueDecoder = Decoder {..}
where
decodeAt = DecodeTarget ["target"]
decoder = withObject "target" $ \o -> o .: "value"
checkedDecoder :: Decoder Checked
checkedDecoder = Decoder {..}
where
decodeAt = DecodeTarget ["target"]
decoder = withObject "target" $ \o ->
Checked <$> (o .: "checked")