packages feed

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

-- | Widget node construction and interaction responses.
module NanoUI.Internal.Widgets.Node
  ( Response (..)
  , HasResponse (..)
  , respId
  , respRect
  , respHovered
  , respPressed
  , respClicked
  , respChanged
  , respSubmitted
  , respHeldWith
  , respClickedWith
  , respRightPressed
  , respRightClicked
  , pointerOnWidget
  , pointerReachable
  , anyControlHitInRange
  , mkResponse
  , setClicked
  , setChanged
  , setSubmitted
  , inertResponse
  , currentParent
  , container
  , styledContainer
  , containerResponse
  , mouseArea
  , inertContainer
  , clipContainer
  , withContainerNode
  , withWidgetChildren
  , floatingPanel
  , dropdownInput
  , dropdownBodyInput
  , inDropdownScope
  , addWidget
  , addWidgetVoid
  , addWidgetStyled
  , addWidgetNode
  , addWidgetWithOptions
  , tagContainer
  , setWidgetValue
  , moveSelection
  , resolveInteraction
  )
where

import Control.Monad (forM, forM_, unless, when)
import Data.Bits ((.|.))
import Data.IORef (readIORef)
import Data.IntSet qualified as IS
import Data.Map.Strict qualified as M
import Data.Text (Text)
import Data.Word (Word64)
import NanoUI.Internal.Context
import NanoUI.Internal.Context.Types (peekContainer, popContainer, pushContainer)
import NanoUI.Internal.Id (WidgetId (..), hashWidgetId, mix64, scopeIdContext, scopeTag)
import NanoUI.Internal.Id.Cursor (popIdScope, pushIdScope)
import NanoUI.Internal.Input
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Monad (NanoUI, (<&&>), askContext, askDefaultLayout, askFrameInput, askInput, currentId, inertView, localInput, nextId, liftIO, withContext, withIdFrame, withKey)
import NanoUI.Internal.WidgetText (containerFlagClip, containerFlagInert, labelFontStyle, packTextNodeStyle)
import NanoUI.Internal.Style (Layout (..), tight)
import NanoUI.Internal.Types (Rect (..), V2, rectContains, rectH, rectUnion, rectW)
import NanoUI.Internal.Frame.Hit (findNodeByWidgetId, nodeInteractionHit, passesPointer, withWidgetNode)

