Created
March 14, 2020 09:57
-
-
Save peterszerzo/3c156543c16dd461a5225b8a533955ec to your computer and use it in GitHub Desktop.
requestAnimationFrame hooke for purescript-react-basic-hooks
This file contains 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
module CustomHooks where | |
import Prelude | |
import Data.Maybe (Maybe(..), maybe) | |
import Data.Newtype (class Newtype) | |
import Data.DateTime.Instant (unInstant) | |
import Data.Nullable (Nullable, notNull, null) | |
import Data.Time.Duration (Milliseconds(..)) | |
import Effect (Effect) | |
import Effect.Now (now) | |
import React.Basic.Hooks | |
( Hook | |
, ReactComponent | |
, UseEffect | |
, UseRef | |
, coerceHook | |
, component | |
, readRefMaybe | |
, useEffect | |
, useRef | |
, useState | |
, writeRef | |
, (/\) | |
) | |
import React.Basic.Hooks as React | |
import Web.HTML (window) | |
import Web.HTML.Window (RequestAnimationFrameId, cancelAnimationFrame, requestAnimationFrame) | |
newtype UseAnimationFrame hooks | |
= UseAnimationFrame (UseEffect Unit (UseRef (Nullable Number) (UseRef (Nullable RequestAnimationFrameId) hooks))) | |
derive instance ntUseAnimationFrame :: Newtype (UseAnimationFrame hooks) _ | |
useAnimationFrame :: (Number -> Effect Unit) -> Hook UseAnimationFrame Unit | |
useAnimationFrame callback = | |
coerceHook React.do | |
requestRef <- useRef null | |
previousTimeRef <- useRef null | |
let | |
animate = do | |
w <- window | |
Milliseconds time <- unInstant <$> now | |
previousTime <- readRefMaybe previousTimeRef | |
case previousTime of | |
Just pt -> callback (time - pt) | |
Nothing -> mempty | |
writeRef previousTimeRef (notNull time) | |
a <- requestAnimationFrame animate w | |
writeRef requestRef (notNull a) | |
useEffect unit do | |
w <- window | |
a <- requestAnimationFrame animate w | |
writeRef requestRef (notNull a) | |
r <- readRefMaybe requestRef | |
pure (maybe mempty (\frameId -> cancelAnimationFrame frameId w) r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment