Skip to content

Instantly share code, notes, and snippets.

@peterszerzo
Created March 14, 2020 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterszerzo/3c156543c16dd461a5225b8a533955ec to your computer and use it in GitHub Desktop.
Save peterszerzo/3c156543c16dd461a5225b8a533955ec to your computer and use it in GitHub Desktop.
requestAnimationFrame hooke for purescript-react-basic-hooks
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