-----------------------------------------------------------------------------
-- |
-- Module      :  Miso.Delegate
-- Copyright   :  (C) 2016-2018 David M. Johnson
-- License     :  BSD3-style (see the file LICENSE)
-- Maintainer  :  David M. Johnson <djohnson.m@gmail.com>
-- Stability   :  experimental
-- Portability :  non-portable
----------------------------------------------------------------------------
module Miso.Delegate where

import           Control.Monad.IO.Class
import           Data.IORef
import qualified Data.Map as M
import           GHCJS.Marshal
import           GHCJS.Types (JSVal)
import qualified JavaScript.Object.Internal as OI
import           Miso.FFI
import           Miso.Html.Types
import           Miso.String

-- | Entry point for event delegation
delegator
  :: JSVal
  -> IORef VTree
  -> M.Map MisoString Bool
  -> JSM ()
delegator :: JSVal -> IORef VTree -> Map MisoString Bool -> JSM ()
delegator JSVal
mountPointElement IORef VTree
vtreeRef Map MisoString Bool
es = do
  JSVal
evts <- [(MisoString, Bool)] -> JSM JSVal
forall a. ToJSVal a => a -> JSM JSVal
toJSVal (Map MisoString Bool -> [(MisoString, Bool)]
forall k a. Map k a -> [(k, a)]
M.toList Map MisoString Bool
es)
  JSVal -> JSVal -> JSM JSVal -> JSM ()
delegateEvent JSVal
mountPointElement JSVal
evts (JSM JSVal -> JSM ()) -> JSM JSVal -> JSM ()
forall a b. (a -> b) -> a -> b
$ do
    VTree (OI.Object JSVal
val) <- IO VTree -> JSM VTree
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IORef VTree -> IO VTree
forall a. IORef a -> IO a
readIORef IORef VTree
vtreeRef)
    JSVal -> JSM JSVal
forall (f :: * -> *) a. Applicative f => a -> f a
pure JSVal
val