packages feed

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

{-# OPTIONS_HADDOCK not-home #-}

-- | Implementation of "NanoUI.Widgets.TextArea", plus loading and saving a
-- text area's state in the widget store and running commands on it from
-- outside its frame.
module NanoUI.Internal.Widgets.TextArea
  ( -- * Pure state
    TextAreaState (..)
  , initTextAreaState
  , setTextAreaViewport
  , setTextAreaSelection
    -- * Widget
  , textArea
  , textArea'
  , textAreaWith
  , textAreaWith'
  , textAreaDocument
  , textAreaDocument'
  , textAreaDocumentWith
  , textAreaDocumentWith'
  , textAreaLayout
  , textAreaBuffer
  , loadTextAreaState
  , saveTextAreaState
  , runTextAreaCommand
  , textAreaFieldEditor
  ) where

import Control.Monad (foldM, unless, void, when)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.IntMap.Strict as IM
import NanoUI.Internal.Context
import NanoUI.Internal.Font (fmLineHeight, fmSnapScale)
import NanoUI.Internal.Frame.Node (packedTextFont, resolveTextFont)
import NanoUI.Internal.Id (WidgetId)
import NanoUI.Internal.Input
import NanoUI.Internal.Layout.Arena (NodeType (..))
import NanoUI.Internal.Monad (NanoUI, askContext, askInput, freshWidget, nextId, liftIO)
import NanoUI.Internal.Store
import NanoUI.Internal.Store.Slots (slotSeen, slotTextAreaAnchorCol, slotTextAreaAnchorRow, slotTextAreaBuffer, slotTextAreaLineH, slotTextAreaReveal, slotTextAreaScroll, slotTextAreaText, slotTextAreaViewport, slotTextChanged, slotTextHistory, slotTextMode)
import NanoUI.Internal.Store.Types (TextHistory (..))
import NanoUI.Internal.Style (Layout (..), defaultLayout, fillW, fixedH, minW)
import NanoUI.Internal.Types (DamageBounds (..), V2 (..), clamp, onGrid)
import NanoUI.Internal.Var (Binding (..), bindVar, bindVarBy)
import NanoUI.Internal.Var.Types (Var)
import NanoUI.Internal.WidgetText (packTextNodeStyle)
import NanoUI.Internal.Widgets.Node (Response, addWidgetStyled, setChanged)
import NanoUI.Internal.Widgets.TextInput (fieldTextCommands, focusAndIme)
import qualified NanoUI.Widgets.TextBuffer as TB
import NanoUI.Internal.Widgets.TextDocument
import NanoUI.Widgets.TextEditor

-- | Editor buffer, selection anchor, viewport, scroll offsets, and undo history.
-- Positions use zero-based character rows/columns; viewport and scrolling use
-- logical pixels. The widget stores this under its stable id.
data TextAreaState = TextAreaState
  { tasBuffer :: !TB.TextBuffer
  , tasSelectionAnchor :: !TB.Cursor
  , tasScrollOffset :: !(Double, Double)
  , tasViewportSize :: !(Double, Double)
  , tasLineHeight :: !Double
  , tasHistory :: !EditHistory
  }
  deriving (Show)

-- | Start at the document origin with no selection or history and an unset viewport.
initTextAreaState :: T.Text -> TextAreaState
initTextAreaState initial =
  TextAreaState
    { tasBuffer = TB.fromText initial
    , tasSelectionAnchor = TB.Cursor 0 0
    , tasScrollOffset = (0.0, 0.0)
    , tasViewportSize = (0.0, 0.0)
    , tasLineHeight = 16.0
    , tasHistory = emptyHistory
    }

-- | Set logical viewport width/height and line height without moving the caret.
setTextAreaViewport :: (Double, Double) -> Double -> TextAreaState -> TextAreaState
setTextAreaViewport vp lh state =
  state {tasViewportSize = vp, tasLineHeight = lh}

-- | Set anchor and cursor, in that order, both clamped into the document, and
-- scroll vertically to reveal the caret.
setTextAreaSelection :: TB.Cursor -> TB.Cursor -> TextAreaState -> TextAreaState
setTextAreaSelection anchor cursor state =
  ensureCaretVisible state {tasBuffer = TB.withCursor cursor (tasBuffer state), tasSelectionAnchor = TB.clampCursor (tasBuffer state) anchor}

-- | Extract buffer, selection, and history for the shared text-command engine.
textAreaEditor :: TextAreaState -> Editor
textAreaEditor state = Editor (tasBuffer state) (tasSelectionAnchor state) (tasHistory state)

withEditor :: TextAreaState -> Editor -> TextAreaState
withEditor state ed =
  ensureCaretVisible state {tasBuffer = editorBuffer ed, tasSelectionAnchor = editorAnchor ed, tasHistory = editorHistory ed}

-- | Run a command that needs no clipboard, keeping the caret in view.
runTextAreaCommand :: TextCommand -> TextAreaState -> TextAreaState
runTextAreaCommand cmd state = withEditor state (runCommand multiLineMode cmd (textAreaEditor state))

ensureCaretVisible :: TextAreaState -> TextAreaState
ensureCaretVisible state =
  let TB.Cursor r _ = TB.getCursor (tasBuffer state)
      lh = tasLineHeight state
      vh = snd (tasViewportSize state)
      (sx, sy) = tasScrollOffset state
      caretY = fromIntegral r * lh
      maxSy = max 0 (fromIntegral (TB.getLineCount (tasBuffer state)) * lh - vh)
      sy'
        | vh <= 0 = 0
        | caretY < sy = caretY
        | caretY + lh > sy + vh = caretY + lh - vh
        | otherwise = sy
   in state {tasScrollOffset = (sx, clamp 0 maxSy sy')}

--------------------------------------------------------------------------------
-- Widget
--------------------------------------------------------------------------------

-- | Default viewport: grow horizontally, at least 200 pixels wide, 140 pixels tall.
textAreaLayout :: Layout
textAreaLayout = fixedH 140 . minW 200 . fillW $ defaultLayout

-- | Multi-line text editor over 'Text' bound to mutable state ('Var'). Pair it
-- with a 'label' when a caption is needed.
--
-- A frame that changes the text joins the whole document and mutates the
-- 'Var' in place, its Windows line ends (@\\r\\n@) written back as @\\n@.
-- For long documents use 'textAreaDocument', whose edits cost only the lines
-- they touch.
{-# INLINE textArea #-}
textArea :: Var Text -> NanoUI ()
textArea = void . textArea'

-- | 'textArea' returning its 'Response'. 'respChanged' reports a frame
-- that changed the text; caret and selection moves leave it unset.
{-# INLINE textArea' #-}
textArea' :: Var Text -> NanoUI Response
textArea' = textAreaWith' id

-- | 'textArea' with a modifier applied to 'textAreaLayout', for example
-- 'grow' to fill the parent. Font modifiers ('fontSize', 'fontMono',
-- 'fontColor' and the like) set the text.
{-# INLINE textAreaWith #-}
textAreaWith :: (Layout -> Layout) -> Var Text -> NanoUI ()
textAreaWith f = void . textAreaWith' f

-- | 'textAreaWith' returning its 'Response'.
textAreaWith' :: (Layout -> Layout) -> Var Text -> NanoUI Response
textAreaWith' f v = bindVar RenderFinal v $ \value -> do
  (wid, ctx) <- freshWidget
  store <- liftIO (getStore ctx)
  let -- The text last passed or returned, and its document: passing it back
      -- neither splits it again nor, while nothing is edited, joins it.
      cached = lookupSpec slotTextAreaText (intKey wid) store
      incoming = case cached of
        Just (t, doc) | t == value -> doc
        _ -> textDocument value
  (resp, doc) <- textAreaCore f wid incoming
  case cached of
    Just (t, d) | sameDocument d doc -> pure (resp, t)
    _ -> do
      let out = if sameDocument doc incoming then value else documentText doc
      liftIO $ modifyStore ctx (insertSpec slotTextAreaText (intKey wid) (out, doc))
      pure (resp, out)

-- | Multi-line text editor over a 'TextDocument' bound to mutable state ('Var').
-- An edit replaces the lines it touches and shares the rest, and a frame
-- without edits leaves the document as it was. Edits avoid joining the whole
-- document, though their cost still depends on affected lines and tree
-- operations. Join it with 'documentText' when the whole text is needed.
{-# INLINE textAreaDocument #-}
textAreaDocument :: Var TextDocument -> NanoUI ()
textAreaDocument = void . textAreaDocument'

-- | 'textAreaDocument' returning its 'Response'. 'respChanged' reports a
-- frame that changed the document; caret and selection moves leave it unset.
{-# INLINE textAreaDocument' #-}
textAreaDocument' :: Var TextDocument -> NanoUI Response
textAreaDocument' = textAreaDocumentWith' id

-- | 'textAreaDocument' with a modifier applied to 'textAreaLayout'.
{-# INLINE textAreaDocumentWith #-}
textAreaDocumentWith :: (Layout -> Layout) -> Var TextDocument -> NanoUI ()
textAreaDocumentWith f = void . textAreaDocumentWith' f

-- | 'textAreaDocumentWith' returning its 'Response'. Documents compare by
-- identity: walking their lines on every frame would cost what they save.
{-# INLINE textAreaDocumentWith' #-}
textAreaDocumentWith' :: (Layout -> Layout) -> Var TextDocument -> NanoUI Response
textAreaDocumentWith' f v = bindVarBy sameDocument RenderFinal v $ \value -> do
  wid <- nextId
  textAreaCore f wid value

-- | The text area at @wid@ over a document, returning its 'Response' and the
-- edited document. The text-area entry points share it after taking an id.
textAreaCore :: (Layout -> Layout) -> WidgetId -> TextDocument -> NanoUI (Response, TextDocument)
textAreaCore f wid value = do
  ctx <- askContext
  inp <- askInput
  store0 <- liftIO (getStore ctx)
  let layout = f textAreaLayout
      -- The face, weight and slant, packed as a text field's are.
      styleIdx = packTextNodeStyle layout 0
      key = intKey wid
      stored = lookupSpec slotTextAreaBuffer key store0
      adoptDocument
        | fmap bufferDocument stored == Just value = id
        | otherwise =
            insertSpec slotTextAreaBuffer key (maybe id keepCaret stored (documentBuffer value))
              . deleteSpec slotTextHistory key
      keepCaret old new = (TB.withCursor (TB.snapToCluster new (TB.getCursor old)) new) {TB.preferredCol = TB.preferredCol old}
  -- Adopt the caller's document the way 'adoptSlot' does. Comparing the
  -- document the caller passes back with the stored one is O(1) ('==' checks
  -- identity first). A replaced document gets a buffer over its lines, whose
  -- widths are then measured afresh, keeping the caret where it was, and its
  -- undo history, recorded against the old text, goes. Seed the scroll slot
  -- too: the wheel and drag paths write offsets through setScrollOffset2D,
  -- which only updates the text area's slot once it exists.
  when (lookupSpec (slotSeen fieldDocument) key store0 /= Just value) $
    liftIO . setStore ctx $
      insertSpec (slotSeen fieldDocument) key value
        . adoptDocument
        . overField fieldPoint (IM.insertWith (\_ old -> old) (specKey slotTextAreaScroll key) (V2 0 0))
        . insertSpec slotTextMode key multiLineMode
        $ store0
  store <- liftIO (getStore ctx)
  let current = maybe value bufferDocument (lookupSpec slotTextAreaBuffer key store)
      -- Set by commands run outside the frame ('applyTextFieldCommand') that
      -- changed the text; their edits carry no keys or chars, so this is the
      -- caller's respChanged pulse for them. Cleared in the state write below.
      menuPulse = memberSpec slotTextChanged key store
  isFocus <- focusAndIme ctx wid True InputNormal
  (newDoc, edited) <-
    if isFocus
      then do
        -- The font the rows are painted in ('resolveTextAreaFont').
        editFm <- fst <$> liftIO (resolveTextFont ctx (packedTextFont (layoutFontSize layout) styleIdx))
        let oldState = loadTextAreaState store key
            -- Rows sit on the device pixel grid ('textAreaLineHeight').
            s1 = setTextAreaViewport (tasViewportSize oldState) (realToFrac (onGrid (fmSnapScale editFm) (fmLineHeight editFm))) oldState
            hadInput = not (T.null (inputChars inp)) || not (inputKeysNull (inputKeys inp))
        newState <- liftIO $ do
          when hadInput $ modifyInteraction ctx (\s -> s {isTextInputDrag = Nothing})
          fieldTextCommands ctx multiLineMode inp >>= \case
            [] -> pure s1
            cmds -> withEditor s1 <$> foldM (flip (runCommandIO ctx multiLineMode)) (textAreaEditor s1) cmds
        let newBuf = tasBuffer newState
            -- Edits make new lines and moves keep them, so this reads no
            -- text; the editor drops edits that would change nothing.
            textChanged = not (sameLines (TB.bufferLines newBuf) (documentLines current))
            doc
              | textChanged = bufferDocument newBuf
              | otherwise = current
            edited = textChanged || menuPulse
            changed =
              edited
                || TB.getCursor newBuf /= TB.getCursor (tasBuffer oldState)
                || tasSelectionAnchor newState /= tasSelectionAnchor oldState
                || tasScrollOffset newState /= tasScrollOffset oldState
        -- Saving writes the new buffer, which is the document, and drops the
        -- menu pulse. The store damage is keyed on slots, not the widget, so
        -- damage the widget itself: a selection-only change (Ctrl+A) would
        -- otherwise repaint nothing until the next frame.
        when changed $
          liftIO $ do
            damageWidget ctx wid DamageSelf
            modifyStore ctx (deleteSpec slotTextChanged key . saveTextAreaState key newState)
        pure (doc, edited)
      else do
        -- A command run on the unfocused area ('applyTextFieldCommand') still
        -- pulses this frame's respChanged, once.
        when menuPulse $
          liftIO $ modifyStore ctx (deleteSpec slotTextChanged key)
        pure (current, menuPulse)
  -- Record what is returned as seen, so the caller passing it back is not
  -- taken for a replacement. A caller that passes an equal copy each frame
  -- gets the stored document back every frame; rewriting the slot then would
  -- damage it and wake the loop forever.
  unless (sameDocument newDoc value) $
    liftIO $ modifyStore ctx $ \st ->
      case lookupSpec (slotSeen fieldDocument) key st of
        Just seen | sameDocument seen newDoc -> st
        _ -> insertSpec (slotSeen fieldDocument) key newDoc st
  resp <- addWidgetStyled wid NodeTextArea "" 0 layout styleIdx
  -- respChanged reports an edit to the text, as on a text input; caret,
  -- selection and scroll moves only repaint the area.
  pure (setChanged edited resp, newDoc)

-- | The text area's 'TB.TextBuffer', which holds its document and caret. The
-- widget stores one over the lines of every document it adopts, so it is only
-- missing for a text area never declared, which holds an empty document.
textAreaBuffer :: WidgetStore -> Int -> TB.TextBuffer
textAreaBuffer store key = fromMaybe TB.empty (lookupSpec slotTextAreaBuffer key store)

-- | The text area's editor state as stored.
loadTextAreaState :: WidgetStore -> Int -> TextAreaState
loadTextAreaState store key =
  let buf = textAreaBuffer store key
      TB.Cursor row col = TB.getCursor buf
      anchorRow = findSpec slotTextAreaAnchorRow row key store
      anchorCol = findSpec slotTextAreaAnchorCol col key store
      V2 sx sy = findSpec slotTextAreaScroll (V2 0 0) key store
      V2 vw vh = findSpec slotTextAreaViewport (V2 200 96) key store
   in TextAreaState
        { tasBuffer = buf
        , tasSelectionAnchor = TB.clampCursor buf (TB.Cursor anchorRow anchorCol)
        , tasScrollOffset = (realToFrac sx, realToFrac sy)
        , tasViewportSize = (realToFrac vw, realToFrac vh)
        , tasLineHeight = realToFrac (findSpec slotTextAreaLineH 16 key store)

        , -- Replacing the document drops its history, so the history is
          -- always the current document's.
          tasHistory = case lookupSpec slotTextHistory key store of
            Just (AreaHistory h) -> h
            _ -> emptyHistory
        }

-- | Store the editor state. The buffer holds the document and the caret. The
-- state keeps the caret in view vertically; the next paint, which has the
-- font, brings it into view across ('SlotTextAreaReveal').
saveTextAreaState :: Int -> TextAreaState -> WidgetStore -> WidgetStore
saveTextAreaState key state =
  insertSpec slotTextAreaScroll key (V2 (realToFrac sx) (realToFrac sy))
    . insertSpec slotTextAreaReveal key 1
    . insertSpec slotTextAreaViewport key (V2 (realToFrac vw) (realToFrac vh))
    . insertSpec slotTextAreaBuffer key (tasBuffer state)
    . insertSpec slotTextHistory key (AreaHistory (tasHistory state))
    . insertSpec slotTextAreaAnchorRow key anchorRow
    . insertSpec slotTextAreaAnchorCol key anchorCol
  where
    TB.Cursor anchorRow anchorCol = tasSelectionAnchor state
    (sx, sy) = tasScrollOffset state
    (vw, vh) = tasViewportSize state

-- | A text area's stored editor, for a command run outside its frame, and
-- how to store the edited editor, keeping the caret in view.
textAreaFieldEditor :: WidgetStore -> Int -> (Editor, Editor -> WidgetStore -> WidgetStore)
textAreaFieldEditor store key =
  let state = loadTextAreaState store key
   in (textAreaEditor state, saveTextAreaState key . withEditor state)