packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Frame/Spans.hs

-- | Collect positioned and clipped text for external renderers and headless tests.
module NanoUI.Internal.Frame.Spans
  ( collectTextSpans
  , collectOverlayTextSpans
  , collectRasterSpans
  , widgetNodeCount
  , cachedWidgetLabel
  , forWidgetTextPlacements_
  , selectableTextGeometry
  , textNodeSpanEntry
  ) where

import Control.Monad (forM, forM_, join, unless, when)
import Data.IORef (readIORef, writeIORef)
import qualified Data.IntMap.Strict as IM
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Data.Word (Word64)
import NanoUI.Internal.Context
import NanoUI.Internal.Damage (floatingPanelRects)
import NanoUI.Internal.Draw (DrawArena (..), DrawFrameExtra (..))
import NanoUI.Internal.Font
import NanoUI.Internal.Frame.Chrome (displayText, textInputFocused, textInputValue, widgetVisualStyle)
import NanoUI.Internal.Frame.Node (childPaintClip, nodeAdornmentInsets, readScrollNode, resolveFontFor)
import NanoUI.Internal.Layout.ScrollGeometry (padContentClip, padTextClipRect, scrollNodeViewport, tagClippedSpans)
import NanoUI.Internal.Frame.Select (collectDropdownSpans)
import NanoUI.Internal.Frame.SpanArena (SpanArena, pushSpans, resetSpanArena, spanArenaToList)
import NanoUI.Internal.Frame.TextArea (textAreaTextPlacements)
import NanoUI.Internal.Frame.TextInput (TextInputFrame (..), nodeTextColor, nodeTextFieldGeom, resolveTextInputFrame, textInputFg)
import NanoUI.Internal.Input (Input)
import NanoUI.Internal.Layout.Arena
import NanoUI.Internal.Layout.Solve (findAncestorMaxW, textWrapCap)
import NanoUI.Internal.Style (AlignX (..), Style (..), Theme (..), resolveFontSize, textToneColor)
import NanoUI.Internal.Types (Color (..), Rect (..), clamp, isBounded, onGrid, rectIntersect)
import NanoUI.Internal.Widgets.ColorPicker (ColorPickerPart (..), colorPickerPartOf, colorPickerPartRect, colorPickerPreviewGeom)
import NanoUI.Internal.WidgetText

-- | Collect page text after layout, omitting spans covered by opaque floating
-- panels. Each tuple is bounds, text, foreground, background, clip; coordinates
-- are logical window coordinates. Rebuilds the context's base span arena.
collectTextSpans :: Context -> IO [(Rect, T.Text, Color, Color, Rect)]
collectTextSpans ctx@Context {ctxSpanBase = arena} = do
  count <- arenaCount (ctxNodeArena ctx)
  resetSpanArena arena
  when (count > 0) $
    collectClippedSpans ctx 0 (Rect 0 0 1e9 1e9) arena
  panels <- floatingPanelRects ctx
  spanArenaToList panels arena

-- | Collect window, modal, popup, dropdown, and edit-menu text in paint order.
-- Uses the same tuple format as 'collectTextSpans' and rebuilds the overlay arena.
collectOverlayTextSpans :: Context -> Input -> IO [(Rect, T.Text, Color, Color, Rect)]
collectOverlayTextSpans ctx@Context {ctxSpanOverlay = arena} inp = do
  resetSpanArena arena
  mapM_ (\nt -> collectFloatingSpansInto ctx nt arena) [NodeWindow, NodeModal, NodePopup]
  collectDropdownSpans ctx inp >>= pushSpans arena
  spanArenaToList IM.empty arena

