summaryrefslogtreecommitdiff
path: root/src/JavaScript.hs
blob: bc278183b2c693fd423eca6eb59039127dddb958 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
module JavaScript (
    getElementById,
    documentQuerySelector,
    querySelector,

    asEventListener,
    addEventListener,

    consoleLog,
    consoleLogVal,
) where

import GHC.Wasm.Prim

getElementById :: String -> IO JSVal
getElementById = js_document_getElementById . toJSString
foreign import javascript unsafe "document.getElementById($1)"
    js_document_getElementById :: JSString -> IO JSVal

documentQuerySelector :: String -> IO (Maybe JSVal)
documentQuerySelector = fmap nullToNothing . js_document_querySelector . toJSString
foreign import javascript unsafe "document.querySelector($1)"
    js_document_querySelector :: JSString -> IO JSVal

querySelector :: String -> JSVal -> IO (Maybe JSVal)
querySelector sel e = nullToNothing <$> js_querySelector e (toJSString sel)
foreign import javascript unsafe "$1.querySelector($2)"
    js_querySelector :: JSVal -> JSString -> IO JSVal

foreign import javascript "wrapper"
    asEventListener :: (JSVal -> IO ()) -> IO JSVal

addEventListener :: JSVal -> String -> (JSVal -> IO ()) -> IO ()
addEventListener obj ev cb = do
    js_addEventListener obj (toJSString ev) =<< asEventListener cb
foreign import javascript unsafe "$1.addEventListener($2, $3)"
    js_addEventListener :: JSVal -> JSString -> JSVal -> IO ()

consoleLog :: String -> IO ()
consoleLog = js_consoleLog . toJSString
foreign import javascript unsafe "console.log($1)"
    js_consoleLog :: JSString -> IO ()

foreign import javascript unsafe "console.log($1)"
    consoleLogVal :: JSVal -> IO ()


nullToNothing :: JSVal -> Maybe JSVal
nullToNothing val | isNull val = Nothing
                  | otherwise  = Just val
foreign import javascript unsafe "$1 === null"
    isNull :: JSVal -> Bool