{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Miso.Event.Decoder
(
Decoder (..)
, DecodeTarget (..)
, at
, emptyDecoder
, keycodeDecoder
, checkedDecoder
, valueDecoder
)
where
import Data.Aeson.Types
import Control.Applicative
import Miso.Event.Types
import Miso.String
data DecodeTarget
= DecodeTarget [MisoString]
| DecodeTargets [[MisoString]]
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")
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")