Last active
December 26, 2020 01:38
-
-
Save ali-abrar/f4c1e43d554f3a1fa28d9f3097120807 to your computer and use it in GitHub Desktop.
reflex-dom <body> key handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# language PackageImports #-} | |
import Control.Monad | |
import "ghcjs-dom" GHCJS.DOM.Document (getBody) | |
import GHCJS.DOM.EventM (on, preventDefault) | |
import GHCJS.DOM.GlobalEventHandlers (keyDown) | |
import Reflex.Dom hiding (preventDefault) | |
import Web.KeyCode | |
main :: IO () | |
main = mainWidget $ do | |
doc <- askDocument | |
mbody <- getBody doc | |
forM_ mbody $ \body -> do | |
kp <- wrapDomEvent body (`on` keyDown) $ do | |
preventDefault -- This 'preventDefault' is here to prevent | |
-- the browser's default behavior when keys | |
-- like <F1> or the arrow keys are pressed. | |
-- If you want to preserve default behavior | |
-- this can be removed, or you can apply it | |
-- selectively, only to certain keypresses. | |
i <- getKeyEvent | |
return i | |
lastKeyPressed <- holdDyn Nothing $ | |
Just . keyCodeLookup . fromEnum <$> kp | |
display lastKeyPressed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision #2 of this gist has been tested against reflex-platform v0.6.2.0