packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Widgets/Tabs.hs

-- | Controlled tab selection, header styles, close requests, and header geometry.
module NanoUI.Internal.Widgets.Tabs
  ( Tab (..), TabStyle (..), TabOrientation (..), TabResponse (..)
  , TabsConfig (..), defaultTabsConfig
  , tab, closableTab
  , tabs, tabs', tabsConfigured, tabsConfigured'
  , tabBar, tabBar', tabBarConfigured, tabBarConfigured'
  , enumTabsBy, enumTabsByConfigured, enumTabs
  , enumTabBarBy, enumTabBarByConfigured, enumTabBar
  )
where

import Control.Monad (void, when)
import Data.Bits ((.|.))
import Data.Foldable (toList)
import Data.Hashable (Hashable (..))
import Data.IORef (newIORef, readIORef, writeIORef)
import Data.List (find)
import Data.Maybe (fromMaybe, isJust, listToMaybe)
import Data.Text (Text)
import Data.Text qualified as T
import NanoUI.Internal.Context
import NanoUI.Internal.Frame.Chrome (tabHeaderVisualStyle)
import NanoUI.Internal.Layout.ScrollGeometry (scrollAxisRange, scrollBare, scrollHorizontalHidden)
import NanoUI.Internal.Id (WidgetId)
import NanoUI.Internal.Input (MouseButton (..), inputMousePos, inputScroll)
import NanoUI.Internal.Layout.Arena (setStyleIdx, setWidgetId)
import NanoUI.Internal.Monad (NanoUI, askInput, disabledWhen, freshWidget, lastRect, nextId, liftIO, styled, uiFontSize, uiTheme, withContext, withKey)
import NanoUI.Internal.Var (Binding (..), bindVarOn)
import NanoUI.Internal.Var.Types (Var, zoomVar)
import NanoUI.Internal.Store (fieldInt, findSpec, lookupSlot, slotWrite, specKey, specWrite)
import NanoUI.Internal.Store.Slots (slotScrollContent)
import NanoUI.Internal.Style
import NanoUI.Internal.Types (Color, Rect (..), clamp, rectContains, rectIntersect, rectW, v2Y)
import NanoUI.Internal.WidgetText (TabChrome (..), buttonCloseTab, buttonFlagClose, tabChromeEncode, tabEncodeStyle)
import NanoUI.Internal.Widgets.Adornment (Adornments, adornButton, control, trailing, view)
import NanoUI.Internal.Widgets.Combinators (buttonStyledEx, widgetBaseLayout)
import NanoUI.Internal.Widgets.Layout (column', columnWith, labelEx, panel', row', rowWith, scrollAreaIdConfigured)
import NanoUI.Internal.Widgets.Node

-- | Visual treatment of the tab headers; does not change tab identity.
data TabStyle
  = TabUnderline
  -- ^ Headers on a rule, the selected one marked by an accent bar on it.
  | TabPill
  -- ^ The selected header filled with the accent colour.
  | TabSegmented
  -- ^ Headers in a rounded track, the selected one raised out of it, as a
  -- segmented control.
  | TabContained
  -- ^ Folder tabs: the selected header opens onto a bordered body, which
  -- 'tabs' draws round the tab's content.
  deriving (Eq, Ord, Show, Enum, Bounded)

instance Hashable TabStyle where
  hashWithSalt salt = hashWithSalt salt . fromEnum

-- | Header strip position relative to the selected tab's body.
data TabOrientation = TabTop | TabBottom | TabLeft | TabRight
  deriving (Eq, Ord, Show, Enum, Bounded)

instance Hashable TabOrientation where
  hashWithSalt salt = hashWithSalt salt . fromEnum

isVertical :: TabOrientation -> Bool
isVertical o = o == TabLeft || o == TabRight

-- | Header look and placement for 'tabsConfigured' and 'tabBarConfigured'.
data TabsConfig = TabsConfig
  { tabsStyle :: !TabStyle
  , tabsOrientation :: !TabOrientation
  , tabsTrailing :: NanoUI ()
  -- ^ Drawn after the headers: at the far end of a horizontal strip, below
  -- a vertical strip's headers. For actions on the strip as a whole, such
  -- as a button that opens a new tab. Child widgets handle their own pointer events.
  }

-- | The trailing view shows as @\<view\>@.
instance Show TabsConfig where
  showsPrec d (TabsConfig style orient _) =
    showParen (d > 10) $
      showString "TabsConfig " . showsPrec 11 style . showChar ' ' . showsPrec 11 orient . showString " <view>"

-- | Underlined headers along the top, with nothing after them.
defaultTabsConfig :: TabsConfig
defaultTabsConfig = TabsConfig TabUnderline TabTop (pure ())

-- | Tab key, header options, and body. Keys must be distinct within the bar.
-- Closing is a request to the caller; the widget does not remove the tab.
data Tab a body = Tab
  { tabKey :: !a
  , tabTitle :: !Text
  , tabClosable :: !Bool
  , tabDisabled :: !Bool
  , tabBadge :: !(Maybe Text)
  -- ^ A short count or status drawn in a pill after the title.
  , tabAdornments :: !Adornments
  -- ^ Icons, texts and views drawn in the header beside its title
  -- ("NanoUI.Adornment"), in the header's label colour. An 'NanoUI.Adornment.AdornControl',
  -- such as a pin button, handles its own pointer events without selecting
  -- or closing the tab.
  , tabBody :: !body
  }

-- | Controlled selection and close requests, with geometry for optional
-- drag sources and insertion targets.
data TabResponse a = TabResponse
  { tabResponse :: !Response
  , tabClosed :: !(Maybe a)
  , tabActive :: !a
  , tabHeaders :: ![(a, Response)]
    -- ^ Ordered header responses, suitable for 'NanoUI.useDrag'.
  , tabStripRect :: !Rect
    -- ^ Visible header viewport, excluding paging buttons and trailing controls.
  }
  deriving (Eq, Show)

instance HasResponse (TabResponse a) where
  {-# INLINE toResponse #-}
  toResponse = tabResponse

-- | Enabled tab without a close button, badge or adornments.
tab :: a -> Text -> body -> Tab a body
tab key title body = Tab key title False False Nothing mempty body

-- | Enabled tab with a close button. A click on it, or a middle click on the
-- header, is reported through 'tabClosed'.
closableTab :: a -> Text -> body -> Tab a body
closableTab key title body = Tab key title True False Nothing mempty body

-- | Header height, shared by the strip, its scroller and the paging arrows.
tabHeaderH :: Float
tabHeaderH = 30

-- | A header's layout. The headers of a vertical strip share its width, and
-- start their labels at their padding (@tabLabelAtStart@).
tabHeaderLay :: Bool -> Layout
tabHeaderLay vertical = (if vertical then fillW else id) . fixedH tabHeaderH . alignMiddle . gap 6 $ defaultLayout

-- | Name the current container @wid@ and give it @part@ of a strip's chrome,
-- painted under its children ('NanoUI.Internal.Frame.Chrome.paintTabChrome').
-- The id tracks the container's rect, so what it paints repaints as it moves.
tagTabChrome :: WidgetId -> TabChrome -> TabStyle -> TabOrientation -> NanoUI ()
tagTabChrome wid part style orient = do
  withContext $ \ctx -> do
    parent <- currentParent ctx
    when (parent >= 0) $ do
      setWidgetId (ctxNodeArena ctx) parent wid
      setStyleIdx (ctxNodeArena ctx) parent (tabChromeEncode part (fromEnum style) (fromEnum orient))

tabStrip ::
  Hashable a =>
  TabsConfig ->
  a ->
  [Tab a body] ->
  Maybe (a -> NanoUI ()) ->
  NanoUI (TabResponse a)
tabStrip (TabsConfig style orient trailingView) cur tabList mRenderBody = do
  (groupId, ctx) <- freshWidget
  let vertical = isVertical orient
      -- Headers ahead of the body take this frame's clicks. A body ahead of
      -- them ran with the key passed in, so they show it too, and the
      -- binding reruns the view to show the new one.
      bodyFirst = bodyAhead orient (isJust mRenderBody)
      headers = renderHeaders ctx style orient (not bodyFirst) cur tabList
      barGap = if style == TabPill then 4 else 2
      edgeChrome = case style of
        TabUnderline -> TabChromeRule
        TabContained -> TabChromeRule
        _ -> TabChromeNone
      -- Contained headers stand off the rule's ends and the strip's far side.
      contained
        | style /= TabContained = id
        | otherwise = case orient of
            TabTop -> padLRTB 6 6 4 0
            TabBottom -> padLRTB 6 6 0 4
            TabLeft -> padLRTB 4 0 6 6
            TabRight -> padLRTB 0 4 6 6
      -- Headers sit on the rule, whatever the trailing view's height.
      onEdge = if orient == TabBottom then alignTop else alignBottom
      headerBar
        | vertical = column' (contained . segmentedColumn . tight . gap barGap $ defaultLayout) $ do
            tagTabChrome groupId (if style == TabSegmented then TabChromeTrack else edgeChrome) style orient
            headers <* trailingView
        | otherwise = row' (contained . onEdge . tight . fillW . gap 8 $ defaultLayout) $ do
            tagTabChrome groupId edgeChrome style orient
            scrollableHeaders ctx style barGap headers <* trailingView
      -- A segmented column hugs its headers in its track; the others run the
      -- body's length.
      segmentedColumn = if style == TabSegmented then padAll 3 else fillH
      bodyGap = if style == TabContained then 0 else if vertical then 16 else 12
  result <- case mRenderBody of
    Nothing -> headerBar
    Just bodyRender ->
      (if vertical then rowWith (tight . fillW . grow . gap bodyGap) else columnWith (tight . fillW . gap bodyGap)) $
        if bodyFirst
          then bodyRender cur *> headerBar
          else headerBar >>= \r -> r <$ bodyRender (tabActive r)
  -- The headers show the selection only through their node values, which no
  -- diff covers, so a slot on the strip damages it when the shown tab changes,
  -- however the change came (a click, a key, a write to the Var).
  liftIO (writeSlot fieldInt ctx groupId (intKey groupId) (hash (if bodyFirst then cur else tabActive result)))
  clip <- liftIO (getPrevClipRect ctx groupId)
  let bounds = tabStripRect result
      visible = maybe bounds (fromMaybe (Rect 0 0 0 0) . rectIntersect bounds) clip
  pure result {tabStripRect = visible}

-- | Horizontal headers that page with chevron buttons when they overflow,
-- in a row that takes the strip's width less its trailing view. Overflowing
-- headers move into a bare horizontal scroller that grows between the two
-- arrows; the vertical wheel over it pages it too, and scrolls nothing
-- round it. Segmented headers sit in their track, which scrolls with them.
scrollableHeaders ::
  Hashable a =>
  Context ->
  TabStyle ->
  Float ->
  NanoUI (TabResponse a) ->
  NanoUI (TabResponse a)
scrollableHeaders ctx style barGap headers = withKey ("tab-headers" :: Text) $ do
  groupId <- nextId
  scrollWid <- nextId
  trackId <- nextId
  let rangeKey = intKey scrollWid
      segmented = style == TabSegmented
      stripH = if segmented then tabHeaderH + 6 else tabHeaderH
      renderInner =
        withKey ("tab-strip" :: Text) $
          row' ((if segmented then padAll 3 else id) . tight . fixedH stripH . gap barGap $ defaultLayout) $ do
            when segmented $ tagTabChrome trackId TabChromeTrack style TabTop
            headers
      -- Whether the strip overflows and can page left and right, at reachable
      -- range @r@ and offset @o@.
      paging r o = (r > 0.5, r > 0.5 && o > 0.5, o < r - 0.5)
  -- The reachable range measured after last frame's layout decides whether
  -- the strip needs the scroller. It is a float slot published after layout,
  -- so the frame that changes it counts as a layout change, not a scroll
  -- ('NanoUI.Internal.Damage.writeDamage').
  store <- liftIO (getStore ctx)
  let maxOff = max 0 (findSpec slotScrollContent 0 rangeKey store)
      -- The hash of the tab the strip last brought into view, if any: a key
      -- that hashes to 0 is followed too.
      followKey = intKey groupId
      followed = lookupSlot fieldInt followKey store
  off <- liftIO (getScrollOffset ctx scrollWid)
  let (overflow, canLeft, canRight) = paging maxOff off
  wheelStep <- liftIO (resolveScrollStep ctx scrollWid)
  -- Not 'lastRect': the strip checks its own layout below, and the bar
  -- moving alone needs no second frame.
  mBar <- liftIO (getPrevRect ctx groupId)
  mScr <- liftIO (getPrevRect ctx scrollWid)
  mClip <- liftIO (getPrevClipRect ctx scrollWid)
  inp <- askInput
  -- Over the scroller only: it keeps the vertical wheel from the scrollers
  -- round it, which the arrows do not. The wheel counts as a scroller takes
  -- it, fractions of a notch from a trackpad too.
  let visScr = maybe mScr (\c -> mScr >>= rectIntersect c) mClip
      overStrip = maybe False (\r -> rectContains r (inputMousePos inp)) visScr
      wheelY = if overStrip then v2Y (inputScroll inp) else 0
      -- A paging arrow while the bar overflows, muted at its end. The muted
      -- look is a font colour, which no diff covers, so a slot at the arrow
      -- repaints it when it turns.
      arrow k enabled glyph
        | overflow = withKey (k :: Text) $ do
            theme <- uiTheme
            let muted = if enabled then Nothing else Just (themeMuted theme)
                lay = (fixedWH 26 stripH . alignCenter . alignMiddle $ defaultLayout) {layoutFontColor = muted}
            resp <- styled subtle (buttonStyledEx enabled glyph 0 lay 0)
            liftIO (writeSlot fieldInt ctx (respId resp) (intKey (respId resp)) (fromEnum enabled))
            pure (respClicked resp)
        | otherwise = pure False
  (leftClicked, tabResp, rightClicked) <-
    row' (tight . grow . alignMiddle . fixedH stripH $ defaultLayout) $ do
      tagContainer groupId
      (,,)
        <$> arrow "tab-arrow-left" canLeft "\8249"
        <*> ( if overflow
                then
                  scrollAreaIdConfigured
                    scrollWid
                    (tight . fillW . fixedH stripH $ defaultLayout {layoutDirection = Row})
                    scrollHorizontalHidden {scrollBare = True}
                    renderInner
                else renderInner
            )
        <*> arrow "tab-arrow-right" canRight "\8250"
  let
    hdrs = tabHeaders tabResp
    viewport = fromMaybe (Rect 0 0 0 0) (if overflow then mScr else mBar)
    viewX = rectX viewport
    viewW = rectW viewport
    page = max 1 (viewW * 0.9)
    -- The range this frame's layout leaves: the headers' right edge past the
    -- start of what shows them, less its width. The first overflow frame has
    -- no scroller rect yet, and keeps the range it has. Headers that would
    -- fit the whole bar without the arrows leave no range, so the arrows go
    -- once the bar is wide enough, however narrow the scroller between them.
    measure = do
      mView <- getPrevRect ctx (if overflow then scrollWid else groupId)
      mBarNow <- if overflow then getPrevRect ctx groupId else pure Nothing
      rights <- mapM (fmap (maybe 0 (\r -> rectX r + rectW r)) . getPrevRect ctx . respId . snd) hdrs
      o <- getScrollOffset ctx scrollWid
      let extent vx = maximum (0 : rights) - vx + (if overflow then o else 0)
          range (Rect vx _ vw _)
            | Just bar <- mBarNow, scrollAxisRange (extent vx) (rectW bar) 0 == 0 = 0
            | otherwise = scrollAxisRange (extent vx) vw 0
      pure (maybe maxOff range mView, o)
  -- After layout, measure the strip for the next frame and request a
  -- follow-up frame only when the overflow or arrow state changes: a width
  -- change that keeps them settles in the frame it happens in. Sub-pixel
  -- churn is ignored so a parked strip never writes.
  liftIO . recordLayoutRead ctx (specKey slotScrollContent rangeKey) $ do
    (maxOff', o) <- measure
    when (abs (maxOff' - maxOff) > 0.5) $
      publishLayoutSlots ctx (specWrite slotScrollContent rangeKey maxOff')
    pure (paging maxOff' o /= paging maxOff off)
  -- While the shown tab is not the one last brought into view, however it
  -- came to be shown (a click, a key, a write to the Var), its header's rect
  -- and the scroller's. Each is last frame's, or, for one laid out for the
  -- first time this frame, a read that brings another frame once it is.
  let shown = tabActive tabResp
      laidOut w = liftIO (getPrevRect ctx w) >>= maybe (lastRect w) (pure . Just)
  target <-
    if overflow && Just (hash shown) /= followed
      then do
        scroller <- laidOut scrollWid
        header <- maybe (pure Nothing) (laidOut . respId) (lookup shown hdrs)
        pure (scroller *> header)
      else pure Nothing
  -- One offset per frame: arrow pages, the wheel and the end clamp, or
  -- whatever brings that header into view.
  let pagedOff
        | leftClicked, canLeft = max 0 (off - page)
        | rightClicked, canRight = min maxOff (off + page)
        | overflow, wheelY /= 0, maxOff > 0 =
            clamp 0 maxOff (off + wheelY * wheelStep)
        | overflow, off > maxOff + 0.5 = maxOff
        | otherwise = off
      follow hr
        | rectX hr < viewX = max 0 (off - (viewX - rectX hr))
        | rectX hr + rectW hr > viewX + viewW =
            min maxOff (off + (rectX hr + rectW hr - viewX - viewW))
        | otherwise = pagedOff
      finalOff = maybe pagedOff follow target
  when (finalOff /= off) $
    liftIO (setScrollOffset ctx scrollWid finalOff)
  -- Compared first, so a parked strip writes nothing.
  when (isJust target) $
    liftIO (publishLayoutSlots ctx (slotWrite fieldInt followKey (hash shown)))
  pure tabResp {tabStripRect = viewport}

-- | The headers and the selection after this frame's clicks, with each
-- header's key and response for the scrolling strip. With @follow@ the
-- headers show the clicked tab as selected at once; without it they show
-- @cur@, the key passed in.
renderHeaders ::
  Hashable a =>
  Context ->
  TabStyle ->
  TabOrientation ->
  Bool ->
  a ->
  [Tab a body] ->
  NanoUI (TabResponse a)
renderHeaders ctx style orient follow cur tabList = do
  hdrs <- mapM (\t -> withKey (tabKey t) (renderHeader style orient cur t)) tabList
  let clickedKeys = [k | (k, r, False) <- hdrs, respClicked r]
      closedKey = listToMaybe [k | (k, _, True) <- hdrs]
      keyed = [(k, r) | (k, r, _) <- hdrs]
      nextTab = fromMaybe cur (listToMaybe clickedKeys)
      hasChanged = nextTab /= cur
      resp = setChanged hasChanged (setClicked (not (null clickedKeys)) (foldMap snd keyed))
  when follow $ liftIO (moveSelection ctx cur nextTab keyed)
  pure (TabResponse resp closedKey nextTab keyed (respRect resp))

-- | One header: its key, its response, and whether it was closed (close
-- button clicked, or header or close button middle-clicked, as in a
-- browser). The header is one button; its adornments, badge and close
-- button are drawn inside it, in its label colour. A press on the close
-- button or on a control among the adornments is theirs, not the header's.
renderHeader :: Eq a => TabStyle -> TabOrientation -> a -> Tab a body -> NanoUI (a, Response, Bool)
renderHeader style orient cur t = disabledWhen (tabDisabled t) $ do
  theme <- uiTheme
  lay <- widgetBaseLayout (tabHeaderLay (isVertical orient)) id
  let isActive = tabKey t == cur
      packed = tabEncodeStyle (fromEnum style) (fromEnum orient)
      labelCol = styleFg (tabHeaderVisualStyle theme packed isActive)
  resp <- buttonStyledEx (not (tabDisabled t)) (tabTitle t) (if isActive then 1 else 0) lay packed
  closeRef <- if tabClosable t then Just <$> liftIO (newIORef False) else pure Nothing
  let badge = foldMap (trailing . view . tabBadgeView labelCol) (tabBadge t)
      closeButton ref = do
        c <- buttonStyledEx True "\215" 0 (tight . fixedWH 18 18 . fontColor labelCol $ defaultLayout) (buttonFlagClose .|. buttonCloseTab)
        liftIO (writeIORef ref (respClicked c || respClickedWith MouseMiddle c))
  header <- adornButton resp lay (const labelCol) (tabAdornments t <> badge <> foldMap (trailing . control . closeButton) closeRef)
  btnClosed <- maybe (pure False) (liftIO . readIORef) closeRef
  pure (tabKey t, header, tabClosable t && (btnClosed || respClickedWith MouseMiddle header))

-- | A badge: its text, smaller, in a pill of the label colour @col@.
tabBadgeView :: Color -> Text -> NanoUI ()
tabBadgeView col txt = do
  -- Scaled from the base size the title is drawn at.
  size <- uiFontSize
  styled (panelStyle (\s -> s {styleBg = fadeAlpha col 44, styleBorderWidth = 0, styleCornerRadius = 8})) $
    panel' (padXY 6 1 . tight . minH 17 . alignCenter . alignMiddle $ defaultLayout) $
      () <$ labelEx (tight . fontSize (size * 0.78) . fontColor col $ defaultLayout) txt

-- | Tab headers and the active tab's body, with the active key bound to
-- mutable state ('Var'): a click, or Enter or Space on a focused header,
-- updates it in place. Only the active tab's body runs. A key no tab has,
-- such as a removed tab's, selects the first tab, and the 'Var' is set to it.
{-# INLINE tabs #-}
tabs :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI ()
tabs = tabsConfigured defaultTabsConfig

-- | 'tabs' returning the 'TabResponse', which also reports a closed tab.
{-# INLINE tabs' #-}
tabs' :: (Foldable f, Hashable a) => Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)
tabs' = tabsConfigured' defaultTabsConfig

-- | 'tabs' with a header style and placement.
{-# INLINE tabsConfigured #-}
tabsConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI ()
tabsConfigured cfg active ts = void (tabsConfigured' cfg active ts)

-- | 'tabsConfigured' with selection, close requests, and header interaction details.
tabsConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a (NanoUI ())) -> NanoUI (TabResponse a)
tabsConfigured' cfg active inputTabs = bindTabs cfg True active (\cur -> tabStrip cfg (shown cur) ts (Just body))
  where
    ts = toList inputTabs
    -- A key no tab has shows the first tab, its header as well as its body,
    -- and the binding writes that tab's key back.
    shown k = if any ((== k) . tabKey) ts then k else maybe k tabKey (listToMaybe ts)
    -- Only the active tab's body runs. Both bodies and headers use the
    -- semantic key: their widget state and focus follow the tab through
    -- reordering and removal of neighbours. A contained body is a bordered
    -- surface the selected header opens onto.
    body k = do
      let contained = tabsStyle cfg == TabContained
          surface = if contained then padAll 12 . (if isVertical (tabsOrientation cfg) then fillH else id) else id
      bodyId <- if contained then withKey ("tab-body" :: Text) (Just <$> nextId) else pure Nothing
      columnWith (surface . tight . fillW) $ do
        mapM_ (\wid -> tagTabChrome wid TabChromeBody (tabsStyle cfg) (tabsOrientation cfg)) bodyId
        mapM_
          (\t -> withKey (tabKey t) (tabBody t))
          (find ((== k) . tabKey) ts)

-- | Run a tab strip on the active key in a Var. A body placed ahead of the
-- headers has already run for the old key when a header is clicked, so a
-- change there runs the view again.
bindTabs :: Hashable a => TabsConfig -> Bool -> Var a -> (a -> NanoUI (TabResponse a)) -> NanoUI (TabResponse a)
bindTabs cfg hasBody active =
  bindVarOn (if bodyAhead (tabsOrientation cfg) hasBody then Conservative else RenderFinal) tabActive active

bodyAhead :: TabOrientation -> Bool -> Bool
bodyAhead orient hasBody = hasBody && (orient == TabBottom || orient == TabRight)

-- | Tab headers only, bound to mutable state ('Var') for the active key; the
-- caller renders the body.
{-# INLINE tabBar #-}
tabBar :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI ()
tabBar = tabBarConfigured defaultTabsConfig

{-# INLINE tabBar' #-}
-- | Header-only 'tabBar' with selection and close requests. Does not run tab bodies.
tabBar' :: (Foldable f, Hashable a) => Var a -> f (Tab a body) -> NanoUI (TabResponse a)
tabBar' = tabBarConfigured' defaultTabsConfig

-- | Header-only bar with explicit style/orientation.
{-# INLINE tabBarConfigured #-}
tabBarConfigured :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI ()
tabBarConfigured cfg active ts = void (tabBarConfigured' cfg active ts)

-- | 'tabBarConfigured' with interaction details and optional close request.
tabBarConfigured' :: (Foldable f, Hashable a) => TabsConfig -> Var a -> f (Tab a body) -> NanoUI (TabResponse a)
tabBarConfigured' cfg active ts = bindTabs cfg False active (\cur -> tabStrip cfg cur (toList ts) Nothing)

-- | 'tabs' with a tab for every value of a bounded enumeration, labeled by
-- @encode@, each showing @body@ of its value. The Var holds the selected
-- value itself, so the enumeration needs no 'Hashable' instance.
--
-- > page <- useEnumVar Overview
-- > enumTabsBy pageTitle page pageBody
{-# INLINE enumTabsBy #-}
enumTabsBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()
enumTabsBy = enumTabsByConfigured defaultTabsConfig

-- | 'enumTabsBy' with a header style and placement.
{-# INLINE enumTabsByConfigured #-}
enumTabsByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> (a -> NanoUI ()) -> NanoUI ()
enumTabsByConfigured cfg encode active body =
  tabsConfigured cfg (enumIndex active) (map (\x -> tab (fromEnum x) (encode x) (body x)) [minBound .. maxBound])

-- | 'enumTabsBy' labeled with 'show'.
{-# INLINE enumTabs #-}
enumTabs :: (Bounded a, Enum a, Show a) => Var a -> (a -> NanoUI ()) -> NanoUI ()
enumTabs = enumTabsBy (T.pack . show)

-- | 'tabBar' with a header for every value of a bounded enumeration,
-- labeled by @encode@.
{-# INLINE enumTabBarBy #-}
enumTabBarBy :: (Bounded a, Enum a) => (a -> Text) -> Var a -> NanoUI ()
enumTabBarBy = enumTabBarByConfigured defaultTabsConfig

-- | 'enumTabBarBy' with a header style and placement; with 'TabSegmented'
-- it is a segmented control:
--
-- > enumTabBarByConfigured defaultTabsConfig {tabsStyle = TabSegmented} alignName alignment
{-# INLINE enumTabBarByConfigured #-}
enumTabBarByConfigured :: (Bounded a, Enum a) => TabsConfig -> (a -> Text) -> Var a -> NanoUI ()
enumTabBarByConfigured cfg encode active =
  tabBarConfigured cfg (enumIndex active) (map (\x -> tab (fromEnum x) (encode x) ()) [minBound .. maxBound])

-- | 'enumTabBarBy' labeled with 'show'.
{-# INLINE enumTabBar #-}
enumTabBar :: (Bounded a, Enum a, Show a) => Var a -> NanoUI ()
enumTabBar = enumTabBarBy (T.pack . show)

-- | An enumeration's Var seen as its index, which keys the tabs. The tabs
-- only ever write the index of a value they list.
{-# INLINE enumIndex #-}
enumIndex :: Enum a => Var a -> Var Int
enumIndex = zoomVar fromEnum (\i _ -> toEnum i)