-- | Collect base and overlay text separately for a host that rasterises text itself.
-- Under external text, each list ends with the drawing text of the last
-- painted (or reused) frame, in paint order, as line boxes with a
-- transparent background and the drawing's clip. 'collectTextSpans' and
-- 'collectOverlayTextSpans' leave those spans out.
collectRasterSpans :: Context -> Input -> IO ([(Rect, T.Text, Color, Color, Rect)], [(Rect, T.Text, Color, Color, Rect)])
collectRasterSpans ctx inp = do
  base <- collectTextSpans ctx
  overlay <- collectOverlayTextSpans ctx inp
  (drawnBase, drawnOverlay) <- dfeTextSpans <$> readIORef (daExtra (ctxDrawArena ctx))
  -- Without drawing spans the node lists are returned as they are, uncopied.
  -- Strict, so the pair holds no thunks.
  let withDrawn xs ys = if null ys then xs else xs ++ reverse ys
      !base' = withDrawn base drawnBase
      !overlay' = withDrawn overlay drawnOverlay
  pure (base', overlay')

-- | Total live arena nodes, including containers and decorative nodes.
widgetNodeCount :: Context -> IO Int
widgetNodeCount ctx = arenaCount (ctxNodeArena ctx)

-- | Spans of node @idx@ and its subtree inside @clip@, floating subtrees left
-- out.
collectClippedSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()
collectClippedSpans ctx@Context {ctxFontMetrics = fm} idx clip arena = do
  nt <- getNodeType (ctxNodeArena ctx) idx
  unless (isFloatingNode nt) $ do
    Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx
    mClipChildren <-
      if isScrollNode nt
        then
          getClipBounds (ctxNodeArena ctx) idx >>= \case
            Just live -> pure (rectIntersect clip live)
            Nothing -> (\sn -> rectIntersect clip (scrollNodeViewport sn x y w h)) <$> readScrollNode (ctxNodeArena ctx) idx
        else
          if isContainerNode nt
            then maybe (Just clip) (rectIntersect clip) <$> childPaintClip ctx idx nt (Rect x y w h)
            else pure (Just clip)
    forM_ mClipChildren $ \clipHere -> do
      -- A text node's spans are cached per node until its inputs change.
      -- Placement uses glyph ink ('alignedTextPen'), not TTF_GetStringSize;
      -- wrapping still measures with the host so line breaks stay on the TTF
      -- width.
      spans <-
        if nt == NodeText
          then sceSpans <$> textNodeSpanEntry ctx idx x y w h
          else if isWidgetNode nt && nt /= NodeTextArea then widgetTextSpans ctx nt idx x y w h else pure []
      here <-
        case nt of
          -- A select's label shares one clip, short of its chevron.
          NodeSelect -> do
            let (ix, _) = widgetContentInset fm
                label = padTextClipRect (Rect (x + ix) y (max 0 (w - ix - selectChevronReserve)) (max 0 h))
            pure [(r, t, fg, bg, c) | Just c <- [rectIntersect clipHere label], (r, t, fg, bg) <- spans]
          NodeTextInput -> do
            si <- getStyleIdx (ctxNodeArena ctx) idx
            if hasFlag textInputFlagSelectable si
              then pure (tagClippedSpans clipHere spans)
              else do
                -- The text clip paint uses ('nodeTextFieldGeom').
                (_, fieldClip) <- nodeTextFieldGeom ctx idx x y w h
                pure (maybe [] (`tagClippedSpans` spans) (rectIntersect clipHere fieldClip))
          -- The document lives in the text area's buffer: its rows in view,
          -- clipped as paint clips them, short of the scrollbars.
          NodeTextArea -> do
            (textClip, rows) <- textAreaTextPlacements ctx idx (Rect x y w h)
            rowSpans <- placedTextSpans ctx nt idx rows
            pure (maybe [] (`tagClippedSpans` rowSpans) (rectIntersect clipHere textClip))
          NodeContainer -> pure (tagClippedSpans clipHere spans)
          NodeText -> pure (tagClippedSpans clipHere spans)
          NodeSpacer -> pure (tagClippedSpans clipHere spans)
          NodeSeparator -> pure (tagClippedSpans clipHere spans)
          NodeButton -> pure (tagClippedSpans clipHere spans)
          NodeSlider -> pure (tagClippedSpans clipHere spans)
          NodeScrollContainer -> pure (tagClippedSpans clipHere spans)
          NodeModal -> pure (tagClippedSpans clipHere spans)
          NodeImage -> pure (tagClippedSpans clipHere spans)
          NodePanel -> pure (tagClippedSpans clipHere spans)
          NodeWindow -> pure (tagClippedSpans clipHere spans)
          NodeBox -> pure (tagClippedSpans clipHere spans)
          NodeColorPicker -> pure (tagClippedSpans clipHere spans)
          NodePopup -> pure (tagClippedSpans clipHere spans)
          NodeDrawing -> pure (tagClippedSpans clipHere spans)
          NodeShader -> pure (tagClippedSpans clipHere spans)
      pushSpans arena here
      kids <- getFirstChild (ctxNodeArena ctx) idx
      -- A widget clips its children, as paint does.
      unless (kids < 0) $
        forM_ (if isWidgetNode nt then rectIntersect clipHere (Rect x y w h) else Just clipHere) $ \childClip ->
          walkChildSpans ctx idx childClip arena

