Toestand.purs 1.84 KB
Newer Older
James Laver's avatar
James Laver committed
1
module Gargantext.Utils.Toestand
2
  ( class Reloadable, reload, Reload, ReloadS, newReload, InitReload(..), ready, useMemberBox )
3
  where
James Laver's avatar
James Laver committed
4

5
import Prelude (class Ord, Unit, bind, pure, unit, (+))
James Laver's avatar
James Laver committed
6 7 8 9 10 11 12 13
import Data.Set as Set
import Data.Set (Set)
import Effect (Effect)
import Reactix as R
import Toestand as T

-- | Reload is a simple counter that can be used to force an update.
type Reload = Int
14
type ReloadS = T.Box Reload
James Laver's avatar
James Laver committed
15 16 17 18 19 20 21 22

class Reloadable t where
  reload :: t -> Effect Unit

-- | An empty Reload is zero as it has not yet been reloaded.
newReload :: Reload
newReload = 0

23 24
instance reloadableBoxReload :: Reloadable (T.Box Int) where
  reload box = T.modify_ (_ + 1) box
James Laver's avatar
James Laver committed
25

26 27 28
instance reloadableInitReloadBox :: Reloadable (c Reload) => Reloadable (T.Box (InitReload c)) where
  reload box = do
    val <- T.read box
James Laver's avatar
James Laver committed
29 30 31 32
    case val of
      Init    -> pure unit
      Ready r -> reload r

33 34
-- inner is a Box wrapping a Reload
data InitReload (inner :: Type -> Type) = Init | Ready (inner Reload)
James Laver's avatar
James Laver committed
35

36
-- | Initialises an InitReload box with the Reload box it contains,
James Laver's avatar
James Laver committed
37
-- | if it has not already been initialised.
38 39 40 41
ready :: forall box c. T.ReadWrite box (InitReload c) => T.ReadWrite (c Reload) Reload
      => box -> (c Reload) -> Effect Unit
ready box with = do
  val <- T.read box
James Laver's avatar
James Laver committed
42
  case val of
43
    Init    -> T.write_ (Ready with) box
James Laver's avatar
James Laver committed
44 45 46 47 48
    Ready _ -> pure unit

-- | Creates a cursor which presents a Boolean over whether the member
-- | is in the set. Adjusting the value will toggle whether the value
-- | is in the underlying set.
49 50 51 52
useMemberBox
  :: forall box v. Ord v => T.ReadWrite box (Set v)
  => v -> box -> R.Hooks (T.Box Boolean)
useMemberBox val box = T.useFocused (Set.member val) (toggleSet val) box
James Laver's avatar
James Laver committed
53

54
-- utility for useMemberBox
James Laver's avatar
James Laver committed
55 56 57
toggleSet :: forall s. Ord s => s -> Boolean -> Set s -> Set s
toggleSet val true  set = Set.insert val set
toggleSet val false set = Set.delete val set