Tab.purs 1.76 KB
Newer Older
1
module Gargantext.Components.Tab where
2

Sudhir Kumar's avatar
Sudhir Kumar committed
3
import Prelude hiding (div)
James Laver's avatar
James Laver committed
4
import Data.FunctorWithIndex (mapWithIndex)
5
import Data.Tuple (Tuple)
James Laver's avatar
James Laver committed
6 7 8
import Data.Tuple.Nested ((/\))
import Reactix as R
import Reactix.DOM.HTML as H
9

James Laver's avatar
James Laver committed
10
type TabsProps = ( tabs :: Array (Tuple String R.Element), selected :: Int )
11

James Laver's avatar
James Laver committed
12 13
tabs :: Record TabsProps -> R.Element
tabs props = R.createElement tabsCpt props []
14

James Laver's avatar
James Laver committed
15 16
-- this is actually just the list of tabs, not the tab contents itself
tabsCpt :: R.Component TabsProps
17
tabsCpt = R.hooksComponent "G.C.Tab.tabs" cpt
18
  where
James Laver's avatar
James Laver committed
19 20 21
    cpt props _ = do
      (activeTab /\ setActiveTab) <- R.useState' props.selected
      pure $
22
        H.div {}
James Laver's avatar
James Laver committed
23 24
        [ H.nav {}
          [ H.div { className: "nav nav-tabs" }
25 26 27
            (mapWithIndex (button setActiveTab activeTab) props.tabs) ]
        , H.div { className: "tab-content" } $ mapWithIndex (item activeTab) props.tabs ]
    button setActiveTab selected index (name /\ _) =
James Laver's avatar
James Laver committed
28 29 30 31 32
      H.a { className, on: { click } } [ H.text name ]
      where
        eq = index == selected
        className = "nav-item nav-link" <> (if eq then " active" else "")
        click e = setActiveTab (const index)
33
    item selected index (_ /\ cpt) = tab { selected, index } [ cpt ]
James Laver's avatar
James Laver committed
34 35 36 37 38 39 40 41 42

-- TODO: document what these are (selection, item indices)
type TabProps = ( selected :: Int, index :: Int )

tab :: Record TabProps -> Array R.Element -> R.Element
tab = R.createElement tabCpt

-- | A tab only shows its contents if it is currently selected
tabCpt :: R.Component TabProps
43
tabCpt = R.staticComponent "G.C.Tab.tab" cpt
44
  where
James Laver's avatar
James Laver committed
45 46 47 48 49
    cpt { selected, index } children = H.div { className } children'
      where
        same = selected == index
        className = "tab-pane" <> (if same then "show active" else "fade")
        children' = if same then children else []
50