walkChildSpans :: Context -> NodeIdx -> Rect -> SpanArena -> IO ()
walkChildSpans ctx idx clip arena = getFirstChild (ctxNodeArena ctx) idx >>= go
  where
    go ci
      | ci < 0 = pure ()
      | otherwise = do
          ns <- getNextSibling (ctxNodeArena ctx) ci
          -- Sibling links run last to first, so recursing before collecting
          -- yields declaration order, which is reading order. It is not
          -- paint order ('forChildrenInPaintOrder_'), which differs where
          -- siblings overlap.
          go ns
          collectClippedSpans ctx ci clip arena

-- | Text node @idx@'s span cache entry at @(x, y)@, @w@ by @h@, brought up to
-- date: its spans, and the metrics prepared for each line, which paint draws
-- with.
textNodeSpanEntry :: Context -> NodeIdx -> Float -> Float -> Float -> Float -> IO SpanCacheEntry
textNodeSpanEntry ctx@Context {ctxNodeArena = arena} idx x y w h = do
  theme <- nodeTheme ctx idx
  raw <- getText arena idx
  si <- getStyleIdx arena idx
  mCustomCol <- getNodeFontColor arena idx
  fontSize <- getNodeFontSize arena idx
  ax <- getAlignX arena idx
  AxisSizing wTag wVal minW maxW <- getWidthSizing arena idx
  isRowChild <- parentIsRow arena idx
  -- 'nodeTextLines' wraps a row child only at its own newlines, and other
  -- text that is not fit at the width it was given ('textWrapCap'), so only
  -- otherwise does the ancestor cap matter; skip the walk to the root. A
  -- fixed width caps itself within its limits, as the solve measures it.
  effMaxW <-
    if wTag == SizingFixed
      then pure (clamp minW maxW wVal)
      else if isBounded maxW || (if isRowChild then not (T.any (== '\n') raw) else wTag /= SizingFit && w > 0)
        then pure maxW
        else findAncestorMaxW arena idx
  -- Wrap at the width layout laid the node out at, before its edges
  -- snapped ('GeomLaidW'), where layout wrapped it. A node restored or placed
  -- without snapping has none recorded.
  laid <- arenaArrays arena >>= \a -> readGeom a idx GeomLaidW
  let rect = Rect x y w h
      !laidW = if laid > 0 then laid else w
      mStripe = tableStripeColor theme si
      fg = fromMaybe (textToneColor theme (textNodeFontTone si)) mCustomCol
      bg = fromMaybe (styleBg (themePanel theme)) mStripe
      !ix = tableStripeInset si
      -- What the lines depend on: everything but where the node is and
      -- how tall, and the colours. Inlined at both uses, so a cache hit
      -- allocates no closure for it.
      {-# INLINE sameLines #-}
      sameLines e =
        sceText e == raw
          && sceStyle e == si
          && sceFontSize e == fontSize
          && sceWidthTag e == fromEnum wTag
          && rectW (sceRect e) == w
          && sceLaidW e == laidW
          && sceEffMaxW e == effMaxW
          && sceRowChild e == isRowChild
          && sceInset e == ix
  cache <- readIORef (ctxSpanCache ctx)
  case IM.lookup idx cache of
    Just e
      | sameLines e
          && sceRect e == rect
          && sceFg e == fg
          && sceBg e == bg
          && sceAlign e == fromEnum ax ->
          pure e
    mEntry -> do
      (fm, textLines) <- case mEntry of
        Just e | sameLines e -> pure (sceFont e, sceLines e)
        _ -> nodeTextLines ctx raw si fontSize wTag maxW effMaxW isRowChild ix laidW
      let spans = [(r, line, fg, bg) | (r, line) <- placeSpanLines ax fm ix x y w h textLines]
          entry =
            SpanCacheEntry
              { sceText = raw
              , sceFg = fg
              , sceBg = bg
              , sceStyle = si
              , sceFontSize = fontSize
              , sceAlign = fromEnum ax
              , sceWidthTag = fromEnum wTag
              , sceRect = rect
              , sceLaidW = laidW
              , sceEffMaxW = effMaxW
              , sceRowChild = isRowChild
              , sceInset = ix
              , sceFont = fm
              , sceLines = textLines
              , sceSpans = spans
              }
      writeIORef (ctxSpanCache ctx) $ IM.insert idx entry cache
      pure entry

-- | A text node's lines for width @w@ and the font they are set in: wrapped
-- where the node wraps (through the context's wrap cache, which the solve
-- shares), otherwise one line, truncated to fit a node that grows or has a
-- maximum width.
nodeTextLines ::
  Context -> T.Text -> Word64 -> Float -> SizingTag -> Float -> Float -> Bool -> Float -> Float -> IO (FontMetrics, SpanLines)
nodeTextLines ctx raw si fontSize wTag maxW effMaxW isRowChild ix w
  | T.null raw = pure (ctxFontMetrics ctx, SpanWrapped [])
  | otherwise = do
      (fm, _, measure) <- resolveFontFor ctx NodeText fontSize si
      let measureW = fmap fst . measure
          contentW = max 0 (w - 2 * ix)
          noWrap = isRowChild || textNodeSingleLine si
          -- A row child or single-line text wraps only at explicit newlines.
          wrapCap = if noWrap then effMaxW else textWrapCap effMaxW wTag w
      tw <- measureW raw
      if T.any (== '\n') raw || (not noWrap && isBounded wrapCap && wrapCap + 0.5 < tw)
        then do
          let !resolvedSize = resolveFontSize (ctxFontSize ctx) fontSize
          wrap <- cachedWrapText ctx (textNodeFontKey resolvedSize si) measureW raw (max 0 (wrapCap - 2 * ix))
          prepared <- forM (wrLines wrap) $ \line -> (,) line <$> prepareFontMetrics fm line
          pure (fm, SpanWrapped prepared)
        else do
          -- Half a pixel over the width is no reason to cut, as it is none
          -- to wrap.
          shown <-
            if tw > contentW + 0.5 && contentW > 0 && (wTag == SizingGrow || isBounded maxW || textNodeSingleLine si)
              then truncateTextWithIO (textNodeEllipsis si) measureW contentW raw
              else pure raw
          (,) fm . SpanSingle shown <$> prepareFontMetrics fm shown

-- | Where the lines of a text node at @(x, y)@, @w@ by @h@, go.
placeSpanLines :: AlignX -> FontMetrics -> Float -> Float -> Float -> Float -> Float -> SpanLines -> [(Rect, T.Text)]
placeSpanLines ax fm ix x y w h = \case
  SpanWrapped textLines ->
    [ (Rect tx ty used lineH, line)
    | (i, (line, prepared)) <- zip [(0 :: Int) ..] textLines
    , let (tx, used) = alignedTextPen ax x w ix prepared line
          ty = centeredTextY fm (y + onGrid (fmSnapScale fm) (fromIntegral i * lineH)) lineH lineH
    ]
  SpanSingle shown prepared ->
    let (tx, used) = alignedTextPen ax x w ix prepared shown
     in [(Rect tx (centeredTextY fm y h lineH) used lineH, shown)]
  where
    lineH = fmLineHeight fm

widgetTextSpans ::
  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(Rect, T.Text, Color, Color)]
