-
Notifications
You must be signed in to change notification settings - Fork 0
/
Canvas.purs
73 lines (62 loc) · 2 KB
/
Canvas.purs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
module Halogen.Canvas
( Dimensions(..)
, component
) where
import Prelude
import Control.Monad.Reader (runReaderT)
import Control.Monad.Rec.Class (class MonadRec)
import Data.Maybe (Maybe(..))
import Data.Traversable (traverse, traverse_)
import Effect.Aff.Class (class MonadAff)
import Graphics.Canvas (getContext2D)
import Graphics.Canvas.Free (CanvasContext, CanvasT, runCanvasT)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Properties as HP
import Unsafe.Coerce (unsafeCoerce)
type Dimensions =
{ width :: Int
, height :: Int
}
type State =
{ dimensions :: Dimensions
, canvas :: Maybe CanvasContext
}
data Action = Initialize
component :: forall o m. MonadAff m => MonadRec m => H.Component (CanvasT m) Dimensions o m
component = do
H.mkComponent
{ initialState: \dimensions -> { dimensions, canvas: Nothing }
, render
, eval: H.mkEval $ H.defaultEval { handleAction = handleAction
, handleQuery = handleQuery
, initialize = Just Initialize
}
}
render :: forall m. State -> H.ComponentHTML Action () m
render { dimensions } =
HH.canvas
[ HP.ref (H.RefLabel "canvas")
, HP.width dimensions.width
, HP.height dimensions.height
]
handleAction :: forall m o .
MonadAff m
=> Action
-> H.HalogenM State Action () o m Unit
handleAction = case _ of
Initialize -> do
e <- H.getRef (H.RefLabel "canvas")
flip traverse_ e $ \ce -> do
let canvasElement = unsafeCoerce ce
context2D <- H.liftEffect $ getContext2D canvasElement
H.modify_ (\st -> st { canvas = Just { canvasElement, context2D } })
handleQuery :: forall m o a .
MonadAff m
=> MonadRec m
=> CanvasT m a
-> H.HalogenM State Action () o m (Maybe a)
handleQuery f = do
{ canvas } <- H.get
flip traverse canvas $ \c -> do
H.lift $ runReaderT (runCanvasT f) c