nano-ui-0.2.0.0: lib/NanoUI/Internal/Widgets/Popup.hs
-- | Anchored floating panels controlled by mutable state ('Var'), and tooltips.
module NanoUI.Internal.Widgets.Popup
( PopupAnchor (..)
, PopupPlacement (..)
, PopupConfig (..)
, defaultPopupConfig
, popup
, popup'
, popupWith
, popupWith'
, bindOpen
, floatingOverlay
, tooltipWidget
, tooltipAt
, tooltip
, withTooltip
, TooltipConfig (..)
, defaultTooltipConfig
, tooltipConfigured
, tooltipWidgetConfigured
)
where
import Control.Monad (void, when)
import Data.IntMap.Strict qualified as IM
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import GHC.Clock (getMonotonicTime)
import NanoUI.Internal.Context
import NanoUI.Internal.Id (WidgetId)
import NanoUI.Internal.Input
import NanoUI.Internal.Frame.Hit (findNodeByWidgetId)
import NanoUI.Internal.Layout.Arena (NodeIdx, NodeType (..), addNodeFromLayout)
import NanoUI.Internal.Monad
import NanoUI.Internal.Store (deleteSpec, findSpec, insertSpec)
import NanoUI.Internal.Store.Slots (slotTooltipShow)
import NanoUI.Internal.Style
import NanoUI.Internal.Tasks (holdAction)
import NanoUI.Internal.Types
import NanoUI.Internal.Var (Binding (..), bindVar)
import NanoUI.Internal.Var.Types (Var, constVar)
import NanoUI.Internal.Widgets.Behavior (useDismissable)
import NanoUI.Internal.Widgets.Layout (label)
import NanoUI.Internal.Widgets.Node
-- | Anchor, preferred side, dismissal, and gap in logical pixels.
-- Anchors use logical window coordinates.
data PopupConfig = PopupConfig
{ popupAnchor :: !PopupAnchor
, popupPlacement :: !PopupPlacement
, popupDismissable :: !Bool
-- ^ Close on Escape and on a press outside the panel and an 'AnchorRect'.
, popupOffset :: !Float
}
deriving (Eq, Show)
-- | Automatic placement with a 4-pixel gap and dismissal enabled.
defaultPopupConfig :: PopupAnchor -> PopupConfig
defaultPopupConfig anchor =
PopupConfig
{ popupAnchor = anchor
, popupPlacement = PlacementAuto
, popupDismissable = True
, popupOffset = 4
}
-- | A floating panel placed by the config, shown while the Var holds
-- 'True'. A dismissal (Escape or a click outside, when 'popupDismissable')
-- writes 'False', so the panel closes in the same frame. A press on an
-- 'AnchorRect' is not outside, so a button that toggles the Var on
-- 'respClicked' closes the popup rather than closing and reopening it. The
-- panel fits its body, however tall: for a body that could outgrow the
-- window, cap the panel through 'popupWith' ('NanoUI.maxH') and scroll the
-- body in a 'NanoUI.scrollWith' that 'NanoUI.grow's.
--
-- > filterOpen <- useVar False
-- > filterR <- button' "Filter"
-- > when (respClicked filterR) (modifyVar filterOpen not)
-- > popup filterOpen (defaultPopupConfig (AnchorRect (respRect filterR))) $ do
-- > checkbox "Fruit" showFruit
--
-- For an open flag derived from other state, or one the caller may refuse
-- to clear, pass a constant and act on the response from 'popup'' instead.
popup :: Var Bool -> PopupConfig -> NanoUI () -> NanoUI ()
popup open cfg child = void (popupWith' open cfg id child)
-- | 'popup' returning the body's result while open, and a 'Response' that
-- reports a dismissal as a click.
popup' :: Var Bool -> PopupConfig -> NanoUI a -> NanoUI (Response, Maybe a)
popup' open cfg = popupWith' open cfg id
-- | 'popup' with a modifier applied to its tight default layout.
popupWith :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI () -> NanoUI ()
popupWith open cfg f child = void (popupWith' open cfg f child)
-- | 'popupWith' returning the body's result and the 'Response'.
popupWith' :: Var Bool -> PopupConfig -> (Layout -> Layout) -> NanoUI a -> NanoUI (Response, Maybe a)
popupWith' open cfg f child = bindOpen open $ \shown -> do
ctx <- askContext
let -- The popup's padding and gap are defaults the caller's modifier can change.
layout = f ((tight defaultLayout) {layoutPadding = Padding 6 6 6 6, layoutGap = 4})
addPopupNode wid parent = do
registerPopupConfig ctx wid (popupAnchor cfg) (popupPlacement cfg) (popupOffset cfg)
addNodeFromLayout (ctxNodeArena ctx) NodePopup parent layout
dismiss
| not (popupDismissable cfg) = Nothing
| AnchorRect r <- popupAnchor cfg = Just r
| otherwise = Just (Rect 0 0 0 0)
floatingOverlay shown dismiss addPopupNode (pure ()) ((,) False <$> child)
-- | Bind a floating panel's open state to a 'Var', mutating it to 'False' when
-- the panel reports a dismissal. Because the panel nodes were already emitted
-- before dismissal is resolved, closing triggers a re-render.
{-# INLINE bindOpen #-}
bindOpen :: Var Bool -> (Bool -> NanoUI (Response, Maybe a)) -> NanoUI (Response, Maybe a)
bindOpen v run = bindVar Conservative v $ \open -> do
r <- run open
let !keep = open && not (respClicked (fst r))
pure (r, keep)
-- | The floating panel behind popups, modals and windows, shown while @open@
-- with its body in its own id scope. @addPanel@, given the panel's id, and
-- @enter@ are those of 'floatingPanel'. The body returns whether it closed
-- the panel along with its result. The 'Response' reports a dismissal (the
-- body's close, Escape, or a click outside when @dismiss@ is 'Just' the rect
-- of what opened the panel, where a press is not outside) as a click. A
-- closed panel still consumes its id scope, so the ids of later siblings do
-- not shift when it opens.
floatingOverlay ::
Bool ->
Maybe Rect ->
(WidgetId -> Int -> IO NodeIdx) ->
IO () ->
NanoUI (Bool, a) ->
NanoUI (Response, Maybe a)
floatingOverlay open dismiss addPanel enter body = do
(wid, _) <- freshWidget
if not open
then do
burstNextIds 1
pure (mempty {rawRespId = wid}, Nothing)
else do
-- Hover uses the pointer routed to the panel's layer, so layers in
-- front of the panel occlude hover.
(mouse, (closed, r)) <-
floatingPanel wid (addPanel wid) enter ((,) <$> uiMousePos <*> body)
panel <- fromMaybe (Rect 0 0 0 0) <$> lastRect wid
outside <- case dismiss of
Just opener | rectNonEmpty panel -> useDismissable wid panel opener
_ -> pure False
let dismissed = closed || outside
pure
( mkResponse wid panel (rectContains panel mouse) dismissed dismissed
, Just r
)
-- | When a tooltip opens, and where.
data TooltipConfig = TooltipConfig
{ tooltipDelay :: !Double
-- ^ Seconds the pointer must rest on the target before the tooltip
-- opens; 0 opens it at once. Moving within the target does not restart it.
, tooltipGrace :: !Double
-- ^ Seconds after the last tooltip closed during which this one skips its
-- delay, so the pointer can sweep along a toolbar reading each tooltip.
, tooltipPlacement :: !PopupPlacement
-- ^ The side of the target to open on. 'PlacementAtCursor' instead puts
-- it below the pointer (above if there is no room) and follows it.
, tooltipGap :: !Float
-- ^ Logical pixels between the tooltip and its target or the pointer.
}
deriving (Eq, Show)
-- | 4 pixels below the target, after a 0.5 s rest, or at once within 0.3 s
-- of another tooltip.
defaultTooltipConfig :: TooltipConfig
defaultTooltipConfig =
TooltipConfig
{ tooltipDelay = 0.5
, tooltipGrace = 0.3
, tooltipPlacement = PlacementBelow
, tooltipGap = 4
}
-- | Attach a rich tooltip widget to any target response, shown once the
-- pointer rests on it ('defaultTooltipConfig').
tooltipWidget ::
HasResponse r =>
r ->
NanoUI () ->
NanoUI ()
tooltipWidget = tooltipWidgetConfigured defaultTooltipConfig
-- | 'tooltipWidget' with a configured delay, placement and gap. The target
-- counts as hovered when the routed pointer is on its visible, uncovered
-- part ('pointerOnWidget'), even when disabled or inert.
tooltipWidgetConfigured ::
HasResponse r =>
TooltipConfig ->
r ->
NanoUI () ->
NanoUI ()
tooltipWidgetConfigured cfg target child = do
-- The id 'popup' takes next; the timer is keyed on it to avoid using a
-- sibling id.
wid <- currentId
ctx <- askContext
frame <- askFrameInput
routed <- inputMousePos <$> askInput
let V2 mx my = inputMousePos frame
follow = tooltipPlacement cfg == PlacementAtCursor
rect = respRect target
tid = respId target
hovered <-
if rectContains rect routed
then liftIO (findNodeByWidgetId ctx tid >>= \mIdx -> pointerOnWidget ctx mIdx tid rect routed)
else pure False
(open, armed) <- liftIO (tooltipTimer ctx cfg (intKey wid) hovered frame)
-- Request a frame when the pointer enters or leaves the target, even a
-- label or container, and on every move while a following tooltip is open.
liftIO (registerHoverZone ctx (open && follow) rect)
let (anchor, placement)
| follow = (AnchorRect (Rect mx my 0 pointerClearance), PlacementBelow)
| otherwise = (AnchorRect rect, tooltipPlacement cfg)
void $
popupWith'
(constVar open)
((defaultPopupConfig anchor) {popupPlacement = placement, popupDismissable = False, popupOffset = tooltipGap cfg})
(pointer PointerPass)
(inertView child)
-- Clear the stored timestamp when a tooltip is no longer declared
-- ('holdAction'), so if it reappears later it waits for the full delay
-- rather than opening immediately or ending other tooltips' delays. The
-- hook consumes one id on both branches.
if armed
then scope (holdAction (modifyStore ctx (deleteSpec slotTooltipShow (intKey wid))))
else burstNextIds 1
-- | Offset below the pointer's hot spot for a following tooltip, before the
-- gap: roughly an arrow cursor's height, so the cursor does not cover it.
pointerClearance :: Float
pointerClearance = 16
-- | Whether the tooltip with store key @k@ is open this frame, and whether it
-- keeps a time (waits or shows) for the next frame. The delay
-- starts when the target becomes @hovered@ and ends after 'tooltipDelay', or
-- at once within 'tooltipGrace' of the last tooltip closing. A held button
-- keeps the tooltip shut and restarts the delay on release; a wheel turn
-- restarts it. Both also end the grace period.
--
-- The times live in quiet store slots, which neither damage nor wake.
-- Opening and closing repaint as a floating panel, and the opening frame is
-- scheduled with 'requestWakeAt', so an idle app draws nothing while waiting.
tooltipTimer :: Context -> TooltipConfig -> Int -> Bool -> Input -> IO (Bool, Bool)
tooltipTimer ctx cfg k hovered inp = do
store <- getStore ctx
let showAt0 = findSpec slotTooltipShow 0 k store
lastUp0 = findSpec slotTooltipShow 0 0 store
held = inputPointerHeld inp
interrupted = anyButtonPressed inp || inputScroll inp /= V2 0 0
-- Fast path: most targets are not near the pointer.
if not hovered && showAt0 == 0 && (lastUp0 == 0 || not interrupted)
then pure (False, False)
else do
now <- getMonotonicTime
let micros t = round (t * 1e6) :: Int
nowUs = micros now
delayUs = micros (max 0 (tooltipDelay cfg))
graceUs = micros (tooltipGrace cfg)
-- No frames run while a tooltip sits open, so the closing frame
-- counts as the last one it was up.
wasUp = showAt0 > 0 && nowUs >= showAt0
starting = hovered && not held && not interrupted && showAt0 == 0
-- A tooltip open last frame whose call comes after this one has
-- not yet recorded closing.
otherUp = any (\k' -> k' /= k && findSpec slotTooltipShow 0 k' store > 0) . IM.keys
warm <-
if not starting || graceUs <= 0 || lastUp0 == 0
then pure False
else (nowUs - lastUp0 < graceUs ||) . otherUp <$> getsOverlay ctx osPrevFloatingRects
let showAt
| not hovered || held = 0
| interrupted = nowUs + delayUs
| showAt0 > 0 = showAt0
| warm = nowUs
| otherwise = nowUs + delayUs
open = showAt > 0 && nowUs >= showAt
lastUp
| interrupted = 0
| open || wasUp = nowUs
| otherwise = lastUp0
set key v = if v > 0 then insertSpec slotTooltipShow key v else deleteSpec slotTooltipShow key
when (showAt /= showAt0 || lastUp /= lastUp0) $
modifyStore ctx (set k showAt . set 0 lastUp)
when (showAt > 0 && not open) $
requestWakeAt ctx (fromIntegral showAt / 1e6)
pure (open, showAt > 0)
-- | Attach a rich tooltip widget to an inner UI computation.
withTooltip ::
NanoUI a ->
NanoUI () ->
NanoUI a
withTooltip mainChild tipChild = do
(res, contResp) <- mouseArea id mainChild
res <$ tooltipWidget contResp tipChild
-- | 'tooltip' with a placement. 'PlacementAtCursor' follows the pointer.
tooltipAt ::
HasResponse r =>
PopupPlacement ->
r ->
Text ->
NanoUI ()
tooltipAt placement = tooltipConfigured defaultTooltipConfig {tooltipPlacement = placement}
-- | 'tooltip' with a configured delay and placement.
--
-- > tooltipConfigured defaultTooltipConfig {tooltipPlacement = PlacementAtCursor} swatch name
tooltipConfigured ::
HasResponse r =>
TooltipConfig ->
r ->
Text ->
NanoUI ()
tooltipConfigured cfg target txt = void (tooltipWidgetConfigured cfg target (label txt))
-- | Text shown below a widget after the pointer rests on it for half a
-- second, until it leaves or a button is pressed ('defaultTooltipConfig').
--
-- > save <- button' "Save"
-- > tooltip save "Write the file to disk"
tooltip ::
HasResponse r =>
r ->
Text ->
NanoUI ()
tooltip = tooltipConfigured defaultTooltipConfig