widgetTextSpans ctx nt idx x y w h = do
  placements <-
    -- A centred label's placement depends on its text, style, font, alignment
    -- and size but not its origin, so it is cached. Field, picker and slider
    -- text depends on their data.
    if hasCenteredLabel nt
      then do
        (lx, lw, ax) <- labelBox ctx nt idx x w
        placement <- cachedWidgetLabel ctx nt idx ax lw h
        pure [(txt, lx + px, y + py, tw, th) | Just (WidgetTextPlacement txt px py tw th) <- [placement]]
      else computeWidgetTextPlacements ctx nt idx x y w h
  placedTextSpans ctx nt idx placements

-- | Widget @idx@'s text placements as spans in its text colour.
placedTextSpans :: Context -> NodeType -> NodeIdx -> [(T.Text, Float, Float, Float, Float)] -> IO [(Rect, T.Text, Color, Color)]
placedTextSpans ctx nt idx placements = do
  style <- widgetVisualStyle ctx nt idx
  let bg = styleBg style
  case nt of
    NodeTextInput -> do
      fg <- join (textInputFg ctx idx (styleFg style) bg <$> textInputValue ctx idx <*> textInputFocused ctx idx)
      pure [(Rect px py tw th, txt, fg, bg) | (txt, px, py, tw, th) <- placements]
    -- Only a text field fades its text while empty; every other widget's
    -- text takes its node's colour.
    _ -> do
      fg <- nodeTextColor ctx nt idx (styleFg style)
      pure [(Rect px py tw th, txt, fg, bg) | (txt, px, py, tw, th) <- placements, not (T.null txt)]

