module Brick.Widgets.Edit
( Editor(editContents, editorName, editDrawContents)
, editor
, editorText
, getEditContents
, handleEditorEvent
, applyEdit
, editContentsL
, editDrawContentsL
, renderEditor
, editAttr
, editFocusedAttr
)
where
import Data.Monoid
import Lens.Micro
import Graphics.Vty (Event(..), Key(..), Modifier(..))
import qualified Data.Text as T
import qualified Data.Text.Zipper as Z hiding ( textZipper )
import qualified Data.Text.Zipper.Generic as Z
import Brick.Types
import Brick.Widgets.Core
import Brick.AttrMap
data Editor t n =
Editor { editContents :: Z.TextZipper t
, editDrawContents :: [t] -> Widget n
, editorName :: n
}
suffixLenses ''Editor
instance Named (Editor t n) n where
getName = editorName
handleEditorEvent :: (Eq t, Monoid t) => Event -> Editor t n -> EventM n (Editor t n)
handleEditorEvent e ed =
let f = case e of
EvKey (KChar 'a') [MCtrl] -> Z.gotoBOL
EvKey (KChar 'e') [MCtrl] -> Z.gotoEOL
EvKey (KChar 'd') [MCtrl] -> Z.deleteChar
EvKey (KChar 'k') [MCtrl] -> Z.killToEOL
EvKey (KChar 'u') [MCtrl] -> Z.killToBOL
EvKey KEnter [] -> Z.breakLine
EvKey KDel [] -> Z.deleteChar
EvKey (KChar c) [] | c /= '\t' -> Z.insertChar c
EvKey KUp [] -> Z.moveUp
EvKey KDown [] -> Z.moveDown
EvKey KLeft [] -> Z.moveLeft
EvKey KRight [] -> Z.moveRight
EvKey KBS [] -> Z.deletePrevChar
_ -> id
in return $ applyEdit f ed
editorText :: n
-> ([T.Text] -> Widget n)
-> Maybe Int
-> T.Text
-> Editor T.Text n
editorText = editor
editor :: Z.GenericTextZipper a
=> n
-> ([a] -> Widget n)
-> Maybe Int
-> a
-> Editor a n
editor name draw limit s = Editor (Z.textZipper (Z.lines s) limit) draw name
applyEdit :: (Z.TextZipper t -> Z.TextZipper t)
-> Editor t n
-> Editor t n
applyEdit f e = e & editContentsL %~ f
editAttr :: AttrName
editAttr = "edit"
editFocusedAttr :: AttrName
editFocusedAttr = editAttr <> "focused"
getEditContents :: Monoid t => Editor t n -> [t]
getEditContents e = Z.getText $ e^.editContentsL
renderEditor :: (Ord n, Show n, Monoid t)
=> Bool
-> Editor t n
-> Widget n
renderEditor foc e =
let cp = Z.cursorPosition $ e^.editContentsL
cursorLoc = Location (cp^._2, cp^._1)
limit = case e^.editContentsL.to Z.getLineLimit of
Nothing -> id
Just lim -> vLimit lim
in withAttr (if foc then editFocusedAttr else editAttr) $
limit $
viewport (e^.editorNameL) Both $
(if foc then showCursor (e^.editorNameL) cursorLoc else id) $
visibleRegion cursorLoc (1, 1) $
e^.editDrawContentsL $
getEditContents e