Loader.purs 2.05 KB
Newer Older
1 2
module Gargantext.Hooks.Loader where

3 4 5
import Data.Functor ((<$>))
import Control.Monad ((=<<))
import Data.Maybe (Maybe(..), isNothing, maybe, maybe')
6 7 8 9 10 11 12 13 14
import Data.Tuple (fst)
import Data.Tuple.Nested ((/\))
import Gargantext.Prelude
import Effect.Aff (Aff)
import Effect.Class (liftEffect)
import Reactix as R
import Gargantext.Utils.Reactix as R2
import Gargantext.Components.LoadingSpinner (loadingSpinner)

15 16 17 18 19 20 21 22 23 24 25 26 27 28
useAff :: forall st. Aff st -> R.Hooks (Maybe st)
useAff loader = do
  (loaded /\ setLoaded) <- R.useState' Nothing
  R.useEffect1 loader $ do
    if isNothing loaded then
      R2.affEffect "G.H.Loader.useAff" $
        loader >>= (liftEffect <<< setLoaded <<< const <<< Just)
    else pure R.nothing
  pure loaded

useLoader :: forall path st. path -> (path -> Aff st) -> (st -> R.Element) -> R.Hooks R.Element
useLoader path loader render
  =   maybe' (\_ -> loadingSpinner {}) render
  <$> (useAff =<< R.useMemo2 path loader (\_ -> loader path))
29

30
useLoader2 :: forall path st. R.State path -> (path -> Aff st) -> (st -> R.Element) -> R.Hooks R.Element
31 32 33 34 35
useLoader2 path loader render = do
  state <- R.useState' Nothing
  useLoaderEffect2 path state loader
  pure $ maybe (loadingSpinner {}) render (fst state)
  
36 37
useLoaderEffect :: forall state. Aff state -> R.State (Maybe state) -> R.Hooks Unit
useLoaderEffect loader (state /\ setState) = do
38 39
  R.useEffect2 state loader $ do
    if isNothing state then
40
      R2.affEffect "G.H.Loader.useLoader" $ loader >>= (liftEffect <<< setState <<< const <<< Just)
41 42 43 44 45
    else pure R.nothing

useLoaderEffect' :: forall state. Aff state -> R.Hooks (R.State (Maybe state))
useLoaderEffect' aff = do
  state <- R.useState' Nothing
46
  useLoaderEffect aff state
47 48 49
  pure state

useLoaderEffect2 :: forall st path. R.State path -> R.State (Maybe st) -> (path -> Aff st) -> R.Hooks Unit
50 51 52
useLoaderEffect2 path state loader = do
  aff <- useRepointer path loader
  useLoaderEffect aff state
53 54

useRepointer :: forall path st. R.State path -> (path -> Aff st) -> R.Hooks (Aff st)
55
useRepointer path@(path' /\ _) loader = R.useMemo2 loader path' (\_ -> loader path')
56 57