-- | Runtime consumer API. The Bool marks the last placement (for table sort
-- arrows); cached labels are translated directly into the consumer.
{-# INLINE forWidgetTextPlacements_ #-}
forWidgetTextPlacements_ ::
  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float ->
  (Bool -> T.Text -> Float -> Float -> Float -> Float -> IO ()) -> IO ()
forWidgetTextPlacements_ ctx nt idx x y w h emit
  | hasCenteredLabel nt = do
      (lx, lw, ax) <- labelBox ctx nt idx x w
      placement <- cachedWidgetLabel ctx nt idx ax lw h
      forM_ placement $ \(WidgetTextPlacement txt px py tw th) ->
        emit True txt (lx + px) (y + py) tw th
  | otherwise = do
      placements <- computeWidgetTextPlacements ctx nt idx x y w h
      let go [] = pure ()
          go ((txt, px, py, tw, th) : rest) =
            emit (null rest) txt px py tw th >> go rest
      go placements

-- | The span of widget @idx@, at @x@ and @w@ wide, its label is placed in,
-- and how a button's label aligns there: beside adornments, the room between
-- them, the label kept to their side so it never runs into one.
{-# INLINE labelBox #-}
labelBox :: Context -> NodeType -> NodeIdx -> Float -> Float -> IO (Float, Float, AlignX)
labelBox ctx nt idx x w
  | nt /= NodeButton = pure (x, w, AlignCenter)
  | otherwise = do
      insets <- nodeAdornmentInsets na idx x w
      si <- getStyleIdx na idx
      -- A vertical tab strip's header starts its label at its padding.
      pure (beside (if tabLabelAtStart si then tabHeaderPadX else 0) insets)
  where
    na = ctxNodeArena ctx
    beside start (lead, trail)
      | lead > 0 = (x + lead, max 0 (w - lead - trail), AlignStart)
      | trail > 0 = (x, max 0 (w - trail), AlignEnd)
      | start > 0 = (x + start, max 0 (w - start), AlignStart)
      | otherwise = (x, w, AlignCenter)

-- | A widget's label placed across @w@, a button's aligned by @labelAlign@.
cachedWidgetLabel :: Context -> NodeType -> NodeIdx -> AlignX -> Float -> Float -> IO (Maybe WidgetTextPlacement)
cachedWidgetLabel ctx nt idx labelAlign w h = do
  let na = ctxNodeArena ctx
  a <- arenaArrays na
  fontSizeVal <- readStyle a idx StyleFontSize
  si <- readStyleIdx a idx
  txt <- if nt == NodeButton then getText na idx else displayText ctx nt idx
  ax <-
    if nt == NodeButton && buttonKindOf si == ButtonTable
      then readAlignX a idx
      else pure labelAlign
  let !ntTag = fromEnum nt
  cache <- readIORef (ctxWidgetTextCache ctx)
  case IM.lookup idx cache of
    Just e
      | wtcNodeType e == ntTag
          && wtcStyle e == si
          && wtcFontSize e == fontSizeVal
          && wtcText e == txt
          && wtcWidth e == w
          && wtcHeight e == h
          && wtcAlign e == fromEnum ax -> pure (wtcPlacement e)
    _ -> do
      placement <- computeWidgetLabel ctx nt txt si fontSizeVal ax w h
      writeIORef
        (ctxWidgetTextCache ctx)
        (IM.insert idx (WidgetTextCacheEntry ntTag si fontSizeVal txt w h (fromEnum ax) placement) cache)
      pure placement

-- All coordinates here are local. centeredTextY snaps the baseline offset,
-- not the origin; final device-pixel snapping stays in the draw backend.
computeWidgetLabel :: Context -> NodeType -> T.Text -> Word64 -> Float -> AlignX -> Float -> Float -> IO (Maybe WidgetTextPlacement)
computeWidgetLabel ctx nt txt si fontSizeVal ax w h
  | kind == ButtonClose = pure Nothing
  | otherwise = do
      (source, _, measure) <- resolveFontFor ctx nt fontSizeVal si
      (tw0, th) <- measure txt
      let (ix, _) = widgetContentInset source
          isTable = kind == ButtonTable
          plain = nt == NodeButton && kind `notElem` [ButtonChoice, ButtonRow, ButtonTable, ButtonMenu]
          -- The room a plain button's or a select's label has: inside the
          -- padding layout gave a centred label, all of the box beside
          -- adornments, and short of a select's chevron.
          room
            | isTable = max 0 (w - tableHeaderPadX)
            | nt == NodeSelect = w - ix - selectChevronReserve
            | ax /= AlignCenter = w
            | kind == ButtonTab = w - 2 * tabHeaderPadX
            | otherwise = w - fst (buttonPadding source)
      -- A label longer than that ends in an ellipsis.
      (label, tw) <-
        if (plain || isTable || nt == NodeSelect) && tw0 > room + 0.5
          then do
            let ell = textNodeEllipsis (nodeFontBits nt si)
            cut <- truncateTextWithIO ell (fmap fst . measure) room txt
            (cut,) . fst <$> measure cut
          else pure (txt, tw0)
      -- Metrics for the label as it is shown, which places it.
      fm <- prepareFontMetrics source label
      let (tx, used)
            | nt /= NodeButton = (ix, min tw (w - ix - selectChevronReserve))
            | otherwise = case kind of
                ButtonChoice -> (checkboxLeading fm, tw)
                ButtonRow ->
                  let (depth, _, _) = treeDecodeStyle si
                   in (treeRowLeading fm depth, tw)
                ButtonTable -> alignedTextPen ax 0 w tableCellInset fm label
                ButtonMenu ->
                  let inset = menuItemPadX + ix
                   in (inset, min tw (max 0 (w - inset - ix)))
                _ -> alignedTextPen ax 0 w 0 fm label
      let !placement = WidgetTextPlacement label tx (centeredTextY fm 0 h th) used th
      pure (Just placement)
  where
    -- A select is the other widget with a centred label.
    !kind = if nt == NodeButton then buttonKindOf si else ButtonPlain

-- | Pure geometry of selectable text: the pen origin, centered baseline box and
-- line height. Selectable text never scrolls, so the pen is just the node x.
-- Paint uses this and skips the width measure; span placement adds it.
selectableTextGeometry :: FontMetrics -> Float -> Float -> Float -> (Float, Float, Float)
selectableTextGeometry fm x y h =
  let lineH = fmLineHeight fm
   in (x, centeredTextY fm y h lineH, lineH)

computeWidgetTextPlacements ::
  Context -> NodeType -> NodeIdx -> Float -> Float -> Float -> Float -> IO [(T.Text, Float, Float, Float, Float)]
computeWidgetTextPlacements ctx nt idx x y w h = do
  fontSizeVal <- getNodeFontSize (ctxNodeArena ctx) idx
  si <- getStyleIdx (ctxNodeArena ctx) idx
  (fm, _, measureTxt) <- resolveFontFor ctx nt fontSizeVal si
  let lineH = fmLineHeight fm
  case nt of
    NodeColorPicker
      | colorPickerPartOf si /= PickerPreview -> pure []
      | otherwise -> do
          band@(Rect bx _ _ _) <- colorPickerPartRect (ctxNodeArena ctx) idx (Rect x y w h)
          let (currentY, _, newY, _) = colorPickerPreviewGeom fm band
          forM [("Current", currentY), ("New", newY)] $ \(lbl, ly) -> do
            (lw, lh) <- measureTxt lbl
            pure (lbl, bx, centeredTextY fm ly lineH lh, lw, lh)
    NodeTextInput
      | hasFlag textInputFlagSelectable si -> do
          value <- textInputValue ctx idx
          let (penX, ty, selLineH) = selectableTextGeometry fm x y h
          (fw, _) <- measureTxt value
          pure [(value, penX, ty, fw, selLineH)]
      | otherwise -> do
          (box, clip) <- nodeTextFieldGeom ctx idx x y w h
          focus <- textInputFocused ctx idx
          ph <- if hasFlag textInputFlagNumeric si then pure "" else getText (ctxNodeArena ctx) idx
          TextInputFrame _ _ _ shown penX penY _ <- resolveTextInputFrame ctx idx si focus box clip
          let fieldTxt = textInputFieldText ph shown focus
          (fw, _) <- measureTxt fieldTxt
          pure [(fieldTxt, penX, penY, fw, lineH)]
    -- Text areas place their rows with their clip
    -- ('textAreaTextPlacements'), and buttons and selects have centred
    -- labels ('cachedWidgetLabel').
    NodeTextArea -> pure []
    NodeButton -> pure []
    NodeSelect -> pure []
    -- Sliders and drawings carry no text, and the other node types are not
    -- widgets.
    NodeContainer -> pure []
    NodeText -> pure []
    NodeSpacer -> pure []
    NodeSeparator -> pure []
    NodeSlider -> pure []
    NodeScrollContainer -> pure []
    NodeModal -> pure []
    NodeImage -> pure []
    NodePanel -> pure []
    NodeWindow -> pure []
    NodeBox -> pure []
    NodePopup -> pure []
    NodeDrawing -> pure []
    NodeShader -> pure []

-- | Spans inside every floating panel of one kind, clipped to its content box.
collectFloatingSpansInto :: Context -> NodeType -> SpanArena -> IO ()
collectFloatingSpansInto ctx wanted arena =
  forFloatingNodes_ (ctxNodeArena ctx) wanted $ \idx -> do
    Rect x y w h <- getNodeRect (ctxNodeArena ctx) idx
    clip <- padContentClip x y w h <$> getPadding (ctxNodeArena ctx) idx
    walkChildSpans ctx idx clip arena