AutoUpdate.purs 2.03 KB
Newer Older
1 2 3 4 5 6 7 8
module Gargantext.Components.AutoUpdate where

import Data.Maybe (Maybe(..))
import Data.Traversable (traverse_)
import React as React
import React (ReactClass, ReactElement, Children)
import React.DOM (div')
import Effect (Effect)
9 10 11 12 13
import Effect.Timer (IntervalId, TimeoutId, setInterval, clearInterval, setTimeout, clearTimeout)
import Reactix as R
import Reactix.DOM.HTML as H

import Gargantext.Prelude
14 15 16
import Gargantext.Utils.Reactix as R2

thisModule = "Gargantext.Components.AutoUpdate"
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

data Action = Update

type PropsRow =
  ( duration :: Int
  , effect   :: Effect Unit
  )

type Props = { | PropsRow }

type State = { intervalId :: Maybe IntervalId }

autoUpdateClass :: ReactClass { children :: Children | PropsRow }
autoUpdateClass =
  React.component "AutoUpdate"
    (\this -> do
       pure { state: {intervalId: Nothing}
            , render: pure $ div' []
            , componentDidMount: do
37
                {duration, effect} <- React.getProps this
38 39 40 41 42 43 44 45 46
                intervalId        <- setInterval duration effect
                React.setState this {intervalId: Just intervalId}
            , componentWillUnmount: do
                {intervalId} <- React.getState this
                traverse_ clearInterval intervalId
            })

autoUpdateElt :: Props -> ReactElement
autoUpdateElt props = React.createElement autoUpdateClass props []
47 48 49 50 51

autoUpdate :: Record PropsRow -> R.Element
autoUpdate props = R.createElement autoUpdateCpt props []

autoUpdateCpt :: R.Component PropsRow
52
autoUpdateCpt = R2.hooksComponent thisModule "autoUpdate" cpt
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  where
    cpt { duration, effect } _ = do
      intervalRef <- R.useRef Nothing

      R.useEffect' $ do
        let mInterval = R.readRef intervalRef
        case mInterval of
          Nothing -> do
            intervalId <- setInterval duration effect
            R.setRef intervalRef $ Just intervalId
          Just intervalId -> do
            clearInterval intervalId
            intervalId <- setInterval duration effect
            R.setRef intervalRef $ Just intervalId

      pure $ H.div {} []