-- | The innermost open container, or @-1@ at the root.
{-# INLINE currentParent #-}
currentParent :: Context -> IO Int
currentParent ctx = peekContainer (ctxContainerStack ctx)

-- | Anything that carries a widget 'Response' (composite widget results such
-- as 'NanoUI.TabResponse'). The @resp*@ accessors work on all of them.
class HasResponse r where
  toResponse :: r -> Response

instance HasResponse Response where
  {-# INLINE toResponse #-}
  toResponse = id

-- | Widget identity used for state, tooltips, and commands.
{-# INLINE respId #-}
respId :: HasResponse r => r -> WidgetId
respId = rawRespId . toResponse

-- | Widget bounds in logical window coordinates. During view construction,
-- these come from the previous frame and can be empty on first appearance.
{-# INLINE respRect #-}
respRect :: HasResponse r => r -> Rect
respRect = rawRespRect . toResponse

-- | Whether the routed pointer is over the widget's visible hit area.
{-# INLINE respHovered #-}
respHovered :: HasResponse r => r -> Bool
respHovered = rawRespHovered . toResponse

-- | 'respHeldWith' 'MouseLeft'. A held state, not a one-frame button-down
-- event.
{-# INLINE respPressed #-}
respPressed :: HasResponse r => r -> Bool
respPressed = respHeldWith MouseLeft

-- | Whether the widget was activated this frame: a left click, or whatever
-- key activates it while focused (usually Enter or Space). For clicks of a
-- specific button only, use 'respClickedWith'.
{-# INLINE respClicked #-}
respClicked :: HasResponse r => r -> Bool
respClicked = rawRespClicked . toResponse

-- | Whether the widget reports a value change. Search fields debounce this flag.
{-# INLINE respChanged #-}
respChanged :: HasResponse r => r -> Bool
respChanged = rawRespChanged . toResponse

-- | Whether the widget reports a commit, such as Enter in a text field.
{-# INLINE respSubmitted #-}
respSubmitted :: HasResponse r => r -> Bool
respSubmitted = rawRespSubmitted . toResponse

-- | Whether the button went down on the widget and is held over it. A
-- button pressed elsewhere and dragged over does not count.
--
-- > (_, area) <- mouseArea id (label "Pan me")
-- > when (respHeldWith MouseMiddle area) (pan =<< uiMousePos)
{-# INLINE respHeldWith #-}
respHeldWith :: HasResponse r => MouseButton -> r -> Bool
respHeldWith b = buttonsMember b . rawRespHeld . toResponse

-- | Whether the button was pressed and released on the widget this frame.
-- Non-left clicks are reported only here, for the view to handle (a middle
-- click closing a tab, say). Left clicks also set 'respClicked'.
{-# INLINE respClickedWith #-}
respClickedWith :: HasResponse r => MouseButton -> r -> Bool
respClickedWith b = buttonsMember b . rawRespClickedWith . toResponse

-- | 'respHeldWith' 'MouseRight'.
{-# INLINE respRightPressed #-}
respRightPressed :: HasResponse r => r -> Bool
respRightPressed = respHeldWith MouseRight

-- | 'respClickedWith' 'MouseRight'.
{-# INLINE respRightClicked #-}
respRightClicked :: HasResponse r => r -> Bool
respRightClicked = respClickedWith MouseRight

-- | Per-frame widget identity, bounds, and interaction flags. Primed widget
-- variants expose this alongside their value. Combining responses unions
-- bounds, flags and buttons, and keeps the last nonzero id.
data Response = Response
  { rawRespId :: {-# UNPACK #-} !WidgetId
  , rawRespRect :: {-# UNPACK #-} !Rect
  , rawRespHovered :: !Bool
  , rawRespClicked :: !Bool
  , rawRespChanged :: !Bool
  , rawRespSubmitted :: !Bool
  , rawRespHeld :: {-# UNPACK #-} !MouseButtons
  -- ^ See 'respHeldWith'.
  , rawRespClickedWith :: {-# UNPACK #-} !MouseButtons
  -- ^ See 'respClickedWith'.
  }
  deriving (Eq, Show)

instance Semigroup Response where
  Response i1 r1 h1 c1 ch1 s1 held1 cw1 <> Response i2 r2 h2 c2 ch2 s2 held2 cw2 =
    Response
      (if i2 == WidgetId 0 then i1 else i2)
      (unionRespRect r1 r2)
      (h1 || h2) (c1 || c2) (ch1 || ch2) (s1 || s2) (held1 <> held2) (cw1 <> cw2)

instance Monoid Response where
  mempty = mkResponse (WidgetId 0) (Rect 0 0 0 0) False False False

unionRespRect :: Rect -> Rect -> Rect
unionRespRect a b
  | rectW a <= 0 || rectH a <= 0 = b
  | rectW b <= 0 || rectH b <= 0 = a
  | otherwise = rectUnion a b

-- | Replace only the activation flag, for composite widgets.
{-# INLINE setClicked #-}
setClicked :: Bool -> Response -> Response
setClicked c r = if rawRespClicked r == c then r else r {rawRespClicked = c}

-- | Replace only the value-change flag.
{-# INLINE setChanged #-}
setChanged :: Bool -> Response -> Response
setChanged c r = if rawRespChanged r == c then r else r {rawRespChanged = c}

-- | Replace only the commit flag.
{-# INLINE setSubmitted #-}
setSubmitted :: Bool -> Response -> Response
setSubmitted s r = if rawRespSubmitted r == s then r else r {rawRespSubmitted = s}

-- | The response of a control that takes no input: its id and rect, and no
-- interaction.
inertResponse :: Response -> Response
inertResponse r =
  r {rawRespHovered = False, rawRespClicked = False, rawRespHeld = noButtons, rawRespClickedWith = noButtons}

-- | An unpressed response with the given hover, click, and change flags.
mkResponse :: WidgetId -> Rect -> Bool -> Bool -> Bool -> Response
mkResponse wid rect hovered clicked changed =
  Response wid rect hovered clicked changed False noButtons noButtons

container :: NodeType -> Layout -> NanoUI a -> NanoUI a
container nt layout child = do
  ctx <- askContext
  liftIO $ do
    parent <- currentParent ctx
    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout
    pushContainer (ctxContainerStack ctx) idx
    pushIdScope (ctxIdCursor ctx) scopeTag
  r <- child
  liftIO $ do
    popContainer (ctxContainerStack ctx)
    popIdScope (ctxIdCursor ctx)
  pure r

-- | A display-only container: child widgets receive no interaction, and
-- pointer events pass through to the enclosing widget
-- ('NanoUI.Internal.Frame.Hit.innermostHit').
inertContainer :: Layout -> NanoUI a -> NanoUI a
inertContainer layout = styledContainer NodeContainer containerFlagInert layout . inertView

-- | A plain container that clips its children to its rect, drawing none of
-- its own. It takes a fresh id, so the pointer is clipped from the frame
-- after it is laid out.
clipContainer :: Layout -> NanoUI a -> NanoUI a
clipContainer layout child = do
  wid <- nextId
  styledContainer NodeContainer containerFlagClip layout (tagContainer wid *> child)

-- | A 'container' of type @nt@ with style index @si@: a plain container's
-- flags, or a panel's row fill (@panelSurface@).
styledContainer :: NodeType -> Word64 -> Layout -> NanoUI a -> NanoUI a
styledContainer nt si layout child = do
  ctx <- askContext
  liftIO $ do
    parent <- currentParent ctx
    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout
    when (si /= 0) (setStyleIdx (ctxNodeArena ctx) idx si)
    pushContainer (ctxContainerStack ctx) idx
    pushIdScope (ctxIdCursor ctx) scopeTag
  r <- child
  liftIO $ do
    popContainer (ctxContainerStack ctx)
    popIdScope (ctxIdCursor ctx)
  pure r

-- | Whether @mouse@ reaches container @wid@: neither covered, disabled, nor
-- outside its enclosing clip from last frame.
pointerReachable :: Context -> WidgetId -> V2 -> IO Bool
pointerReachable ctx wid mouse =
  (not <$> pointerCovered ctx wid)
    <&&> (not <$> isDisabled ctx wid)
    <&&> (maybe True (`rectContains` mouse) <$> getPrevClipRect ctx wid)

-- | Whether @mouse@ is on an enabled, uncovered widget node in @[from .. to)@.
anyControlHitInRange :: Context -> V2 -> Int -> Int -> IO Bool
anyControlHitInRange ctx mouse from to = go from
  where
    na = ctxNodeArena ctx
    go !i
      | i >= to = pure False
      | otherwise = do
          hit <-
            (isWidgetNode <$> getNodeType na i) <&&> do
              w <- getWidgetId na i
              (not <$> isDisabled ctx w)
                <&&> (not <$> pointerCovered ctx w)
                <&&> (maybe (pure False) (\r -> nodeInteractionHit ctx i r mouse) =<< getPrevRect ctx w)
          if hit then pure True else go (i + 1)

-- | A 'container' tagged with a fresh id, and its interaction under that id.
containerResponse :: NodeType -> Layout -> NanoUI a -> NanoUI (a, Response)
containerResponse nt layout child = do
  wid <- nextId
  inp <- askInput
  r <- container nt layout (tagContainer wid >> child)
  resp <- withContext (\ctx -> resolveInteraction ctx inp (-1) wid)
  pure (r, resp)

-- | An unpadded column that reports pointer activity over itself and its
-- contents, like iced's @mouse_area@: 'respHovered', 'respHeldWith',
-- 'respClickedWith' and 'respClicked'. A press on an interactive child (a
-- button, field or slider) belongs to that child, whichever mouse button it
-- is; presses on passive content such as labels, and between children, go
-- to the area. Children do not cover the area, so hover stays true while the
-- pointer is over them:
--
-- > hovered <- useVar False
-- > (_, item) <- mouseArea (fillW . gap 6) $ do
-- >   label name
-- >   whenM (readVar hovered) (void (button "Delete"))
-- > writeVar hovered (respHovered item)
-- > when (respClickedWith MouseMiddle item) (openInNewTab name)
mouseArea :: (Layout -> Layout) -> NanoUI a -> NanoUI (a, Response)
mouseArea f body = do
  base <- askDefaultLayout
  containerResponse NodeContainer (f (tight base)) body

-- | Push container node @idx@ (already added under the current parent), run
-- @child@ inside it, then pop. @scoped@ also runs the children in a fresh id
-- scope; it changes the children's widget ids (and so their store keys), so
-- callers pick it explicitly: plain containers scope, scroll containers do not.
--
-- Like every view build scope, it installs no exception handler
-- ('NanoUI.Internal.Monad.withBuildScope'); 'NanoUI.Internal.Monad.catchView'
-- restores the container stack for a view that recovers.
withContainerNode :: Bool -> NodeIdx -> NanoUI a -> NanoUI a
withContainerNode scoped idx child = do
  ctx <- askContext
  liftIO $ do
    pushContainer (ctxContainerStack ctx) idx
    when scoped $ pushIdScope (ctxIdCursor ctx) scopeTag
  r <- child
  liftIO $ do
    popContainer (ctxContainerStack ctx)
    when scoped $ popIdScope (ctxIdCursor ctx)
  pure r

-- | Run @child@ inside the node of widget @wid@, just added, in the id scope
-- the widget's id opens, so its siblings' ids do not move; 'Nothing' when it
-- has no node.
withWidgetChildren :: WidgetId -> NanoUI a -> NanoUI (Maybe a)
withWidgetChildren wid@(WidgetId w) child = do
  mIdx <- withContext (\ctx -> lookupNodeByWidgetId (ctxNodeArena ctx) wid)
  forM mIdx $ \idx ->
    withContainerNode False idx (withIdFrame (\ids -> (ids, scopeIdContext (mix64 w scopeTag))) child)

-- | A floating panel (popup, modal, window): its node attaches to the root
-- layer, and @body@ runs as a layer of its own, with the pointer when the
-- panel is what the frame routed it to. @addPanel@ adds the node under the
-- given parent; @enter@ runs once the node is pushed (seeding its rect,
-- opening a modal). The body runs in a fresh id scope.
floatingPanel ::
  WidgetId -> (Int -> IO NodeIdx) -> IO () -> NanoUI a -> NanoUI a
floatingPanel wid addPanel enter body = do
  ctx <- askContext
  let arena = ctxNodeArena ctx
  idx <- liftIO $ do
    idx <- addPanel =<< rootAttachParent arena =<< currentParent ctx
    setWidgetId arena idx wid
    pure idx
  withContainerNode True idx $ do
    -- A modal has to be entered first: that is what lets its own body through.
    liftIO enter
    frame <- askFrameInput
    inp <- liftIO (routedInput ctx (intKey wid) frame)
    localInput inp body

-- | Run @body@ in the keyed scope that holds field @owner@'s dropdown popup:
-- the popup is the first id the scope issues, so 'dropdownInput' knows its
-- key before it is declared.
inDropdownScope :: WidgetId -> NanoUI a -> NanoUI a
inDropdownScope owner = withKey (intKey owner, dropdownScopeTag)

dropdownScopeTag :: Text
dropdownScopeTag = "dropdown"

-- | The input for field @owner@ of a dropdown it declares in
-- 'inDropdownScope': the frame's while the pointer is routed to that
-- dropdown, and the view's otherwise.
dropdownInput :: WidgetId -> NanoUI Input
dropdownInput owner = do
  popup <- inDropdownScope owner currentId
  withContext (\ctx -> getsInteraction ctx isPointerRoute) >>= \case
    RouteDropdown k | k == intKey popup -> askFrameInput
    _ -> askInput

-- | The input for the body of field @owner@'s dropdown popup: its layer's,
-- or the frame's while the left press that went down on @owner@ is held, so
-- that a press on the field released on a row picks that row.
dropdownBodyInput :: WidgetId -> NanoUI Input
dropdownBodyInput owner = do
  inp <- askInput
  active <- withContext (readIORef . ctxActiveId)
  if active == owner && hashWidgetId owner /= 0 then askFrameInput else pure inp

{-# INLINE addWidget #-}
addWidget ::
  WidgetId
  -> NodeType
  -> Text
  -> Float
  -> Layout
  -> NanoUI Response
addWidget wid nt txt value layout = addWidgetStyled wid nt txt value layout 0

-- | Add a passive node (such as a plain label) without computing an
-- interaction 'Response'.
{-# INLINE addWidgetVoid #-}
addWidgetVoid ::
  WidgetId
  -> NodeType
  -> Text
  -> Float
  -> Layout
  -> NanoUI ()
addWidgetVoid wid nt txt value layout = do
  ctx <- askContext
  liftIO $ do
    parent <- currentParent ctx
    let na = ctxNodeArena ctx
    idx <- addNodeFromLayout na nt parent layout
    setNodeText na idx txt
    setNodeValue na idx value
    setStyleIdx na idx $ case nt of
      NodeText -> packTextNodeStyle layout 0
      NodeButton -> labelFontStyle layout
      _ -> 0
    setWidgetId na idx wid

{-# INLINE addWidgetStyled #-}
addWidgetStyled ::
  WidgetId
  -> NodeType
  -> Text
  -> Float
  -> Layout
  -> Word64
  -> NanoUI Response
addWidgetStyled wid nt txt value layout styleIdx =
  addWidgetNode wid nt txt value layout $ \arena idx ->
    setStyleIdx arena idx $ case nt of
      NodeText -> packTextNodeStyle layout (fromIntegral styleIdx)
      NodeButton -> styleIdx .|. labelFontStyle layout
      _ -> styleIdx

-- The initializer specializes at each call site; the node allocation, identity
-- and interaction path are shared by styled leaves and option controls.
{-# INLINE addWidgetNode #-}
addWidgetNode ::
  WidgetId
  -> NodeType
  -> Text
  -> Float
  -> Layout
  -> (NodeArena -> NodeIdx -> IO ())
  -> NanoUI Response
addWidgetNode wid nt txt value layout initialize = do
  ctx <- askContext
  inp <- askInput
  liftIO $ do
    parent <- currentParent ctx
    idx <- addNodeFromLayout (ctxNodeArena ctx) nt parent layout
    setNodeText (ctxNodeArena ctx) idx txt
    setNodeValue (ctxNodeArena ctx) idx value
    initialize (ctxNodeArena ctx) idx
    setWidgetId (ctxNodeArena ctx) idx wid
    resolveInteraction ctx inp idx wid

addWidgetWithOptions ::
  WidgetId
  -> NodeType
  -> Text
  -> [Text]
  -> Float
  -> Layout
  -> NanoUI Response
addWidgetWithOptions wid nt txt opts value layout =
  addWidgetNode wid nt txt value layout $ \arena idx -> do
    setOptions arena idx opts
    setStyleIdx arena idx (if nt == NodeSelect then labelFontStyle layout else 0)

-- | Whether @mouse@ is on widget @wid@ (last frame's @rect@, node @mIdx@):
-- inside its scroll-visible part ('nodeInteractionHit'), not covered by
-- another pointer-taking node ('pointerCovered'), and not 'passesPointer'.
-- Disabled and drag-capture checks are left to the caller.
pointerOnWidget :: Context -> Maybe NodeIdx -> WidgetId -> Rect -> V2 -> IO Bool
pointerOnWidget ctx mIdx wid rect mouse =
  (not <$> pointerCovered ctx wid)
    <&&> (not <$> maybe (pure False) (passesPointer (ctxNodeArena ctx)) mIdx)
    <&&> widgetHit ctx mIdx rect mouse

-- | Whether @p@ is inside the scroll-visible part of @rect@
-- ('nodeInteractionHit'), or inside @rect@ when there is no node.
widgetHit :: Context -> Maybe NodeIdx -> Rect -> V2 -> IO Bool
widgetHit ctx mIdx rect p = maybe (pure (rectContains rect p)) (\idx -> nodeInteractionHit ctx idx rect p) mIdx

-- | The interaction of widget @wid@, declared as node @idx@ (or -1), with
-- the pointer and buttons of @inp@, judged against its last-frame rect.
-- Inlined so unhovered widgets whose callers only inspect 'respClicked' or
-- discard the 'Response' never allocate it.
{-# INLINE resolveInteraction #-}
resolveInteraction :: Context -> Input -> NodeIdx -> WidgetId -> IO Response
resolveInteraction ctx inp idx wid = do
  rect <- getPrevRectAt ctx idx wid
  pending <- readIORef (ctxClickedId ctx)
  if not (rectContains rect (inputMousePos inp) || pending == wid)
    then pure $! mkResponse wid rect False False False
    else resolveInteractionSlow ctx inp wid rect pending

{-# NOINLINE resolveInteractionSlow #-}
resolveInteractionSlow :: Context -> Input -> WidgetId -> Rect -> WidgetId -> IO Response
resolveInteractionSlow ctx inp wid rect pending = do
  let mouse = inputMousePos inp
  active <- readIORef (ctxActiveId ctx)
  disabled <- isDisabled ctx wid
  mIdx <- findNodeByWidgetId ctx wid
  presses <- readIORef (ctxPressPos ctx)
  let
    -- Whether the button press started on this widget, in the frame the
    -- user saw: a left press on the widget it reached or one of its
    -- ancestors, another button only on the widget itself. A press that
    -- reached nothing (passive content) is judged by this widget's
    -- rect, and one with no record (synthesized or swallowed input) is
    -- allowed.
    startedHere b = case M.lookup b presses of
      Just PressPoint {ppOwner = Just owner, ppReached = reached}
        | b /= MouseLeft -> pure (owner == wid)
        | otherwise -> pure (IS.member (intKey wid) reached)
      Just PressPoint {ppPos = p} -> widgetHit ctx mIdx rect p
      Nothing -> pure True
  -- A held left button belongs to the widget it went down on; others
  -- the drag passes over are not hovered.
  -- A container the press went down inside (a mouse area around the
  -- pressed button) keeps its hover.
  enclosing <- maybe (pure False) (fmap (not . isWidgetNode) . getNodeType (ctxNodeArena ctx)) mIdx
  captured <-
    pure (heldIn MouseLeft inp)
      <&&> if hashWidgetId active /= 0 && active /= wid && not enclosing
        then pure True
        else not <$> startedHere MouseLeft
  -- Covered widgets and 'PointerPass' nodes get no hover.
  hovered <- pure (not (disabled || captured)) <&&> pointerOnWidget ctx mIdx wid rect mouse
  -- Other buttons count only if pressed here. A hovered widget already
  -- owns a held left button.
  let ownedHere bs = if hovered then buttonsFilterM startedHere bs else pure noButtons
      leftHeld = if hovered && heldIn MouseLeft inp then buttonsInsert MouseLeft noButtons else noButtons
  held <- (leftHeld <>) <$> ownedHere (buttonsDelete MouseLeft (inputButtonsHeld inp))
  released <- ownedHere (inputButtonsReleased inp)
  -- The click belongs to whatever the press went down on: a release that
  -- drifted here from a neighbouring widget is not this widget's click,
  -- nor is one on a widget that moved under the pointer after another
  -- widget took the press.
  let ownsRelease = hashWidgetId active == 0 || active == wid
      clickedWith = if ownsRelease then released else buttonsDelete MouseLeft released
      leftClicked = buttonsMember MouseLeft clickedWith
      clicked = leftClicked || pending == wid
  pure $! Response wid rect hovered clicked False False held clickedWith

-- | Set the value of widget @wid@'s node, added this frame: a checkbox
-- showing the click read after it was added.
setWidgetValue :: Context -> WidgetId -> Float -> IO ()
setWidgetValue ctx wid v = withWidgetNode ctx wid () (\i -> setNodeValue (ctxNodeArena ctx) i v)

-- | Move a group's selection, which its members' values mark, from member
-- @old@ to member @new@. The members were added with @old@ selected, since the
-- click or key that moves it is read after them.
moveSelection :: Eq k => Context -> k -> k -> [(k, Response)] -> IO ()
moveSelection ctx old new members =
  unless (old == new) $ forM_ members $ \(k, r) ->
    when (k == old || k == new) $ setWidgetValue ctx (rawRespId r) (if k == new then 1 else 0)

-- | Stamp the current container with a widget id (a radio or tree group key),
-- so store keys and damage requests under that id resolve to the container.
-- Containers are never hot, so the id does not make it hoverable.
tagContainer :: WidgetId -> NanoUI ()
tagContainer wid = do
  withContext $ \ctx -> do
    parent <- currentParent ctx
    when (parent >= 0) $ setWidgetId (ctxNodeArena ctx) parent wid