layoutz 0.4.0.0 → 1.0.0.0
raw patch · 46 files changed
+8636/−4345 lines, 46 filesdep +arraydep +bytestringdep +filepathdep ~containersdep ~directorydep ~textnew-component:exe:ask-mininew-component:exe:click-demonew-component:exe:counter-demonew-component:exe:fill-demonew-component:exe:focus-demonew-component:exe:focus-mininew-component:exe:loader-demonew-component:exe:mouse-mininew-component:exe:napkin-demonew-component:exe:plot-demonew-component:exe:readme-demonew-component:exe:simple-gamenew-component:exe:sizing-mininew-component:exe:spinner-demonew-component:exe:task-list-demonew-component:exe:tile-demonew-component:exe:widgets-mininew-component:exe:zoom-demoPVP ok
version bump matches the API change (PVP)
Dependencies added: array, bytestring, filepath, process, unix
Dependency ranges changed: containers, directory, text
API changes (from Hackage documentation)
Files
- CHANGELOG.md +25/−2
- Layoutz.hs +3361/−2909
- README.md +1134/−1086
- bench/Dashboard.hs +47/−0
- bench/Main.hs +255/−0
- bench/Pty.hs +136/−0
- bench/Report.hs +215/−0
- bench/cbits/pty.c +25/−0
- examples/AskDemo.hs +11/−11
- examples/AskMini.hs +13/−0
- examples/ClickDemo.hs +69/−0
- examples/CounterDemo.hs +37/−0
- examples/FillDemo.hs +42/−0
- examples/FocusDemo.hs +98/−0
- examples/FocusMini.hs +31/−0
- examples/InlineBar.hs +11/−11
- examples/InlineLoadingDemo.hs +10/−10
- examples/LoaderDemo.hs +21/−0
- examples/MouseMini.hs +15/−0
- examples/NapkinDemo.hs +36/−0
- examples/PlotDemo.hs +9/−0
- examples/RayMarcher.hs +26/−26
- examples/ReadmeDemo.hs +60/−0
- examples/ShowcaseApp.hs +141/−141
- examples/SimpleGame.hs +270/−0
- examples/SizingMini.hs +14/−0
- examples/SpinnerDemo.hs +63/−0
- examples/TaskListDemo.hs +253/−0
- examples/TileDemo.hs +691/−0
- examples/WidgetsMini.hs +29/−0
- examples/ZoomDemo.hs +914/−0
- layoutz.cabal +190/−10
- pix/haskell-kitty-1.png binary
- pix/haskell-kitty-2.png binary
- pix/intro-demo.png binary
- pix/layoutz-color-1.png binary
- pix/layoutz-color-2.png binary
- pix/layoutz-demo-1.png binary
- pix/layoutz-demo-2.png binary
- pix/layoutz-demo-3.png binary
- pix/layoutz-demo-4.png binary
- pix/layoutz-demo.png binary
- pix/layoutz-hs.png binary
- pix/layoutz-styles-1.png binary
- pix/layoutz-styles-2.png binary
- test/Test.hs +384/−139
@@ -1,8 +1,31 @@ # Changelog -All notable changes to layoutz-hs will be documented in this file.+## [1.0.0.0] - 2026-12-02 -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+layoutz 1.0. The runtime has been rewritten.++Apps now get mouse clicks and scrolling,+keyboard focus, text inputs and select lists, overlays for popups, scrollable viewports,+and layouts that adapt to the terminal size and redraw when you resize it.++Views can be tested without a terminal: render them at a given size, or simulate clicks and keypresses.++From here on the API will be more stable, and breaking changes will be rare. This release does break+the 0.4 API, though. In short:++ -- 0.4 -- 1.0+ L View msg+ layout [..] vstack [..]+ tightRow [..] row [..] & gap 0+ withColor ColorRed (box "Hi" xs) box "Hi" xs & fg ColorRed+ withBorder BorderRound x x & border BorderRound+ runAppWith opts app run opts app -- returns the final model+ CmdExit / subBatch [..] cmdQuit / (<>)+ styleDots loaderDots+ renderText x T.pack (render x)++Also fixes the plotStackedBar legend colours (#51). Text is used internally now, but+the public API still takes String. Adds a dependency on unix (not on Windows). ## [0.4.0.0] - 2026-07-12
@@ -3,2912 +3,3364 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-}--{- |-Module : Layoutz-Description : Friendly, expressive print-layout DSL for Haskell-Copyright : (c) 2026 Matthieu Court-License : Apache-2.0--A simple Haskell port of the layoutz library for creating structured terminal layouts.--}--module Layoutz- ( -- * Core Types- Element(..)- , Border(..)- , HasBorder(..)- , Color(..)- , Style(..)- , L- , Tree(..)- -- * Basic Elements- , layout- , text- , br- -- * Layout Functions- , center, center'- , row, tightRow- , columns, columns'- , underline, underline', underlineColored- , alignLeft, alignRight, alignCenter, justify, wrap- , truncate', truncate''- -- * Containers- , box- , banner- , statusCard- -- * Widgets- , ul- , ol- , inlineBar- , table- , section, section', section''- , kv- , tree, leaf, branch- -- * Visual Elements- , margin- , hr, hr', hr''- , vr, vr', vr''- , pad- , chart- -- * Spinners- , spinner- , SpinnerStyle(..)- -- * Visualizations- , plotSparkline- , Series(..), plotLine- , Slice(..), plotPie- , BarItem(..), plotBar- , StackedBarGroup(..), plotStackedBar- , HeatmapData(..), plotHeatmap, plotHeatmap'- -- * Border utilities- , withBorder- -- * Color utilities- , withColor- -- * Style utilities- , withStyle- -- * Rendering- , render- , renderText- -- * TUI Runtime- , LayoutzApp(..)- , Key(..)- , Cmd(..)- , cmdFire- , cmdTask- , cmdAfterMs- , executeCmd- , cmdIsExit- , Sub(..)- , AppOptions(..)- , defaultAppOptions- , AppAlignment(..)- , runApp- , runAppFinal- , runAppWith- , runAppWithFinal- , runInline- -- * Subscriptions- , subKeyPress- , subEveryMs- , subBatch- -- * Kitty graphics- , KittyImage(..)- , kittyImage- , kittyRGB- , kittyRGBA- , kittyImageFile- -- * Progress loaders- , LoaderStyle(..)- , styleBlocks, styleBar, styleAscii, styleDots, styleLine, stylePipes, loaderStyles- , loader, loaderStyled, loaderStream, loaderStreamStyled- -- * Interactive prompts (Ask)- , askInput- , askConfirm- , askChoose- , askChooseMany- , askSpin- , askWrite- , askFilter- , askFile- , askPager- ) where--import Data.List (intercalate, transpose, nub, sortOn, isPrefixOf)-import qualified Data.Text-import qualified Data.Text as T-import qualified Data.IntSet as IntSet-import Data.Bits ((.|.), (.&.), xor, shiftL, shiftR)-import Data.Word (Word8)-import Data.String (IsString(..))-import Data.Char (ord, chr, toLower, isDigit)-import Text.Printf (printf)-import System.IO-import Control.Exception (catch, finally, throwIO, AsyncException(..), IOException, SomeException)-import System.Timeout (timeout)-import Control.Monad (when, unless, forever, forM)-import Control.Concurrent (forkIO, threadDelay, killThread, newChan, writeChan, readChan)-import Data.IORef (IORef, newIORef, readIORef, writeIORef, atomicModifyIORef', modifyIORef')-import GHC.Clock (getMonotonicTimeNSec)-import System.Directory (listDirectory, doesDirectoryExist, doesPathExist, canonicalizePath)---- | Strip ANSI escape codes from a string for accurate width calculation.--- Also drops kitty graphics APC escapes (@ESC _ G ... ESC \\@) so an inline--- image's transmit block doesn't get counted as visible width.-stripAnsi :: String -> String-stripAnsi [] = []-stripAnsi ('\ESC':'[':rest) = stripAnsi (dropAfterM rest)- where- dropAfterM [] = []- dropAfterM ('m':xs) = xs- dropAfterM (_:xs) = dropAfterM xs-stripAnsi ('\ESC':'_':rest) = stripAnsi (dropAfterST rest)- where- -- APC string terminates at ST (ESC \)- dropAfterST [] = []- dropAfterST ('\ESC':'\\':xs) = xs- dropAfterST (_:xs) = dropAfterST xs-stripAnsi (c:rest) = c : stripAnsi rest---- | Returns width of a character in a monospace terminal: 0 for combining--- characters, 1 for regular characters, 2 for East Asian wide and emoji.-charWidth :: Char -> Int-charWidth c- | c < '\x0300' = 1 -- Fast path for ASCII and common Latin- | c == kittyPlaceholderChar = 1 -- Kitty Unicode placeholder (one cell)- | isRowColumnDiacritic c = 0 -- Kitty row/column combining diacritics- | c >= '\x0300' && c < '\x0370' = 0 -- Combining diacriticals- | c >= '\x1100' && c < '\x1200' = 2 -- Hangul Jamo- | c >= '\x2E80' && c < '\x9FFF' = 2 -- CJK- | c >= '\xAC00' && c < '\xD7A4' = 2 -- Hangul Syllables- | c >= '\xF900' && c < '\xFB00' = 2 -- CJK Compatibility Ideographs- | c >= '\xFE10' && c < '\xFE20' = 2 -- Vertical forms- | c >= '\xFE30' && c < '\xFE70' = 2 -- CJK Compatibility Forms- | c >= '\xFF00' && c < '\xFF61' = 2 -- Fullwidth Forms- | c >= '\xFFE0' && c < '\xFFE7' = 2 -- Fullwidth symbols- | c >= '\x1F000' = 2 -- Emoji, symbols, supplementary ideographs- | c >= '\x20000' && c < '\x2FFFF' = 2 -- Supplementary ideographs- | c >= '\x30000' && c < '\x3FFFF' = 2 -- Tertiary ideographs- | otherwise = 1---- | Calculate visible width of string (handles ANSI codes, emoji, CJK)-visibleLength :: String -> Int-visibleLength = sum . map charWidth . stripAnsi---- | The Unicode placeholder code point (U+10EEEE) the kitty graphics protocol--- uses to reserve one terminal cell per pixel-block of an inline image.-kittyPlaceholderChar :: Char-kittyPlaceholderChar = '\x10EEEE'---- | Row/column combining diacritics used by the kitty placeholder protocol to--- encode a cell's (row, column) into the placeholder glyph. Each renders with--- zero width. The table's length also caps the maximum image dimensions.-rowColumnDiacritics :: [Int]-rowColumnDiacritics =- [ 0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346- , 0x034a, 0x034b, 0x034c, 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363- , 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369, 0x036a, 0x036b, 0x036c- , 0x036d, 0x036e, 0x036f, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592- , 0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059c, 0x059d, 0x059e- , 0x059f, 0x05a0, 0x05a1, 0x05a8, 0x05a9, 0x05ab, 0x05ac, 0x05af, 0x05c4- , 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615, 0x0616, 0x0617, 0x0657- , 0x0658, 0x0659, 0x065a, 0x065b, 0x065d, 0x065e, 0x06d6, 0x06d7, 0x06d8- , 0x06d9, 0x06da, 0x06db, 0x06dc, 0x06df, 0x06e0, 0x06e1, 0x06e2, 0x06e4- , 0x06e7, 0x06e8, 0x06eb, 0x06ec, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736- , 0x073a, 0x073d, 0x073f, 0x0740, 0x0741, 0x0743, 0x0745, 0x0747, 0x0749- , 0x074a, 0x07eb, 0x07ec, 0x07ed, 0x07ee, 0x07ef, 0x07f0, 0x07f1, 0x07f3- , 0x0816, 0x0817, 0x0818, 0x0819, 0x081b, 0x081c, 0x081d, 0x081e, 0x081f- , 0x0820, 0x0821, 0x0822, 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082a- , 0x082b, 0x082c, 0x082d, 0x0951, 0x0953, 0x0954, 0x0f82, 0x0f83, 0x0f86- , 0x0f87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76- , 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e- , 0x1b6f, 0x1b70, 0x1b71, 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda- , 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4, 0x1dc5, 0x1dc6, 0x1dc7- , 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5- , 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde- , 0x1ddf, 0x1de0, 0x1de1, 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe- , 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7, 0x20db, 0x20dc, 0x20e1- , 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2- , 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb- , 0x2dec, 0x2ded, 0x2dee, 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4- , 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa, 0x2dfb, 0x2dfc, 0x2dfd- , 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1- , 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea- , 0xa8eb, 0xa8ec, 0xa8ed, 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2- , 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1, 0xfe20, 0xfe21, 0xfe22- , 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186- , 0x1d187, 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242- , 0x1d243, 0x1d244- ]---- | O(1)-ish membership test for the zero-width kitty diacritics above.-rowColumnDiacriticsSet :: IntSet.IntSet-rowColumnDiacriticsSet = IntSet.fromList rowColumnDiacritics--isRowColumnDiacritic :: Char -> Bool-isRowColumnDiacritic c = IntSet.member (ord c) rowColumnDiacriticsSet---- | Apply a function to each line, preserving trailing newlines-mapLines :: (String -> String) -> String -> String-mapLines f str- | null str = str- | otherwise = let ls = lines str- hasTrailingNewline = last str == '\n'- in if hasTrailingNewline- then unlines (map f ls)- else intercalate "\n" (map f ls)---- | Helper: pad a string to a target width on the right (ANSI-aware)-padRight :: Int -> String -> String-padRight targetWidth str = str ++ replicate (max 0 (targetWidth - visibleLength str)) ' '---- | Helper: pad a string to a target width on the left (ANSI-aware)-padLeft :: Int -> String -> String-padLeft targetWidth str = replicate (max 0 (targetWidth - visibleLength str)) ' ' ++ str---- | Helper: center a string within a target width (ANSI-aware)-centerString :: Int -> String -> String-centerString targetWidth str- | len >= targetWidth = str- | otherwise = leftPad ++ str ++ rightPad- where- len = visibleLength str- totalPadding = targetWidth - len- leftPad = replicate (totalPadding `div` 2) ' '- rightPad = replicate (totalPadding - length leftPad) ' '---- | Helper: justify text (spread words evenly to fill width)-justifyString :: Int -> String -> String-justifyString targetWidth str- | len >= targetWidth = str- | length ws <= 1 = str -- Can't justify single word- | otherwise = intercalate "" $ zipWith (++) ws spaces- where- ws = words str- len = length str- wordLengths = sum (map length ws)- totalSpaces = targetWidth - wordLengths- gaps = length ws - 1- baseSpaces = totalSpaces `div` gaps- extraSpaces = totalSpaces `mod` gaps- spaces = replicate extraSpaces (replicate (baseSpaces + 1) ' ')- ++ replicate (gaps - extraSpaces) (replicate baseSpaces ' ')- ++ [""] -- No space after last word---- | Core Element typeclass-class Element a where- renderElement :: a -> String-- -- | Calculate element width (longest line)- width :: a -> Int- width element =- let rendered = renderElement element- renderedLines = lines rendered- in if null renderedLines then 0- else maximum $ 0 : map visibleLength renderedLines-- -- | Calculate element height (number of lines)- height :: a -> Int- height element =- let rendered = renderElement element- in if null rendered then 1- else length (lines rendered)--render :: Element a => a -> String-render = renderElement--renderText :: Element a => a -> Data.Text.Text-renderText = T.pack . renderElement---- | L is the universal layout element type - a type-erased wrapper for the DSL.------ This allows mixing different element types in layouts while providing a common interface.--- Uses existential quantification to store any Element type inside L.------ Constructors:------ * @L a@ - Wraps any Element (Text, Box, Table, etc.)--- * @UL [L]@ - Special case for unordered lists (allows nesting)--- * @AutoCenter L@ - Smart centering that adapts to layout context width--- * @LBox@, @LStatusCard@, @LTable@ - Specialized constructors for bordered elements------ Example usage:------ @--- 'layout' ['text' "title", 'box' "content" [...], 'center' ('text' "footer")]--- @------ All different types unified as L, so they can be composed together.-data L = forall a. Element a => L a- | UL [L]- | OL [L]- | AutoCenter L- | Colored Color L- | Styled Style L- | LBox String [L] Border- | LStatusCard String String Border- | LTable [String] [[L]] Border--instance Element L where- renderElement (L x) = render x- renderElement (UL items) = render (UnorderedList items)- renderElement (OL items) = render (OrderedList items)- renderElement (AutoCenter element) = render element -- Will be handled by Layout- renderElement (Colored color element) = mapLines (wrapAnsi color) (render element)- renderElement (Styled style element) = mapLines (wrapStyle style) (render element)- renderElement (LBox title elements border) = render (Box title elements border)- renderElement (LStatusCard label content border) = render (StatusCard label content border)- renderElement (LTable headers rows border) = render (Table headers rows border)-- width (L x) = width x- width (UL items) = width (UnorderedList items)- width (OL items) = width (OrderedList items)- width (AutoCenter element) = width element- width (Colored _ element) = width element -- Width ignores color- width (Styled _ element) = width element -- Width ignores style- width (LBox title elements border) = width (Box title elements border)- width (LStatusCard label content border) = width (StatusCard label content border)- width (LTable headers rows border) = width (Table headers rows border)-- height (L x) = height x- height (UL items) = height (UnorderedList items)- height (OL items) = height (OrderedList items)- height (AutoCenter element) = height element- height (Colored _ element) = height element -- Height ignores color- height (Styled _ element) = height element -- Height ignores style- height (LBox title elements border) = height (Box title elements border)- height (LStatusCard label content border) = height (StatusCard label content border)- height (LTable headers rows border) = height (Table headers rows border)--instance Show L where- show = render---- | Enable string literals to be used directly as elements with OverloadedStrings------ With OverloadedStrings enabled, you can write @layout [\"Hello\", \"World\"]@--- instead of @layout [text \"Hello\", text \"World\"]@.-instance IsString L where- fromString = text---- | Border styles-data Border- = BorderNormal- | BorderDouble- | BorderThick- | BorderRound- | BorderAscii- | BorderBlock- | BorderDashed- | BorderDotted- | BorderInnerHalfBlock- | BorderOuterHalfBlock- | BorderMarkdown- | BorderCustom String String String -- ^ corner, horizontal, vertical- | BorderNone- deriving (Show, Eq)---- | Typeclass for elements that support customizable borders-class HasBorder a where- -- | Set the border style for an element- setBorder :: Border -> a -> a--instance HasBorder L where- setBorder border (LBox title elements _) = LBox title elements border- setBorder border (LStatusCard label content _) = LStatusCard label content border- setBorder border (LTable headers rows _) = LTable headers rows border- setBorder border (Colored color element) = Colored color (setBorder border element)- setBorder border (Styled style element) = Styled style (setBorder border element)- setBorder _ other = other -- Non-bordered elements remain unchanged---- | Color support with ANSI codes-data Color = ColorDefault | ColorBlack | ColorRed | ColorGreen | ColorYellow- | ColorBlue | ColorMagenta | ColorCyan | ColorWhite- | ColorBrightBlack | ColorBrightRed | ColorBrightGreen | ColorBrightYellow- | ColorBrightBlue | ColorBrightMagenta | ColorBrightCyan | ColorBrightWhite- | ColorFull Int -- ^ 256-color palette (0-255)- | ColorTrue Int Int Int -- ^ 24-bit RGB true color (r, g, b)- deriving (Show, Eq)---- | Get ANSI foreground color code-colorCode :: Color -> String-colorCode ColorDefault = ""-colorCode ColorBlack = "30"-colorCode ColorRed = "31"-colorCode ColorGreen = "32"-colorCode ColorYellow = "33"-colorCode ColorBlue = "34"-colorCode ColorMagenta = "35"-colorCode ColorCyan = "36"-colorCode ColorWhite = "37"-colorCode ColorBrightBlack = "90"-colorCode ColorBrightRed = "91"-colorCode ColorBrightGreen = "92"-colorCode ColorBrightYellow = "93"-colorCode ColorBrightBlue = "94"-colorCode ColorBrightMagenta = "95"-colorCode ColorBrightCyan = "96"-colorCode ColorBrightWhite = "97"-colorCode (ColorFull n) = "38;5;" ++ show (clamp n)-colorCode (ColorTrue r g b) = "38;2;" ++ show (clamp r) ++ ";" ++ show (clamp g) ++ ";" ++ show (clamp b)---- | Clamp value to 0-255 range for color codes-clamp :: Int -> Int-clamp = max 0 . min 255---- | Wrap text with ANSI color codes-wrapAnsi :: Color -> String -> String-wrapAnsi color str- | null (colorCode color) = str- | otherwise = "\ESC[" ++ colorCode color ++ "m" ++ str ++ "\ESC[0m"---- | Style support with ANSI codes-data Style = StyleDefault | StyleBold | StyleDim | StyleItalic | StyleUnderline- | StyleBlink | StyleReverse | StyleHidden | StyleStrikethrough- | StyleCombined [Style] -- ^ Combine multiple styles- deriving (Show, Eq)---- | Combine styles using @<>@-instance Semigroup Style where- StyleDefault <> other = other- other <> StyleDefault = other- StyleCombined styles1 <> StyleCombined styles2 = StyleCombined (styles1 ++ styles2)- StyleCombined styles <> style = StyleCombined (styles ++ [style])- style <> StyleCombined styles = StyleCombined (style : styles)- style1 <> style2 = StyleCombined [style1, style2]--instance Monoid Style where- mempty = StyleDefault---- | Get ANSI style code-styleCode :: Style -> String-styleCode StyleDefault = ""-styleCode StyleBold = "1"-styleCode StyleDim = "2"-styleCode StyleItalic = "3"-styleCode StyleUnderline = "4"-styleCode StyleBlink = "5"-styleCode StyleReverse = "7"-styleCode StyleHidden = "8"-styleCode StyleStrikethrough = "9"-styleCode (StyleCombined styles) =- let codes = filter (not . null) (map styleCode styles)- in if null codes then "" else intercalate ";" codes---- | Wrap text with ANSI style codes-wrapStyle :: Style -> String -> String-wrapStyle style str- | null (styleCode style) = str- | otherwise = "\ESC[" ++ styleCode style ++ "m" ++ str ++ "\ESC[0m"---- | Border character set supporting asymmetric borders (e.g. half-block styles)-data BorderChars = BorderChars- { bcTL, bcTR, bcBL, bcBR :: String -- corners- , bcHTop, bcHBottom :: String -- horizontal (top vs bottom)- , bcVLeft, bcVRight :: String -- vertical (left vs right)- , bcLeftTee, bcRightTee, bcCross :: String -- separator connectors- , bcTopTee, bcBottomTee :: String -- top/bottom column connectors- }---- | Helper for symmetric borders (hTop == hBottom, vLeft == vRight)-mkSymmetric :: String -> String -> String -> String -> String -> String- -> String -> String -> String -> String -> String -> BorderChars-mkSymmetric tl tr bl br' h v lt rt cross tt bt = BorderChars- { bcTL = tl, bcTR = tr, bcBL = bl, bcBR = br'- , bcHTop = h, bcHBottom = h- , bcVLeft = v, bcVRight = v- , bcLeftTee = lt, bcRightTee = rt, bcCross = cross- , bcTopTee = tt, bcBottomTee = bt- }--borderChars :: Border -> BorderChars-borderChars BorderNormal = mkSymmetric "┌" "┐" "└" "┘" "─" "│" "├" "┤" "┼" "┬" "┴"-borderChars BorderDouble = mkSymmetric "╔" "╗" "╚" "╝" "═" "║" "╠" "╣" "╬" "╦" "╩"-borderChars BorderThick = mkSymmetric "┏" "┓" "┗" "┛" "━" "┃" "┣" "┫" "╋" "┳" "┻"-borderChars BorderRound = mkSymmetric "╭" "╮" "╰" "╯" "─" "│" "├" "┤" "┼" "┬" "┴"-borderChars BorderAscii = mkSymmetric "+" "+" "+" "+" "-" "|" "+" "+" "+" "+" "+"-borderChars BorderBlock = mkSymmetric "█" "█" "█" "█" "█" "█" "█" "█" "█" "█" "█"-borderChars BorderDashed = mkSymmetric "┌" "┐" "└" "┘" "╌" "╎" "├" "┤" "┼" "┬" "┴"-borderChars BorderDotted = mkSymmetric "┌" "┐" "└" "┘" "┈" "┊" "├" "┤" "┼" "┬" "┴"-borderChars BorderInnerHalfBlock = BorderChars- { bcTL = "▗", bcTR = "▖", bcBL = "▝", bcBR = "▘"- , bcHTop = "▄", bcHBottom = "▀"- , bcVLeft = "▐", bcVRight = "▌"- , bcLeftTee = "▐", bcRightTee = "▌", bcCross = "▄"- , bcTopTee = "▄", bcBottomTee = "▀"- }-borderChars BorderOuterHalfBlock = BorderChars- { bcTL = "▛", bcTR = "▜", bcBL = "▙", bcBR = "▟"- , bcHTop = "▀", bcHBottom = "▄"- , bcVLeft = "▌", bcVRight = "▐"- , bcLeftTee = "▌", bcRightTee = "▐", bcCross = "▀"- , bcTopTee = "▀", bcBottomTee = "▄"- }-borderChars BorderMarkdown = mkSymmetric "|" "|" "|" "|" "-" "|" "|" "|" "|" "|" "|"-borderChars (BorderCustom corner h v) = mkSymmetric corner corner corner corner h v corner corner corner corner corner-borderChars BorderNone = mkSymmetric " " " " " " " " " " " " " " " " " " " " " "---- Elements-newtype Text = Text String-instance Element Text where renderElement (Text s) = s--data LineBreak = LineBreak-instance Element LineBreak where renderElement _ = ""--data Layout = Layout [L]-instance Element Layout where- renderElement (Layout elements) =- let -- Calculate max width of all non-AutoCenter elements- nonAutoCenterElements = [e | e <- elements, not (isAutoCenter e)]- maxWidth = if null nonAutoCenterElements- then 80 -- fallback- else maximum (0 : map width nonAutoCenterElements)-- -- Render elements, providing context width to AutoCenter elements- renderedElements = map (renderWithContext maxWidth) elements- in intercalate "\n" renderedElements- where- isAutoCenter (AutoCenter _) = True- isAutoCenter _ = False-- renderWithContext contextWidth (AutoCenter element) =- render (Centered (render element) contextWidth)- renderWithContext _ element = render element---- | Centered element with custom width-data Centered = Centered String Int -- content, target_width-instance Element Centered where- renderElement (Centered content targetWidth) =- intercalate "\n" $ map (centerString targetWidth) (lines content)---- | Underlined element with custom character-data Underlined = Underlined String String (Maybe Color) -- content, underline_char, optional color-instance Element Underlined where- renderElement (Underlined content underlineChar maybeColor) =- let contentLines = lines content- maxWidth = if null contentLines then 0- else maximum (map visibleLength contentLines)- repeats = maxWidth `div` length underlineChar- remainder = maxWidth `mod` length underlineChar- underlinePart = concat (replicate repeats underlineChar) ++ take remainder underlineChar- coloredUnderline = maybe underlinePart (`wrapAnsi` underlinePart) maybeColor- in content ++ "\n" ++ coloredUnderline--data Row = Row [L] Bool -- elements, tight (no spacing)-instance Element Row where- renderElement (Row elements tight)- | null elements = ""- | otherwise = intercalate "\n" $ map (intercalate separator) (transpose paddedElements)- where- separator = if tight then "" else " "- elementStrings = map render elements- elementLines = map lines elementStrings- maxHeight = maximum (map length elementLines)- elementWidths = map (maximum . map visibleLength) elementLines- paddedElements = zipWith padElement elementWidths elementLines-- padElement :: Int -> [String] -> [String]- padElement cellWidth linesList =- let currentLines = linesList ++ replicate (maxHeight - length linesList) ""- in map (padRight cellWidth) currentLines---- | Text alignment options-data Alignment = AlignLeft | AlignRight | AlignCenter | Justify- deriving (Show, Eq)---- | Aligned text with specified width and alignment-data AlignedText = AlignedText String Int Alignment -- content, width, alignment-instance Element AlignedText where- renderElement (AlignedText content targetWidth alignment) =- let alignFn = case alignment of- AlignLeft -> padRight targetWidth- AlignRight -> padLeft targetWidth- AlignCenter -> centerString targetWidth- Justify -> justifyString targetWidth- in intercalate "\n" $ map alignFn (lines content)--data Box = Box String [L] Border--instance HasBorder Box where- setBorder border (Box title elements _) = Box title elements border--instance Element Box where- renderElement (Box title elements border) =- let elementStrings = map render elements- content = intercalate "\n" elementStrings- contentLines = if null content then [""] else lines content- contentWidth = maximum (0 : map visibleLength contentLines)- titleWidth = if null title then 0 else visibleLength title + 2- innerWidth = max contentWidth titleWidth- totalWidth = innerWidth + 4- BorderChars{..} = borderChars border- hTopChar = head bcHTop- hBottomChar = head bcHBottom-- topBorder- | null title = bcTL ++ replicate (totalWidth - 2) hTopChar ++ bcTR- | otherwise = let titlePadding = totalWidth - visibleLength title - 2- leftPad = titlePadding `div` 2- rightPad = titlePadding - leftPad- in bcTL ++ replicate leftPad hTopChar ++ title ++ replicate rightPad hTopChar ++ bcTR-- bottomBorder = bcBL ++ replicate (totalWidth - 2) hBottomChar ++ bcBR- paddedContent = map (\line -> bcVLeft ++ " " ++ padRight innerWidth line ++ " " ++ bcVRight) contentLines-- in intercalate "\n" (topBorder : paddedContent ++ [bottomBorder])--data StatusCard = StatusCard String String Border--instance HasBorder StatusCard where- setBorder border (StatusCard label content _) = StatusCard label content border--instance Element StatusCard where- renderElement (StatusCard label content border) =- let labelLines = lines label- contentLines = lines content- allLines = labelLines ++ contentLines- maxWidth = maximum (0 : map visibleLength allLines)- contentWidth = maxWidth + 2- BorderChars{..} = borderChars border- hTopChar = head bcHTop- hBottomChar = head bcHBottom-- topBorder = bcTL ++ replicate (contentWidth + 2) hTopChar ++ bcTR- bottomBorder = bcBL ++ replicate (contentWidth + 2) hBottomChar ++ bcBR- createCardLine line = bcVLeft ++ " " ++ padRight contentWidth line ++ " " ++ bcVRight-- in intercalate "\n" $ [topBorder] ++ map createCardLine allLines ++ [bottomBorder]---- | Margin element that adds prefix to each line-data Margin = Margin String [L] -- prefix, elements-instance Element Margin where- renderElement (Margin prefix elements) =- let content = case elements of- [single] -> render single- _ -> render (Layout elements)- in intercalate "\n" $ map ((prefix ++ " ") ++) (lines content)---- | Horizontal rule with custom character and width-data HorizontalRule = HorizontalRule String Int -- char, width-instance Element HorizontalRule where- renderElement (HorizontalRule char ruleWidth) = concat (replicate ruleWidth char)---- | Vertical rule with custom character and height-data VerticalRule = VerticalRule String Int -- char, height-instance Element VerticalRule where- renderElement (VerticalRule char ruleHeight) = intercalate "\n" (replicate ruleHeight char)---- | Padded element with padding around all sides-data Padded = Padded String Int -- content, padding-instance Element Padded where- renderElement (Padded content padding) =- let contentLines = lines content- maxWidth = maximum (0 : map length contentLines)- horizontalPad = replicate padding ' '- totalWidth = maxWidth + padding * 2- verticalPad = replicate totalWidth ' '- paddedLines = map (\line -> horizontalPad ++ padRight maxWidth line ++ horizontalPad) contentLines- verticalLines = replicate padding verticalPad- in intercalate "\n" (verticalLines ++ paddedLines ++ verticalLines)---- | Columns: place elements side by side, each padded to its own width-data Columns = Columns [L] Int -- elements, spacing between columns-instance Element Columns where- renderElement (Columns elements spacing)- | null elements = ""- | otherwise = intercalate "\n" $ map (intercalate separator) (transpose paddedElements)- where- separator = replicate spacing ' '- elementLines = map (lines . render) elements- maxHeight = maximum (map length elementLines)- elementWidths = map (maximum . (0 :) . map visibleLength) elementLines- paddedElements = zipWith padColumn elementWidths elementLines-- padColumn :: Int -> [String] -> [String]- padColumn cellWidth linesList =- let filled = linesList ++ replicate (maxHeight - length linesList) ""- in map (padRight cellWidth) filled---- | Truncate each line with an ellipsis when it exceeds the max width-data Truncated = Truncated String Int String -- content, maxWidth, ellipsis-instance Element Truncated where- renderElement (Truncated content maxWidth ellipsis) =- intercalate "\n" $ map truncateLine (lines content)- where- truncateLine line- | visibleLength line <= maxWidth = line- | truncateAt <= 0 = take maxWidth ellipsis- | otherwise = take truncateAt (stripAnsi line) ++ ellipsis- where truncateAt = maxWidth - length ellipsis---- | Chart for data visualization-data Chart = Chart [(String, Double)] -- (label, value) pairs-instance Element Chart where- renderElement (Chart dataPoints)- | null dataPoints = "No data"- | otherwise = intercalate "\n" $ map renderBar dataPoints- where- maxValue = maximum (0 : map snd dataPoints)- maxLabelWidth = minimum [15, maximum (0 : map (length . fst) dataPoints)]- chartWidth = 40-- renderBar :: (String, Double) -> String- renderBar (label, value) =- let truncatedLabel- | length label > maxLabelWidth = take (maxLabelWidth - 3) label ++ "..."- | otherwise = label- paddedLabel = padRight maxLabelWidth truncatedLabel- percentage = value / maxValue- barLength = floor (percentage * fromIntegral chartWidth)- bar = replicate barLength '█' ++ replicate (chartWidth - barLength) '─'- valueStr- | value == fromInteger (round value) = show (round value :: Integer)- | otherwise = printf "%.1f" value- in paddedLabel ++ " │" ++ bar ++ "│ " ++ valueStr---- | Table with headers and borders (fixed alignment)-data Table = Table [String] [[L]] Border -- headers, rows, border--instance HasBorder Table where- setBorder border (Table headers rows _) = Table headers rows border--instance Element Table where- renderElement (Table headers rows border) =- let normalizedRows = map (normalizeRow (length headers)) rows- columnWidths = calculateColumnWidths headers normalizedRows- BorderChars{..} = borderChars border- hTopChar = head bcHTop- hBottomChar = head bcHBottom-- -- Top border- topParts = map (\w -> replicate w hTopChar) columnWidths- topBorder = bcTL ++ [hTopChar] ++ intercalate ([hTopChar] ++ bcTopTee ++ [hTopChar]) topParts ++ [hTopChar] ++ bcTR-- -- Separator (between header and data)- separatorParts = map (\w -> replicate w hTopChar) columnWidths- separatorBorder = bcLeftTee ++ [hTopChar] ++ intercalate ([hTopChar] ++ bcCross ++ [hTopChar]) separatorParts ++ [hTopChar] ++ bcRightTee-- -- Bottom border- bottomParts = map (\w -> replicate w hBottomChar) columnWidths- bottomBorder = bcBL ++ [hBottomChar] ++ intercalate ([hBottomChar] ++ bcBottomTee ++ [hBottomChar]) bottomParts ++ [hBottomChar] ++ bcBR-- -- Header row- headerCells = zipWith padRight columnWidths headers- headerRow = bcVLeft ++ " " ++ intercalate (" " ++ bcVLeft ++ " ") headerCells ++ " " ++ bcVRight-- -- Data rows- dataRows = concatMap (renderTableRow columnWidths bcVLeft bcVRight) normalizedRows-- in intercalate "\n" ([topBorder, headerRow, separatorBorder] ++ dataRows ++ [bottomBorder])- where- normalizeRow :: Int -> [L] -> [L]- normalizeRow expectedLen rowData- | currentLen >= expectedLen = take expectedLen rowData- | otherwise = rowData ++ replicate (expectedLen - currentLen) (text "")- where currentLen = length rowData-- calculateColumnWidths :: [String] -> [[L]] -> [Int]- calculateColumnWidths hdrs rws =- let headerWidths = map visibleLength hdrs- rowWidths = map (map (maximum . (0:) . map visibleLength . lines . render)) rws- allWidths = headerWidths : rowWidths- in map (maximum . (0:)) (transpose allWidths)-- renderTableRow :: [Int] -> String -> String -> [L] -> [String]- renderTableRow widths vLeft vRight rowData =- let cellContents = map render rowData- cellLines = map lines cellContents- maxCellHeight = maximum (1 : map length cellLines)- paddedCells = zipWith (padCell maxCellHeight) widths cellLines- tableRows = transpose paddedCells- in map (\rowCells -> vLeft ++ " " ++ intercalate (" " ++ vLeft ++ " ") rowCells ++ " " ++ vRight) tableRows-- padCell :: Int -> Int -> [String] -> [String]- padCell cellHeight cellWidth cellLines =- let paddedLines = cellLines ++ replicate (cellHeight - length cellLines) ""- in map (padRight cellWidth) paddedLines---- | Section with decorative header-data Section = Section String [L] String Int -- title, content, glyph, flanking_chars-instance Element Section where- renderElement (Section title content glyph flankingChars) =- let header = replicate flankingChars (head glyph) ++ " " ++ title ++ " " ++ replicate flankingChars (head glyph)- body = render (Layout content)- in header ++ "\n" ++ body---- | Key-value pairs with alignment-data KeyValue = KeyValue [(String, String)]-instance Element KeyValue where- renderElement (KeyValue pairs) =- if null pairs then ""- else let maxKeyLength = maximum (map (visibleLength . fst) pairs)- alignmentPosition = maxKeyLength + 2- in intercalate "\n" $ map (renderPair alignmentPosition) pairs- where- renderPair alignPos (key, value) =- let keyWithColon = key ++ ":"- spacesNeeded = alignPos - visibleLength keyWithColon- padding = replicate (max 1 spacesNeeded) ' '- in keyWithColon ++ padding ++ value---- | Tree structure for hierarchical data-data Tree = Tree String [Tree]--instance Element Tree where- renderElement treeData = renderTree treeData "" True []- where- renderTree (Tree name children) prefix isLast parentPrefixes =- let nodeLine = if null parentPrefixes- then name- else prefix ++ (if isLast then "└── " else "├── ") ++ name- childPrefix = if null parentPrefixes- then ""- else prefix ++ (if isLast then " " else "│ ")- childLines = zipWith (\child idx ->- renderTree child childPrefix (idx == length children - 1) (parentPrefixes ++ [not isLast])- ) children [0..]- in if null children- then nodeLine- else nodeLine ++ "\n" ++ intercalate "\n" childLines---newtype UnorderedList = UnorderedList [L]-instance Element UnorderedList where- renderElement (UnorderedList items) = renderAtLevel 0 items- where- bulletStyles = ["•", "◦", "▪"]-- renderAtLevel level itemList =- let currentBullet = bulletStyles !! (level `mod` length bulletStyles)- indent = replicate (level * 2) ' '- in intercalate "\n" $ map (renderItem level indent currentBullet) itemList-- renderItem level indent bullet item = case item of- UL nested -> renderAtLevel (level + 1) nested- _ -> let content = render item- contentLines = lines content- in case contentLines of- [singleLine] -> indent ++ bullet ++ " " ++ singleLine- (firstLine:restLines) ->- let firstOutput = indent ++ bullet ++ " " ++ firstLine- restIndent = replicate (length indent + length bullet + 1) ' '- restOutput = map (restIndent ++) restLines- in intercalate "\n" (firstOutput : restOutput)- [] -> indent ++ bullet ++ " "--newtype OrderedList = OrderedList [L]-instance Element OrderedList where- renderElement (OrderedList items) = renderAtLevel 1 0 items- where- renderAtLevel startNum level itemList =- let indent = replicate (level * 2) ' '- numbered = zip [startNum..] itemList- in intercalate "\n" $ map (renderItem level indent) numbered-- renderItem level indent (num, item) = case item of- OL nested -> renderAtLevel 1 (level + 1) nested- _ -> let numStr = formatNumber level num ++ ". "- content = render item- contentLines = lines content- in case contentLines of- [singleLine] -> indent ++ numStr ++ singleLine- (firstLine:restLines) ->- let firstOutput = indent ++ numStr ++ firstLine- restIndent = replicate (length numStr) ' '- restOutput = map ((indent ++ restIndent) ++) restLines- in intercalate "\n" (firstOutput : restOutput)- [] -> indent ++ numStr-- formatNumber :: Int -> Int -> String- formatNumber lvl num = case lvl `mod` 3 of- 0 -> show num -- 1, 2, 3- 1 -> [toEnum (96 + num)] -- a, b, c- _ -> toRoman num -- i, ii, iii-- toRoman :: Int -> String- toRoman = \case- 1 -> "i"; 2 -> "ii"; 3 -> "iii"; 4 -> "iv"; 5 -> "v"- 6 -> "vi"; 7 -> "vii"; 8 -> "viii"; 9 -> "ix"; 10 -> "x"- n -> show n--data InlineBar = InlineBar String Double-instance Element InlineBar where- renderElement (InlineBar label progress) =- let clampedProgress = max 0.0 (min 1.0 progress)- barWidth = 20- filledSegments = floor (clampedProgress * fromIntegral barWidth)- emptySegments = barWidth - filledSegments- bar = replicate filledSegments '█' ++ replicate emptySegments '─'- percentage = floor (clampedProgress * 100) :: Int- in printf "%s [%s] %d%%" label bar percentage---- Smart constructors and automatic conversions-text :: String -> L-text s = L (Text s)--br :: L-br = L LineBreak--center :: Element a => a -> L-center element = AutoCenter (L element)---- | Center element within specified width-center' :: Element a => Int -> a -> L-center' targetWidth element = L (Centered (render element) targetWidth)--underline :: Element a => a -> L-underline element = L (Underlined (render element) "─" Nothing)---- | Add underline with custom character-underline' :: Element a => String -> a -> L-underline' char element = L (Underlined (render element) char Nothing)---- | Add colored underline with custom character and color------ @--- 'underlineColored' "=" 'ColorRed' $ 'text' "Error Section"--- 'underlineColored' "~" 'ColorGreen' $ 'text' "Success"--- 'underlineColored' "─" 'ColorBrightCyan' $ 'text' "Info"--- @-underlineColored :: Element a => String -> Color -> a -> L-underlineColored char color element = L (Underlined (render element) char (Just color))--ul :: [L] -> L-ul = UL--ol :: [L] -> L-ol = OL--inlineBar :: String -> Double -> L-inlineBar label progress = L (InlineBar label progress)--statusCard :: String -> String -> L-statusCard label content = LStatusCard label content BorderNormal--layout :: [L] -> L-layout elements = L (Layout elements)--row :: [L] -> L-row elements = L (Row elements False)---- | Create horizontal row with no spacing between elements (for gradients, etc.)-tightRow :: [L] -> L-tightRow elements = L (Row elements True)---- | Align text to the left within specified width-alignLeft :: Int -> String -> L-alignLeft targetWidth content = L (AlignedText content targetWidth AlignLeft)---- | Align text to the right within specified width-alignRight :: Int -> String -> L-alignRight targetWidth content = L (AlignedText content targetWidth AlignRight)---- | Align text to the center within specified width-alignCenter :: Int -> String -> L-alignCenter targetWidth content = L (AlignedText content targetWidth AlignCenter)---- | Justify text (spread words evenly to fill width)-justify :: Int -> String -> L-justify targetWidth content = L (AlignedText content targetWidth Justify)---- | Wrap text to multiple lines with specified width-wrap :: Int -> String -> L-wrap targetWidth content =- let ws = words content- wrappedLines = wrapWords targetWidth ws- in layout (map text wrappedLines)- where- wrapWords :: Int -> [String] -> [String]- wrapWords _ [] = []- wrapWords maxWidth wordsList =- let (line, rest) = takeLine maxWidth wordsList- in line : wrapWords maxWidth rest-- takeLine :: Int -> [String] -> (String, [String])- takeLine _ [] = ("", [])- takeLine maxWidth (firstWord:restWords)- | length firstWord > maxWidth = (firstWord, restWords) -- Word too long, put it on its own line- | otherwise = go (length firstWord) [firstWord] restWords- where- go _ acc [] = (unwords (reverse acc), [])- go currentLen acc (nextWord:remainingWords)- | currentLen + 1 + length nextWord <= maxWidth = go (currentLen + 1 + length nextWord) (nextWord:acc) remainingWords- | otherwise = (unwords (reverse acc), nextWord:remainingWords)--box :: String -> [L] -> L-box title elements = LBox title elements BorderNormal---- | Banner: a titleless bordered box (Double border by default)------ @--- 'banner' ["System Dashboard"]--- -- ╔══════════════════╗--- -- ║ System Dashboard ║--- -- ╚══════════════════╝--- @-banner :: [L] -> L-banner content = LBox "" content BorderDouble---- | Create margin with custom prefix------ @--- 'margin' "[error]" ['text' "Something went wrong"]--- 'margin' "[info]" ['text' "FYI: Check the logs"]--- @-margin :: String -> [L] -> L-margin prefix elements = L (Margin prefix elements)---- | Horizontal rule with default character and width-hr :: L-hr = L (HorizontalRule "─" 50)---- | Horizontal rule with custom character-hr' :: String -> L-hr' char = L (HorizontalRule char 50)---- | Horizontal rule with custom character and width-hr'' :: String -> Int -> L-hr'' char ruleWidth = L (HorizontalRule char ruleWidth)---- | Vertical rule with default character and height-vr :: L-vr = L (VerticalRule "│" 10)---- | Vertical rule with custom character-vr' :: String -> L-vr' char = L (VerticalRule char 10)---- | Vertical rule with custom character and height-vr'' :: String -> Int -> L-vr'' char ruleHeight = L (VerticalRule char ruleHeight)---- | Add padding around element-pad :: Element a => Int -> a -> L-pad padding element = L (Padded (render element) padding)---- | Place elements side by side (2 spaces between columns)------ @--- 'columns' ['layout' ["A", "B"], 'layout' ["C", "D"]]--- -- A C--- -- B D--- @-columns :: [L] -> L-columns elements = L (Columns elements 2)---- | Like 'columns' with a custom gap between columns-columns' :: Int -> [L] -> L-columns' spacing elements = L (Columns elements spacing)---- | Truncate an element with a trailing @"..."@ when it is too wide------ @--- 'truncate'' 15 "Very long text that will be cut off" -- Very long te...--- @-truncate' :: Element a => Int -> a -> L-truncate' maxWidth element = L (Truncated (render element) maxWidth "...")---- | Like 'truncate'' with a custom ellipsis-truncate'' :: Element a => Int -> String -> a -> L-truncate'' maxWidth ellipsis element = L (Truncated (render element) maxWidth ellipsis)---- | Create horizontal bar chart-chart :: [(String, Double)] -> L-chart dataPoints = L (Chart dataPoints)---- | Create table with headers and rows-table :: [String] -> [[L]] -> L-table headers rows = LTable headers rows BorderNormal---- | Create section with title and content-section :: String -> [L] -> L-section title content = L (Section title content "=" 3)---- | Create section with custom glyph-section' :: String -> String -> [L] -> L-section' glyph title content = L (Section title content glyph 3)---- | Create section with custom glyph and flanking chars-section'' :: String -> String -> Int -> [L] -> L-section'' glyph title flanking content = L (Section title content glyph flanking)---- | Create key-value pairs-kv :: [(String, String)] -> L-kv pairs = L (KeyValue pairs)---- | Apply a border style to elements that support borders------ Elements that support borders: 'box', 'statusCard', 'table'.--- Other elements are returned unchanged.------ @--- withBorder BorderDouble $ table [\"Name\"] [[text \"Alice\"]]--- @-withBorder :: Border -> L -> L-withBorder = setBorder---- | Apply a color to an element------ @--- withColor ColorBrightYellow $ box \"Warning\" [text "Check logs"]--- @-withColor :: Color -> L -> L-withColor = Colored---- | Apply a style to an element------ @--- withStyle StyleBold $ text "Important!"--- @-withStyle :: Style -> L -> L-withStyle = Styled---- | Create tree structure-tree :: String -> [Tree] -> L-tree name children = L (Tree name children)---- | Create leaf tree node (no children)-leaf :: String -> Tree-leaf name = Tree name []---- | Create branch tree node with children-branch :: String -> [Tree] -> Tree-branch name children = Tree name children---- ============================================================================--- Spinner Animations--- ============================================================================---- | Spinner style with animation frames-data SpinnerStyle- = SpinnerDots- | SpinnerLine- | SpinnerClock- | SpinnerBounce- | SpinnerEarth- | SpinnerMoon- | SpinnerGrow- | SpinnerArrow- deriving (Show, Eq)---- | Get animation frames for a spinner style-spinnerFrames :: SpinnerStyle -> [String]-spinnerFrames SpinnerDots = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]-spinnerFrames SpinnerLine = ["|", "/", "-", "\\"]-spinnerFrames SpinnerClock = ["🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚", "🕛"]-spinnerFrames SpinnerBounce = ["⠁", "⠂", "⠄", "⠂"]-spinnerFrames SpinnerEarth = ["🌍", "🌎", "🌏"]-spinnerFrames SpinnerMoon = ["🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"]-spinnerFrames SpinnerGrow = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█", "▉", "▊", "▋", "▌", "▍", "▎"]-spinnerFrames SpinnerArrow = ["←", "↖", "↑", "↗", "→", "↘", "↓", "↙"]---- | Spinner animation element-data Spinner = Spinner String Int SpinnerStyle -- label, frame, style--instance Element Spinner where- renderElement (Spinner label frame style) =- let frames = spinnerFrames style- spinChar = frames !! (frame `mod` length frames)- in if null label- then spinChar- else spinChar ++ " " ++ label---- | Create an animated spinner------ Example usage:------ @--- 'spinner' \"Loading\" 5 'SpinnerDots' -- Shows the 5th frame of dots spinner--- 'spinner' \"Processing\" 0 'SpinnerLine' -- Shows first frame with label--- @------ Increment the frame number each render to animate:------ @--- 'layout' ['spinner' \"Working\" (tickCount \`mod\` 10) 'SpinnerDots']--- @-spinner :: String -> Int -> SpinnerStyle -> L-spinner label frame style = L (Spinner label frame style)---- ============================================================================--- Visualization Primitives--- ============================================================================---- | Block characters for sparklines and bar charts (indices 0–8)-blockChars :: String-blockChars = " ▁▂▃▄▅▆▇█"---- | Braille dot bit flag for position (row 0–3, col 0–1) in a 2×4 braille cell-brailleDot :: Int -> Int -> Int-brailleDot 0 0 = 0x01-brailleDot 1 0 = 0x02-brailleDot 2 0 = 0x04-brailleDot 3 0 = 0x40-brailleDot 0 1 = 0x08-brailleDot 1 1 = 0x10-brailleDot 2 1 = 0x20-brailleDot 3 1 = 0x80-brailleDot _ _ = 0---- | Default color palette for cycling through series/slices-defaultPalette :: [Color]-defaultPalette = [ ColorBrightCyan, ColorBrightMagenta, ColorBrightYellow- , ColorBrightGreen, ColorBrightRed, ColorBrightBlue ]---- | Use explicit color if not ColorDefault, else cycle palette by index-pickColor :: Int -> Color -> Color-pickColor idx ColorDefault = defaultPalette !! (idx `mod` length defaultPalette)-pickColor _ c = c---- | Format number for axis labels: "3" for integers, "3.5" for decimals-formatAxisNum :: Double -> String-formatAxisNum v- | v == fromInteger (round v) = show (round v :: Integer)- | otherwise = printf "%.1f" v---- | ANSI 256-color background escape sequence-bgColor256 :: Int -> String-bgColor256 n = "\ESC[48;5;" ++ show n ++ "m"---- | ANSI reset sequence-ansiReset :: String-ansiReset = "\ESC[0m"---- Sparkline ----------------------------------------------------data SparklineData = SparklineData [Double]--instance Element SparklineData where- renderElement (SparklineData []) = ""- renderElement (SparklineData vals) =- let mn = minimum vals- mx = maximum vals- rng = mx - mn- idx v | rng == 0 = 4- | otherwise = max 1 $ min 8 $ floor ((v - mn) / rng * 8)- in map (\v -> blockChars !! idx v) vals---- | Create a sparkline from a list of values-plotSparkline :: [Double] -> L-plotSparkline = L . SparklineData---- Line Plot (Braille) ------------------------------------------------------ | A data series for line plots: points, label, color-data Series = Series [(Double, Double)] String Color--data PlotData = PlotData [Series] Int Int -- series, width, height--instance Element PlotData where- renderElement (PlotData ss w h)- | null ss || all (\(Series ps _ _) -> null ps) ss = "No data"- | otherwise =- let allPts = concatMap (\(Series ps _ _) -> ps) ss- (xs, ys) = unzip allPts- xMin = minimum xs; xMax = maximum xs- yMin = minimum ys; yMax = maximum ys- xRng = if xMax == xMin then 1.0 else xMax - xMin- yRng = if yMax == yMin then 1.0 else yMax - yMin- pxW = w * 2; pxH = h * 4-- toPixel (x, y) =- ( clampI 0 (pxW - 1) $ round ((x - xMin) / xRng * fromIntegral (pxW - 1))- , clampI 0 (pxH - 1) $ round ((yMax - y) / yRng * fromIntegral (pxH - 1))- )- clampI lo hi = max lo . min hi-- emptyGrid = replicate h (replicate w (0 :: Int, -1 :: Int))-- plotSeries grd sIdx (Series ps _ _) =- foldl (\g p ->- let (px, py) = toPixel p- cx = px `div` 2; cy = py `div` 4- dx = px `mod` 2; dy = py `mod` 4- bit = brailleDot dy dx- in updGrid cy cx (\(b, si) -> (b .|. bit, if si < 0 then sIdx else si)) g- ) grd ps-- updGrid r c f g =- [ if ri == r- then [ if ci == c then f cell else cell | (ci, cell) <- zip [0..] row' ]- else row'- | (ri, row') <- zip [0..] g ]-- grid = foldl (\g (i, s) -> plotSeries g i s) emptyGrid (zip [0..] ss)-- yTicks = [ yMax - yRng * fromIntegral i / fromIntegral (max 1 (h - 1)) | i <- [0 .. h-1] ]- yLabels = map formatAxisNum yTicks- yLabelW = maximum (0 : map length yLabels)-- gridLines = zipWith (\yLbl row' ->- padLeft yLabelW yLbl ++ " │" ++- concatMap (\(bits, si) ->- let ch = if bits == 0 then ' ' else chr (0x2800 + bits)- c = if si >= 0 then pickColor si (sColor (ss !! si)) else ColorDefault- in if c == ColorDefault then [ch] else wrapAnsi c [ch]- ) row'- ) yLabels grid-- xAxis = replicate (yLabelW + 2) ' ' ++ replicate w '─'- xMinL = formatAxisNum xMin- xMaxL = formatAxisNum xMax- xLabels = replicate (yLabelW + 2) ' ' ++ xMinL- ++ replicate (max 1 (w - length xMinL - length xMaxL)) ' '- ++ xMaxL-- legend- | length ss <= 1 = []- | otherwise = ["", intercalate " " $- zipWith (\i (Series _ nm cl) ->- wrapAnsi (pickColor i cl) "●" ++ " " ++ nm- ) [0..] ss]-- in intercalate "\n" (gridLines ++ [xAxis, xLabels] ++ legend)- where sColor (Series _ _ c) = c---- | Create a braille line plot-plotLine :: Int -> Int -> [Series] -> L-plotLine w h ss = L (PlotData ss w h)---- Pie Chart (Braille) ------------------------------------------------------ | A slice of a pie chart: value, label, color-data Slice = Slice Double String Color--data PieData = PieData [Slice] Int Int--instance Element PieData where- renderElement (PieData [] _ _) = "No data"- renderElement (PieData slices w h) =- let total = sum [ v | Slice v _ _ <- slices ]- cumAngs = scanl (+) 0 [ v / total * 2 * pi | Slice v _ _ <- slices ]-- cxF = fromIntegral w :: Double- cyF = fromIntegral (h * 4) / 2.0 :: Double- radius = min cxF (cyF * 0.9)-- findSlice ang = go 0 (tail cumAngs)- where go i [] = max 0 (i - 1)- go i (a:as') = if ang < a then i else go (i + 1) as'-- renderCell gcx gcy =- let subPx = [ (dy, dx, dist, nAng)- | dy <- [0..3], dx <- [0..1]- , let dpx = fromIntegral (gcx * 2 + dx) :: Double- dpy = fromIntegral (gcy * 4 + dy) :: Double- relX = dpx - cxF- relY = (dpy - cyF) * 2.0- dist = sqrt (relX * relX + relY * relY)- ang = atan2 relY relX- nAng = if ang < 0 then ang + 2 * pi else ang- ]- inside = [ (dy, dx, nAng) | (dy, dx, dist, nAng) <- subPx, dist <= radius ]- bits = foldl (\acc (dy, dx, _) -> acc .|. brailleDot dy dx) 0 inside- domSi = case inside of- [] -> -1- ((_, _, a):_) -> findSlice a- ch = if bits == 0 then ' ' else chr (0x2800 + bits)- color = if domSi >= 0 && domSi < length slices- then pickColor domSi (slColor (slices !! domSi))- else ColorDefault- in if bits == 0 then " " else wrapAnsi color [ch]-- gridLines = [ concatMap (\gcx -> renderCell gcx gcy) [0..w-1] | gcy <- [0..h-1] ]-- legendLines = zipWith (\i (Slice v nm cl) ->- let c = pickColor i cl- pct = printf "%.0f" (v / total * 100) :: String- in " " ++ wrapAnsi c "●" ++ " " ++ nm ++ " (" ++ pct ++ "%)"- ) [0..] slices-- in intercalate "\n" (gridLines ++ [""] ++ legendLines)- where slColor (Slice _ _ c) = c---- | Create a braille pie chart-plotPie :: Int -> Int -> [Slice] -> L-plotPie w h sl = L (PieData sl w h)---- Bar Chart (Vertical) ------------------------------------------------------------ | A bar item: value, label, color-data BarItem = BarItem Double String Color--data BarChartData = BarChartData [BarItem] Int Int--instance Element BarChartData where- renderElement (BarChartData [] _ _) = "No data"- renderElement (BarChartData items w h) =- let maxVal = maximum [ v | BarItem v _ _ <- items ]- nBars = length items- barW = max 1 $ (w - nBars + 1) `div` nBars- totalSub = h * 8- barHts = [ round (v / maxVal * fromIntegral totalSub) :: Int | BarItem v _ _ <- items ]-- yTicks = [ maxVal * fromIntegral (h - 1 - i) / fromIntegral (max 1 (h - 1)) | i <- [0..h-1] ]- yLabels = map formatAxisNum yTicks- yLabelW = maximum (0 : map length yLabels)-- gridLines =- [ let r = h - 1 - rowIdx- barCells = intercalate " " $- map (\(i, (bh, BarItem _ _ cl)) ->- let filled = min 8 $ max 0 (bh - r * 8)- color' = pickColor i cl- barStr = replicate barW (blockChars !! filled)- in if filled > 0 then wrapAnsi color' barStr else barStr- ) (zip [0..] (zip barHts items))- in padLeft yLabelW (yLabels !! rowIdx) ++ " │" ++ barCells- | rowIdx <- [0..h-1]- ]-- xAxisW = nBars * barW + nBars - 1- xAxis = replicate (yLabelW + 2) ' ' ++ replicate xAxisW '─'- barLabels = replicate (yLabelW + 2) ' ' ++- intercalate " " [ take barW (nm ++ replicate barW ' ') | BarItem _ nm _ <- items ]-- in intercalate "\n" (gridLines ++ [xAxis, barLabels])---- | Create a vertical bar chart-plotBar :: Int -> Int -> [BarItem] -> L-plotBar w h items = L (BarChartData items w h)---- Stacked Bar Chart ----------------------------------------------------------- | A group of stacked bars: segments and group label-data StackedBarGroup = StackedBarGroup [BarItem] String--data StackedBarChartData = StackedBarChartData [StackedBarGroup] Int Int--instance Element StackedBarChartData where- renderElement (StackedBarChartData [] _ _) = "No data"- renderElement (StackedBarChartData groups w h) =- let maxTotal = maximum [ sum [ v | BarItem v _ _ <- segs ] | StackedBarGroup segs _ <- groups ]- nGroups = length groups- barW = max 1 $ (w - nGroups + 1) `div` nGroups- totalSub = h * 8-- groupBounds = map (\(StackedBarGroup segs _) ->- let vals = [ v | BarItem v _ _ <- segs ]- subHts = map (\v -> round (v / maxTotal * fromIntegral totalSub) :: Int) vals- cumHts = scanl (+) 0 subHts- bottoms = init cumHts- tops = tail cumHts- in zip segs (zip bottoms tops)- ) groups-- allLabels = nub [ nm | StackedBarGroup segs _ <- groups, BarItem _ nm _ <- segs ]- labelIdx nm = case lookup nm (zip allLabels [0..]) of- Just i -> i- Nothing -> 0-- yTicks = [ maxTotal * fromIntegral (h - 1 - i) / fromIntegral (max 1 (h - 1)) | i <- [0..h-1] ]- yLabels = map formatAxisNum yTicks- yLabelW = maximum (0 : map length yLabels)-- gridLines =- [ let r = h - 1 - rowIdx- subBot = r * 8- subTop = r * 8 + 8- barCells = intercalate " " $- map (\bounds ->- let overlapping = [ (bi, bot, top)- | (bi, (bot, top)) <- bounds- , top > subBot, bot < subTop ]- topSeg = case overlapping of- [] -> Nothing- _ -> Just $ foldl1 (\a@(_, _, t1) b@(_, _, t2) ->- if t2 > t1 then b else a) overlapping- in case topSeg of- Nothing -> replicate barW ' '- Just (BarItem _ nm cl, _, top) ->- let filled = min 8 $ max 0 (top - subBot)- color' = case cl of- ColorDefault -> pickColor (labelIdx nm) ColorDefault- _ -> cl- barStr = replicate barW (blockChars !! filled)- in if filled > 0 then wrapAnsi color' barStr else barStr- ) groupBounds- in padLeft yLabelW (yLabels !! rowIdx) ++ " │" ++ barCells- | rowIdx <- [0..h-1]- ]-- xAxisW = nGroups * barW + nGroups - 1- xAxis = replicate (yLabelW + 2) ' ' ++ replicate xAxisW '─'- grpLabels = replicate (yLabelW + 2) ' ' ++- intercalate " " [ take barW (nm ++ replicate barW ' ')- | StackedBarGroup _ nm <- groups ]-- legendItems = map (\nm ->- let i = labelIdx nm- c = defaultPalette !! (i `mod` length defaultPalette)- in wrapAnsi c "█" ++ " " ++ nm- ) allLabels- legendLine- | length allLabels <= 1 = []- | otherwise = ["", intercalate " " legendItems]-- in intercalate "\n" (gridLines ++ [xAxis, grpLabels] ++ legendLine)---- | Create a stacked vertical bar chart-plotStackedBar :: Int -> Int -> [StackedBarGroup] -> L-plotStackedBar w h groups = L (StackedBarChartData groups w h)---- Heatmap --------------------------------------------------------------- | Heatmap data: grid of values, row labels, column labels-data HeatmapData = HeatmapData [[Double]] [String] [String]--data HeatmapElement = HeatmapElement HeatmapData Int -- data, cellWidth--instance Element HeatmapElement where- renderElement (HeatmapElement (HeatmapData [] _ _) _) = "No data"- renderElement (HeatmapElement (HeatmapData grid rowLbls colLbls) cellW) =- let allVals = concat grid- mn = minimum allVals- mx = maximum allVals- rng = if mx == mn then 1.0 else mx - mn- normalize v = (v - mn) / rng-- toColor256 :: Double -> Int- toColor256 t- | t <= 0.0 = 21- | t >= 1.0 = 196- | t < 0.25 = let s = t / 0.25 in round (21.0 + s * 30.0)- | t < 0.5 = let s = (t-0.25)/0.25 in round (51.0 + s * (-5.0))- | t < 0.75 = let s = (t-0.5)/0.25 in round (46.0 + s * 180.0)- | otherwise = let s = (t-0.75)/0.25 in round (226.0 + s * (-30.0))-- rowLblW = maximum (0 : map length rowLbls)-- header = replicate (rowLblW + 1) ' ' ++- intercalate " " (map (\l -> padRight cellW (take cellW l)) colLbls)-- dataRows = zipWith (\lbl rowVals ->- padRight rowLblW (take rowLblW lbl) ++ " " ++- intercalate " " (map (\v ->- let n = normalize v- c256 = toColor256 n- vs = formatAxisNum v- in bgColor256 c256 ++ padRight cellW (take cellW vs) ++ ansiReset- ) rowVals)- ) rowLbls grid-- legendCs = map (\i -> toColor256 (fromIntegral i / 10.0)) [0..10 :: Int]- legendBar = concatMap (\c -> bgColor256 c ++ " " ++ ansiReset) legendCs- legendLine = replicate (rowLblW + 1) ' ' ++- formatAxisNum mn ++ " " ++ legendBar ++ " " ++ formatAxisNum mx-- in intercalate "\n" ([header] ++ dataRows ++ ["", legendLine])---- | Create a heatmap with default cell width (6)-plotHeatmap :: HeatmapData -> L-plotHeatmap dat = L (HeatmapElement dat 6)---- | Create a heatmap with custom cell width-plotHeatmap' :: Int -> HeatmapData -> L-plotHeatmap' cellW dat = L (HeatmapElement dat cellW)---- ============================================================================--- TUI Runtime - Simple event loop for interactive terminal applications--- ============================================================================---- | Keyboard input representation-data Key- = KeyChar Char -- ^ Regular character keys: 'a', '1', ' ', etc.- | KeyCtrl Char -- ^ Ctrl+key: KeyCtrl 'C', KeyCtrl 'Q', etc.- | KeyEnter -- ^ Enter/Return key- | KeyBackspace -- ^ Backspace key- | KeyTab -- ^ Tab key- | KeyEscape -- ^ Escape key- | KeyDelete -- ^ Delete key- | KeyUp -- ^ Up arrow- | KeyDown -- ^ Down arrow- | KeyLeft -- ^ Left arrow- | KeyRight -- ^ Right arrow- | KeyPageUp -- ^ Page Up- | KeyPageDown -- ^ Page Down- | KeyHome -- ^ Home- | KeyEnd -- ^ End- | KeySpecial String -- ^ Other unrecognized escape sequences- deriving (Show, Eq)---- | Commands - side effects the runtime will execute after each update-data Cmd msg- = CmdNone -- ^ No effect- | CmdRun (IO (Maybe msg)) -- ^ Run IO, optionally produce a message- | CmdBatch [Cmd msg] -- ^ Combine multiple commands- | CmdExit -- ^ Gracefully quit the application---- | Create a command from an IO action (fire and forget)-cmdFire :: IO () -> Cmd msg-cmdFire io = CmdRun (io >> pure Nothing)---- | Create a command that produces a message after IO completes-cmdTask :: IO msg -> Cmd msg-cmdTask io = CmdRun (Just <$> io)---- | Create a command that fires a message after a delay-cmdAfterMs :: Int -> msg -> Cmd msg-cmdAfterMs delayMs msg = CmdRun (threadDelay (delayMs * 1000) >> pure (Just msg))---- | Execute a command and return any resulting message.--- Returns 'Nothing' for 'CmdExit' — the exit signal is handled by the runtime.-executeCmd :: Cmd msg -> IO (Maybe msg)-executeCmd CmdNone = pure Nothing-executeCmd CmdExit = pure Nothing-executeCmd (CmdRun io) = io-executeCmd (CmdBatch cmds) = do- results <- mapM executeCmd cmds- pure $ foldr pickFirst Nothing results- where- pickFirst (Just m) _ = Just m- pickFirst Nothing r = r---- | Check whether a command (or any sub-command in a batch) is 'CmdExit'.-cmdIsExit :: Cmd msg -> Bool-cmdIsExit CmdExit = True-cmdIsExit (CmdBatch cmds) = any cmdIsExit cmds-cmdIsExit _ = False---- | Subscriptions - event sources your app listens to-data Sub msg- = SubNone -- ^ No subscriptions- | SubKeyPress (Key -> Maybe msg) -- ^ Subscribe to keyboard input- | SubEveryMs Int msg -- ^ Subscribe to periodic ticks (interval in ms + message)- | SubBatch [Sub msg] -- ^ Combine multiple subscriptions---- | Combine multiple subscriptions-subBatch :: [Sub msg] -> Sub msg-subBatch = SubBatch---- | Subscribe to keyboard events-subKeyPress :: (Key -> Maybe msg) -> Sub msg-subKeyPress = SubKeyPress---- | Subscribe to periodic ticks with custom interval (milliseconds)-subEveryMs :: Int -> msg -> Sub msg-subEveryMs = SubEveryMs---- | The core application structure - Elm Architecture style------ Build interactive TUI apps by defining:------ * Initial state and startup commands--- * How to update state based on messages--- * What events to subscribe to--- * How to render state to UI------ Example:------ @--- data CounterMsg = Inc | Dec------ counterApp :: 'LayoutzApp' Int CounterMsg--- counterApp = 'LayoutzApp'--- { 'appInit' = (0, 'CmdNone')--- , 'appUpdate' = \\msg count -> case msg of--- 'Inc' -> (count + 1, 'CmdNone')--- 'Dec' -> (count - 1, 'CmdNone')--- , 'appSubscriptions' = \\_ -> 'subKeyPress' $ \\key -> case key of--- 'KeyChar' \'+\' -> Just 'Inc'--- 'KeyChar' \'-\' -> Just 'Dec'--- _ -> Nothing--- , 'appView' = \\count -> 'layout' ['text' $ "Count: " <> show count]--- }--- @-data LayoutzApp state msg = LayoutzApp- { appInit :: (state, Cmd msg) -- ^ Initial state and startup commands- , appUpdate :: msg -> state -> (state, Cmd msg) -- ^ Update state with message, return new state and commands- , appSubscriptions :: state -> Sub msg -- ^ Declare event subscriptions based on current state- , appView :: state -> L -- ^ Render state to UI- }---- | App-level alignment within the terminal window-data AppAlignment = AppAlignLeft | AppAlignCenter | AppAlignRight- deriving (Show, Eq)---- | Options for running a 'LayoutzApp'. Use 'defaultAppOptions' and override--- the fields you care about:------ @--- 'runAppWith' 'defaultAppOptions' { 'optAlignment' = 'AppAlignCenter' } myApp--- @-data AppOptions = AppOptions- { optAlignment :: AppAlignment -- ^ Alignment of the app block in the terminal (default: 'AppAlignLeft')- , optClearOnStart :: Bool -- ^ Enter alt screen and clear on start (default: 'True')- , optClearOnExit :: Bool -- ^ Exit alt screen on quit (default: 'True')- } deriving (Show, Eq)---- | Sensible defaults: left-aligned, full-screen (alt screen on start\/exit).-defaultAppOptions :: AppOptions-defaultAppOptions = AppOptions- { optAlignment = AppAlignLeft- , optClearOnStart = True- , optClearOnExit = True- }---- | Get terminal width via ANSI cursor position report (zero dependencies).--- Moves cursor to far bottom-right, queries position, restores cursor.--- Falls back to 80 columns on timeout or parse failure.-getTerminalWidth :: IO Int-getTerminalWidth = do- -- Save cursor, move to 999;999, query position, restore cursor- putStr "\ESC7\ESC[999;999H\ESC[6n\ESC8"- hFlush stdout- -- Terminal responds with: ESC [ rows ; cols R- result <- timeout 100000 readCPR -- 100ms timeout- pure $ maybe 80 id result- where- readCPR = do- c <- getChar- if c == '\ESC' then do- c2 <- getChar- if c2 == '[' then parseResponse ""- else pure 80- else pure 80- parseResponse acc = do- c <- getChar- if c == 'R' then- let resp = reverse acc- in pure $ case break (== ';') resp of- (_, ';':cols) -> case reads cols of- [(n, "")] -> n- _ -> 80- _ -> 80- else parseResponse (c : acc)---- | Get terminal size as @(rows, cols)@ via an ANSI cursor position report.--- Falls back to @(24, 80)@ on timeout or parse failure. Must be called while--- raw mode is active and nothing else is reading stdin.-getTerminalSize :: IO (Int, Int)-getTerminalSize = do- putStr "\ESC7\ESC[999;999H\ESC[6n\ESC8"- hFlush stdout- result <- timeout 100000 (readCPR "")- pure $ maybe (24, 80) id result- where- readCPR acc = do- c <- getChar- case c of- '\ESC' -> getChar >> readCPR acc -- skip ESC and the following '['- '[' -> readCPR acc- 'R' -> pure (parseRC (reverse acc))- _ -> readCPR (c : acc)- parseRC resp = case break (== ';') resp of- (rows, ';':cols) -> (readOr 24 rows, readOr 80 cols)- _ -> (24, 80)- readOr d s = case reads s of- [(n, "")] -> n- _ -> d---- | Run an interactive TUI application with default options.------ This function:------ * Sets up raw terminal mode (no echo, no buffering)--- * Clears screen and hides cursor--- * Enters event loop that:------ * Listens to subscribed events (keyboard, ticks, etc.)--- * Dispatches messages to update function--- * Updates state and re-renders------ * Restores terminal on exit (ESC, Ctrl+C, or Ctrl+D)------ Press ESC, Ctrl+C, or Ctrl+D to quit the application.-runApp :: LayoutzApp state msg -> IO ()-runApp app = runAppWithFinal defaultAppOptions app >> pure ()---- | Like 'runApp', but returns the final application state after exit.--- Useful for interactive tweaking of state followed by further processing.-runAppFinal :: LayoutzApp state msg -> IO state-runAppFinal = runAppWithFinal defaultAppOptions---- | Run an app inline — no alt screen, no clearing. The app renders in-place--- below whatever is already on screen and returns when it issues 'CmdExit'.--- Useful for embedding animated progress bars or spinners in scripts.-runInline :: LayoutzApp state msg -> IO ()-runInline app = runAppWithFinal defaultAppOptions- { optClearOnStart = False, optClearOnExit = False } app >> pure ()---- | Run an interactive TUI application with custom options.------ @--- 'runAppWith' 'defaultAppOptions' { 'optAlignment' = 'AppAlignCenter' } myApp--- @-runAppWith :: AppOptions -> LayoutzApp state msg -> IO ()-runAppWith opts app = runAppWithFinal opts app >> pure ()---- | Internal runtime event. Every source (keypresses, interval ticks, command--- results) is funnelled into a single channel as one of these, so there is--- exactly one consumer applying 'appUpdate' with no races on state-data AppEvent msg- = AppMsg msg- | AppExit---- | Like 'runAppWith', but returns the final application state after exit.--- Useful for interactive tweaking of state followed by further processing.------ @--- finalState <- 'runAppWithFinal' 'defaultAppOptions' { 'optAlignment' = 'AppAlignCenter' } myApp--- @-runAppWithFinal :: AppOptions -> LayoutzApp state msg -> IO state-runAppWithFinal opts LayoutzApp{..} = do- oldBuffering <- hGetBuffering stdin- oldEcho <- hGetEcho stdin-- hSetBuffering stdin NoBuffering- hSetBuffering stdout NoBuffering- hSetEcho stdin False-- when (optClearOnStart opts) $ do- enterAltScreen- clearScreen- hideCursor-- -- Query terminal width once, after raw mode is set, before threads- termWidth <- getTerminalWidth-- let (initialState, initialCmd) = appInit-- stateRef <- newIORef initialState- eventChan <- newChan -- Single event stream: keys, ticks, cmd results, exit- cmdChan <- newChan -- Commands awaiting async execution-- let applyMsg msg = do- cmdToRun <- atomicModifyIORef' stateRef $ \s ->- let (newState, c) = appUpdate msg s in (newState, c)- case cmdToRun of- CmdNone -> pure ()- CmdExit -> writeChan eventChan AppExit- _ -> writeChan cmdChan cmdToRun-- cmdThread <- forkIO $ forever $ do- cmdToRun <- readChan cmdChan- when (cmdIsExit cmdToRun) $ writeChan eventChan AppExit- maybeMsg <- executeCmd cmdToRun- case maybeMsg of- Just msg -> writeChan eventChan (AppMsg msg)- Nothing -> pure ()-- case initialCmd of- CmdNone -> pure ()- _ -> writeChan cmdChan initialCmd-- lastLineCount <- newIORef 0- lastRendered <- newIORef ""- sentKittyIds <- newIORef IntSet.empty -- kitty images already transmitted this session-- renderThread <- forkIO $ forever $ do- state <- readIORef stateRef- let rendered = render (appView state)- lastRender <- readIORef lastRendered-- when (rendered /= lastRender) $ do- prevLineCount <- readIORef lastLineCount- -- Drop transmit blocks for images already sent, so each distinct kitty- -- image is uploaded only once across frames.- priorIds <- readIORef sentKittyIds- let (deduped, newKittyIds) = dedupeTransmits priorIds rendered- writeIORef sentKittyIds newKittyIds- let renderedLines = lines deduped- currentLineCount = length renderedLines- maxLineWidth = maximum (0 : map visibleLength renderedLines)- blockPad = case optAlignment opts of- AppAlignLeft -> 0- AppAlignCenter -> max 0 ((termWidth - maxLineWidth) `div` 2)- AppAlignRight -> max 0 (termWidth - maxLineWidth)- padding = replicate blockPad ' '- alignedLines = if blockPad > 0- then map (padding ++) renderedLines- else renderedLines- moveUp = if optClearOnStart opts- then "\ESC[H"- else if prevLineCount > 0- then "\ESC[" ++ show prevLineCount ++ "A\r"- else ""- output = moveUp ++ concatMap (\l -> l ++ "\ESC[K\n") alignedLines- ++ concat (replicate (max 0 (prevLineCount - currentLineCount)) "\ESC[K\n")- putStr output- hFlush stdout- writeIORef lastRendered rendered- writeIORef lastLineCount currentLineCount-- threadDelay 33333-- let getKeyHandler sub = case sub of- SubKeyPress handler -> Just handler- SubBatch subs -> case [h | SubKeyPress h <- subs] of- (h:_) -> Just h- [] -> Nothing- _ -> Nothing-- getTicks sub = case sub of- SubEveryMs interval msg -> [(interval, msg)]- SubBatch subs -> concatMap getTicks subs- _ -> []-- tickThread <- forkIO $- let tickLoop deadlines = do- state <- readIORef stateRef- now <- getMonotonicTimeNSec- let ticks = getTicks (appSubscriptions state)- nsOf ms = fromIntegral ms * 1000 * 1000- intervals = foldr (\i acc -> if i `elem` acc then acc else i : acc)- [] (map fst ticks)- armed = [ (i, maybe (now + nsOf i) id (lookup i deadlines))- | i <- intervals ]- dueNow = [ i | (i, d) <- armed, d <= now ]- fired = [ (i, msg) | (i, msg) <- ticks, i `elem` dueNow ]- deadlines' = [ (i, if i `elem` dueNow- then let nd = d + nsOf i- in if nd <= now then now + nsOf i else nd- else d)- | (i, d) <- armed ]- mapM_ (\(_, msg) -> writeChan eventChan (AppMsg msg)) fired- threadDelay 5000 -- 5ms poll: bounds tick jitter without busy-waiting- tickLoop deadlines'- in tickLoop []-- -- Input thread: translate keypresses into events. Exit keys become AppExit;- -- a closed stdin (EOF) is treated as a quit request, like Ctrl-D.- inputThread <- forkIO $- let readLoop = do- key <- readKey- case key of- KeyEscape -> writeChan eventChan AppExit- KeyCtrl 'C' -> writeChan eventChan AppExit- KeyCtrl 'D' -> writeChan eventChan AppExit- _ -> do- state <- readIORef stateRef- case getKeyHandler (appSubscriptions state) of- Just handler -> maybe (pure ()) (writeChan eventChan . AppMsg) (handler key)- Nothing -> pure ()- readLoop- in readLoop `catch` \e ->- let _ = (e :: IOException) in writeChan eventChan AppExit-- let killThreads = killThread renderThread >> killThread cmdThread- >> killThread tickThread >> killThread inputThread-- doCleanup = do- killThreads- showCursor- when (optClearOnExit opts) exitAltScreen- hFlush stdout- hSetBuffering stdin oldBuffering- hSetEcho stdin oldEcho-- dispatchLoop = do- ev <- readChan eventChan- case ev of- AppExit -> pure () -- stop looping; `finally` restores the tty- AppMsg msg -> applyMsg msg >> dispatchLoop-- -- Ctrl-C quits gracefully; every other exit path (normal quit, an- -- exception from update/view, or an async kill) still restores the- -- terminal via `finally`, so the tty is never left in raw mode.- onAsync :: AsyncException -> IO ()- onAsync UserInterrupt = pure ()- onAsync e = throwIO e-- (dispatchLoop `catch` onAsync) `finally` doCleanup-- readIORef stateRef---- | Clear the screen and move cursor to top-left-clearScreen :: IO ()-clearScreen = putStr "\ESC[2J\ESC[H"---- | Hide the terminal cursor-hideCursor :: IO ()-hideCursor = putStr "\ESC[?25l"---- | Show the terminal cursor-showCursor :: IO ()-showCursor = putStr "\ESC[?25h"---- | Enter alternate screen buffer (like vim/less use)-enterAltScreen :: IO ()-enterAltScreen = putStr "\ESC[?1049h"---- | Exit alternate screen buffer-exitAltScreen :: IO ()-exitAltScreen = putStr "\ESC[?1049l"---- | Read a single key from stdin and parse it-readKey :: IO Key-readKey = do- c <- getChar- case ord c of- 10 -> return KeyEnter -- LF (Unix)- 13 -> return KeyEnter -- CR (Windows/Mac)- 27 -> readEscapeSequence -- ESC - might be arrow key- 9 -> return KeyTab- 127 -> return KeyBackspace -- DEL (often used as backspace)- 8 -> return KeyBackspace -- BS- n | n >= 32 && n <= 126 -> return $ KeyChar (chr n) -- Printable ASCII- | n < 32 -> return $ KeyCtrl (chr (n + 64)) -- Ctrl+Key- | otherwise -> return $ KeyChar (chr n)---- | Read escape sequence for arrow keys and other special keys--- Uses a small timeout to distinguish between ESC key and ESC sequences-readEscapeSequence :: IO Key-readEscapeSequence = do- -- Try to read next character with 50ms timeout- -- If timeout, it's just ESC key; if character arrives, it's an escape sequence- maybeChar <- timeout 50000 getChar -- 50000 microseconds = 50ms- case maybeChar of- Nothing -> return KeyEscape -- Timeout - just ESC key pressed- Just '[' -> do- -- It's an escape sequence, read the command character- c2 <- getChar- case c2 of- 'A' -> return KeyUp- 'B' -> return KeyDown- 'C' -> return KeyRight- 'D' -> return KeyLeft- 'H' -> return KeyHome- 'F' -> return KeyEnd- -- Numeric sequences terminated by '~': ESC [ n ~- n | n >= '1' && n <= '6' -> do- c3 <- getChar- if c3 == '~'- then return $ case n of- '1' -> KeyHome- '3' -> KeyDelete- '4' -> KeyEnd- '5' -> KeyPageUp- '6' -> KeyPageDown- _ -> KeyEscape- else return KeyEscape- _ -> return KeyEscape- Just 'O' -> do- -- Application cursor mode: ESC O H/F for Home/End- c2 <- getChar- case c2 of- 'H' -> return KeyHome- 'F' -> return KeyEnd- _ -> return KeyEscape- Just _ -> return KeyEscape -- Some other character after ESC----- ============================================================================--- Shared helpers (small string/ANSI utilities used by kitty, loader and Ask)--- ============================================================================---- | Dim a string with the SGR faint style.-dimText :: String -> String-dimText = wrapStyle StyleDim---- | Colour a string, leaving it untouched for 'ColorDefault'.-paintColor :: Color -> String -> String-paintColor = wrapAnsi---- | Split on a single character, keeping empty trailing segments (like--- Scala's @split(sep, -1)@ — unlike 'lines', a trailing separator yields a--- final empty segment).-splitOnChar :: Char -> String -> [String]-splitOnChar c s = case break (== c) s of- (a, []) -> [a]- (a, _:rest) -> a : splitOnChar c rest---- | Split a string at the first occurrence of a substring pattern, returning--- @(before, fromPattern)@ where @fromPattern@ begins with the pattern.-splitOnFirst :: String -> String -> Maybe (String, String)-splitOnFirst pat = go ""- where- go acc s- | pat `isPrefixOf` s = Just (reverse acc, s)- | otherwise = case s of- [] -> Nothing- (x:xs) -> go (x:acc) xs---- | Break a list into chunks of at most @n@ elements.-chunksOf :: Int -> [a] -> [[a]]-chunksOf n xs- | n <= 0 = [xs]- | null xs = []- | otherwise = let (a, b) = splitAt n xs in a : chunksOf n b---- | ANSI background-colour SGR code corresponding to a foreground 'Color'.-bgColorCode :: Color -> String-bgColorCode ColorDefault = ""-bgColorCode (ColorFull n) = "48;5;" ++ show (clamp n)-bgColorCode (ColorTrue r g b) = "48;2;" ++ show (clamp r) ++ ";" ++ show (clamp g) ++ ";" ++ show (clamp b)-bgColorCode c = case reads (colorCode c) :: [(Int, String)] of- [(n, "")] -> show (n + 10) -- 30-37 -> 40-47, 90-97 -> 100-107- _ -> ""---- ============================================================================--- Kitty graphics protocol--- ============================================================================---- | Kitty transmit format: PNG.-formatPng :: Int-formatPng = 100---- | Kitty transmit format: raw RGB (3 bytes/pixel).-formatRgb :: Int-formatRgb = 24---- | Kitty transmit format: raw RGBA (4 bytes/pixel).-formatRgba :: Int-formatRgba = 32---- | An inline image rendered via the kitty graphics protocol using Unicode--- placeholders, so it composes like any other element: it measures exactly--- @cols@ wide and @rows@ tall and drops into 'box', 'row', 'table', 'center', …------ Prefer the smart constructors 'kittyImage', 'kittyRGB', 'kittyRGBA' (or the--- 'kittyImageFile' loader) over building this record directly.-data KittyImage = KittyImage- { kiPayload :: [Word8] -- ^ Raw image bytes (PNG, or raw RGB\/RGBA pixels)- , kiFormat :: Int -- ^ 100 = PNG, 24 = RGB, 32 = RGBA- , kiCols :: Int -- ^ Cell width- , kiRows :: Int -- ^ Cell height- , kiPxW :: Int -- ^ Source pixel width (raw formats only)- , kiPxH :: Int -- ^ Source pixel height (raw formats only)- , kiAlt :: String -- ^ Alt text (kept for parity; unused by terminals)- , kiIdOverride :: Maybe Int -- ^ Explicit image id (otherwise a content hash)- }--instance Element KittyImage where- renderElement img = kittyTransmit img ++ kittyPlacement img- width = kiCols- height = kiRows---- | Deterministic 24-bit image id: an explicit override, or an FNV-1a hash of--- the payload masked to 24 bits (forced non-zero). Stable across redraws so a--- runtime can transmit each distinct image only once.-kittyImageId :: [Word8] -> Maybe Int -> Int-kittyImageId payload override =- let raw = maybe (foldl step 0x811c9dc5 payload) id override- masked = raw .&. 0xffffff- in if masked == 0 then 1 else masked- where- step h b = (h `xor` fromIntegral b) * 0x01000193 .&. 0xffffffff---- | Standard base64 (RFC 4648, @+/@ alphabet, @=@ padding). Shipped inline to--- keep the library dependency-light.-kittyBase64 :: [Word8] -> String-kittyBase64 = go- where- alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"- idx i = alphabet !! i- go [] = ""- go (b0:b1:b2:rest) =- let t = (fromIntegral b0 `shiftL` 16) .|. (fromIntegral b1 `shiftL` 8) .|. fromIntegral b2- in idx ((t `shiftR` 18) .&. 0x3f) : idx ((t `shiftR` 12) .&. 0x3f)- : idx ((t `shiftR` 6) .&. 0x3f) : idx (t .&. 0x3f) : go rest- go [b0, b1] =- let t = (fromIntegral b0 `shiftL` 16) .|. (fromIntegral b1 `shiftL` 8) :: Int- in idx ((t `shiftR` 18) .&. 0x3f) : idx ((t `shiftR` 12) .&. 0x3f)- : idx ((t `shiftR` 6) .&. 0x3f) : "="- go [b0] =- let t = fromIntegral b0 `shiftL` 16 :: Int- in idx ((t `shiftR` 18) .&. 0x3f) : idx ((t `shiftR` 12) .&. 0x3f) : "=="--kittyApcG :: String-kittyApcG = "\ESC_G"--kittyST :: String-kittyST = "\ESC\\"---- | Transmit block: base64 the payload, chunk into <=4096-char escapes. Every--- chunk carries @i=\<id\>@ so 'dedupeTransmits' can drop all chunks of an--- already-sent image.-kittyTransmit :: KittyImage -> String-kittyTransmit img =- let b64 = kittyBase64 (kiPayload img)- chunks = if null b64 then [""] else chunksOf 4096 b64- theId = kittyImageId (kiPayload img) (kiIdOverride img)- dims = if kiFormat img == formatPng then ""- else ",s=" ++ show (kiPxW img) ++ ",v=" ++ show (kiPxH img)- firstKeys = "a=T,U=1,i=" ++ show theId ++ ",f=" ++ show (kiFormat img)- ++ ",c=" ++ show (kiCols img) ++ ",r=" ++ show (kiRows img) ++ dims ++ ",q=2"- contKeys = "i=" ++ show theId ++ ",q=2"- lastIdx = length chunks - 1- block i chunk =- let m = if i == lastIdx then "0" else "1"- keys = (if i == 0 then firstKeys else contKeys) ++ ",m=" ++ m- in kittyApcG ++ keys ++ ";" ++ chunk ++ kittyST- in concat (zipWith block [0 ..] chunks)---- | Placement grid: one line per image row of @U+10EEEE@ placeholders; the--- image id rides in the foreground colour and the (row, column) in two--- combining diacritics on the first cell of each row.-kittyPlacement :: KittyImage -> String-kittyPlacement img =- let theId = kittyImageId (kiPayload img) (kiIdOverride img)- fg = "\ESC[38;2;" ++ show ((theId `shiftR` 16) .&. 0xff) ++ ";"- ++ show ((theId `shiftR` 8) .&. 0xff) ++ ";" ++ show (theId .&. 0xff) ++ "m"- reset = "\ESC[0m"- placeholder = [kittyPlaceholderChar]- col0 = [chr (head rowColumnDiacritics)]- rowLine r =- let firstCell = placeholder ++ [chr (rowColumnDiacritics !! r)] ++ col0- in fg ++ firstCell ++ concat (replicate (kiCols img - 1) placeholder) ++ reset- in intercalate "\n" (map rowLine [0 .. kiRows img - 1])---- | Strip transmit blocks whose image id is already in the seen-set, adding--- new ids as they are encountered. Returns the rewritten string and the--- updated set. Placement grids are always left intact.-dedupeTransmits :: IntSet.IntSet -> String -> (String, IntSet.IntSet)-dedupeTransmits ids0 input = go ids0 input- where- go ids s = case splitOnFirst kittyApcG s of- Nothing -> (s, ids)- Just (before, rest) ->- let (block, after) = takeBlock rest- bid = parseId block- (keep, ids')- | bid /= 0 && IntSet.member bid ids = ("", ids)- | bid /= 0 = (block, IntSet.insert bid ids)- | otherwise = (block, ids)- (restOut, idsF) = go ids' after- in (before ++ keep ++ restOut, idsF)-- -- @s@ starts with the APC introducer; return (whole block incl. ST, rest).- takeBlock s = case splitOnFirst kittyST (drop (length kittyApcG) s) of- Nothing -> (s, "") -- unterminated: keep verbatim- Just (mid, after) -> (kittyApcG ++ mid ++ kittyST, drop (length kittyST) after)-- parseId block =- let body = drop (length kittyApcG) block- keys = takeWhile (/= ';') body- fields = splitOnChar ',' keys- in case [ drop 2 f | f <- fields, "i=" `isPrefixOf` f ] of- (v:_) -> let ds = takeWhile isDigit v in if null ds then 0 else read ds- [] -> 0---- | Validate dimensions/format and build a 'KittyImage'.-mkKitty :: [Word8] -> Int -> Int -> Int -> Int -> Int -> String -> KittyImage-mkKitty payload fmt cols rows pxW pxH alt- | cols < 1 || rows < 1 = error "KittyImage cols/rows must be >= 1"- | cols > maxCells || rows > maxCells =- error ("KittyImage cols/rows must be <= " ++ show maxCells ++ " (the diacritics table size)")- | not validFormat =- error "raw RGB/RGBA images (format 24/32) require pxW > 0 and pxH > 0"- | otherwise = KittyImage payload fmt cols rows pxW pxH alt Nothing- where- maxCells = length rowColumnDiacritics- validFormat = fmt == formatPng- || ((fmt == formatRgb || fmt == formatRgba) && pxW > 0 && pxH > 0)---- | Inline PNG image sized to a @cols@x@rows@ cell footprint. The terminal--- decodes the PNG and fits it into that box; layout math uses @cols@\/@rows@.-kittyImage :: [Word8] -> Int -> Int -> L-kittyImage bytes cols rows = L (mkKitty bytes formatPng cols rows 0 0 "")---- | Inline raw RGB image (@format 24@): @pxW@x@pxH@ source pixels shown in a--- @cols@x@rows@ cell footprint.-kittyRGB :: [Word8] -> Int -> Int -> Int -> Int -> L-kittyRGB pixels pxW pxH cols rows = L (mkKitty pixels formatRgb cols rows pxW pxH "")---- | Inline raw RGBA image (@format 32@): like 'kittyRGB' with an alpha channel.-kittyRGBA :: [Word8] -> Int -> Int -> Int -> Int -> L-kittyRGBA pixels pxW pxH cols rows = L (mkKitty pixels formatRgba cols rows pxW pxH "")---- | Load an image file and size it to a @cols@x@rows@ cell footprint. PNG bytes--- are sent to the terminal as-is.-kittyImageFile :: FilePath -> Int -> Int -> IO L-kittyImageFile path cols rows = do- bytes <- readFileBytes path- pure (kittyImage bytes cols rows)---- | Read a file strictly as a list of bytes (binary mode, no dependencies).-readFileBytes :: FilePath -> IO [Word8]-readFileBytes path = withBinaryFile path ReadMode $ \h -> do- contents <- hGetContents h- let n = length contents- n `seq` pure (map (fromIntegral . ord) contents)---- ============================================================================--- Progress loaders--- ============================================================================---- | Visual preset for a 'loader'. Controls the bar glyphs and colour for--- bounded loaders, and the spinner frames + colour for streaming loaders.-data LoaderStyle = LoaderStyle- { lsFill :: Char- , lsEmpty :: Char- , lsOpen :: String- , lsClose :: String- , lsHead :: String- , lsSmooth :: Bool- , lsSpinner :: SpinnerStyle- , lsColor :: Color- }---- | Smooth gradient blocks @████▊░░░@ (default).-styleBlocks :: LoaderStyle-styleBlocks = LoaderStyle '█' '░' "" "" "" True SpinnerGrow ColorCyan---- | Classic bracketed bar @[██████░░░░]@.-styleBar :: LoaderStyle-styleBar = LoaderStyle '█' '░' "[" "]" "" False SpinnerDots ColorGreen---- | Retro ASCII with an arrow head @[====> ]@.-styleAscii :: LoaderStyle-styleAscii = LoaderStyle '=' ' ' "[" "]" ">" False SpinnerLine ColorYellow---- | Dotted @●●●●∙∙∙∙@.-styleDots :: LoaderStyle-styleDots = LoaderStyle '●' '∙' "" "" "" False SpinnerBounce ColorMagenta---- | Heavy\/light rule @━━━━────@.-styleLine :: LoaderStyle-styleLine = LoaderStyle '━' '─' "" "" "" False SpinnerLine ColorBlue---- | Segmented pipes @▰▰▰▱▱▱@.-stylePipes :: LoaderStyle-stylePipes = LoaderStyle '▰' '▱' "" "" "" False SpinnerArrow ColorBrightMagenta---- | All built-in styles, in display order.-loaderStyles :: [LoaderStyle]-loaderStyles = [styleBlocks, styleBar, styleAscii, styleDots, styleLine, stylePipes]---- | Fractional block glyphs for the smooth-fill boundary cell (1\/8 .. 8\/8).-blockEighths :: [String]-blockEighths = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]---- | Render a progress bar of the given style filled to @progress@ (0..1) over--- @w@ cells.-renderProgressBar :: LoaderStyle -> Double -> Int -> String-renderProgressBar style progress w =- let p = max 0.0 (min 1.0 progress)- exact = p * fromIntegral w- filled = floor exact :: Int- in if lsSmooth style- then let eighths = floor ((exact - fromIntegral filled) * 8) :: Int- hasPartial = filled < w && eighths > 0- partial = if hasPartial then blockEighths !! eighths else ""- used = filled + (if hasPartial then 1 else 0)- body = paintColor (lsColor style) (replicate filled (lsFill style) ++ partial)- in lsOpen style ++ body ++ dimText (replicate (w - used) (lsEmpty style)) ++ lsClose style- else let showHead = not (null (lsHead style)) && filled > 0 && filled < w- hd = if showHead then lsHead style else ""- emptyCount = max 0 (w - filled - length hd)- body = paintColor (lsColor style) (replicate filled (lsFill style) ++ hd)- in lsOpen style ++ body ++ dimText (replicate emptyCount (lsEmpty style)) ++ lsClose style---- | Run an inline progress line: a background ticker redraws @renderLine@ every--- 80ms while the main thread maps @action@ over @items@, bumping @counter@ per--- item. On completion the ticker stops and @finalLine@ is drawn.-runLoader :: (Int -> IO String) -> IO String -> IORef Int -> [a] -> (a -> IO b) -> IO [b]-runLoader renderLine finalLine counter items action = do- hideCursor- hFlush stdout- stopRef <- newIORef False- ticker <- forkIO $- let tick frame = do- stop <- readIORef stopRef- unless stop $ do- line <- renderLine frame- putStr ("\r" ++ line ++ "\ESC[K")- hFlush stdout- threadDelay 80000- tick (frame + 1)- in tick 0- results <- mapM (\x -> do r <- action x; modifyIORef' counter (+ 1); pure r) items- writeIORef stopRef True- killThread ticker- final <- finalLine- putStr ("\r" ++ final ++ "\ESC[K\n")- showCursor- hFlush stdout- pure results--boundedRender :: LoaderStyle -> String -> Int -> IORef Int -> Int -> IO String-boundedRender style label total counter _frame = do- done <- readIORef counter- let progress = if total > 0 then min 1.0 (fromIntegral done / fromIntegral total) else 1.0- bar = renderProgressBar style progress 20- pct = floor (progress * 100) :: Int- prefix = if null label then "" else label ++ " "- pure (prefix ++ bar ++ " " ++ show done ++ "/" ++ show total ++ " (" ++ show pct ++ "%)")--streamingRender :: LoaderStyle -> String -> IORef Int -> Int -> IO String-streamingRender style label counter frame = do- done <- readIORef counter- let frames = spinnerFrames (lsSpinner style)- spin = paintColor (lsColor style) (frames !! (frame `mod` length frames))- prefix = if null label then "" else label ++ " "- pure (spin ++ " " ++ prefix ++ "(" ++ show done ++ " processed)")--streamingFinal :: String -> IORef Int -> IO String-streamingFinal label counter = do- done <- readIORef counter- let prefix = if null label then "" else label ++ " "- pure (prefix ++ show done ++ " processed")---- | Iterate a sized collection while streaming an inline progress bar (blocks--- style). Returns the results of @action@ over each item.------ @--- _ <- 'loader' "Processing" [1..100] (\\_ -> threadDelay 20000)--- @-loader :: String -> [a] -> (a -> IO b) -> IO [b]-loader = loaderStyled styleBlocks---- | Like 'loader' with an explicit 'LoaderStyle' (e.g. 'styleAscii').-loaderStyled :: LoaderStyle -> String -> [a] -> (a -> IO b) -> IO [b]-loaderStyled style label items action = do- let total = length items- counter <- newIORef 0- let rl = boundedRender style label total counter- runLoader rl (rl 0) counter items action---- | Iterate a collection of unknown \"size\", streaming a spinner + running--- count (blocks style spinner).-loaderStream :: String -> [a] -> (a -> IO b) -> IO [b]-loaderStream = loaderStreamStyled styleBlocks---- | Like 'loaderStream' with an explicit 'LoaderStyle'.-loaderStreamStyled :: LoaderStyle -> String -> [a] -> (a -> IO b) -> IO [b]-loaderStreamStyled style label items action = do- counter <- newIORef 0- runLoader (streamingRender style label counter) (streamingFinal label counter) counter items action---- ============================================================================--- Interactive prompts (Ask)--- ============================================================================------ One-shot prompts. Each takes over the tty briefly, returns a value, and--- leaves a single committed line behind. 'Nothing' means the user cancelled--- (Esc / Ctrl-C / Ctrl-D).--askCursorUp :: Int -> String-askCursorUp n = "\ESC[" ++ show n ++ "A\r"--askClearEol :: String-askClearEol = "\ESC[K"--askClearBelow :: String-askClearBelow = "\ESC[J"---- | Put the tty into raw mode, hide the cursor, run the body, and restore the--- terminal afterwards (even on exception).-withAskTty :: IO a -> IO a-withAskTty body = do- oldBuffering <- hGetBuffering stdin- oldEcho <- hGetEcho stdin- hSetBuffering stdin NoBuffering- hSetBuffering stdout NoBuffering- hSetEcho stdin False- hideCursor- body `finally` do- showCursor- hSetEcho stdin oldEcho- hSetBuffering stdin oldBuffering- hFlush stdout---- | Redraw a multi-line frame in place, returning its line count.-askRepaint :: String -> Int -> IO Int-askRepaint frame prevLines = do- let ls = splitOnChar '\n' frame- up = if prevLines > 0 then askCursorUp prevLines else ""- body = concatMap (\l -> l ++ askClearEol ++ "\n") ls- belw = if prevLines > length ls then askClearBelow else ""- putStr (up ++ body ++ belw)- hFlush stdout- pure (length ls)---- | Replace the live frame with a single committed summary line.-askCommit :: String -> Int -> IO ()-askCommit summary prevLines = do- let up = if prevLines > 0 then askCursorUp prevLines else ""- belw = if prevLines > 1 then askClearBelow else ""- putStr (up ++ summary ++ askClearEol ++ "\n" ++ belw)- hFlush stdout---- | Wipe the live frame entirely (used on cancel).-askErase :: Int -> IO ()-askErase prevLines = when (prevLines > 0) $ do- putStr (askCursorUp prevLines ++ askClearBelow)- hFlush stdout---- | Render an active confirm button (white on a coloured background, bold).-askActiveBtn :: Color -> String -> String-askActiveBtn bg t = "\ESC[1;37;" ++ bgColorCode bg ++ "m" ++ t ++ "\ESC[0m"--renderInputFrame :: String -> String -> String -> String-renderInputFrame prompt value placeholder =- let body = if null value && not (null placeholder) then dimText placeholder else value- in prompt ++ body ++ paintColor ColorCyan "▌"--renderConfirmFrame :: String -> Bool -> String -> String -> String-renderConfirmFrame question yes affirmative negative =- question ++ "\n " ++ btn affirmative yes ColorGreen ++ " " ++ btn negative (not yes) ColorRed- where- btn t active bg = let padded = " " ++ t ++ " "- in if active then askActiveBtn bg padded else padded--renderChooseFrame :: String -> [a] -> Int -> (a -> String) -> String-renderChooseFrame prompt items idx renderItem =- let rows = [ if i == idx then paintColor ColorCyan ("› " ++ renderItem item) else " " ++ renderItem item- | (item, i) <- zip items [0 ..] ]- in (if not (null prompt) then prompt ++ "\n" else "") ++ intercalate "\n" rows--renderChooseManyFrame :: String -> [a] -> Int -> [Int] -> Int -> (a -> String) -> String-renderChooseManyFrame prompt items idx selected limit renderItem =- let rows = [ let mark = if i `elem` selected then paintColor ColorGreen "[x]" else dimText "[ ]"- line = mark ++ " " ++ renderItem item- in if i == idx then paintColor ColorCyan "› " ++ line else " " ++ line- | (item, i) <- zip items [0 ..] ]- header- | null prompt = ""- | otherwise =- let tag | limit > 0 = " (" ++ show (length selected) ++ "/" ++ show limit ++ ")"- | not (null selected) = " (" ++ show (length selected) ++ ")"- | otherwise = ""- in prompt ++ dimText tag ++ "\n"- in header ++ intercalate "\n" rows--renderWriteFrame :: String -> String -> String -> String -> String-renderWriteFrame prompt value placeholder hint =- let header = if not (null prompt) then prompt ++ "\n" else ""- body = if null value && not (null placeholder)- then dimText placeholder ++ paintColor ColorCyan "▌"- else value ++ paintColor ColorCyan "▌"- footer = if not (null hint) then "\n" ++ dimText hint else ""- in header ++ body ++ footer--renderFilterFrame :: String -> String -> [a] -> Int -> Int -> (a -> String) -> String-renderFilterFrame prompt query matches idx viewHeight renderItem =- let total = length matches- h = max 0 (min viewHeight total)- top = if total <= h then 0 else max 0 (min (idx - h `div` 2) (total - h))- visible = take h (drop top matches)- rows = [ let absIdx = top + i; label = renderItem item- in if absIdx == idx then paintColor ColorCyan ("› " ++ label) else " " ++ label- | (item, i) <- zip visible [0 ..] ]- header = prompt ++ query ++ paintColor ColorCyan "▌"- list = if null rows then dimText " (no matches)" else intercalate "\n" rows- in header ++ "\n" ++ list---- | Fuzzy-match score: 'Nothing' if @query@ isn't a subsequence of @target@,--- otherwise @Just gap@ where a smaller gap sum means a tighter match.-fuzzyScore :: String -> String -> Maybe Int-fuzzyScore query target- | null query = Just 0- | otherwise = loop (map toLower query) (map toLower target) (-1) 0 0- where- loop [] _ _ gap _ = Just gap- loop _ [] _ _ _ = Nothing- loop (qc:qs) (sc:ss) lastMatch gap ti- | qc == sc = let gap' = if lastMatch >= 0 then gap + (ti - lastMatch - 1) else gap- in loop qs ss ti gap' (ti + 1)- | otherwise = loop (qc:qs) ss lastMatch gap (ti + 1)---- | Filter items to those matching @query@, best (tightest) matches first.-fuzzyMatches :: String -> [a] -> (a -> String) -> [a]-fuzzyMatches query items renderItem- | null query = items- | otherwise = map fst $ sortOn snd- [ (item, score) | item <- items, Just score <- [fuzzyScore query (renderItem item)] ]---- | A directory entry for the file picker.-data FileEntry = FileEntry { feName :: String, feIsDir :: Bool }--feDisplay :: FileEntry -> String-feDisplay e = if feIsDir e then feName e ++ "/" else feName e--renderFileFrame :: String -> [FileEntry] -> Int -> Int -> String-renderFileFrame path entries idx viewHeight =- let total = length entries- h = max 0 (min viewHeight total)- top = if total <= h then 0 else max 0 (min (idx - h `div` 2) (total - h))- visible = take h (drop top entries)- rows = [ let absIdx = top + i- name = if feIsDir e then paintColor ColorBlue (feDisplay e) else feDisplay e- in if absIdx == idx then paintColor ColorCyan "› " ++ name else " " ++ name- | (e, i) <- zip visible [0 ..] ]- in dimText path ++ "\n" ++ intercalate "\n" rows--renderPagerFrame :: [String] -> Int -> Int -> Int -> Bool -> String-renderPagerFrame allLines top h viewWidth lineNumbers =- let total = length allLines- visible = take h (drop top allLines)- numWidth = length (show total)- gutter = if lineNumbers then numWidth + 3 else 0- maxLineW = max 20 (viewWidth - gutter)- body = intercalate "\n"- [ let truncated = if length line > maxLineW then take (maxLineW - 1) line ++ "…" else line- in if lineNumbers- then dimText (padNum numWidth (top + i + 1) ++ " │ ") ++ truncated- else truncated- | (line, i) <- zip visible [0 ..] ]- viewEnd = min (top + h) total- percent = if total == 0 then 100 else (viewEnd * 100) `div` total- status = dimText (" L" ++ show (top + 1) ++ "–" ++ show viewEnd ++ " of " ++ show total- ++ " " ++ show percent ++ "% ↑↓ PgUp/PgDn Home/End q to quit")- in body ++ "\n" ++ status- where- padNum w n = let s = show n in replicate (max 0 (w - length s)) ' ' ++ s---- | Prompt for a single line of text. Returns 'Nothing' if cancelled.-askInput :: String -- ^ prompt (e.g. @"› "@)- -> String -- ^ placeholder shown when empty- -> String -- ^ initial value- -> IO (Maybe String)-askInput prompt placeholder initial = withAskTty $ do- initLines <- askRepaint (renderInputFrame prompt initial placeholder) 0- let loop value prevLines = do- key <- readKey- case key of- KeyEnter -> askCommit (prompt ++ value) prevLines >> pure (Just value)- KeyEscape -> askErase prevLines >> pure Nothing- KeyCtrl 'C' -> askErase prevLines >> pure Nothing- KeyCtrl 'D' -> askErase prevLines >> pure Nothing- KeyBackspace | not (null value) -> do- let nv = init value- n <- askRepaint (renderInputFrame prompt nv placeholder) prevLines- loop nv n- KeyChar c -> do- let nv = value ++ [c]- n <- askRepaint (renderInputFrame prompt nv placeholder) prevLines- loop nv n- _ -> loop value prevLines- loop initial initLines---- | Yes\/No confirmation. On cancel returns the opposite of @def@ (matching the--- Scala @Ask.confirm@).-askConfirm :: String -- ^ question- -> Bool -- ^ default selection- -> String -- ^ affirmative label (e.g. @"Yes"@)- -> String -- ^ negative label (e.g. @"No"@)- -> IO Bool-askConfirm question def affirmative negative = do- r <- withAskTty $ do- initLines <- askRepaint (renderConfirmFrame question def affirmative negative) 0- let picked yes prevLines = do- let label = if yes then affirmative else negative- askCommit (question ++ " " ++ paintColor ColorCyan label) prevLines- pure (Just yes)- loop yes prevLines = do- let flipSel = do- let ny = not yes- n <- askRepaint (renderConfirmFrame question ny affirmative negative) prevLines- loop ny n- key <- readKey- case key of- KeyEnter -> picked yes prevLines- KeyChar c | c `elem` ("yY" :: String) -> picked True prevLines- | c `elem` ("nN" :: String) -> picked False prevLines- KeyLeft -> flipSel- KeyRight -> flipSel- KeyTab -> flipSel- KeyEscape -> askErase prevLines >> pure (Just (not def))- KeyCtrl 'C' -> askErase prevLines >> pure (Just (not def))- KeyCtrl 'D' -> askErase prevLines >> pure (Just (not def))- _ -> loop yes prevLines- loop def initLines- pure (maybe def id r)---- | Single-choice menu. Returns 'Nothing' if cancelled or @items@ is empty.-askChoose :: String -> [a] -> (a -> String) -> IO (Maybe a)-askChoose prompt items renderItem- | null items = pure Nothing- | otherwise = withAskTty $ do- initLines <- askRepaint (renderChooseFrame prompt items 0 renderItem) 0- let n = length items- loop idx prevLines = do- let move ni = do- pl <- askRepaint (renderChooseFrame prompt items ni renderItem) prevLines- loop ni pl- key <- readKey- case key of- KeyEnter -> do- let pick = items !! idx- askCommit (prompt ++ " " ++ paintColor ColorCyan (renderItem pick)) prevLines- pure (Just pick)- KeyUp -> move ((idx - 1 + n) `mod` n)- KeyDown -> move ((idx + 1) `mod` n)- KeyTab -> move ((idx + 1) `mod` n)- KeyEscape -> askErase prevLines >> pure Nothing- KeyCtrl 'C' -> askErase prevLines >> pure Nothing- KeyCtrl 'D' -> askErase prevLines >> pure Nothing- _ -> loop idx prevLines- loop 0 initLines---- | Multi-choice menu. @limit@ of 0 means unlimited. Space\/Tab toggles the--- current row; Enter commits. Returns 'Nothing' if cancelled or empty.-askChooseMany :: String -> [a] -> Int -> (a -> String) -> IO (Maybe [a])-askChooseMany prompt items limit renderItem- | null items = pure Nothing- | otherwise = withAskTty $ do- let n = length items- toggle i sel- | i `elem` sel = filter (/= i) sel- | limit > 0 && length sel >= limit = sel- | otherwise = sel ++ [i]- loop idx selected prevLines = do- pl <- askRepaint (renderChooseManyFrame prompt items idx selected limit renderItem) prevLines- key <- readKey- case key of- KeyEnter -> do- let picks = [ item | (item, i) <- zip items [0 ..], i `elem` selected ]- summary = if null picks- then prompt ++ " " ++ dimText "(nothing)"- else prompt ++ " " ++ paintColor ColorCyan (intercalate ", " (map renderItem picks))- askCommit summary pl- pure (Just picks)- KeyUp -> loop ((idx - 1 + n) `mod` n) selected pl- KeyDown -> loop ((idx + 1) `mod` n) selected pl- KeyChar ' ' -> loop idx (toggle idx selected) pl- KeyTab -> loop idx (toggle idx selected) pl- KeyEscape -> askErase pl >> pure Nothing- KeyCtrl 'C' -> askErase pl >> pure Nothing- KeyCtrl 'D' -> askErase pl >> pure Nothing- _ -> loop idx selected pl- loop 0 [] 0---- | Run @task@ while animating a spinner labelled @label@; print a ✓\/✗ line--- when it finishes. Re-throws if the task threw.-askSpin :: String -> SpinnerStyle -> IO a -> IO a-askSpin label style task = do- hideCursor- hFlush stdout- stopRef <- newIORef False- ticker <- forkIO $- let tick i = do- stop <- readIORef stopRef- unless stop $ do- let frames = spinnerFrames style- frame = paintColor ColorCyan (frames !! (i `mod` length frames)) ++ " " ++ label- putStr ("\r" ++ frame ++ askClearEol)- hFlush stdout- threadDelay 80000- tick (i + 1)- in tick 0- outcome <- (Right <$> task) `catch` \e -> pure (Left (e :: SomeException))- writeIORef stopRef True- killThread ticker- let (glyph, col) = case outcome of- Right _ -> ("✓", ColorGreen)- Left _ -> ("✗", ColorRed)- putStr ("\r" ++ paintColor col (glyph ++ " " ++ label) ++ askClearEol ++ "\n")- showCursor- hFlush stdout- case outcome of- Right v -> pure v- Left e -> throwIO e---- | Multi-line text editor. Enter inserts a newline; Ctrl-D submits; Esc--- cancels.-askWrite :: String -- ^ prompt- -> String -- ^ placeholder- -> String -- ^ initial value- -> String -- ^ hint line- -> IO (Maybe String)-askWrite prompt placeholder initial hint = withAskTty $ do- let loop value prevLines = do- pl <- askRepaint (renderWriteFrame prompt value placeholder hint) prevLines- key <- readKey- case key of- KeyCtrl 'D' -> do- let firstLine = case splitOnChar '\n' value of (x:_) -> x; [] -> ""- summary = if '\n' `elem` value then firstLine ++ " …" else firstLine- askCommit ((if not (null prompt) then prompt ++ " " else "") ++ paintColor ColorCyan summary) pl- pure (Just value)- KeyEscape -> askErase pl >> pure Nothing- KeyCtrl 'C' -> askErase pl >> pure Nothing- KeyEnter -> loop (value ++ "\n") pl- KeyChar c -> loop (value ++ [c]) pl- KeyBackspace | not (null value) -> loop (init value) pl- _ -> loop value pl- loop initial 0---- | Fuzzy incremental filter over @items@. Type to narrow, arrows to move,--- Enter to pick. Returns 'Nothing' if cancelled or empty.-askFilter :: String -> [a] -> Int -> (a -> String) -> IO (Maybe a)-askFilter prompt items viewHeight renderItem- | null items = pure Nothing- | otherwise = withAskTty $ do- let loop query idx prevLines = do- let matches = fuzzyMatches query items renderItem- safeIdx = if null matches then 0 else max 0 (min idx (length matches - 1))- m = length matches- pl <- askRepaint (renderFilterFrame prompt query matches safeIdx viewHeight renderItem) prevLines- key <- readKey- case key of- KeyEnter | not (null matches) -> do- let pick = matches !! safeIdx- askCommit (prompt ++ query ++ " " ++ paintColor ColorCyan (renderItem pick)) pl- pure (Just pick)- KeyUp | not (null matches) -> loop query ((safeIdx - 1 + m) `mod` m) pl- KeyDown | not (null matches) -> loop query ((safeIdx + 1) `mod` m) pl- KeyTab | not (null matches) -> loop query ((safeIdx + 1) `mod` m) pl- KeyBackspace | not (null query) -> loop (init query) 0 pl- KeyChar c -> loop (query ++ [c]) 0 pl- KeyEscape -> askErase pl >> pure Nothing- KeyCtrl 'C' -> askErase pl >> pure Nothing- KeyCtrl 'D' -> askErase pl >> pure Nothing- _ -> loop query safeIdx pl- loop "" 0 0---- | Directory browser. Enter descends into a directory or picks a file; Right--- descends; Left\/Backspace goes to the parent. Returns the chosen file path.-askFile :: String -> Int -> IO (Maybe String)-askFile start viewHeight = withAskTty (loop start 0 0)- where- loop dir idx prevLines = do- canonical <- canonicalizePath dir- res <- listEntries canonical- case res of- Left err -> askCommit (dimText err) prevLines >> pure Nothing- Right entries -> do- let count = length entries- safeIdx = max 0 (min idx (count - 1))- target = entries !! safeIdx- pl <- askRepaint (renderFileFrame canonical entries safeIdx viewHeight) prevLines- key <- readKey- case key of- KeyEnter -> do- full <- canonicalizePath (canonical ++ "/" ++ feName target)- if feIsDir target- then loop full 0 pl- else askCommit (paintColor ColorCyan full) pl >> pure (Just full)- KeyRight ->- if feIsDir target- then do full <- canonicalizePath (canonical ++ "/" ++ feName target); loop full 0 pl- else loop canonical safeIdx pl- KeyUp -> loop canonical ((safeIdx - 1 + count) `mod` count) pl- KeyDown -> loop canonical ((safeIdx + 1) `mod` count) pl- KeyTab -> loop canonical ((safeIdx + 1) `mod` count) pl- KeyLeft -> goParent canonical safeIdx pl- KeyBackspace -> goParent canonical safeIdx pl- KeyEscape -> askErase pl >> pure Nothing- KeyCtrl 'C' -> askErase pl >> pure Nothing- KeyCtrl 'D' -> askErase pl >> pure Nothing- _ -> loop canonical safeIdx pl- goParent canonical safeIdx pl = do- parent <- canonicalizePath (canonical ++ "/..")- if parent /= canonical then loop parent 0 pl else loop canonical safeIdx pl---- | List a directory as sorted 'FileEntry's (dirs first), with @".."@ prepended.-listEntries :: String -> IO (Either String [FileEntry])-listEntries path = do- exists <- doesPathExist path- isDir <- doesDirectoryExist path- if not exists then pure (Left ("not found: " ++ path))- else if not isDir then pure (Left ("not a directory: " ++ path))- else do- names <- listDirectory path `catch` \e -> let _ = (e :: IOException) in pure []- entries <- forM names $ \nm -> do- d <- doesDirectoryExist (path ++ "/" ++ nm)- pure (FileEntry nm d)- let sorted = sortOn (\e -> (not (feIsDir e), map toLower (feName e))) entries- pure (Right (FileEntry ".." True : sorted))---- | Scrollable pager. @viewHeight@ of 0 auto-sizes to the terminal.--- Arrows\/PgUp\/PgDn\/Home\/End navigate; q or Esc quits.-askPager :: String -> Int -> Bool -> IO ()-askPager content viewHeight lineNumbers = do- let ls = if null content then [""] else splitOnChar '\n' content- _ <- withAskTty $ do- (termH, termW) <- getTerminalSize- let h = if viewHeight > 0 then viewHeight else max 5 (termH - 3)- total = length ls- maxTop = max 0 (total - h)- loop top prevLines = do- let safeTop = max 0 (min top maxTop)- pl <- askRepaint (renderPagerFrame ls safeTop h termW lineNumbers) prevLines- key <- readKey- case key of- KeyChar 'q' -> askErase pl- KeyEscape -> askErase pl- KeyCtrl 'C' -> askErase pl- KeyUp -> loop (safeTop - 1) pl- KeyDown -> loop (safeTop + 1) pl- KeyEnter -> loop (safeTop + 1) pl- KeyPageUp -> loop (safeTop - h) pl- KeyPageDown -> loop (safeTop + h) pl- KeyChar ' ' -> loop (safeTop + h) pl- KeyHome -> loop 0 pl- KeyEnd -> loop maxTop pl- _ -> loop safeTop pl- loop 0 0- pure ()-+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ExplicitNamespaces #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE MagicHash #-}++{- |+Module : Layoutz+Description : Friendly, expressive print-layout DSL for Haskell+Copyright : (c) 2026 Matthieu Court+License : Apache-2.0++Compositional terminal layouts, charts, prompts and a small Elm-style TUI runtime.+-}++module Layoutz+ ( -- * Views+ View+ , render+ , renderIn+ , width+ , height+ -- * Content+ , text+ , display+ , br+ , vstack+ , row+ , box+ , banner+ , statusCard+ , ul+ , ol+ , table+ , section+ , kv+ , tree+ , leaf+ , branch+ , Tree(..)+ , hr+ , vr+ , inlineBar+ , chart+ -- * Attributes+ -- | Apply with @&@ or as plain functions: @box "T" xs & border BorderRound@.+ , fg+ , Color(..)+ , styleBold+ , styleDim+ , styleItalic+ , styleUnderline+ , styleBlink+ , styleReverse+ , styleHidden+ , styleStrikethrough+ , border+ , Border(..)+ , gap+ , glyph+ , size+ , accent+ , ellipsis+ , underline+ , center+ , centerIn+ , pad+ , margin+ , clip+ , fill+ , sized+ , overlay+ , fixedWidth+ , fixedHeight+ , alignLeft+ , alignRight+ , alignCenter+ , justify+ , wrap+ , (&)+ -- * Events+ , onClick+ , onScroll+ , onKey+ , button+ , focusable+ , focusStyle+ , clickAt+ , scrollAt+ , pressKey+ , focusOrder+ -- * Widgets+ , Viewport+ , viewport+ , viewportTop+ , viewportBottom+ , SelectList+ , selectList+ , selectListOf+ , selectedItem+ -- * Spinners+ , spinner+ , SpinnerStyle(..)+ -- * Plots+ , plotSparkline+ , Series(..)+ , plotLine+ , Slice(..)+ , plotPie+ , BarItem(..)+ , plotBar+ , StackedBarGroup(..)+ , plotStackedBar+ , HeatmapData(..)+ , plotHeatmap+ , plotHeatmap'+ -- * Apps+ , LayoutzApp(..)+ , sandbox+ , run+ , runApp+ , runInline+ , Options(..)+ , defaultOptions+ , AppAlignment(..)+ , Key(..)+ -- ** Terminal input+ , Input(..)+ , MouseEvent(..)+ , parseInput+ , Cmd+ , cmdNone+ , cmdFire+ , cmdTask+ , cmdAfterMs+ , cmdQuit+ , cmdFocus+ , executeCmd+ , Sub+ , subNone+ , subKeyPress+ , subEveryMs+ , subAnimationFrame+ , subFocus+ -- * Kitty graphics+ , KittyImage(..)+ , kittyImage+ , kittyRGB+ , kittyRGBA+ , kittyImageFile+ -- * Progress loaders+ , LoaderStyle(..)+ , loaderBlocks+ , loaderBar+ , loaderAscii+ , loaderDots+ , loaderLine+ , loaderPipes+ , loaderStyles+ , loader+ , loaderStyled+ , loaderStream+ , loaderStreamStyled+ -- * Interactive prompts (Ask)+ , askInput+ , askConfirm+ , askChoose+ , askChooseMany+ , askSpin+ , askWrite+ , askFilter+ , askFile+ , askPager+ ) where++import Data.List (transpose, nub, sortOn, intercalate, elemIndex, find)+import Data.Text (type Text, pattern (:<), pattern Empty)+import qualified Data.Text as T+import qualified Data.Text.IO.Utf8 as Utf8+import qualified Data.IntSet as IntSet+import qualified Data.IntMap.Strict as IntMap+import Data.Bits ((.|.), (.&.), xor, shiftL, shiftR, bit, setBit, testBit)+import Data.Maybe (fromMaybe, listToMaybe, catMaybes, mapMaybe, isJust, isNothing)+import Data.Function ((&))+import Control.Applicative ((<|>))+import Data.Word (Word8, Word64)+import GHC.Arr (Array, listArray, unsafeAt)+import Data.String (IsString(..))+import Data.Char (ord, chr, toLower, isDigit)+import Text.Printf (printf)+import System.IO+#if !defined(mingw32_HOST_OS)+import System.Posix.Signals (installHandler, Handler(..))+import System.Posix.Signals.Exts (sigWINCH)+#endif+import Control.Exception (catch, finally, throwIO, AsyncException(..), IOException, SomeException)+import System.Timeout (timeout)+import Control.Monad (when, unless, forever, forM, forM_, void)+import Control.Concurrent (forkIO, threadDelay, killThread, newChan, writeChan, readChan)+import Control.Concurrent.MVar (MVar, newMVar, putMVar, newEmptyMVar, takeMVar, tryTakeMVar, tryPutMVar)+import Data.IORef (IORef, newIORef, readIORef, writeIORef, atomicModifyIORef', modifyIORef')+import GHC.Clock (getMonotonicTimeNSec)+import GHC.Exts (isTrue#, reallyUnsafePtrEquality#)+import System.Directory (listDirectory, doesDirectoryExist, doesPathExist, canonicalizePath)++--------------------------------------------------------------------------------+-- Text measurement++replicateChar :: Int -> Char -> Text+replicateChar n = T.replicate n . T.singleton++-- | Drop SGR sequences and kitty APC blocks (@ESC _ ... ESC \\@) so neither+-- counts towards visible width.+stripAnsi :: Text -> Text+stripAnsi t = case T.break (== '\ESC') t of+ (before, rest) -> case rest of+ '\ESC' :< '[' :< more -> before <> stripAnsi (dropAfterM more)+ '\ESC' :< '_' :< more -> before <> stripAnsi (dropAfterST more)+ '\ESC' :< more -> before <> T.cons '\ESC' (stripAnsi more)+ _ -> before+ where+ dropAfterM ('m' :< xs) = xs+ dropAfterM (_ :< xs) = dropAfterM xs+ dropAfterM Empty = ""+ dropAfterST ('\ESC' :< '\\' :< xs) = xs+ dropAfterST (_ :< xs) = dropAfterST xs+ dropAfterST Empty = ""++-- | Terminal cell width: 0 for combining marks, 2 for wide CJK / emoji.+charWidth :: Char -> Int+charWidth c+ | c < '\x0300' = 1+ | c == kittyPlaceholderChar = 1+ | isRowColumnDiacritic c = 0+ | c >= '\x0300' && c < '\x0370' = 0 -- combining diacriticals+ | c >= '\x1100' && c < '\x1200' = 2 -- Hangul Jamo+ | c >= '\x2E80' && c < '\x9FFF' = 2 -- CJK+ | c >= '\xAC00' && c < '\xD7A4' = 2 -- Hangul syllables+ | c >= '\xF900' && c < '\xFB00' = 2 -- CJK compatibility ideographs+ | c >= '\xFE10' && c < '\xFE20' = 2 -- vertical forms+ | c >= '\xFE30' && c < '\xFE70' = 2 -- CJK compatibility forms+ | c >= '\xFF00' && c < '\xFF61' = 2 -- fullwidth forms+ | c >= '\xFFE0' && c < '\xFFE7' = 2 -- fullwidth symbols+ | c >= '\x1F000' = 2 -- emoji, supplementary planes+ | c >= '\x20000' && c < '\x2FFFF' = 2+ | c >= '\x30000' && c < '\x3FFFF' = 2+ | otherwise = 1++visibleLength :: Text -> Int+visibleLength = T.foldl' (\acc c -> acc + charWidth c) 0 . stripAnsi++-- | Kitty reserves one cell per placeholder glyph.+kittyPlaceholderChar :: Char+kittyPlaceholderChar = '\x10EEEE'++-- | Zero-width diacritics kitty uses to encode a placeholder's (row, column).+-- Its length caps the image size in cells.+rowColumnDiacritics :: [Int]+rowColumnDiacritics =+ [ 0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346+ , 0x034a, 0x034b, 0x034c, 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363+ , 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369, 0x036a, 0x036b, 0x036c+ , 0x036d, 0x036e, 0x036f, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592+ , 0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059c, 0x059d, 0x059e+ , 0x059f, 0x05a0, 0x05a1, 0x05a8, 0x05a9, 0x05ab, 0x05ac, 0x05af, 0x05c4+ , 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615, 0x0616, 0x0617, 0x0657+ , 0x0658, 0x0659, 0x065a, 0x065b, 0x065d, 0x065e, 0x06d6, 0x06d7, 0x06d8+ , 0x06d9, 0x06da, 0x06db, 0x06dc, 0x06df, 0x06e0, 0x06e1, 0x06e2, 0x06e4+ , 0x06e7, 0x06e8, 0x06eb, 0x06ec, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736+ , 0x073a, 0x073d, 0x073f, 0x0740, 0x0741, 0x0743, 0x0745, 0x0747, 0x0749+ , 0x074a, 0x07eb, 0x07ec, 0x07ed, 0x07ee, 0x07ef, 0x07f0, 0x07f1, 0x07f3+ , 0x0816, 0x0817, 0x0818, 0x0819, 0x081b, 0x081c, 0x081d, 0x081e, 0x081f+ , 0x0820, 0x0821, 0x0822, 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082a+ , 0x082b, 0x082c, 0x082d, 0x0951, 0x0953, 0x0954, 0x0f82, 0x0f83, 0x0f86+ , 0x0f87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76+ , 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e+ , 0x1b6f, 0x1b70, 0x1b71, 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda+ , 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4, 0x1dc5, 0x1dc6, 0x1dc7+ , 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5+ , 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde+ , 0x1ddf, 0x1de0, 0x1de1, 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe+ , 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7, 0x20db, 0x20dc, 0x20e1+ , 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2+ , 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb+ , 0x2dec, 0x2ded, 0x2dee, 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4+ , 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa, 0x2dfb, 0x2dfc, 0x2dfd+ , 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1+ , 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea+ , 0xa8eb, 0xa8ec, 0xa8ed, 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2+ , 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1, 0xfe20, 0xfe21, 0xfe22+ , 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186+ , 0x1d187, 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242+ , 0x1d243, 0x1d244+ ]++rowColumnDiacriticsSet :: IntSet.IntSet+rowColumnDiacriticsSet = IntSet.fromList rowColumnDiacritics++isRowColumnDiacritic :: Char -> Bool+isRowColumnDiacritic c = IntSet.member (ord c) rowColumnDiacriticsSet++padRight :: Int -> Text -> Text+padRight w str = str <> T.replicate (max 0 (w - visibleLength str)) " "++padLeft :: Int -> Text -> Text+padLeft w str = T.replicate (max 0 (w - visibleLength str)) " " <> str++-- | Spread words across @w@ columns, leftmost gaps taking the remainder.+justifyString :: Int -> Text -> Text+justifyString w str+ | T.length str >= w = str+ | length ws <= 1 = str+ | otherwise = T.concat (zipWith (<>) ws spaces)+ where+ ws = T.words str+ totalSpaces = w - sum (map T.length ws)+ gaps = length ws - 1+ (base, extra) = totalSpaces `divMod` gaps+ spaces = replicate extra (T.replicate (base + 1) " ")+ <> replicate (gaps - extra) (T.replicate base " ")+ <> [""]++--------------------------------------------------------------------------------+-- Core++-- | Anything that draws itself as text: the leaves of a 'View'.+class Element a where+ renderElement :: a -> Text++render :: View m -> String+render = T.unpack . blockText . drawView natural++-- | Render with @w@ x @h@ cells of room, the way an app's root is laid out:+-- 'fill' takes what's left.+renderIn :: Int -> Int -> View m -> String+renderIn w h = T.unpack . blockText . drawView (Room (Just w) (Just h) False)++-- | Widest visible line.+width :: View m -> Int+width = blockWidth . drawView natural++-- | Line count (an empty view still takes one line).+height :: View m -> Int+height v = case trimmed (bRows (drawView natural v)) of+ [] -> 1+ rs -> length rs++-- | The layout tree. @msg@ is what its handlers send ('onClick', 'onScroll');+-- a view without handlers fits any @msg@, so write helpers as @Model -> View m@.+--+-- Constructors take content; everything else is an attribute you apply with+-- @&@ (or plain function application):+--+-- @+-- 'vstack'+-- [ 'text' "Status" & 'styleBold' & 'underline'+-- , 'box' "Deploy" ['inlineBar' "build" 0.8] & 'border' BorderRound & 'fg' ColorGreen+-- , 'row' ['button' "-" Dec, 'display' n, 'button' "+" Inc]+-- ]+-- @+data View msg+ = forall a. Element a => Leaf a+ | Stack [View msg]+ | Row Int [View msg] -- gap+ | Margin Text (View msg)+ | Section Text Text Int [View msg] -- title, glyph, flank width+ | Rule Axis Text Int -- glyph, length+ | Underline Text (Maybe Color) (View msg)+ | Clip Int Text (View msg) -- max width, ellipsis+ | Pad Int (View msg)+ | Aligned Alignment Int (View msg)+ | Bullets [View msg]+ | Numbered [View msg]+ | AutoCenter (View msg)+ | Colored Color (View msg)+ | Styled Style (View msg)+ | Box Text [View msg] Border+ | StatusCard Text Text Border+ | Table [Text] [[View msg]] Border+ | Mapped (Text -> Text) (View msg) -- reflow the child's text+ | OnEvent (Handlers msg) (View msg)+ | Fill (View msg)+ | Fixed (Maybe Int) (Maybe Int) (View msg)+ | Focusable Text (View msg)+ | WhenFocused (forall n. View n -> View n) (View msg)+ | Scrolled (Viewport -> msg) Viewport (View msg)+ | Following Int (View msg) -- keep this row in sight+ | Sized (Int -> Int -> View msg) -- built from the room it gets+ | Overlay (View msg) (View msg) -- base, then centred on top of it++data Axis = Horizontal | Vertical++instance Show (View m) where+ show = render++-- | Lets you write @layout [\"Hello\", \"World\"]@ under @OverloadedStrings@.+instance IsString (View m) where+ fromString = text++data Border+ = BorderNormal+ | BorderDouble+ | BorderThick+ | BorderRound+ | BorderAscii+ | BorderBlock+ | BorderDashed+ | BorderDotted+ | BorderInnerHalfBlock+ | BorderOuterHalfBlock+ | BorderMarkdown+ | BorderCustom Text Text Text -- ^ corner, horizontal, vertical+ | BorderNone+ deriving (Show, Eq)++data Color = ColorDefault | ColorBlack | ColorRed | ColorGreen | ColorYellow+ | ColorBlue | ColorMagenta | ColorCyan | ColorWhite+ | ColorBrightBlack | ColorBrightRed | ColorBrightGreen | ColorBrightYellow+ | ColorBrightBlue | ColorBrightMagenta | ColorBrightCyan | ColorBrightWhite+ | ColorFull Int -- ^ 256-colour palette index+ | ColorTrue Int Int Int -- ^ 24-bit RGB+ deriving (Show, Eq)++colorCode :: Color -> Text+colorCode ColorDefault = ""+colorCode ColorBlack = "30"+colorCode ColorRed = "31"+colorCode ColorGreen = "32"+colorCode ColorYellow = "33"+colorCode ColorBlue = "34"+colorCode ColorMagenta = "35"+colorCode ColorCyan = "36"+colorCode ColorWhite = "37"+colorCode ColorBrightBlack = "90"+colorCode ColorBrightRed = "91"+colorCode ColorBrightGreen = "92"+colorCode ColorBrightYellow = "93"+colorCode ColorBrightBlue = "94"+colorCode ColorBrightMagenta = "95"+colorCode ColorBrightCyan = "96"+colorCode ColorBrightWhite = "97"+colorCode (ColorFull n) = "38;5;" <> T.show (clamp n)+colorCode (ColorTrue r g b) = "38;2;" <> T.show (clamp r) <> ";" <> T.show (clamp g) <> ";" <> T.show (clamp b)++clamp :: Int -> Int+clamp = max 0 . min 255++-- | No-op for 'ColorDefault'.+wrapAnsi :: Color -> Text -> Text+wrapAnsi color str+ | T.null (colorCode color) = str+ | otherwise = "\ESC[" <> colorCode color <> "m" <> str <> "\ESC[0m"++data Style = StyleDefault | StyleBold | StyleDim | StyleItalic | StyleUnderline+ | StyleBlink | StyleReverse | StyleHidden | StyleStrikethrough+ | StyleCombined [Style]+ deriving (Show, Eq)++-- | Combine styles with @<>@, e.g. @StyleBold <> StyleItalic@.+instance Semigroup Style where+ StyleDefault <> other = other+ other <> StyleDefault = other+ StyleCombined a <> StyleCombined b = StyleCombined (a <> b)+ StyleCombined a <> s = StyleCombined (a <> [s])+ s <> StyleCombined b = StyleCombined (s : b)+ a <> b = StyleCombined [a, b]++instance Monoid Style where+ mempty = StyleDefault++styleCode :: Style -> Text+styleCode StyleDefault = ""+styleCode StyleBold = "1"+styleCode StyleDim = "2"+styleCode StyleItalic = "3"+styleCode StyleUnderline = "4"+styleCode StyleBlink = "5"+styleCode StyleReverse = "7"+styleCode StyleHidden = "8"+styleCode StyleStrikethrough = "9"+styleCode (StyleCombined styles) =+ T.intercalate ";" (filter (not . T.null) (map styleCode styles))++wrapStyle :: Style -> Text -> Text+wrapStyle style str+ | T.null (styleCode style) = str+ | otherwise = "\ESC[" <> styleCode style <> "m" <> str <> "\ESC[0m"++-- | Top/bottom and left/right glyphs are separate so half-block borders work.+data BorderChars = BorderChars+ { bcTL, bcTR, bcBL, bcBR :: Text+ , bcHTop, bcHBottom :: Text+ , bcVLeft, bcVRight :: Text+ , bcLeftTee, bcRightTee, bcCross :: Text+ , bcTopTee, bcBottomTee :: Text+ }++mkSymmetric :: Text -> Text -> Text -> Text -> Text -> Text+ -> Text -> Text -> Text -> Text -> Text -> BorderChars+mkSymmetric tl tr bl br' h v lt rt cross tt bt = BorderChars+ { bcTL = tl, bcTR = tr, bcBL = bl, bcBR = br'+ , bcHTop = h, bcHBottom = h+ , bcVLeft = v, bcVRight = v+ , bcLeftTee = lt, bcRightTee = rt, bcCross = cross+ , bcTopTee = tt, bcBottomTee = bt+ }++borderChars :: Border -> BorderChars+borderChars BorderNormal = mkSymmetric "┌" "┐" "└" "┘" "─" "│" "├" "┤" "┼" "┬" "┴"+borderChars BorderDouble = mkSymmetric "╔" "╗" "╚" "╝" "═" "║" "╠" "╣" "╬" "╦" "╩"+borderChars BorderThick = mkSymmetric "┏" "┓" "┗" "┛" "━" "┃" "┣" "┫" "╋" "┳" "┻"+borderChars BorderRound = mkSymmetric "╭" "╮" "╰" "╯" "─" "│" "├" "┤" "┼" "┬" "┴"+borderChars BorderAscii = mkSymmetric "+" "+" "+" "+" "-" "|" "+" "+" "+" "+" "+"+borderChars BorderBlock = mkSymmetric "█" "█" "█" "█" "█" "█" "█" "█" "█" "█" "█"+borderChars BorderDashed = mkSymmetric "┌" "┐" "└" "┘" "╌" "╎" "├" "┤" "┼" "┬" "┴"+borderChars BorderDotted = mkSymmetric "┌" "┐" "└" "┘" "┈" "┊" "├" "┤" "┼" "┬" "┴"+borderChars BorderInnerHalfBlock = BorderChars+ { bcTL = "▗", bcTR = "▖", bcBL = "▝", bcBR = "▘"+ , bcHTop = "▄", bcHBottom = "▀"+ , bcVLeft = "▐", bcVRight = "▌"+ , bcLeftTee = "▐", bcRightTee = "▌", bcCross = "▄"+ , bcTopTee = "▄", bcBottomTee = "▀"+ }+borderChars BorderOuterHalfBlock = BorderChars+ { bcTL = "▛", bcTR = "▜", bcBL = "▙", bcBR = "▟"+ , bcHTop = "▀", bcHBottom = "▄"+ , bcVLeft = "▌", bcVRight = "▐"+ , bcLeftTee = "▌", bcRightTee = "▐", bcCross = "▀"+ , bcTopTee = "▀", bcBottomTee = "▄"+ }+borderChars BorderMarkdown = mkSymmetric "|" "|" "|" "|" "-" "|" "|" "|" "|" "|" "|"+borderChars (BorderCustom corner h v) = mkSymmetric corner corner corner corner h v corner corner corner corner corner+borderChars BorderNone = mkSymmetric " " " " " " " " " " " " " " " " " " " " " "++--------------------------------------------------------------------------------+-- Elements++instance Element Text where renderElement = id++data LineBreak = LineBreak+instance Element LineBreak where renderElement _ = ""++data Alignment = AlignLeft | AlignRight | AlignCenter | Justify+ deriving (Show, Eq)++renderStatusCard :: Text -> Text -> Border -> Text+renderStatusCard label content bdr =+ T.intercalate "\n" $ [topBorder] <> map cardLine allLines <> [bottomBorder]+ where+ allLines = T.lines label <> T.lines content+ inner = maximum (0 : map visibleLength allLines) + 2+ BorderChars{..} = borderChars bdr+ topBorder = bcTL <> T.replicate (inner + 2) (T.take 1 bcHTop) <> bcTR+ bottomBorder = bcBL <> T.replicate (inner + 2) (T.take 1 bcHBottom) <> bcBR+ cardLine l = bcVLeft <> " " <> padRight inner l <> " " <> bcVRight++newtype Chart = Chart [(Text, Double)]+instance Element Chart where+ renderElement (Chart points)+ | null points = "No data"+ | otherwise = T.intercalate "\n" $ map bar points+ where+ maxValue = maximum (0 : map snd points)+ labelWidth = min 15 (maximum (0 : map (T.length . fst) points))+ barWidth = 40++ bar (label, value) =+ let label'+ | T.length label > labelWidth = T.take (labelWidth - 3) label <> "..."+ | otherwise = label+ filled = floor (value / maxValue * fromIntegral barWidth)+ body = T.replicate filled "█" <> T.replicate (barWidth - filled) "─"+ in padRight labelWidth label' <> " │" <> body <> "│ " <> formatAxisNum value++newtype KeyValue = KeyValue [(Text, Text)]+instance Element KeyValue where+ renderElement (KeyValue []) = ""+ renderElement (KeyValue pairs) = T.intercalate "\n" $ map pair pairs+ where+ col = maximum (map (visibleLength . fst) pairs) + 2+ pair (k, v) =+ let k' = k <> ":"+ in k' <> T.replicate (max 1 (col - visibleLength k')) " " <> v++data Tree = Tree Text [Tree]++instance Element Tree where+ renderElement = go True "" True+ where+ go isRoot prefix isLast (Tree name children) =+ let nodeLine+ | isRoot = name+ | otherwise = prefix <> (if isLast then "└── " else "├── ") <> name+ childPrefix+ | isRoot = ""+ | otherwise = prefix <> (if isLast then " " else "│ ")+ n = length children+ childLines = zipWith (\i c -> go False childPrefix (i == n - 1) c) [0 :: Int ..] children+ in T.intercalate "\n" (nodeLine : childLines)++data InlineBar = InlineBar Text Double+instance Element InlineBar where+ renderElement (InlineBar label progress) =+ let p = max 0.0 (min 1.0 progress)+ filled = floor (p * 20)+ bar = T.replicate filled "█" <> T.replicate (20 - filled) "─"+ in label <> " [" <> bar <> "] " <> T.show (floor (p * 100) :: Int) <> "%"++--------------------------------------------------------------------------------+-- Drawing+--+-- A view draws into a block: rows of cells, the click regions inside them, and+-- any kitty uploads to send ahead of the grid. Rows are ragged like lines of+-- text, and containers pad exactly where the old text renderer did, so+-- 'render' prints the same thing it always has.++data Attr = Attr { aStyle :: !Int, aFg :: !Text, aBg :: !Text } -- SGR style bits, colour params++-- Cells and attrs are compared for every cell of every frame (diffing, pen+-- changes, recolouring), and most of them are shared: 'charText' for the+-- text, one 'Attr' per run. Checking for the very same object first skips+-- the byte comparison for nearly all of them.+instance Eq Attr where+ a@(Attr s f b) == a'@(Attr s' f' b') = same a a' || (s == s' && sameText f f' && sameText b b')++sameText :: Text -> Text -> Bool+sameText t t' = same t t' || t == t'+{-# INLINE sameText #-}++-- | Pointer equality, only ever a shortcut: 'False' says nothing.+same :: a -> a -> Bool+same x y = isTrue# (reallyUnsafePtrEquality# x y)+{-# INLINE same #-}++plain :: Attr+plain = Attr 0 "" ""++-- | One terminal column. The right half of a wide character is @Cell ""@.+data Cell = Cell !Text !Attr++instance Eq Cell where+ Cell t a == Cell t' a' = sameText t t' && a == a'++type Cells = [Cell]++data Rect = Rect !Int !Int !Int !Int -- top, left, height, width++data Block m = Block+ { bRows :: [Cells]+ , bHits :: [(Rect, Handlers m)] -- outermost first+ , bRaw :: [Text]+ }++-- | Room a view may grow into. Views keep their natural size unless they sit+-- under 'fill' or 'fixedWidth' / 'fixedHeight', which set 'roomStretch'.+data Room = Room { roomW, roomH :: !(Maybe Int), roomStretch :: !Bool }++natural :: Room+natural = Room Nothing Nothing False++blank :: Cell+blank = Cell " " plain++rowsBlock :: [Cells] -> Block m+rowsBlock rs = Block rs [] []++rowsWidth :: [Cells] -> Int+rowsWidth = maximum . (0 :) . map length++blockWidth :: Block m -> Int+blockWidth = rowsWidth . bRows++-- | What 'T.lines' would have seen: a trailing empty row goes.+trimmed :: [Cells] -> [Cells]+trimmed rs+ | not (null rs), null (last rs) = init rs+ | otherwise = rs++padTo :: Int -> Cells -> Cells+padTo w r+ | n <= 0 = r -- already wide enough: share the row instead of copying it+ | otherwise = r <> replicate n blank+ where n = w - length r++moveHits :: Int -> Int -> [(Rect, h)] -> [(Rect, h)]+moveHits dy dx = map (\(Rect t l h w, x) -> (Rect (t + dy) (l + dx) h w, x))++-- | Stack blocks top to bottom.+vcat :: [Block m] -> Block m+vcat bs = Block (concatMap bRows bs) hits (concatMap bRaw bs)+ where+ tops = scanl (+) 0 (map (length . bRows) bs)+ hits = concat (zipWith (\t b -> moveHits t 0 (bHits b)) tops bs)++cellsOf :: Attr -> Text -> Cells+cellsOf a = reverse . pushText a []++-- | Add text to a row kept in reverse: combining marks join the cell before,+-- wide characters take two.+pushText :: Attr -> Cells -> Text -> Cells+pushText a = T.foldl' step+ where+ step acc c = case charWidth c of+ 0 | Cell "" r : Cell t a' : rest <- acc -> Cell "" r : Cell (T.snoc t c) a' : rest -- onto the wide character, not its right half+ | Cell t a' : rest <- acc -> Cell (T.snoc t c) a' : rest+ | otherwise -> acc+ 2 -> Cell "" a : Cell (charText c) a : acc+ _ -> Cell (charText c) a : acc++-- | A one-character 'Text', shared for ASCII, box drawing and block elements so+-- drawing a row doesn't allocate a fresh string per cell.+charText :: Char -> Text+charText c+ | i < 0x80 = asciiTexts `unsafeAt` i+ | i >= 0x2500 && i < 0x25A0 = boxTexts `unsafeAt` (i - 0x2500)+ | otherwise = T.singleton c+ where i = ord c++asciiTexts, boxTexts :: Array Int Text+asciiTexts = listArray (0, 0x7F) [ T.singleton (chr n) | n <- [0 .. 0x7F] ]+boxTexts = listArray (0, 0x9F) [ T.singleton (chr n) | n <- [0x2500 .. 0x259F] ]++-- | Read text the way a terminal would: SGR moves the pen, kitty uploads are+-- set aside, any other escape is dropped.+textBlock :: Text -> Block m+textBlock = go plain [] [] . T.splitOn "\n"+ where+ go _ rows raw [] = Block (reverse rows) [] (reverse raw)+ go a rows raw (l : ls) =+ let (line, a', raw') = scan a [] raw l+ in go a' (reverse line : rows) raw' ls++ scan a acc raw s =+ let (chunk, rest) = T.break (== '\ESC') s+ acc' = pushText a acc chunk+ in case rest of+ '\ESC' :< '[' :< more ->+ let (params, after) = T.span (\c -> c < '@' || c > '~') more+ in case after of+ 'm' :< after' -> scan (applySgr a params) acc' raw after'+ _ :< after' -> scan a acc' raw after'+ Empty -> (acc', a, raw)+ '\ESC' :< '_' :< more ->+ let (body, after) = T.breakOn kittyST more+ raw' | "G" `T.isPrefixOf` body = ("\ESC_" <> body <> kittyST) : raw+ | otherwise = raw+ in scan a acc' raw' (T.drop (T.length kittyST) after)+ '\ESC' :< _ :< more -> scan a acc' raw more+ _ -> (acc', a, raw)++applySgr :: Attr -> Text -> Attr+applySgr a0 = go a0 . map param . T.splitOn ";"+ where+ param t+ | not (T.null t), T.all isDigit t = T.foldl' (\n c -> n * 10 + ord c - 48) 0 t+ | otherwise = 0 :: Int+ rgb k r g b = T.intercalate ";" (map T.show [k, 2, r, g, b])++ go a [] = a+ go _ (0 : ps) = go plain ps+ go a (38 : 5 : n : ps) = go a { aFg = "38;5;" <> T.show n } ps+ go a (38 : 2 : r : g : b : ps) = go a { aFg = rgb 38 r g b } ps+ go a (48 : 5 : n : ps) = go a { aBg = "48;5;" <> T.show n } ps+ go a (48 : 2 : r : g : b : ps) = go a { aBg = rgb 48 r g b } ps+ go a (n : ps)+ | n >= 1 && n <= 9 = go a { aStyle = setBit (aStyle a) n } ps+ | n >= 30 && n <= 37 || n >= 90 && n <= 97 = go a { aFg = T.show n } ps+ | n >= 40 && n <= 47 || n >= 100 && n <= 107 = go a { aBg = T.show n } ps+ | n == 39 = go a { aFg = "" } ps+ | n == 49 = go a { aBg = "" } ps+ | otherwise = go a ps++-- | A row as text, switching the pen only where the attributes change.+rowText :: Cells -> Text+rowText = T.concat . go plain+ where+ go a [] = [ "\ESC[0m" | a /= plain ]+ go a (Cell t a' : cs)+ | a' == a = t : go a cs+ | otherwise = [ "\ESC[0m" | a /= plain ] <> [pen a', t] <> go a' cs++ pen (Attr st f b) = sgr (T.intercalate ";" [ T.show n | n <- [1 .. 9 :: Int], testBit st n ]) <> sgr f <> sgr b+ sgr p = if T.null p then "" else "\ESC[" <> p <> "m"++-- | What turns a screen showing @old@ into one showing @new@ (1-based rows+-- from the top): each run of changed cells behind one cursor move, with short+-- unchanged gaps rewritten rather than jumped over, and leftover cells cleared.+-- Assumes the screen is blank past the end of each old row.+diffRows :: [Cells] -> [Cells] -> Text+diffRows old new = T.concat (zipWith3 diffRow [1 ..] (upTo old) (upTo new))+ where+ upTo rs = take (max (length old) (length new)) (rs <> repeat [])++diffRow :: Int -> Cells -> Cells -> Text+diffRow i old new = foldMap draw (runs (changedAt 0 new old)) <> clearTail+ where+ newLen = length new++ -- columns where @new@ differs from @old@, in one pass over both+ changedAt :: Int -> Cells -> Cells -> [Int]+ changedAt c (x : xs) (o : os)+ | x == o = c `seq` changedAt (c + 1) xs os+ | otherwise = c : changedAt (c + 1) xs os+ changedAt c xs [] = take (length xs) [c ..]+ changedAt _ [] _ = []++ -- a cursor move costs about as much as rewriting a few cells+ runs [] = []+ runs (c : cs) = go c c cs+ where+ go a b (d : ds)+ | d - b <= 5 = go a d ds+ | otherwise = (a, b) : go d d ds+ go a b [] = [(a, b)]++ draw (a, b) =+ let a' = startAt a+ in goto (a' + 1) <> rowText (take (b - a' + 1) (drop a' new))++ -- Never start on the right half of a wide character, or on a kitty+ -- placeholder that takes its image position from the cell before it.+ startAt a+ | a > 0, Cell t _ : _ <- drop a new, T.null t || t == T.singleton kittyPlaceholderChar = startAt (a - 1)+ | otherwise = a++ clearTail+ | length old > newLen = goto (newLen + 1) <> "\ESC[K"+ | otherwise = ""++ goto c = "\ESC[" <> T.show i <> ";" <> T.show c <> "H"++-- | Every row in full, then whatever is left of the screen cleared. For after+-- a resize, when nothing on screen can be trusted. Unlike clearing first, a+-- terminal that paints mid-frame (no synchronized updates) shows the old+-- frame under the new one rather than blank rows.+repaintRows :: Int -> Int -> [Cells] -> Text+repaintRows termW termH rows =+ T.concat [ goto i <> rowText r <> clearRight r | (i, r) <- zip [1 ..] rows ]+ <> (if length rows < termH then goto (length rows + 1) <> "\ESC[J" else "")+ where+ goto i = "\ESC[" <> T.show (i :: Int) <> ";1H"+ -- not on a full row: the cursor sits on the last cell and would erase it+ clearRight r = if length r < termW then "\ESC[K" else ""++blockText :: Block m -> Text+blockText b = T.concat (bRaw b) <> T.intercalate "\n" (map rowText (bRows b))++recolor :: (Attr -> Attr) -> Block m -> Block m+recolor f b = b { bRows = map (go plain (f plain)) (bRows b) }+ where+ -- runs of cells share an Attr: compute it once per run, not per cell+ go _ _ [] = []+ go i o (Cell t a : cs)+ | a == i = Cell t o : go i o cs+ | otherwise = let o' = f a in Cell t o' : go a o' cs++styleBits :: Style -> Int+styleBits = \case+ StyleDefault -> 0+ StyleBold -> bit 1+ StyleDim -> bit 2+ StyleItalic -> bit 3+ StyleUnderline -> bit 4+ StyleBlink -> bit 5+ StyleReverse -> bit 7+ StyleHidden -> bit 8+ StyleStrikethrough -> bit 9+ StyleCombined ss -> foldr ((.|.) . styleBits) 0 ss++drawView :: Room -> View m -> Block m+drawView room = \case+ Leaf x -> textBlock (renderElement x)+ Stack xs -> drawStack room xs+ Row g xs -> drawRow room g xs+ Margin p v ->+ let b = drawView natural v+ pre = cellsOf plain (p <> " ")+ in b { bRows = map (pre <>) (trimmed (bRows b)), bHits = moveHits 0 (length pre) (bHits b) }+ Section t g n xs ->+ let flank = T.replicate n (T.take 1 g)+ in vcat [rowsBlock [cellsOf plain (flank <> " " <> t <> " " <> flank)], drawStack natural xs]+ Rule h g n -> drawRule room h g n+ Underline g c v -> drawUnderline g c (drawView natural v)+ Clip n e v -> drawClip n e (drawView natural v)+ Pad p v -> drawPad p (drawView natural v)+ Aligned a w v -> alignBlock a w (drawView natural v)+ Bullets xs -> drawBullets xs+ Numbered xs -> drawNumbered xs+ AutoCenter v -> drawView room v -- the enclosing stack does the centring+ Colored c v -> recolor (\a -> if T.null (aFg a) then a { aFg = colorCode c } else a) (drawView room v)+ Styled st v -> recolor (\a -> a { aStyle = aStyle a .|. styleBits st }) (drawView room v)+ Box t xs b -> drawBox room t xs b+ StatusCard l c b -> textBlock (renderStatusCard l c b)+ Table hs rs b -> drawTable hs rs b+ Mapped f v -> textBlock (f (blockText (drawView natural v)))+ OnEvent h v ->+ let b = drawView room v+ in b { bHits = (Rect 0 0 (length (bRows b)) (blockWidth b), h { hScope = hScope h <|> focusName v }) : bHits b }+ Focusable n v ->+ let b = drawView room v+ own = (Rect 0 0 (length (bRows b)) (blockWidth b), noHandlers { hFocus = Just n, hScope = Just n })+ mine = [ (r, if isNothing (hScope h) then h { hScope = Just n } else h) | (r, h) <- bHits b ]+ in b { bHits = own : mine }+ WhenFocused _ v -> drawView room v -- 'resolveFocus' already applied the focused ones+ Scrolled k vp v -> drawScrolled room k vp v+ Following i v ->+ let (inner, h, w) = windowed room v+ in window (max 0 (min (length (bRows inner) - h) (i - h `div` 2))) h w inner+ Fill v -> claim room { roomStretch = True } (drawView room { roomStretch = True } v)+ Fixed mw mh v ->+ let r = Room (mw <|> roomW room) (mh <|> roomH room) True+ in crop mw mh (claim r (drawView r v))+ Sized k -> drawView room (k (fromMaybe 80 (roomW room)) (fromMaybe 24 (roomH room)))+ Overlay b t -> drawOverlay (drawView room b) (drawView natural t)++-- | Paste @top@ centred over @base@. Where it covers, its cells and handlers+-- win; a wide character it cuts in half becomes a space.+drawOverlay :: Block m -> Block m -> Block m+drawOverlay base top = Block rows (bHits base <> moveHits dy dx (bHits top)) (bRaw base <> bRaw top)+ where+ bw = blockWidth base+ tw = blockWidth top+ dy = max 0 ((length (bRows base) - length (bRows top)) `div` 2)+ dx = max 0 ((bw - tw) `div` 2)+ rows = zipWith pick [0 ..] (bRows base)+ pick i r = maybe r (paste r) (lookup (i - dy) (zip [0 ..] (bRows top)))+ paste r t =+ let (pre, rest) = splitAt dx (padTo bw r)+ post = drop tw rest+ halved = \case Cell c _ : _ -> T.null c; [] -> False+ pre' = if halved rest then take (dx - 1) pre <> [blank] else pre+ post' = if halved post then blank : drop 1 post else post+ in pre' <> take (bw - dx) (padTo tw t) <> post'++-- | Under 'fill', take the whole room even where nothing was drawn.+claim :: Room -> Block m -> Block m+claim (Room mw mh True) b = b { bRows = rows' }+ where+ w = fromMaybe (blockWidth b) mw+ rows = maybe id padTo mw `map` bRows b+ rows' = rows <> replicate (maybe 0 (subtract (length rows)) mh) (replicate w blank)+claim _ b = b++crop :: Maybe Int -> Maybe Int -> Block m -> Block m+crop mw mh b = b { bRows = maybe id take mh (map (maybe id take mw) (bRows b)) }++-- | The content of a scrolling view, the rows it has to show it in, and the+-- width its scrollbar goes after.+windowed :: Room -> View m -> (Block m, Int, Int)+windowed room v = (inner, h, max (blockWidth inner) (fromMaybe 0 innerW))+ where+ stretched = roomStretch room+ innerW = if stretched then subtract 1 <$> roomW room else Nothing+ -- lines wider than the room are cut rather than pushing the parent out+ inner = crop innerW Nothing (drawView (Room innerW Nothing False) v)+ h | stretched, Just rh <- roomH room = rh+ | otherwise = length (bRows inner)++-- | @h@ rows of a block starting at @top@, with a scrollbar after column @w@+-- if it doesn't fit.+window :: Int -> Int -> Int -> Block m -> Block m+window top h w b+ | total <= h = b+ | otherwise = Block (zipWith (\r bar -> padTo w r <> [bar]) (take h (drop top rows) <> repeat []) bars) hits (bRaw b)+ where+ rows = bRows b+ total = length rows+ thumb = max 1 (h * h `div` total)+ at = top * (h - thumb) `div` max 1 (total - h)+ bars = [ Cell (if i >= at && i < at + thumb then "█" else "│") plain | i <- [0 .. h - 1] ]+ hits = [ (Rect t' l (b' - t') ww, x)+ | (Rect t l hh ww, x) <- bHits b+ , let t' = max 0 (t - top); b' = min h (t + hh - top)+ , b' > t' ]++drawScrolled :: Room -> (Viewport -> msg) -> Viewport -> View msg -> Block msg+drawScrolled room moved (Viewport off) v = b { bHits = own : bHits b }+ where+ (inner, h, w) = windowed room v+ maxTop = max 0 (length (bRows inner) - h)+ top = max 0 (min maxTop off)+ b = window top h w inner+ to n = moved (Viewport (if n >= maxTop then maxBound else max 0 n))+ own = (Rect 0 0 h (blockWidth b), noHandlers { hScroll = Just (\d -> to (top + 3 * d)), hKey = Just keys })+ keys = \case+ KeyUp -> Just (to (top - 1))+ KeyDown -> Just (to (top + 1))+ KeyPageUp -> Just (to (top - h))+ KeyPageDown -> Just (to (top + h))+ KeyHome -> Just (to 0)+ KeyEnd -> Just (to maxTop)+ _ -> Nothing++-- | Children whose size is up to the parent: wrapped in 'fill', perhaps under+-- colour, style or a handler.+isFill :: View m -> Bool+isFill = \case+ Fill _ -> True+ Colored _ v -> isFill v+ Styled _ v -> isFill v+ OnEvent _ v -> isFill v+ Focusable _ v -> isFill v+ WhenFocused _ v -> isFill v+ _ -> False++-- | Draw children along one axis: the rest first, offered only the room+-- across it, then the 'fill' ones sharing whatever is left along it.+share :: (Block m -> Int) -> Int -> Maybe Int -> (Maybe Int -> Room) -> [View m] -> [Block m]+share extent gaps room roomFor xs = map draw' (zip xs fixed)+ where+ fixed = [ if isFill x then Nothing else Just (drawView (roomFor Nothing) x) | x <- xs ]+ used = sum [ extent b | Just b <- fixed ] + gaps+ nFills = length (filter isFill xs)+ each = (\r -> max 0 (r - used) `div` max 1 nFills) <$> room+ draw' (x, Nothing) = drawView (roomFor each) x+ draw' (_, Just b) = b++drawStack :: Room -> [View m] -> Block m+drawStack room xs = vcat (zipWith place xs blocks)+ where+ blocks = share (length . bRows) 0 (roomH room) (\h -> Room (roomW room) h False) xs+ placed = [ b | (x, b) <- zip xs blocks, not (isAutoCenter x) ]+ ctx | roomStretch room, Just w <- roomW room = w+ | null placed = 80+ | otherwise = maximum (map blockWidth placed)++ isAutoCenter (AutoCenter _) = True+ isAutoCenter _ = False++ place (AutoCenter _) b = alignBlock AlignCenter ctx b+ place _ b = b++drawRow :: Room -> Int -> [View m] -> Block m+drawRow _ _ [] = rowsBlock []+drawRow room g xs = Block rows hits (concatMap bRaw blocks)+ where+ blocks = share blockWidth (g * (length xs - 1)) (roomW room) (\w -> Room w (roomH room) False) xs+ cols = map (trimmed . bRows) blocks+ widths = map rowsWidth cols+ h = maximum (map length cols)+ padded = zipWith (\w c -> map (padTo w) (take h (c <> repeat []))) widths cols+ rows = map (intercalate (replicate g blank)) (transpose padded)+ lefts = scanl (\x w -> x + w + g) 0 widths+ hits = concat (zipWith (\x b -> moveHits 0 x (bHits b)) lefts blocks)++-- | Prefix the first row with @first@ and the others with @rest@.+hang :: Text -> Text -> Block m -> Block m+hang first rest b = Block rows (moveHits 0 (length firstCells) (bHits b)) (bRaw b)+ where+ firstCells = cellsOf plain first+ rows = case trimmed (bRows b) of+ [] -> [firstCells]+ r : rs -> (firstCells <> r) : map (cellsOf plain rest <>) rs++drawRule :: Room -> Axis -> Text -> Int -> Block m+drawRule room axis g n = rowsBlock $ case axis of+ Horizontal -> [cellsOf plain (T.replicate (stretched roomW) g)]+ Vertical -> replicate (stretched roomH) (cellsOf plain g)+ where+ stretched along+ | roomStretch room = fromMaybe n (along room)+ | otherwise = n++drawUnderline :: Text -> Maybe Color -> Block m -> Block m+drawUnderline g color b = b { bRows = bRows b <> [cellsOf pen rule] }+ where+ (reps, rest) = rowsWidth (trimmed (bRows b)) `divMod` T.length g+ rule = T.replicate reps g <> T.take rest g+ pen = maybe plain (\c -> plain { aFg = colorCode c }) color++drawClip :: Int -> Text -> Block m -> Block m+drawClip n ell b = Block (map cut (trimmed (bRows b))) hits (bRaw b)+ where+ keep = n - T.length ell+ cut cs+ | length cs <= n = cs+ | keep <= 0 = cellsOf plain (T.take n ell)+ | otherwise = whole (take keep cs) (drop keep cs) <> cellsOf plain ell+ -- don't leave half a wide character behind+ whole kept (Cell "" _ : _) = init kept <> [blank]+ whole kept _ = kept+ hits = [ (Rect t l h (min w (n - l)), x) | (Rect t l h w, x) <- bHits b, l < n ]++drawPad :: Int -> Block m -> Block m+drawPad p b = Block (border' <> map (\r -> side <> padTo w r <> side) rows <> border') (moveHits p p (bHits b)) (bRaw b)+ where+ rows = trimmed (bRows b)+ w = rowsWidth rows+ side = replicate p blank+ border' = replicate p (replicate (w + 2 * p) blank)++alignBlock :: Alignment -> Int -> Block m -> Block m+alignBlock a w b = Block (zipWith (\l r -> lead l <> align r) lefts rows) hits (bRaw b)+ where+ rows = trimmed (bRows b)+ lefts = map leftPad rows+ leftPad r+ | length r >= w = 0+ | otherwise = case a of+ AlignRight -> w - length r+ AlignCenter -> (w - length r) `div` 2+ _ -> 0+ lead l = replicate l blank+ align r = case a of+ AlignLeft -> padTo w r+ AlignRight -> r+ AlignCenter -> padTo (w - leftPad r) r+ Justify -> case bRows (textBlock (justifyString w (rowText r))) of+ r' : _ -> r'+ [] -> r+ hits = [ (Rect t (l + dx) h ww, x) | (Rect t l h ww, x) <- bHits b, let dx = fromMaybe 0 (lookup t (zip [0 ..] lefts)) ]++drawBox :: Room -> Text -> [View m] -> Border -> Block m+drawBox room title xs bdr = Block (cellsOf plain top : body <> [cellsOf plain bottom]) hits (concatMap bRaw blocks)+ where+ inner | roomStretch room = Room (subtract 4 <$> roomW room) (subtract 2 <$> roomH room) False+ | otherwise = natural+ blocks = share (length . bRows) 0 (roomH inner) (\h -> Room (roomW inner) h False) xs+ rows = case trimmed (concatMap bRows blocks) of+ [] -> [[]]+ rs -> rs+ content = rows <> replicate (maybe 0 (subtract (length rows)) (roomH inner)) []+ titleW = if T.null title then 0 else visibleLength title + 2+ innerW = maximum [rowsWidth rows, titleW, fromMaybe 0 (roomW inner)]+ totalW = innerW + 4+ BorderChars{..} = borderChars bdr+ hTop = T.take 1 bcHTop+ hBottom = T.take 1 bcHBottom++ top+ | T.null title = bcTL <> T.replicate (totalW - 2) hTop <> bcTR+ | otherwise =+ let slack = totalW - visibleLength title - 2+ l = slack `div` 2+ in bcTL <> T.replicate l hTop <> title <> T.replicate (slack - l) hTop <> bcTR+ bottom = bcBL <> T.replicate (totalW - 2) hBottom <> bcBR+ body = map (\r -> cellsOf plain (bcVLeft <> " ") <> padTo innerW r <> cellsOf plain (" " <> bcVRight)) content++ tops = scanl (+) 0 (map (length . bRows) blocks)+ hits = concat (zipWith (\t b -> moveHits (1 + t) 2 (bHits b)) tops blocks)++drawTable :: [Text] -> [[View m]] -> Border -> Block m+drawTable headers rows bdr =+ Block (map (cellsOf plain) [topBorder, headerRow, separator] <> concat dataRows <> [cellsOf plain bottomBorder])+ hits (concatMap bRaw (concat cells))+ where+ cells = map (map (drawView natural) . fitRow (length headers)) rows+ cellRows = map (map (trimmed . bRows)) cells+ widths = map (maximum . (0 :)) (transpose (map visibleLength headers : map (map rowsWidth) cellRows))+ BorderChars{..} = borderChars bdr+ hTop = T.take 1 bcHTop+ hBottom = T.take 1 bcHBottom++ rule l mid r h = l <> h <> T.intercalate (h <> mid <> h) [T.replicate w h | w <- widths] <> h <> r+ topBorder = rule bcTL bcTopTee bcTR hTop+ separator = rule bcLeftTee bcCross bcRightTee hTop+ bottomBorder = rule bcBL bcBottomTee bcBR hBottom++ headerRow = bcVLeft <> " " <> T.intercalate (" " <> bcVLeft <> " ") (zipWith padRight widths headers) <> " " <> bcVRight+ line cs = cellsOf plain (bcVLeft <> " ") <> intercalate (cellsOf plain (" " <> bcVLeft <> " ")) cs+ <> cellsOf plain (" " <> bcVRight)++ fitRow n cs+ | length cs >= n = take n cs+ | otherwise = cs <> replicate (n - length cs) (text "")++ -- a row is as tall as its tallest cell+ heights = [ maximum (1 : map length r) | r <- cellRows ]+ dataRows = [ map line (transpose (zipWith (\w c -> map (padTo w) (take h (c <> repeat []))) widths r))+ | (h, r) <- zip heights cellRows ]++ lefts = scanl (\x w -> x + w + 3) 2 widths+ tops = scanl (+) 3 heights+ hits = concat [ moveHits t l (bHits b) | (t, rowCells) <- zip tops cells, (l, b) <- zip lefts rowCells ]++drawBullets :: [View m] -> Block m+drawBullets = go 0+ where+ bullets = ["•", "◦", "▪"]+ go level = vcat . map item+ where+ bullet = bullets !! (level `mod` length bullets)+ indent = T.replicate (level * 2) " "+ item (Bullets nested) = go (level + 1) nested+ item x = hangMarker indent (bullet <> " ") (drawView natural x)++drawNumbered :: [View m] -> Block m+drawNumbered = go (0 :: Int)+ where+ go level = vcat . zipWith item [1 ..]+ where+ indent = T.replicate (level * 2) " "+ item _ (Numbered nested) = go (level + 1) nested+ item n x = hangMarker indent (marker n <> ". ") (drawView natural x)++ marker n = case level `mod` 3 of+ 0 -> T.show n+ 1 -> T.singleton (toEnum (96 + n))+ _ -> roman n++ roman :: Int -> Text+ roman = \case+ 1 -> "i"; 2 -> "ii"; 3 -> "iii"; 4 -> "iv"; 5 -> "v"+ 6 -> "vi"; 7 -> "vii"; 8 -> "viii"; 9 -> "ix"; 10 -> "x"+ n -> T.show n++hangMarker :: Text -> Text -> Block m -> Block m+hangMarker indent marker = hang (indent <> marker) (indent <> T.replicate (T.length marker) " ")++--------------------------------------------------------------------------------+-- Content++text :: String -> View m+text = Leaf . T.pack++-- | @text . show@+display :: Show a => a -> View m+display = text . show++br :: View m+br = Leaf LineBreak++-- | Top to bottom.+vstack :: [View m] -> View m+vstack = Stack++-- | Left to right, one space apart; change it with 'gap'.+--+-- @+-- 'row' ['vstack' ["A", "B"], 'vstack' ["C", "D"]] & 'gap' 2+-- -- A C+-- -- B D+-- @+row :: [View m] -> View m+row = Row 1++box :: String -> [View m] -> View m+box title elements = Box (T.pack title) elements BorderNormal++-- | Titleless box with a double border.+--+-- @+-- 'banner' ["System Dashboard"]+-- -- ╔══════════════════╗+-- -- ║ System Dashboard ║+-- -- ╚══════════════════╝+-- @+banner :: [View m] -> View m+banner content = Box "" content BorderDouble++statusCard :: String -> String -> View m+statusCard label content = StatusCard (T.pack label) (T.pack content) BorderNormal++ul :: [View m] -> View m+ul = Bullets++ol :: [View m] -> View m+ol = Numbered++table :: [String] -> [[View m]] -> View m+table headers rows = Table (map T.pack headers) rows BorderNormal++-- | @=== title ===@ over its content; see 'glyph' and 'size'.+section :: String -> [View m] -> View m+section title = Section (T.pack title) "=" 3++kv :: [(String, String)] -> View m+kv pairs = Leaf (KeyValue [ (T.pack k, T.pack v) | (k, v) <- pairs ])++tree :: String -> [Tree] -> View m+tree name children = Leaf (Tree (T.pack name) children)++leaf :: String -> Tree+leaf name = Tree (T.pack name) []++branch :: String -> [Tree] -> Tree+branch name = Tree (T.pack name)++-- | 50 wide; see 'glyph' and 'size'.+hr :: View m+hr = Rule Horizontal "─" 50++-- | 10 tall; see 'glyph' and 'size'.+vr :: View m+vr = Rule Vertical "│" 10++inlineBar :: String -> Double -> View m+inlineBar label progress = Leaf (InlineBar (T.pack label) progress)++-- | Horizontal bar chart.+chart :: [(String, Double)] -> View m+chart points = Leaf (Chart [ (T.pack label, v) | (label, v) <- points ])++--------------------------------------------------------------------------------+-- Attributes+--+-- Each is a @View m -> View m@. Ones that tune a setting ('gap', 'glyph',+-- 'size', 'accent', 'ellipsis', 'border') adjust the nearest node that has+-- it, looking through colour, style and handlers, and leave anything else+-- alone.++adjust :: (View m -> Maybe (View m)) -> View m -> View m+adjust f v = fromMaybe inward (f v)+ where+ inward = case v of+ Colored c x -> Colored c (adjust f x)+ Styled st x -> Styled st (adjust f x)+ OnEvent h x -> OnEvent h (adjust f x)+ AutoCenter x -> AutoCenter (adjust f x)+ Fill x -> Fill (adjust f x)+ Fixed w h x -> Fixed w h (adjust f x)+ Focusable n x -> Focusable n (adjust f x)+ WhenFocused t x -> WhenFocused t (adjust f x)+ _ -> v++fg :: Color -> View m -> View m+fg = Colored++styled :: Style -> View m -> View m+styled st (Styled st' v) = Styled (st' <> st) v+styled st v = Styled st v++styleBold, styleDim, styleItalic, styleUnderline, styleBlink, styleReverse, styleHidden, styleStrikethrough+ :: View m -> View m+styleBold = styled StyleBold+styleDim = styled StyleDim+styleItalic = styled StyleItalic+styleUnderline = styled StyleUnderline+styleBlink = styled StyleBlink+styleReverse = styled StyleReverse+styleHidden = styled StyleHidden+styleStrikethrough = styled StyleStrikethrough++-- | For 'box', 'banner', 'statusCard' and 'table'.+border :: Border -> View m -> View m+border b = adjust $ \case+ Box t xs _ -> Just (Box t xs b)+ StatusCard l c _ -> Just (StatusCard l c b)+ Table hs rs _ -> Just (Table hs rs b)+ _ -> Nothing++-- | Space between 'row' items.+gap :: Int -> View m -> View m+gap n = adjust $ \case+ Row _ xs -> Just (Row n xs)+ _ -> Nothing++-- | The character drawn by 'hr', 'vr', 'underline' and 'section'.+glyph :: String -> View m -> View m+glyph g = adjust $ \case+ Rule h _ n -> Just (Rule h g' n)+ Underline _ c x -> Just (Underline g' c x)+ Section t _ n xs -> Just (Section t g' n xs)+ _ -> Nothing+ where g' = T.pack g++-- | Length of an 'hr' or 'vr', or the flanks of a 'section'.+size :: Int -> View m -> View m+size n = adjust $ \case+ Rule h g _ -> Just (Rule h g n)+ Section t g _ xs -> Just (Section t g n xs)+ _ -> Nothing++-- | Colour of an 'underline' rule, leaving the text alone.+accent :: Color -> View m -> View m+accent c = adjust $ \case+ Underline g _ x -> Just (Underline g (Just c) x)+ _ -> Nothing++-- | What 'clip' appends, @...@ by default.+ellipsis :: String -> View m -> View m+ellipsis e = adjust $ \case+ Clip n _ x -> Just (Clip n (T.pack e) x)+ _ -> Nothing++-- | A rule under the content, as wide as it is.+underline :: View m -> View m+underline = Underline "─" Nothing++-- | Centre against the widest sibling in the enclosing 'vstack'.+center :: View m -> View m+center = AutoCenter++centerIn :: Int -> View m -> View m+centerIn = Aligned AlignCenter++pad :: Int -> View m -> View m+pad = Pad++-- | Take all the room the parent offers: the leftover width of a 'row',+-- the leftover height of a 'vstack', or the terminal for an app's root.+-- Boxes and rules stretch to it; other views keep their size inside it.+--+-- @+-- 'row' ['box' "nav" navItems & 'fixedWidth' 20, 'box' "main" content & 'fill'] & 'fill'+-- @+fill :: View m -> View m+fill = Fill++-- | Build a view from the width and height it is given, for things drawn to+-- a size such as plots. Under 'fill' that is the room the parent offers, so+-- it redraws as the terminal is resized; with no room to go by it gets 80x24.+--+-- @+-- 'box' "traffic" ['sized' (\w h -> 'plotLine' (w - 8) (h - 2) series) & 'fill'] & 'fill'+-- @+sized :: (Int -> Int -> View m) -> View m+sized = Sized++-- | Draw the second view centred over the first, for popups and dialogs. Its+-- handlers take clicks where it covers the base.+--+-- @+-- 'overlay' screen ('box' "Quit?" ['row' ['button' "yes" Quit, 'button' "no" Stay]])+-- @+overlay :: View m -> View m -> View m+overlay = Overlay++fixedWidth :: Int -> View m -> View m+fixedWidth w = \case+ Fixed _ h v -> Fixed (Just w) h v+ v -> Fixed (Just w) Nothing v++fixedHeight :: Int -> View m -> View m+fixedHeight h = \case+ Fixed w _ v -> Fixed w (Just h) v+ v -> Fixed Nothing (Just h) v++-- | Prefix every line, e.g. @'text' "boom" & 'margin' "[error]"@.+margin :: String -> View m -> View m+margin prefix = Margin (T.pack prefix)++-- | Cut lines longer than @n@, ending them with the 'ellipsis'.+--+-- @+-- 'text' "Very long text that will be cut off" & 'clip' 15 -- Very long te...+-- @+clip :: Int -> View m -> View m+clip n = Clip n "..."++alignLeft, alignRight, alignCenter, justify :: Int -> View m -> View m+alignLeft = aligned AlignLeft+alignRight = aligned AlignRight+alignCenter = aligned AlignCenter+justify = aligned Justify++aligned :: Alignment -> Int -> View m -> View m+aligned = Aligned++-- | Greedy word wrap at @w@ columns. A longer word gets a line to itself.+wrap :: Int -> View m -> View m+wrap w = Mapped (T.intercalate "\n" . wrapWords . T.words)+ where+ wrapWords :: [Text] -> [Text]+ wrapWords [] = []+ wrapWords ws = let (line, rest) = takeLine ws in line : wrapWords rest++ takeLine [] = ("", [])+ takeLine (x:xs)+ | T.length x > w = (x, xs)+ | otherwise = go (T.length x) [x] xs++ go _ acc [] = (T.unwords (reverse acc), [])+ go len acc (y:ys)+ | len' <= w = go len' (y:acc) ys+ | otherwise = (T.unwords (reverse acc), y:ys)+ where len' = len + 1 + T.length y++--------------------------------------------------------------------------------+-- Events+--+-- Handlers ride along in the tree as 'OnEvent' nodes. Drawing turns each into+-- a rectangle on the block it lands in, so a click is answered by the last+-- (innermost) rectangle under it that handles it.++data Handlers m = Handlers+ { hClick :: Maybe m+ , hScroll :: Maybe (Int -> m) -- +1 per notch down, -1 up+ , hKey :: Maybe (Key -> Maybe m)+ , hFocus :: Maybe Text -- this rectangle is a 'focusable'+ , hScope :: Maybe Text -- the focusable whose focus 'hKey' needs+ }++noHandlers :: Handlers m+noHandlers = Handlers Nothing Nothing Nothing Nothing Nothing++instance Functor Handlers where+ fmap f h = h { hClick = f <$> hClick h+ , hScroll = (f .) <$> hScroll h+ , hKey = (fmap f .) <$> hKey h }++-- | Rebuild a node from its children run through @f@, mapping messages with @onMsg@.+descend :: (a -> b) -> (View a -> View b) -> View a -> View b+descend onMsg f = \case+ Leaf x -> Leaf x+ Stack xs -> Stack (map f xs)+ Row g xs -> Row g (map f xs)+ Margin p v -> Margin p (f v)+ Section t g n xs -> Section t g n (map f xs)+ Rule h g n -> Rule h g n+ Underline g c v -> Underline g c (f v)+ Clip n e v -> Clip n e (f v)+ Pad p v -> Pad p (f v)+ Aligned a w v -> Aligned a w (f v)+ Bullets xs -> Bullets (map f xs)+ Numbered xs -> Numbered (map f xs)+ AutoCenter v -> AutoCenter (f v)+ Colored c v -> Colored c (f v)+ Styled st v -> Styled st (f v)+ Box t xs b -> Box t (map f xs) b+ StatusCard l c b -> StatusCard l c b+ Table hs rs b -> Table hs (map (map f) rs) b+ Mapped g v -> Mapped g (f v)+ OnEvent h v -> OnEvent (fmap onMsg h) (f v)+ Fill v -> Fill (f v)+ Fixed w h v -> Fixed w h (f v)+ Focusable n v -> Focusable n (f v)+ WhenFocused t v -> WhenFocused t (f v)+ Scrolled k vp v -> Scrolled (onMsg . k) vp (f v)+ Following i v -> Following i (f v)+ Sized k -> Sized (\w h -> f (k w h))+ Overlay b t -> Overlay (f b) (f t)++-- | Embed a child component: @fmap ChildMsg (childView model)@.+instance Functor View where+ fmap g = descend g (fmap g)++attach :: Handlers m -> View m -> View m+attach h (AutoCenter v) = AutoCenter (attach h v) -- so the enclosing stack still sees it and centres it+attach h v = OnEvent h v++-- | Send @msg@ when the element is left-clicked. Clicks go to the innermost+-- element that handles them.+onClick :: msg -> View msg -> View msg+onClick msg = attach noHandlers { hClick = Just msg }++-- | Mouse wheel over the element: @+1@ per notch down, @-1@ up.+onScroll :: (Int -> msg) -> View msg -> View msg+onScroll f = attach noHandlers { hScroll = Just f }++-- | Keys for this view. Inside a 'focusable' they only arrive while it has+-- focus; elsewhere they arrive whenever nothing focused took the key first.+onKey :: (Key -> Maybe msg) -> View msg -> View msg+onKey f = attach noHandlers { hKey = Just f }++-- | A view that can hold the keyboard. Tab and Shift-Tab move focus between+-- them in screen order, a click focuses one, and the first is focused to+-- start with.+focusable :: String -> View msg -> View msg+focusable name = Focusable (T.pack name)++-- | How the view looks while it has focus, e.g. @'focusStyle' ('border' BorderDouble)@.+focusStyle :: (forall n. View n -> View n) -> View m -> View m+focusStyle = WhenFocused++-- | Apply each 'focusStyle' whose view has focus.+resolveFocus :: Maybe Text -> View m -> View m+resolveFocus focused = go False+ where+ go on = \case+ Focusable n v -> Focusable n (go (Just n == focused) v)+ WhenFocused t v ->+ let v' = go on v+ in if on || focusName v == focused && isJust focused then t v' else v'+ v -> descend id (go on) v++-- | The 'focusable' a view is, under colour, style, handlers and sizing.+focusName :: View m -> Maybe Text+focusName = \case+ Focusable n _ -> Just n+ Colored _ v -> focusName v+ Styled _ v -> focusName v+ OnEvent _ v -> focusName v+ WhenFocused _ v -> focusName v+ Fill v -> focusName v+ Fixed _ _ v -> focusName v+ AutoCenter v -> focusName v+ _ -> Nothing++-- | A clickable label in reverse video.+button :: String -> msg -> View msg+button label msg = onClick msg (styleReverse (text (" " <> label <> " ")))++-- | Handlers under a cell, innermost first.+hitsAt :: (Int, Int) -> [(Rect, h)] -> [h]+hitsAt (r, c) hits = reverse [ h | (Rect t l hh w, h) <- hits, r >= t, r < t + hh, c >= l, c < l + w ]++dispatchAt :: (Handlers m -> Maybe m) -> (Int, Int) -> [(Rect, Handlers m)] -> Maybe m+dispatchAt pick pos = listToMaybe . mapMaybe pick . hitsAt pos++-- | Focusables in screen order.+focusNames :: [(Rect, Handlers m)] -> [Text]+focusNames hits = [ n | (_, h) <- hits, Just n <- [hFocus h] ]++-- | Where a key goes: the focused view's handlers, innermost first, then+-- handlers outside any focusable.+keyMsg :: Maybe Text -> [(Rect, Handlers m)] -> Key -> Maybe m+keyMsg focused hits key = (focused >>= try . Just) <|> try Nothing+ where+ try scope = listToMaybe (mapMaybe ($ key) (reverse [ k | (_, h) <- hits, hScope h == scope, Just k <- [hKey h] ]))++-- | What a left click at @(row, col)@ of the rendered view sends. For tests.+clickAt :: (Int, Int) -> View m -> Maybe m+clickAt pos = dispatchAt hClick pos . bHits . drawView natural++-- | What one wheel notch at @(row, col)@ sends (@+1@ down, @-1@ up).+scrollAt :: Int -> (Int, Int) -> View m -> Maybe m+scrollAt d pos = dispatchAt (\h -> ($ d) <$> hScroll h) pos . bHits . drawView natural++-- | What pressing a key sends while the named 'focusable' has focus. For tests.+pressKey :: Maybe String -> Key -> View m -> Maybe m+pressKey focused key v = keyMsg f (bHits (drawView natural (resolveFocus f v))) key+ where f = T.pack <$> focused++-- | The 'focusable' names in Tab order. For tests.+focusOrder :: View m -> [String]+focusOrder = map T.unpack . focusNames . bHits . drawView natural++--------------------------------------------------------------------------------+-- Widgets+--+-- Their state lives in your model. Each message carries the widget's next+-- state, worked out where the real size is known, so 'appUpdate' just stores it.++-- | How far a 'viewport' is scrolled.+newtype Viewport = Viewport Int -- first row shown; maxBound sticks to the bottom+ deriving (Show, Eq)++viewportTop, viewportBottom :: Viewport+viewportTop = Viewport 0+viewportBottom = Viewport maxBound++-- | A scrollable area: wheel, arrows, PgUp\/PgDn, Home\/End, with a scrollbar+-- once the content outgrows it. Give it a height with 'fill' or+-- 'fixedHeight'. Scrolled to the end, it stays there as content grows.+--+-- @+-- 'viewport' LogMoved (logView m) (map text (logs m)) & 'fill' & 'focusable' "logs"+-- @+viewport :: (Viewport -> msg) -> Viewport -> [View msg] -> View msg+viewport moved vp = Scrolled moved vp . vstack++-- | A list with a cursor. Keys, clicks and the wheel move it; Enter picks.+data SelectList a = SelectList [a] Int++instance Functor SelectList where+ fmap f (SelectList xs i) = SelectList (map f xs) i++selectListOf :: [a] -> SelectList a+selectListOf xs = SelectList xs 0++selectedItem :: SelectList a -> Maybe a+selectedItem (SelectList xs i) = listToMaybe (drop i xs)++-- | @selectList moved picked draw list@. Keeps the cursor in sight when it+-- has less room than it needs.+selectList :: (SelectList a -> msg) -> (a -> msg) -> (a -> View msg) -> SelectList a -> View msg+selectList moved picked draw sl@(SelectList xs i) =+ Following i (vstack (zipWith item [0 ..] xs))+ & onKey keys+ & onScroll (\d -> moved (at (i + d)))+ where+ at j = SelectList xs (max 0 (min (length xs - 1) j))+ item j x+ | j == i = row ["›", draw x] & fg ColorCyan & onClick (moved (at j))+ | otherwise = row [" ", draw x] & onClick (moved (at j))+ keys = \case+ KeyUp -> Just (moved (at (i - 1)))+ KeyDown -> Just (moved (at (i + 1)))+ KeyPageUp -> Just (moved (at (i - 10)))+ KeyPageDown -> Just (moved (at (i + 10)))+ KeyHome -> Just (moved (at 0))+ KeyEnd -> Just (moved (at (length xs - 1)))+ KeyEnter -> picked <$> selectedItem sl+ _ -> Nothing++--------------------------------------------------------------------------------+-- Spinners++data SpinnerStyle+ = SpinnerDots+ | SpinnerLine+ | SpinnerClock+ | SpinnerBounce+ | SpinnerEarth+ | SpinnerMoon+ | SpinnerGrow+ | SpinnerArrow+ deriving (Show, Eq)++spinnerFrames :: SpinnerStyle -> [Text]+spinnerFrames SpinnerDots = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]+spinnerFrames SpinnerLine = ["|", "/", "-", "\\"]+spinnerFrames SpinnerClock = ["🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖", "🕗", "🕘", "🕙", "🕚", "🕛"]+spinnerFrames SpinnerBounce = ["⠁", "⠂", "⠄", "⠂"]+spinnerFrames SpinnerEarth = ["🌍", "🌎", "🌏"]+spinnerFrames SpinnerMoon = ["🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"]+spinnerFrames SpinnerGrow = ["▏", "▎", "▍", "▌", "▋", "▊", "▉", "█", "▉", "▊", "▋", "▌", "▍", "▎"]+spinnerFrames SpinnerArrow = ["←", "↖", "↑", "↗", "→", "↘", "↓", "↙"]++spinnerFrame :: SpinnerStyle -> Int -> Text+spinnerFrame style i = let fs = spinnerFrames style in fs !! (i `mod` length fs)++data Spinner = Spinner Text Int SpinnerStyle++instance Element Spinner where+ renderElement (Spinner label frame style)+ | T.null label = frameGlyph+ | otherwise = frameGlyph <> " " <> label+ where frameGlyph = spinnerFrame style frame++-- | One frame of a spinner; bump the frame each tick to animate.+--+-- @+-- 'vstack' ['spinner' \"Working\" tick 'SpinnerDots']+-- @+spinner :: String -> Int -> SpinnerStyle -> View m+spinner label frame style = Leaf (Spinner (T.pack label) frame style)++--------------------------------------------------------------------------------+-- Plots++-- | Eighth-block ramp, index 0 (blank) to 8 (full).+blockChars :: Text+blockChars = " ▁▂▃▄▅▆▇█"++-- | Bit for dot (row, col) of a 2x4 braille cell.+brailleDot :: Int -> Int -> Int+brailleDot 0 0 = 0x01+brailleDot 1 0 = 0x02+brailleDot 2 0 = 0x04+brailleDot 3 0 = 0x40+brailleDot 0 1 = 0x08+brailleDot 1 1 = 0x10+brailleDot 2 1 = 0x20+brailleDot 3 1 = 0x80+brailleDot _ _ = 0++defaultPalette :: [Color]+defaultPalette = [ ColorBrightCyan, ColorBrightMagenta, ColorBrightYellow+ , ColorBrightGreen, ColorBrightRed, ColorBrightBlue ]++-- | Explicit colour wins; 'ColorDefault' cycles the palette by index.+pickColor :: Int -> Color -> Color+pickColor idx ColorDefault = defaultPalette !! (idx `mod` length defaultPalette)+pickColor _ c = c++-- | @3@ for whole numbers, @3.5@ otherwise. Rounds to one decimal first, so a+-- tick a hair below zero reads @0@, not @-0.0@.+formatAxisNum :: Double -> Text+formatAxisNum v+ | tenths `mod` 10 == 0 = T.show (tenths `div` 10)+ | otherwise = T.pack (printf "%.1f" (fromInteger tenths / 10 :: Double))+ where tenths = round (v * 10) :: Integer++-- | The smallest of 1, 2, 5, 10, 20, 50 ... (or 0.1, 0.2, 0.5 ...) that is at+-- least @minStep@, and how many decimals it takes to write its multiples.+tickStep :: Double -> (Double, Int)+tickStep minStep = (step, max 0 (negate e))+ where+ e = floor (logBase 10 minStep) :: Int+ step = fromMaybe (10 ^^ (e + 1)) (find (>= minStep * (1 - 1e-9)) [ m * 10 ^^ e | m <- [1, 2, 5] ])++-- | A tick value with at most @d@ decimals, trailing zeros dropped: @0.5@, @1@, @-0.25@.+formatTick :: Int -> Double -> Text+formatTick d t = T.dropWhileEnd (== '.') (if d > 0 then T.dropWhileEnd (== '0') s else s)+ where+ n = round (t * 10 ^^ d) :: Integer+ s = T.pack (printf "%.*f" d (fromInteger n / 10 ^^ d :: Double))++bgColor256 :: Int -> Text+bgColor256 n = "\ESC[48;5;" <> T.show n <> "m"++ansiReset :: Text+ansiReset = "\ESC[0m"++newtype SparklineData = SparklineData [Double]++instance Element SparklineData where+ renderElement (SparklineData []) = ""+ renderElement (SparklineData vals) = T.pack (map (T.index blockChars . level) vals)+ where+ mn = minimum vals+ rng = maximum vals - mn+ level v+ | rng == 0 = 4+ | otherwise = max 1 $ min 8 $ floor ((v - mn) / rng * 8)++plotSparkline :: [Double] -> View m+plotSparkline = Leaf . SparklineData++-- | Points, label, colour.+data Series = Series [(Double, Double)] String Color++data PlotData = PlotData [Series] Int Int++instance Element PlotData where+ renderElement (PlotData ss w h)+ | all (\(Series ps _ _) -> null ps) ss = "No data"+ | otherwise =+ let (xs, ys) = unzip (concatMap (\(Series ps _ _) -> ps) ss)+ xMin = minimum xs; xMax = maximum xs+ yMin = minimum ys; yMax = maximum ys+ xRng = if xMax == xMin then 1.0 else xMax - xMin+ yRng = if yMax == yMin then 1.0 else yMax - yMin+ pxW = w * 2; pxH = h * 4++ toPixel (x, y) =+ ( clampI 0 (pxW - 1) $ round ((x - xMin) / xRng * fromIntegral (pxW - 1))+ , clampI 0 (pxH - 1) $ round ((yMax - y) / yRng * fromIntegral (pxH - 1))+ )+ clampI lo hi = max lo . min hi++ -- Each cell holds its braille bits and the first series to touch it,+ -- built in one pass so a dense series doesn't cost points × cells.+ dots = IntMap.fromListWith (\(b, si) (b', si') -> (b .|. b', min si si'))+ [ ((py `div` 4) * w + px `div` 2, (brailleDot (py `mod` 4) (px `mod` 2), sIdx))+ | (sIdx, Series ps _ _) <- zip [0 :: Int ..] ss+ , (px, py) <- map toPixel ps ]++ grid = [ [ IntMap.findWithDefault (0, -1) (r * w + c) dots | c <- [0 .. w - 1] ]+ | r <- [0 .. h - 1] ]++ -- Label the rows nearest round values (1, 2 or 5 times a power of+ -- ten), at least two rows apart so labels never touch.+ rowStep = yRng / fromIntegral (max 1 (h - 1))+ (step, decimals) = tickStep (2 * rowStep)+ -- a tick within half a row of either edge still labels that edge row+ slack = rowStep / 2+ ticks = [ fromInteger k * step+ | k <- [ceiling ((yMax - yRng - slack) / step) .. floor ((yMax + slack) / step)] ]+ rowOf t = floor ((yMax - t) / rowStep + 0.5) :: Int+ labeled = IntMap.fromList [ (rowOf t, formatTick decimals t) | t <- ticks ]+ yLabels = [ IntMap.findWithDefault "" r labeled | r <- [0 .. h - 1] ]+ yLabelW = maximum (0 : map T.length yLabels)++ cell (bits, si)+ | bits == 0 = " "+ | si < 0 = dot+ | otherwise = wrapAnsi (pickColor si (sColor (ss !! si))) dot+ where dot = T.singleton (chr (0x2800 + bits))++ gridLines = zipWith (\lbl r -> padLeft yLabelW lbl <> " │" <> foldMap cell r) yLabels grid++ gutter = T.replicate (yLabelW + 2) " "+ xMinL = formatAxisNum xMin+ xMaxL = formatAxisNum xMax+ xAxis = gutter <> T.replicate w "─"+ xLabels = gutter <> xMinL+ <> T.replicate (max 1 (w - T.length xMinL - T.length xMaxL)) " "+ <> xMaxL++ legend+ | length ss <= 1 = []+ | otherwise = ["", T.intercalate " "+ [ wrapAnsi (pickColor i cl) "●" <> " " <> T.pack nm | (i, Series _ nm cl) <- zip [0..] ss ]]++ in T.intercalate "\n" (gridLines <> [xAxis, xLabels] <> legend)+ where sColor (Series _ _ c) = c++-- | Braille line plot, @w@x@h@ cells.+plotLine :: Int -> Int -> [Series] -> View m+plotLine w h ss = Leaf (PlotData ss w h)++-- | Value, label, colour.+data Slice = Slice Double String Color++data PieData = PieData [Slice] Int Int++instance Element PieData where+ renderElement (PieData [] _ _) = "No data"+ renderElement (PieData slices w h) =+ let total = sum [ v | Slice v _ _ <- slices ]+ cumAngs = scanl (+) 0 [ v / total * 2 * pi | Slice v _ _ <- slices ]++ cxF = fromIntegral w :: Double+ cyF = fromIntegral (h * 4) / 2.0 :: Double+ radius = min cxF (cyF * 0.9)++ sliceAt ang = go 0 (drop 1 cumAngs)+ where go i [] = max 0 (i - 1)+ go i (a:as) = if ang < a then i else go (i + 1) as++ -- Cells are twice as tall as wide, so y distances are doubled.+ renderCell gcx gcy =+ let inside = [ (dy, dx, if ang < 0 then ang + 2 * pi else ang)+ | dy <- [0..3], dx <- [0..1]+ , let relX = fromIntegral (gcx * 2 + dx) - cxF+ relY = (fromIntegral (gcy * 4 + dy) - cyF) * 2.0+ ang = atan2 relY relX+ , sqrt (relX * relX + relY * relY) <= radius ]+ bits = foldl (\acc (dy, dx, _) -> acc .|. brailleDot dy dx) 0 inside+ si = case inside of+ [] -> -1+ ((_, _, a):_) -> sliceAt a+ color = if si >= 0 && si < length slices+ then pickColor si (slColor (slices !! si))+ else ColorDefault+ in if bits == 0 then " " else wrapAnsi color (T.singleton (chr (0x2800 + bits)))++ gridLines = [ foldMap (`renderCell` gcy) [0..w-1] | gcy <- [0..h-1] ]++ legendLines =+ [ " " <> wrapAnsi (pickColor i cl) "●" <> " " <> T.pack nm+ <> " (" <> T.pack (printf "%.0f" (v / total * 100)) <> "%)"+ | (i, Slice v nm cl) <- zip [0..] slices ]++ in T.intercalate "\n" (gridLines <> [""] <> legendLines)+ where slColor (Slice _ _ c) = c++-- | Braille pie chart, @w@x@h@ cells.+plotPie :: Int -> Int -> [Slice] -> View m+plotPie w h sl = Leaf (PieData sl w h)++-- | Value, label, colour.+data BarItem = BarItem Double String Color++data BarChartData = BarChartData [BarItem] Int Int++-- | Y-axis labels top to bottom, plus their width.+yAxisLabels :: Double -> Int -> ([Text], Int)+yAxisLabels top h =+ let ls = [ formatAxisNum (top * fromIntegral (h - 1 - i) / fromIntegral (max 1 (h - 1))) | i <- [0..h-1] ]+ in (ls, maximum (0 : map T.length ls))++-- | One bar's slice of a row, @filled@ eighths high.+barCell :: Int -> Color -> Int -> Text+barCell barW color filled+ | filled > 0 = wrapAnsi color glyphs+ | otherwise = glyphs+ where glyphs = replicateChar barW (T.index blockChars filled)++instance Element BarChartData where+ renderElement (BarChartData [] _ _) = "No data"+ renderElement (BarChartData items w h) =+ let maxVal = maximum [ v | BarItem v _ _ <- items ]+ nBars = length items+ barW = max 1 $ (w - nBars + 1) `div` nBars+ barHts = [ round (v / maxVal * fromIntegral (h * 8)) :: Int | BarItem v _ _ <- items ]+ (yLabels, yLabelW) = yAxisLabels maxVal h++ gridLines =+ [ padLeft yLabelW yLab <> " │" <> T.intercalate " "+ [ barCell barW (pickColor i cl) (min 8 $ max 0 (bh - r * 8))+ | (i, bh, BarItem _ _ cl) <- zip3 [0..] barHts items ]+ | (r, yLab) <- zip [h - 1, h - 2 ..] yLabels ]++ gutter = T.replicate (yLabelW + 2) " "+ xAxis = gutter <> T.replicate (nBars * barW + nBars - 1) "─"+ barLabels = gutter <> T.intercalate " "+ [ T.take barW (T.pack nm <> T.replicate barW " ") | BarItem _ nm _ <- items ]++ in T.intercalate "\n" (gridLines <> [xAxis, barLabels])++-- | Vertical bar chart, @w@x@h@ cells.+plotBar :: Int -> Int -> [BarItem] -> View m+plotBar w h items = Leaf (BarChartData items w h)++-- | Segments bottom to top, and the group label.+data StackedBarGroup = StackedBarGroup [BarItem] String++data StackedBarChartData = StackedBarChartData [StackedBarGroup] Int Int++instance Element StackedBarChartData where+ renderElement (StackedBarChartData [] _ _) = "No data"+ renderElement (StackedBarChartData groups w h) =+ let maxTotal = maximum [ sum [ v | BarItem v _ _ <- segs ] | StackedBarGroup segs _ <- groups ]+ nGroups = length groups+ barW = max 1 $ (w - nGroups + 1) `div` nGroups+ (yLabels, yLabelW) = yAxisLabels maxTotal h++ -- (segment, (bottom, top)) in eighths+ groupBounds =+ [ let cum = scanl (+) 0 [ round (v / maxTotal * fromIntegral (h * 8)) :: Int | BarItem v _ _ <- segs ]+ in zip segs (zip cum (drop 1 cum))+ | StackedBarGroup segs _ <- groups ]++ allLabels = nub [ nm | StackedBarGroup segs _ <- groups, BarItem _ nm _ <- segs ]++ -- A label keeps one colour across bars and legend: its first explicit+ -- colour, else the palette slot for its index.+ labelColors = [ (nm, pickColor i (firstExplicit nm)) | (i, nm) <- zip [0..] allLabels ]+ firstExplicit nm = case [ cl | StackedBarGroup segs _ <- groups+ , BarItem _ nm' cl <- segs+ , nm' == nm, cl /= ColorDefault ] of+ (cl:_) -> cl+ [] -> ColorDefault+ labelColor nm = fromMaybe ColorDefault (lookup nm labelColors)++ -- Only the highest segment reaching into a row is drawn in it.+ cellAt r bounds =+ case [ (seg, top) | (seg, (bot, top)) <- bounds, top > r * 8, bot < r * 8 + 8 ] of+ [] -> T.replicate barW " "+ overlapping ->+ let (BarItem _ nm _, top) = foldl1 (\a b -> if snd b > snd a then b else a) overlapping+ in barCell barW (labelColor nm) (min 8 $ max 0 (top - r * 8))++ gridLines =+ [ padLeft yLabelW yLab <> " │" <> T.intercalate " " (map (cellAt r) groupBounds)+ | (r, yLab) <- zip [h - 1, h - 2 ..] yLabels ]++ gutter = T.replicate (yLabelW + 2) " "+ xAxis = gutter <> T.replicate (nGroups * barW + nGroups - 1) "─"+ grpLabels = gutter <> T.intercalate " "+ [ T.take barW (T.pack nm <> T.replicate barW " ") | StackedBarGroup _ nm <- groups ]++ legend+ | length allLabels <= 1 = []+ | otherwise = ["", T.intercalate " "+ [ wrapAnsi (labelColor nm) "█" <> " " <> T.pack nm | nm <- allLabels ]]++ in T.intercalate "\n" (gridLines <> [xAxis, grpLabels] <> legend)++plotStackedBar :: Int -> Int -> [StackedBarGroup] -> View m+plotStackedBar w h groups = Leaf (StackedBarChartData groups w h)++-- | Grid of values, row labels, column labels.+data HeatmapData = HeatmapData [[Double]] [String] [String]++data HeatmapElement = HeatmapElement HeatmapData Int++instance Element HeatmapElement where+ renderElement (HeatmapElement (HeatmapData [] _ _) _) = "No data"+ renderElement (HeatmapElement (HeatmapData grid rowLbls colLbls) cellW) =+ let allVals = concat grid+ mn = minimum allVals+ mx = maximum allVals+ rng = if mx == mn then 1.0 else mx - mn++ -- blue -> cyan -> green -> yellow -> red through the 256-colour cube+ toColor256 :: Double -> Int+ toColor256 t+ | t <= 0.0 = 21+ | t >= 1.0 = 196+ | t < 0.25 = let s = t / 0.25 in round (21.0 + s * 30.0)+ | t < 0.5 = let s = (t-0.25)/0.25 in round (51.0 + s * (-5.0))+ | t < 0.75 = let s = (t-0.5)/0.25 in round (46.0 + s * 180.0)+ | otherwise = let s = (t-0.75)/0.25 in round (226.0 + s * (-30.0))++ rowLblW = maximum (0 : map length rowLbls)+ gutter = T.replicate (rowLblW + 1) " "+ fit n = padRight n . T.take n++ header = gutter <> T.intercalate " " (map (fit cellW . T.pack) colLbls)++ dataRows = zipWith (\lbl vals ->+ fit rowLblW (T.pack lbl) <> " " <> T.intercalate " "+ [ bgColor256 (toColor256 ((v - mn) / rng)) <> fit cellW (formatAxisNum v) <> ansiReset | v <- vals ]+ ) rowLbls grid++ legendBar = foldMap (\i -> bgColor256 (toColor256 (fromIntegral i / 10.0)) <> " " <> ansiReset) [0..10 :: Int]+ legendLine = gutter <> formatAxisNum mn <> " " <> legendBar <> " " <> formatAxisNum mx++ in T.intercalate "\n" ([header] <> dataRows <> ["", legendLine])++-- | Heatmap with 6-column cells.+plotHeatmap :: HeatmapData -> View m+plotHeatmap = plotHeatmap' 6++plotHeatmap' :: Int -> HeatmapData -> View m+plotHeatmap' cellW dat = Leaf (HeatmapElement dat cellW)++--------------------------------------------------------------------------------+-- Terminal+--+-- Everything that touches the tty directly: setup and teardown, escape codes+-- out, keys and mouse reports in. The runtime and the Ask prompts sit on top.++data TermMode = FullScreen | Inline++-- | Unbuffered, no echo, cursor hidden (and the alt screen for 'FullScreen')+-- while @body@ runs. Put back on the way out, exceptions included.+withTerm :: TermMode -> IO a -> IO a+withTerm mode body = do+ oldBuffering <- hGetBuffering stdin+ oldEcho <- hGetEcho stdin+ hSetBuffering stdin NoBuffering+ hSetBuffering stdout NoBuffering+ hSetEcho stdin False+ when full $ enterAltScreen >> clearScreen+ hideCursor+ body `finally` do+ showCursor+ when full exitAltScreen+ hFlush stdout+ hSetBuffering stdin oldBuffering+ hSetEcho stdin oldEcho+ where+ full = case mode of+ FullScreen -> True+ Inline -> False++-- | Run @action@ on every SIGWINCH while @body@ runs. Nothing on Windows.+onResize :: IO () -> IO a -> IO a+#if !defined(mingw32_HOST_OS)+onResize action body = do+ old <- installHandler sigWINCH (Catch action) Nothing+ body `finally` installHandler sigWINCH old Nothing+#else+onResize _ body = body+#endif++-- | Press, release and wheel, SGR-encoded.+mouseEnable, mouseDisable :: Text+mouseEnable = "\ESC[?1000h\ESC[?1006h"+mouseDisable = "\ESC[?1006l\ESC[?1000l"++-- | One write(2) per call. Data.Text.IO on an unbuffered handle issues a+-- syscall per character, so big frames reach the terminal in pieces and tear.+putText :: Text -> IO ()+putText = Utf8.putStr++clearScreen :: IO ()+clearScreen = putText "\ESC[2J\ESC[H"++hideCursor :: IO ()+hideCursor = putText "\ESC[?25l"++showCursor :: IO ()+showCursor = putText "\ESC[?25h"++enterAltScreen :: IO ()+enterAltScreen = putText "\ESC[?1049h"++exitAltScreen :: IO ()+exitAltScreen = putText "\ESC[?1049l"++-- | Save cursor, jump to the far corner, ask where we ended up, restore.+cursorProbe :: Text+cursorProbe = "\ESC7\ESC[999;999H\ESC[6n\ESC8"++-- | @(rows, cols)@, falling back to @(24, 80)@. Needs raw mode and nobody+-- else reading stdin.+getTerminalSize :: IO (Int, Int)+getTerminalSize = do+ putText cursorProbe+ hFlush stdout+ fromMaybe (24, 80) <$> timeout 100000 (readCPR "")+ where+ readCPR acc = do+ c <- getChar+ case c of+ '\ESC' -> getChar >> readCPR acc+ '[' -> readCPR acc+ 'R' -> pure (parseRC (reverse acc))+ _ -> readCPR (c : acc)+ parseRC resp = case break (== ';') resp of+ (rows, ';':cols) -> (readOr 24 rows, readOr 80 cols)+ _ -> (24, 80)+ readOr d s = case reads s of+ [(n, "")] -> n+ _ -> d++-- | SGR mouse report: button code, 0-based (row, col), press or release.+data MouseEvent = MouseEvent { meButton :: Int, mePos :: (Int, Int), mePress :: Bool }+ deriving (Show, Eq)++data Input = InputKey Key | InputMouse MouseEvent | InputSize Int Int -- rows, cols+ deriving (Show, Eq)++-- | Keys only; mouse reports are dropped.+readKey :: IO Key+readKey = readInput >>= \case+ InputKey k -> pure k+ _ -> readKey++-- | Read a char at a time until 'parseInput' has a whole input, so nothing+-- is ever read past it. A lone ESC is told apart from the start of a sequence+-- by waiting 50ms for the next byte.+readInput :: IO Input+readInput = getChar >>= go . pure+ where+ go buf = case parseInput buf of+ Just (i, _) -> pure i+ Nothing+ | buf == "\ESC" -> timeout 50000 getChar >>= maybe (pure (InputKey KeyEscape)) (more buf)+ | otherwise -> getChar >>= more buf+ more buf c = go (buf <> [c])++-- | The first input in what the terminal sent, and what's left after it.+-- 'Nothing' if it's empty or stops partway through a sequence. A lone ESC is+-- 'Nothing' too: it's only an Esc keypress once nothing follows it in time,+-- and that's up to the caller.+--+-- Sequences we don't know come back as 'KeySpecial' rather than being+-- mistaken for Esc.+parseInput :: String -> Maybe (Input, String)+parseInput = \case+ [] -> Nothing+ '\ESC' : cs -> escape cs+ c : cs -> Just (InputKey (plainKey c), cs)+ where+ plainKey c = case ord c of+ 10 -> KeyEnter+ 13 -> KeyEnter+ 9 -> KeyTab+ 127 -> KeyBackspace+ 8 -> KeyBackspace+ n | n >= 32 && n <= 126 -> KeyChar c+ | n < 32 -> KeyCtrl (chr (n + 64))+ | otherwise -> KeyChar c++ escape = \case+ [] -> Nothing+ '[' : cs -> csi "" cs+ 'O' : c : cs -> Just (InputKey (ss3 c), cs) -- application cursor mode+ "O" -> Nothing+ c : cs -> Just (InputKey (KeySpecial [c]), cs)++ ss3 = \case+ 'H' -> KeyHome+ 'F' -> KeyEnd+ c -> KeySpecial ['O', c]++ -- parameter and intermediate bytes, then one final byte in @..~+ csi acc = \case+ [] -> Nothing+ c : cs+ | c >= '@' && c <= '~' -> Just (decode (reverse acc) c, cs)+ | otherwise -> csi (c : acc) cs++ decode ('<' : ps) f | f == 'M' || f == 'm' = sgrMouse ps (f == 'M')+ -- A cursor position report answering 'cursorProbe'. Modified F3 has the+ -- same shape (ESC [ 1 ; mods R), but a probe at row 999 never reports row 1.+ decode ps 'R' | Just [r, c] <- mapM readInt (splitOnChar ';' (T.pack ps)), r > 1 =+ InputSize r c+ decode ps f = InputKey $ case (ps, f) of+ ("", 'A') -> KeyUp+ ("", 'B') -> KeyDown+ ("", 'C') -> KeyRight+ ("", 'D') -> KeyLeft+ ("", 'H') -> KeyHome+ ("", 'F') -> KeyEnd+ ("", 'Z') -> KeyBackTab+ ("1", '~') -> KeyHome+ ("3", '~') -> KeyDelete+ ("4", '~') -> KeyEnd+ ("5", '~') -> KeyPageUp+ ("6", '~') -> KeyPageDown+ _ -> KeySpecial ('[' : ps <> [f])++ -- ESC [ < button ; col ; row (M | m), coordinates 1-based+ sgrMouse ps press = case mapM readInt (splitOnChar ';' (T.pack ps)) of+ Just [b, x, y] -> InputMouse (MouseEvent b (y - 1, x - 1) press)+ _ -> InputKey (KeySpecial ("[<" <> ps))+ readInt t = case reads (T.unpack t) of+ [(n, "")] -> Just n+ _ -> Nothing++--------------------------------------------------------------------------------+-- TUI runtime++data Key+ = KeyChar Char+ | KeyCtrl Char -- ^ e.g. @KeyCtrl 'C'@+ | KeyEnter+ | KeyBackspace+ | KeyTab+ | KeyBackTab -- ^ Shift-Tab+ | KeyEscape+ | KeyDelete+ | KeyUp+ | KeyDown+ | KeyLeft+ | KeyRight+ | KeyPageUp+ | KeyPageDown+ | KeyHome+ | KeyEnd+ | KeySpecial String -- ^ unrecognised escape sequence+ deriving (Show, Eq)++-- | Effects for the runtime to run after an update. Combine with @<>@; every+-- message they produce is delivered.+data Cmd msg = Cmd [IO (Maybe msg)] (Maybe Text) Bool -- effects, focus, then quit?++instance Semigroup (Cmd msg) where+ Cmd a f q <> Cmd b g r = Cmd (a <> b) (g <|> f) (q || r)++instance Monoid (Cmd msg) where+ mempty = Cmd [] Nothing False++instance Functor Cmd where+ fmap f (Cmd ios fo q) = Cmd (map (fmap (fmap f)) ios) fo q++cmdNone :: Cmd msg+cmdNone = mempty++-- | Fire and forget.+cmdFire :: IO () -> Cmd msg+cmdFire io = Cmd [Nothing <$ io] Nothing False++-- | Run IO and feed the result back as a message.+cmdTask :: IO msg -> Cmd msg+cmdTask io = Cmd [Just <$> io] Nothing False++cmdAfterMs :: Int -> msg -> Cmd msg+cmdAfterMs ms msg = cmdTask (threadDelay (ms * 1000) >> pure msg)++-- | Stop the app once the other effects in the same command have run.+cmdQuit :: Cmd msg+cmdQuit = Cmd [] Nothing True++-- | Move keyboard focus to the named 'focusable'.+cmdFocus :: String -> Cmd msg+cmdFocus name = Cmd [] (Just (T.pack name)) False++-- | Run a command's effects in order, collecting the messages.+executeCmd :: Cmd msg -> IO [msg]+executeCmd (Cmd ios _ _) = catMaybes <$> sequence ios++-- | What the app listens to. Combine with @<>@. Key handlers see every key a+-- focused view didn't take.+data Sub msg = Sub [Key -> Maybe msg] [(Int, msg)] [String -> msg] [Double -> msg]++instance Semigroup (Sub msg) where+ Sub a b c d <> Sub e f g h = Sub (a <> e) (b <> f) (c <> g) (d <> h)++instance Monoid (Sub msg) where+ mempty = Sub [] [] [] []++instance Functor Sub where+ fmap f (Sub ks ts fs as) = Sub (map (fmap f .) ks) [ (n, f m) | (n, m) <- ts ] (map (f .) fs) (map (f .) as)++subNone :: Sub msg+subNone = mempty++subKeyPress :: (Key -> Maybe msg) -> Sub msg+subKeyPress k = Sub [k] [] [] []++-- | A message every @n@ milliseconds.+subEveryMs :: Int -> msg -> Sub msg+subEveryMs n m = Sub [] [(n, m)] [] []++-- | The name of the 'focusable' that just got focus.+subFocus :: (String -> msg) -> Sub msg+subFocus f = Sub [] [] [f] []++-- | A message every frame while subscribed, carrying the monotonic time in+-- seconds, for animation. The first one comes as soon as the subscription+-- appears rather than an interval later, so motion starts on the frame after+-- the change that asked for it. Drop it once things are still and an idle app+-- stops waking up.+--+-- @+-- subscriptions m = if moving m then 'subAnimationFrame' Frame else 'subNone'+-- @+subAnimationFrame :: (Double -> msg) -> Sub msg+subAnimationFrame f = Sub [] [] [] [f]++-- | An Elm-style app.+--+-- @+-- data Msg = Inc | Dec+--+-- counter :: 'LayoutzApp' Int Msg+-- counter = 'sandbox' 0 step $ \\n ->+-- 'row' ['button' "-" Dec, 'display' n, 'button' "+" Inc]+-- where step Inc = (+ 1); step Dec = subtract 1+-- @+data LayoutzApp model msg = LayoutzApp+ { appInit :: (model, Cmd msg)+ , appUpdate :: msg -> model -> (model, Cmd msg)+ , appSubscriptions :: model -> Sub msg+ , appView :: model -> View msg+ }++-- | An app with no effects and no subscriptions.+sandbox :: model -> (msg -> model -> model) -> (model -> View msg) -> LayoutzApp model msg+sandbox m step view = LayoutzApp+ { appInit = (m, cmdNone)+ , appUpdate = \msg s -> (step msg s, cmdNone)+ , appSubscriptions = const subNone+ , appView = view+ }++data AppAlignment = AppAlignLeft | AppAlignCenter | AppAlignRight+ deriving (Show, Eq)++-- |+-- @+-- 'run' 'defaultOptions' { 'optAlignment' = 'AppAlignCenter' } myApp+-- @+data Options = Options+ { optAlignment :: AppAlignment+ , optInline :: Bool -- ^ draw in place under the current output, no alt screen+ , optQuitKeys :: [Key] -- ^ keys that end the app; Ctrl-C always does+ , optMaxFps :: Int -- ^ frame cap; changes in between share one frame+ } deriving (Show, Eq)++-- | Full screen, left-aligned, Esc or Ctrl-D quits.+defaultOptions :: Options+defaultOptions = Options+ { optAlignment = AppAlignLeft+ , optInline = False+ , optQuitKeys = [KeyEscape, KeyCtrl 'D']+ , optMaxFps = 60+ }++-- | Full screen with 'defaultOptions'.+runApp :: LayoutzApp model msg -> IO ()+runApp = void . run defaultOptions++-- | Draw in place under the current output until 'cmdQuit'. Handy for+-- progress bars in scripts.+runInline :: LayoutzApp model msg -> IO ()+runInline = void . run defaultOptions { optInline = True }++-- | Every source (keys, mouse, ticks, command results) feeds one channel, so+-- a single thread applies 'appUpdate'.+data AppEvent msg+ = AppMsg msg+ | AppFrame Double (MVar ()) -- an animation frame's time; acked once applied+ | AppExit++isQuitKey :: Key -> Bool+isQuitKey k = k == KeyEscape || k == KeyCtrl 'C' || k == KeyCtrl 'D'++-- | Run an app, returning its final model.+--+-- Mouse reporting is on exactly while the view has an 'onClick' or+-- 'onScroll' in it, so apps without them keep native text selection.+run :: Options -> LayoutzApp model msg -> IO model+run opts app+ | optInline opts = withTerm Inline (runIn opts app)+ -- on resize, ask for the size again; the input thread reads the answer+ | otherwise = withTerm FullScreen (onResize (putText cursorProbe >> hFlush stdout) (runIn opts app))++-- | 'run' once the terminal is set up.+runIn :: Options -> LayoutzApp model msg -> IO model+runIn opts LayoutzApp{..} = do+ let fullScreen = not (optInline opts)+ quits k = k == KeyCtrl 'C' || k `elem` optQuitKeys opts++ -- before any thread starts reading stdin+ termSize <- newIORef =<< getTerminalSize++ let (initialState, initialCmd) = appInit++ stateRef <- newIORef initialState+ eventChan <- newChan+ cmdChan <- newChan++ focusRef <- newIORef Nothing++ -- Full while something the view depends on has changed since the last+ -- frame; the render thread sleeps on it instead of polling.+ dirty <- newMVar ()+ -- Full when the model changed, so the subscriptions may have: wakes the+ -- tick thread when it has nothing to wait for.+ modelChanged <- newEmptyMVar++ let send = writeChan eventChan . AppMsg+ markDirty = void (tryPutMVar dirty ())+ frameNs = 1000000000 `div` fromIntegral (max 1 (optMaxFps opts)) :: Word64++ setFocus new = do+ old <- atomicModifyIORef' focusRef (\o -> (new, o))+ when (new /= old) $ do+ markDirty+ Sub _ _ listeners _ <- appSubscriptions <$> readIORef stateRef+ forM_ new $ \n -> mapM_ (send . ($ T.unpack n)) listeners++ schedule cmd@(Cmd ios focusOn q) = do+ mapM_ (setFocus . Just) focusOn+ if null ios then when q (writeChan eventChan AppExit) else writeChan cmdChan cmd++ -- Only this thread writes the model. An update that hands back the+ -- model it was given (@(m, cmd)@) changed nothing on screen, so it+ -- doesn't cost a frame, which would hold up the next real one.+ applyMsg msg = do+ old <- readIORef stateRef+ case appUpdate msg old of+ (new, cmd) -> do+ unless (same old new) $ do+ writeIORef stateRef $! new+ markDirty+ void (tryPutMVar modelChanged ())+ schedule cmd++ cmdThread <- forkIO $ forever $ do+ cmd@(Cmd _ _ q) <- readChan cmdChan+ executeCmd cmd >>= mapM_ (writeChan eventChan . AppMsg)+ when q $ writeChan eventChan AppExit++ schedule initialCmd++ lastFrame <- newIORef ([], [])+ onScreen <- newIORef [] -- rows as last written, alignment included+ sentKittyIds <- newIORef IntSet.empty+ hitMap <- newIORef [] -- click regions of what's on screen+ mouseOn <- newIORef False+ resized <- newIORef False++ let drawFrame = do+ (termH, termW) <- readIORef termSize+ redraw <- atomicModifyIORef' resized (\r -> (False, r))+ -- Full-screen apps get the terminal as room for 'fill'. Inline ones don't+ -- know which row they start on, so they get no room and no mouse.+ let room | fullScreen = Room (Just termW) (Just termH) False+ | otherwise = natural+ focused <- readIORef focusRef+ block <- drawView room . resolveFocus focused . appView <$> readIORef stateRef+ let frame = (bRaw block, bRows block)+ prev <- readIORef lastFrame+ shown <- readIORef onScreen+ wasOn <- readIORef mouseOn+ -- upload each kitty image once, not every frame+ sent <- readIORef sentKittyIds+ let (uploads, sent') = dedupeTransmits sent (T.concat (bRaw block))+ indent = case optAlignment opts of+ AppAlignLeft -> 0+ AppAlignCenter -> max 0 ((termW - blockWidth block) `div` 2)+ AppAlignRight -> max 0 (termW - blockWidth block)+ rows = map (replicate indent blank <>) (snd frame)+ hits = moveHits 0 indent (bHits block)+ wantMouse = fullScreen && not (null hits)+ mouseMode+ | wantMouse == wasOn = ""+ | wantMouse = mouseEnable+ | otherwise = mouseDisable+ body+ | fullScreen && redraw = repaintRows termW termH rows+ | fullScreen = diffRows shown rows -- only the cells that changed+ | otherwise =+ (if null shown then "" else "\ESC[" <> T.show (length shown) <> "A\r")+ <> foldMap ((<> "\ESC[K\n") . rowText) rows+ <> T.replicate (max 0 (length shown - length rows)) "\ESC[K\n"+ -- Full screen, the diff already says whether anything changed; inline+ -- rewrites every row, so compare the frames instead.+ changed+ | redraw = True+ | fullScreen = not (T.null body && T.null mouseMode) || fst frame /= fst prev+ | otherwise = frame /= prev++ when changed $ do+ putText $ "\ESC[?2026h" <> mouseMode <> uploads <> body <> "\ESC[?2026l"+ hFlush stdout+ writeIORef sentKittyIds sent'+ writeIORef mouseOn wantMouse+ writeIORef hitMap hits+ -- keep focus on something that's on screen+ case focusNames hits of+ first : _ | maybe True (`notElem` focusNames hits) focused -> setFocus (Just first)+ _ -> pure ()+ writeIORef onScreen rows+ writeIORef lastFrame frame+++ animating = (\(Sub _ _ _ frames) -> not (null frames)) . appSubscriptions <$> readIORef stateRef++ -- Draws whenever something changed, at most once a frame. While the app+ -- wants animation frames this loop also keeps the beat: each frame the app+ -- is handed that frame's own time, evenly spaced, and the frame is drawn+ -- once that update is in. One clock, so motion doesn't judder from two+ -- loops drifting in and out of step.+ renderThread <- forkIO $+ let loop due = animating >>= \case+ False -> do+ takeMVar dirty+ frameStart <- getMonotonicTimeNSec+ drawFrame+ -- changes arriving before the next frame is due share it+ spent <- (`div` 1000) . subtract frameStart <$> getMonotonicTimeNSec+ threadDelay (max 0 (1000000 `div` max 1 (optMaxFps opts) - fromIntegral spent))+ loop Nothing+ True -> do+ now <- getMonotonicTimeNSec+ -- on the beat, unless this is the first frame or one ran long+ let t = case due of+ Just d | d + frameNs > now -> d+ _ -> now+ when (t > now) $ threadDelay (fromIntegral ((t - now) `div` 1000))+ applied <- newEmptyMVar+ writeChan eventChan (AppFrame (fromIntegral t / 1e9) applied)+ takeMVar applied+ _ <- tryTakeMVar dirty+ drawFrame+ loop (Just (t + frameNs))+ in loop Nothing++ -- Deadlines are tracked per interval so re-subscribing each frame doesn't+ -- reset the clock. Sleeps until the next deadline, waking at least every+ -- 20ms to pick up changed subscriptions. With no ticks at all it sleeps+ -- until the model changes, so an idle app doesn't wake up.+ tickThread <- forkIO $+ let loop deadlines = do+ _ <- tryTakeMVar modelChanged+ Sub _ ticks _ _ <- appSubscriptions <$> readIORef stateRef+ if null ticks then takeMVar modelChanged >> loop [] else do+ now <- getMonotonicTimeNSec+ let ns ms = fromIntegral ms * 1000 * 1000+ armed = [ (i, fromMaybe (now + ns i) (lookup i deadlines)) | i <- nub (map fst ticks) ]+ due = [ i | (i, d) <- armed, d <= now ]+ deadlines' =+ [ (i, if i `elem` due then let nd = d + ns i in if nd <= now then now + ns i else nd else d)+ | (i, d) <- armed ]+ mapM_ (writeChan eventChan . AppMsg) [ msg | (i, msg) <- ticks, i `elem` due ]+ let nextNs = minimum (now + 20000000 : map snd deadlines')+ threadDelay (max 1000 (min 20000 (fromIntegral ((nextNs - now) `div` 1000))))+ loop deadlines'+ in loop []++ -- EOF on stdin quits, same as Ctrl-D.+ inputThread <- forkIO $+ let loop = readInput >>= \case+ InputSize r c -> do+ writeIORef termSize (r, c)+ writeIORef resized True+ markDirty+ loop+ InputMouse ev -> do+ hits <- readIORef hitMap+ when (mePress ev && meButton ev .&. 0x43 == 0) $ -- a left click focuses+ mapM_ (setFocus . Just) (listToMaybe (mapMaybe hFocus (hitsAt (mePos ev) hits)))+ mapM_ send (mouseMsg ev hits)+ loop+ InputKey key+ | quits key -> writeChan eventChan AppExit+ | otherwise -> do+ hits <- readIORef hitMap+ focused <- readIORef focusRef+ let order = focusNames hits+ step = if key == KeyBackTab then -1 else 1+ case order of+ first : _ | key `elem` [KeyTab, KeyBackTab] ->+ setFocus $ Just $ case focused >>= (`elemIndex` order) of+ Just i -> order !! ((i + step) `mod` length order)+ Nothing -> first+ _ -> case keyMsg focused hits key of+ Just m -> send m+ Nothing -> do+ Sub keys _ _ _ <- appSubscriptions <$> readIORef stateRef+ mapM_ send (mapMaybe ($ key) keys)+ loop+ in loop `catch` \(_ :: IOException) -> writeChan eventChan AppExit++ let cleanup = do+ mapM_ killThread [renderThread, cmdThread, tickThread, inputThread]+ readIORef mouseOn >>= \on -> when on (putText mouseDisable)++ dispatch = readChan eventChan >>= \case+ AppExit -> pure ()+ AppMsg msg -> applyMsg msg >> dispatch+ AppFrame t applied -> do+ Sub _ _ _ frames <- appSubscriptions <$> readIORef stateRef+ mapM_ (applyMsg . ($ t)) frames+ putMVar applied ()+ dispatch++ -- Ctrl-C is a normal quit, everything else rethrows. withTerm puts+ -- the tty back either way.+ onAsync UserInterrupt = pure ()+ onAsync e = throwIO e++ (dispatch `catch` onAsync) `finally` cleanup++ readIORef stateRef++-- | Left press without modifiers is a click; codes 64\/65 are the wheel.+mouseMsg :: MouseEvent -> [(Rect, Handlers m)] -> Maybe m+mouseMsg MouseEvent{..} hits+ | not mePress = Nothing+ | meButton .&. 64 /= 0 = dispatchAt (\h -> ($ notch) <$> hScroll h) mePos hits+ | meButton .&. 0x3f == 0 = dispatchAt hClick mePos hits+ | otherwise = Nothing+ where notch = if meButton .&. 1 == 0 then -1 else 1++--------------------------------------------------------------------------------+-- Small ANSI / text helpers++dimText :: Text -> Text+dimText = wrapStyle StyleDim++-- | Unlike 'T.lines', a trailing separator yields a final empty segment.+splitOnChar :: Char -> Text -> [Text]+splitOnChar c = T.splitOn (T.singleton c)++-- | @(before, rest)@ where @rest@ starts with @pat@.+splitOnFirst :: Text -> Text -> Maybe (Text, Text)+splitOnFirst pat s+ | T.null pat = Just ("", s)+ | otherwise = case T.breakOn pat s of+ (before, rest) | T.null rest -> Nothing+ | otherwise -> Just (before, rest)++-- | Background SGR for a foreground 'Color'.+bgColorCode :: Color -> Text+bgColorCode ColorDefault = ""+bgColorCode (ColorFull n) = "48;5;" <> T.show (clamp n)+bgColorCode (ColorTrue r g b) = "48;2;" <> T.show (clamp r) <> ";" <> T.show (clamp g) <> ";" <> T.show (clamp b)+bgColorCode c = case reads (T.unpack (colorCode c)) :: [(Int, String)] of+ [(n, "")] -> T.show (n + 10) -- 3x -> 4x, 9x -> 10x+ _ -> ""++--------------------------------------------------------------------------------+-- Kitty graphics++formatPng, formatRgb, formatRgba :: Int+formatPng = 100+formatRgb = 24+formatRgba = 32++-- | An inline image drawn with kitty's Unicode placeholders. It measures+-- exactly @cols@ x @rows@, so it lays out like any other element inside+-- 'box', 'row', 'table' and friends.+--+-- Build one with 'kittyImage', 'kittyRGB', 'kittyRGBA' or 'kittyImageFile'.+data KittyImage = KittyImage+ { kiPayload :: [Word8] -- ^ PNG bytes, or raw RGB\/RGBA pixels+ , kiFormat :: Int -- ^ 100 = PNG, 24 = RGB, 32 = RGBA+ , kiCols :: Int+ , kiRows :: Int+ , kiPxW :: Int -- ^ source pixel width (raw formats only)+ , kiPxH :: Int -- ^ source pixel height (raw formats only)+ , kiAlt :: Text+ , kiIdOverride :: Maybe Int -- ^ defaults to a hash of the payload+ }++instance Element KittyImage where+ renderElement img = kittyTransmit img <> kittyPlacement img++-- | 24-bit FNV-1a of the payload (never 0). Stable across frames, which is+-- what lets the runtime skip re-uploading.+kittyImageId :: [Word8] -> Maybe Int -> Int+kittyImageId payload override =+ let masked = fromMaybe (foldl step 0x811c9dc5 payload) override .&. 0xffffff+ in if masked == 0 then 1 else masked+ where+ step h b = (h `xor` fromIntegral b) * 0x01000193 .&. 0xffffffff++kittyBase64 :: [Word8] -> Text+kittyBase64 = T.pack . go+ where+ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" :: String+ sextet t s = alphabet !! ((t `shiftR` s) .&. 0x3f)+ go [] = ""+ go (b0:b1:b2:rest) =+ let t = (fromIntegral b0 `shiftL` 16) .|. (fromIntegral b1 `shiftL` 8) .|. fromIntegral b2+ in sextet t 18 : sextet t 12 : sextet t 6 : sextet t 0 : go rest+ go [b0, b1] =+ let t = (fromIntegral b0 `shiftL` 16) .|. (fromIntegral b1 `shiftL` 8) :: Int+ in sextet t 18 : sextet t 12 : sextet t 6 : "="+ go [b0] =+ let t = fromIntegral b0 `shiftL` 16 :: Int+ in sextet t 18 : sextet t 12 : "=="++kittyApcG :: Text+kittyApcG = "\ESC_G"++kittyST :: Text+kittyST = "\ESC\\"++-- | Base64 payload split into 4096-byte APC chunks. Every chunk carries+-- @i=<id>@ so 'dedupeTransmits' can drop all of them at once.+kittyTransmit :: KittyImage -> Text+kittyTransmit img = T.concat (zipWith block [0 ..] chunks)+ where+ b64 = kittyBase64 (kiPayload img)+ chunks = if T.null b64 then [""] else T.chunksOf 4096 b64+ theId = kittyImageId (kiPayload img) (kiIdOverride img)+ dims+ | kiFormat img == formatPng = ""+ | otherwise = ",s=" <> T.show (kiPxW img) <> ",v=" <> T.show (kiPxH img)+ firstKeys = "a=T,U=1,i=" <> T.show theId <> ",f=" <> T.show (kiFormat img)+ <> ",c=" <> T.show (kiCols img) <> ",r=" <> T.show (kiRows img) <> dims <> ",q=2"+ contKeys = "i=" <> T.show theId <> ",q=2"+ lastIdx = length chunks - 1+ block :: Int -> Text -> Text+ block i chunk =+ let more = if i == lastIdx then "0" else "1"+ keys = (if i == 0 then firstKeys else contKeys) <> ",m=" <> more+ in kittyApcG <> keys <> ";" <> chunk <> kittyST++-- | One line of placeholders per image row. The id travels in the foreground+-- colour; the first cell of each row carries (row, col 0) as diacritics.+kittyPlacement :: KittyImage -> Text+kittyPlacement img = T.intercalate "\n" (map rowLine [0 .. kiRows img - 1])+ where+ theId = kittyImageId (kiPayload img) (kiIdOverride img)+ fgCode = "\ESC[38;2;" <> T.show ((theId `shiftR` 16) .&. 0xff) <> ";"+ <> T.show ((theId `shiftR` 8) .&. 0xff) <> ";" <> T.show (theId .&. 0xff) <> "m"+ placeholder = T.singleton kittyPlaceholderChar+ diacritic i = T.singleton (chr (rowColumnDiacritics !! i))+ rowLine r = fgCode <> placeholder <> diacritic r <> diacritic 0+ <> T.replicate (kiCols img - 1) placeholder <> ansiReset++-- | Drop transmit blocks for ids already in the set, adding new ones.+-- Placements are left alone.+dedupeTransmits :: IntSet.IntSet -> Text -> (Text, IntSet.IntSet)+dedupeTransmits = go+ where+ go ids s = case splitOnFirst kittyApcG s of+ Nothing -> (s, ids)+ Just (before, rest) ->+ let (block, after) = takeBlock rest+ bid = parseId block+ (keep, ids')+ | bid /= 0 && IntSet.member bid ids = ("", ids)+ | bid /= 0 = (block, IntSet.insert bid ids)+ | otherwise = (block, ids)+ (restOut, idsF) = go ids' after+ in (before <> keep <> restOut, idsF)++ takeBlock s = case splitOnFirst kittyST (T.drop (T.length kittyApcG) s) of+ Nothing -> (s, "") -- unterminated, keep as is+ Just (mid, after) -> (kittyApcG <> mid <> kittyST, T.drop (T.length kittyST) after)++ parseId block =+ let keys = T.takeWhile (/= ';') (T.drop (T.length kittyApcG) block)+ in case [ T.drop 2 f | f <- splitOnChar ',' keys, "i=" `T.isPrefixOf` f ] of+ (v:_) | ds <- T.takeWhile isDigit v, not (T.null ds) -> read (T.unpack ds)+ _ -> 0++mkKitty :: [Word8] -> Int -> Int -> Int -> Int -> Int -> Text -> KittyImage+mkKitty payload fmt cols rows pxW pxH alt+ | cols < 1 || rows < 1 = error "KittyImage cols/rows must be >= 1"+ | cols > maxCells || rows > maxCells =+ error ("KittyImage cols/rows must be <= " <> show maxCells <> " (the diacritics table size)")+ | not validFormat =+ error "raw RGB/RGBA images (format 24/32) require pxW > 0 and pxH > 0"+ | otherwise = KittyImage payload fmt cols rows pxW pxH alt Nothing+ where+ maxCells = length rowColumnDiacritics+ validFormat = fmt == formatPng+ || ((fmt == formatRgb || fmt == formatRgba) && pxW > 0 && pxH > 0)++-- | PNG bytes shown in a @cols@ x @rows@ cell box. The terminal does the+-- decoding and scaling.+kittyImage :: [Word8] -> Int -> Int -> View m+kittyImage bytes cols rows = Leaf (mkKitty bytes formatPng cols rows 0 0 "")++-- | Raw RGB pixels, @pxW@ x @pxH@, shown in a @cols@ x @rows@ cell box.+kittyRGB :: [Word8] -> Int -> Int -> Int -> Int -> View m+kittyRGB pixels pxW pxH cols rows = Leaf (mkKitty pixels formatRgb cols rows pxW pxH "")++-- | 'kittyRGB' with an alpha channel.+kittyRGBA :: [Word8] -> Int -> Int -> Int -> Int -> View m+kittyRGBA pixels pxW pxH cols rows = Leaf (mkKitty pixels formatRgba cols rows pxW pxH "")++-- | Load a PNG from disk.+kittyImageFile :: FilePath -> Int -> Int -> IO (View m)+kittyImageFile path cols rows = (\bytes -> kittyImage bytes cols rows) <$> readFileBytes path++readFileBytes :: FilePath -> IO [Word8]+readFileBytes path = withBinaryFile path ReadMode $ \h -> do+ contents <- hGetContents h+ length contents `seq` pure (map (fromIntegral . ord) contents)++--------------------------------------------------------------------------------+-- Progress loaders++-- | Bar glyphs and colour for bounded loaders; spinner and colour for+-- streaming ones.+data LoaderStyle = LoaderStyle+ { lsFill :: Char+ , lsEmpty :: Char+ , lsOpen :: Text+ , lsClose :: Text+ , lsHead :: Text+ , lsSmooth :: Bool+ , lsSpinner :: SpinnerStyle+ , lsColor :: Color+ }++-- | @████▊░░░@, the default.+loaderBlocks :: LoaderStyle+loaderBlocks = LoaderStyle '█' '░' "" "" "" True SpinnerGrow ColorCyan++-- | @[██████░░░░]@+loaderBar :: LoaderStyle+loaderBar = LoaderStyle '█' '░' "[" "]" "" False SpinnerDots ColorGreen++-- | @[====> ]@+loaderAscii :: LoaderStyle+loaderAscii = LoaderStyle '=' ' ' "[" "]" ">" False SpinnerLine ColorYellow++-- | @●●●●∙∙∙∙@+loaderDots :: LoaderStyle+loaderDots = LoaderStyle '●' '∙' "" "" "" False SpinnerBounce ColorMagenta++-- | @━━━━────@+loaderLine :: LoaderStyle+loaderLine = LoaderStyle '━' '─' "" "" "" False SpinnerLine ColorBlue++-- | @▰▰▰▱▱▱@+loaderPipes :: LoaderStyle+loaderPipes = LoaderStyle '▰' '▱' "" "" "" False SpinnerArrow ColorBrightMagenta++loaderStyles :: [LoaderStyle]+loaderStyles = [loaderBlocks, loaderBar, loaderAscii, loaderDots, loaderLine, loaderPipes]++-- | Partial cells for smooth bars, in eighths.+blockEighths :: [Text]+blockEighths = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]++renderProgressBar :: LoaderStyle -> Double -> Int -> Text+renderProgressBar LoaderStyle{..} progress w =+ lsOpen <> wrapAnsi lsColor (replicateChar filled lsFill <> tip) <> dimText (replicateChar rest lsEmpty) <> lsClose+ where+ exact = max 0.0 (min 1.0 progress) * fromIntegral w+ filled = floor exact :: Int+ eighths = floor ((exact - fromIntegral filled) * 8) :: Int+ (tip, rest)+ | lsSmooth = if filled < w && eighths > 0+ then (blockEighths !! eighths, w - filled - 1)+ else ("", w - filled)+ | not (T.null lsHead) && filled > 0 && filled < w = (lsHead, max 0 (w - filled - T.length lsHead))+ | otherwise = ("", max 0 (w - filled))++-- | Redraw @frameAt i@ on the current line every 80ms while @action@ runs.+withTicker :: (Int -> IO Text) -> IO a -> IO a+withTicker frameAt action = do+ stopRef <- newIORef False+ let tick i = do+ stop <- readIORef stopRef+ unless stop $ do+ line <- frameAt i+ putText ("\r" <> line <> "\ESC[K")+ hFlush stdout+ threadDelay 80000+ tick (i + 1)+ ticker <- forkIO (tick 0)+ r <- action+ writeIORef stopRef True+ killThread ticker+ pure r++runLoader :: (Int -> IO Text) -> IO Text -> IORef Int -> [a] -> (a -> IO b) -> IO [b]+runLoader frameAt finalLine counter items action = do+ hideCursor+ hFlush stdout+ results <- withTicker frameAt $+ mapM (\x -> action x <* modifyIORef' counter (+ 1)) items+ final <- finalLine+ putText ("\r" <> final <> "\ESC[K\n")+ showCursor+ hFlush stdout+ pure results++labelPrefix :: Text -> Text+labelPrefix label = if T.null label then "" else label <> " "++boundedFrame :: LoaderStyle -> Text -> Int -> IORef Int -> IO Text+boundedFrame style label total counter = do+ done <- readIORef counter+ let progress = if total > 0 then min 1.0 (fromIntegral done / fromIntegral total) else 1.0+ pure $ labelPrefix label <> renderProgressBar style progress 20+ <> " " <> T.show done <> "/" <> T.show total+ <> " (" <> T.show (floor (progress * 100) :: Int) <> "%)"++streamingFrame :: LoaderStyle -> Text -> IORef Int -> Int -> IO Text+streamingFrame style label counter i = do+ done <- readIORef counter+ pure $ wrapAnsi (lsColor style) (spinnerFrame (lsSpinner style) i)+ <> " " <> labelPrefix label <> "(" <> T.show done <> " processed)"++streamingFinal :: Text -> IORef Int -> IO Text+streamingFinal label counter = do+ done <- readIORef counter+ pure (labelPrefix label <> T.show done <> " processed")++-- | Map an action over a list while drawing an inline progress bar.+--+-- @+-- _ <- 'loader' "Processing" [1..100] (\\_ -> threadDelay 20000)+-- @+loader :: String -> [a] -> (a -> IO b) -> IO [b]+loader = loaderStyled loaderBlocks++loaderStyled :: LoaderStyle -> String -> [a] -> (a -> IO b) -> IO [b]+loaderStyled style labelS items action = do+ counter <- newIORef 0+ let frame = boundedFrame style (T.pack labelS) (length items) counter+ runLoader (const frame) frame counter items action++-- | Like 'loader' but for when the length isn't worth forcing: a spinner and+-- a running count.+loaderStream :: String -> [a] -> (a -> IO b) -> IO [b]+loaderStream = loaderStreamStyled loaderBlocks++loaderStreamStyled :: LoaderStyle -> String -> [a] -> (a -> IO b) -> IO [b]+loaderStreamStyled style labelS items action = do+ let label = T.pack labelS+ counter <- newIORef 0+ runLoader (streamingFrame style label counter) (streamingFinal label counter) counter items action++--------------------------------------------------------------------------------+-- Ask: one-shot prompts+--+-- Each grabs the tty, returns a value and leaves one summary line behind.+-- 'Nothing' means cancelled (Esc / Ctrl-C / Ctrl-D).++askCursorUp :: Int -> Text+askCursorUp n = "\ESC[" <> T.show n <> "A\r"++askClearEol :: Text+askClearEol = "\ESC[K"++askClearBelow :: Text+askClearBelow = "\ESC[J"++-- | Redraw a frame over the previous one; returns its height.+askRepaint :: Text -> Int -> IO Int+askRepaint frame prevLines = do+ let ls = splitOnChar '\n' frame+ putText $ (if prevLines > 0 then askCursorUp prevLines else "")+ <> foldMap (<> askClearEol <> "\n") ls+ <> (if prevLines > length ls then askClearBelow else "")+ hFlush stdout+ pure (length ls)++-- | Replace the live frame with a single summary line.+askCommit :: Text -> Int -> IO ()+askCommit summary prevLines = do+ putText $ (if prevLines > 0 then askCursorUp prevLines else "")+ <> summary <> askClearEol <> "\n"+ <> (if prevLines > 1 then askClearBelow else "")+ hFlush stdout++askErase :: Int -> IO ()+askErase prevLines = when (prevLines > 0) $ do+ putText (askCursorUp prevLines <> askClearBelow)+ hFlush stdout++askActiveBtn :: Color -> Text -> Text+askActiveBtn bg t = "\ESC[1;37;" <> bgColorCode bg <> "m" <> t <> "\ESC[0m"++caret :: Text+caret = wrapAnsi ColorCyan "▌"++-- | Show @window@ rows of @xs@, scrolled to keep @idx@ roughly centred.+-- Returns the offset of the first visible row.+visibleSlice :: Int -> Int -> [a] -> (Int, [a])+visibleSlice rows idx xs = (top, take h (drop top xs))+ where+ total = length xs+ h = max 0 (min rows total)+ top = if total <= h then 0 else max 0 (min (idx - h `div` 2) (total - h))++renderInputFrame :: Text -> Text -> Text -> Text+renderInputFrame prompt value placeholder =+ prompt <> (if T.null value && not (T.null placeholder) then dimText placeholder else value) <> caret++renderConfirmFrame :: Text -> Bool -> Text -> Text -> Text+renderConfirmFrame question yes affirmative negative =+ question <> "\n " <> btn affirmative yes ColorGreen <> " " <> btn negative (not yes) ColorRed+ where+ btn t active bg = let padded = " " <> t <> " "+ in if active then askActiveBtn bg padded else padded++renderChooseFrame :: Text -> [a] -> Int -> (a -> Text) -> Text+renderChooseFrame prompt items idx renderItem =+ (if T.null prompt then "" else prompt <> "\n") <> T.intercalate "\n"+ [ if i == idx then wrapAnsi ColorCyan ("› " <> renderItem item) else " " <> renderItem item+ | (item, i) <- zip items [0 ..] ]++renderChooseManyFrame :: Text -> [a] -> Int -> [Int] -> Int -> (a -> Text) -> Text+renderChooseManyFrame prompt items idx picked limit renderItem =+ header <> T.intercalate "\n" rows+ where+ rows = [ let mark = if i `elem` picked then wrapAnsi ColorGreen "[x]" else dimText "[ ]"+ line = mark <> " " <> renderItem item+ in if i == idx then wrapAnsi ColorCyan "› " <> line else " " <> line+ | (item, i) <- zip items [0 ..] ]+ n = T.show (length picked)+ tag | limit > 0 = " (" <> n <> "/" <> T.show limit <> ")"+ | not (null picked) = " (" <> n <> ")"+ | otherwise = ""+ header+ | T.null prompt = ""+ | otherwise = prompt <> dimText tag <> "\n"++renderWriteFrame :: Text -> Text -> Text -> Text -> Text+renderWriteFrame prompt value placeholder hint =+ (if T.null prompt then "" else prompt <> "\n")+ <> (if T.null value && not (T.null placeholder) then dimText placeholder else value) <> caret+ <> (if T.null hint then "" else "\n" <> dimText hint)++renderFilterFrame :: Text -> Text -> [a] -> Int -> Int -> (a -> Text) -> Text+renderFilterFrame prompt query matches idx viewHeight renderItem =+ prompt <> query <> caret <> "\n" <> body+ where+ (top, visible) = visibleSlice viewHeight idx matches+ rows = [ if top + i == idx then wrapAnsi ColorCyan ("› " <> label) else " " <> label+ | (item, i) <- zip visible [0 ..], let label = renderItem item ]+ body = if null rows then dimText " (no matches)" else T.intercalate "\n" rows++-- | 'Nothing' unless @query@ is a case-insensitive subsequence of @target@;+-- otherwise the total gap between matched characters (lower is tighter).+fuzzyScore :: Text -> Text -> Maybe Int+fuzzyScore query target+ | T.null query = Just 0+ | otherwise = go (T.toLower query) (T.toLower target) (-1) 0 0+ where+ go Empty _ _ slack _ = Just slack+ go _ Empty _ _ _ = Nothing+ go q@(qc :< qs) (sc :< ss) lastHit slack i+ | qc == sc = go qs ss i (if lastHit >= 0 then slack + (i - lastHit - 1) else slack) (i + 1)+ | otherwise = go q ss lastHit slack (i + 1)++fuzzyMatches :: Text -> [a] -> (a -> Text) -> [a]+fuzzyMatches query items renderItem+ | T.null query = items+ | otherwise = map fst $ sortOn snd+ [ (item, score) | item <- items, Just score <- [fuzzyScore query (renderItem item)] ]++data FileEntry = FileEntry { feName :: FilePath, feIsDir :: Bool }++feDisplay :: FileEntry -> Text+feDisplay e = T.pack (if feIsDir e then feName e <> "/" else feName e)++renderFileFrame :: FilePath -> [FileEntry] -> Int -> Int -> Text+renderFileFrame path entries idx viewHeight =+ dimText (T.pack path) <> "\n" <> T.intercalate "\n" rows+ where+ (top, visible) = visibleSlice viewHeight idx entries+ rows = [ let name = if feIsDir e then wrapAnsi ColorBlue (feDisplay e) else feDisplay e+ in if top + i == idx then wrapAnsi ColorCyan "› " <> name else " " <> name+ | (e, i) <- zip visible [0 ..] ]++renderPagerFrame :: [Text] -> Int -> Int -> Int -> Bool -> Text+renderPagerFrame allLines top h viewWidth lineNumbers = body <> "\n" <> status+ where+ total = length allLines+ numWidth = length (show total)+ maxLineW = max 20 (viewWidth - if lineNumbers then numWidth + 3 else 0)+ body = T.intercalate "\n"+ [ let line' = if T.length line > maxLineW then T.take (maxLineW - 1) line <> "…" else line+ in if lineNumbers then dimText (padLeft numWidth (T.show (top + i + 1)) <> " │ ") <> line' else line'+ | (line, i) <- zip (take h (drop top allLines)) [0 ..] ]+ viewEnd = min (top + h) total+ percent = if total == 0 then 100 else (viewEnd * 100) `div` total+ status = dimText (" L" <> T.show (top + 1) <> "–" <> T.show viewEnd <> " of " <> T.show total+ <> " " <> T.show percent <> "% ↑↓ PgUp/PgDn Home/End q to quit")++-- | Single-line text input.+askInput :: String -- ^ prompt, e.g. @"› "@+ -> String -- ^ placeholder+ -> String -- ^ initial value+ -> IO (Maybe String)+askInput promptS placeholderS initialS = withTerm Inline $ do+ let prompt = T.pack promptS; placeholder = T.pack placeholderS+ frame v = renderInputFrame prompt v placeholder+ edit v pl = askRepaint (frame v) pl >>= loop v+ loop value pl = readKey >>= \case+ KeyEnter -> askCommit (prompt <> value) pl >> pure (Just (T.unpack value))+ k | isQuitKey k -> askErase pl >> pure Nothing+ KeyBackspace | not (T.null value) -> edit (T.init value) pl+ KeyChar c -> edit (T.snoc value c) pl+ _ -> loop value pl+ edit (T.pack initialS) 0++-- | Yes\/no. Cancelling returns the opposite of the default.+askConfirm :: String -- ^ question+ -> Bool -- ^ default+ -> String -- ^ affirmative label, e.g. @"Yes"@+ -> String -- ^ negative label, e.g. @"No"@+ -> IO Bool+askConfirm questionS def affirmativeS negativeS = withTerm Inline $ do+ let question = T.pack questionS; affirmative = T.pack affirmativeS; negative = T.pack negativeS+ draw yes pl = askRepaint (renderConfirmFrame question yes affirmative negative) pl >>= loop yes+ pick yes pl = do+ askCommit (question <> " " <> wrapAnsi ColorCyan (if yes then affirmative else negative)) pl+ pure yes+ loop yes pl = readKey >>= \case+ KeyEnter -> pick yes pl+ KeyChar c | c `elem` ("yY" :: String) -> pick True pl+ | c `elem` ("nN" :: String) -> pick False pl+ KeyLeft -> draw (not yes) pl+ KeyRight -> draw (not yes) pl+ KeyTab -> draw (not yes) pl+ k | isQuitKey k -> askErase pl >> pure (not def)+ _ -> loop yes pl+ draw def 0++-- | Pick one. 'Nothing' if cancelled or @items@ is empty.+askChoose :: String -> [a] -> (a -> String) -> IO (Maybe a)+askChoose _ [] _ = pure Nothing+askChoose promptS items renderItemS = withTerm Inline $ do+ let prompt = T.pack promptS; renderItem = T.pack . renderItemS+ n = length items+ draw i pl = askRepaint (renderChooseFrame prompt items i renderItem) pl >>= loop i+ loop i pl = readKey >>= \case+ KeyEnter -> do+ let picked = items !! i+ askCommit (prompt <> " " <> wrapAnsi ColorCyan (renderItem picked)) pl+ pure (Just picked)+ KeyUp -> draw ((i - 1 + n) `mod` n) pl+ KeyDown -> draw ((i + 1) `mod` n) pl+ KeyTab -> draw ((i + 1) `mod` n) pl+ k | isQuitKey k -> askErase pl >> pure Nothing+ _ -> loop i pl+ draw 0 0++-- | Pick several. Space or Tab toggles, Enter commits; @limit@ 0 means no+-- limit. 'Nothing' if cancelled or @items@ is empty.+askChooseMany :: String -> [a] -> Int -> (a -> String) -> IO (Maybe [a])+askChooseMany _ [] _ _ = pure Nothing+askChooseMany promptS items limit renderItemS = withTerm Inline $ do+ let prompt = T.pack promptS; renderItem = T.pack . renderItemS+ n = length items+ toggle i sel+ | i `elem` sel = filter (/= i) sel+ | limit > 0 && length sel >= limit = sel+ | otherwise = sel <> [i]+ loop i sel prev = do+ pl <- askRepaint (renderChooseManyFrame prompt items i sel limit renderItem) prev+ readKey >>= \case+ KeyEnter -> do+ let picks = [ item | (item, j) <- zip items [0 ..], j `elem` sel ]+ askCommit (prompt <> " " <> if null picks+ then dimText "(nothing)"+ else wrapAnsi ColorCyan (T.intercalate ", " (map renderItem picks))) pl+ pure (Just picks)+ KeyUp -> loop ((i - 1 + n) `mod` n) sel pl+ KeyDown -> loop ((i + 1) `mod` n) sel pl+ KeyChar ' ' -> loop i (toggle i sel) pl+ KeyTab -> loop i (toggle i sel) pl+ k | isQuitKey k -> askErase pl >> pure Nothing+ _ -> loop i sel pl+ loop 0 [] 0++-- | Spin while @task@ runs, then print a ✓ or ✗ line. Exceptions from the+-- task are rethrown.+askSpin :: String -> SpinnerStyle -> IO a -> IO a+askSpin labelS style task = do+ let label = T.pack labelS+ hideCursor+ hFlush stdout+ outcome <- withTicker (\i -> pure (wrapAnsi ColorCyan (spinnerFrame style i) <> " " <> label)) $+ (Right <$> task) `catch` \(e :: SomeException) -> pure (Left e)+ let (mark, col) = either (const ("✗", ColorRed)) (const ("✓", ColorGreen)) outcome+ putText ("\r" <> wrapAnsi col (mark <> " " <> label) <> askClearEol <> "\n")+ showCursor+ hFlush stdout+ either throwIO pure outcome++-- | Multi-line input. Enter adds a newline, Ctrl-D submits, Esc cancels.+askWrite :: String -- ^ prompt+ -> String -- ^ placeholder+ -> String -- ^ initial value+ -> String -- ^ hint line+ -> IO (Maybe String)+askWrite promptS placeholderS initialS hintS = withTerm Inline $ do+ let prompt = T.pack promptS; placeholder = T.pack placeholderS; hint = T.pack hintS+ loop value prev = do+ pl <- askRepaint (renderWriteFrame prompt value placeholder hint) prev+ readKey >>= \case+ KeyCtrl 'D' -> do+ let firstLine = case splitOnChar '\n' value of (x:_) -> x; [] -> ""+ summary = if T.elem '\n' value then firstLine <> " …" else firstLine+ askCommit ((if T.null prompt then "" else prompt <> " ") <> wrapAnsi ColorCyan summary) pl+ pure (Just (T.unpack value))+ KeyEscape -> askErase pl >> pure Nothing+ KeyCtrl 'C' -> askErase pl >> pure Nothing+ KeyEnter -> loop (value <> "\n") pl+ KeyChar c -> loop (T.snoc value c) pl+ KeyBackspace | not (T.null value) -> loop (T.init value) pl+ _ -> loop value pl+ loop (T.pack initialS) 0++-- | Type to fuzzy-filter, arrows to move, Enter to pick.+askFilter :: String -> [a] -> Int -> (a -> String) -> IO (Maybe a)+askFilter _ [] _ _ = pure Nothing+askFilter promptS items viewHeight renderItemS = withTerm Inline $ do+ let prompt = T.pack promptS; renderItem = T.pack . renderItemS+ loop query idx prev = do+ let matches = fuzzyMatches query items renderItem+ m = length matches+ i = if null matches then 0 else max 0 (min idx (m - 1))+ hasMatches = not (null matches)+ pl <- askRepaint (renderFilterFrame prompt query matches i viewHeight renderItem) prev+ readKey >>= \case+ KeyEnter | hasMatches -> do+ let picked = matches !! i+ askCommit (prompt <> query <> " " <> wrapAnsi ColorCyan (renderItem picked)) pl+ pure (Just picked)+ KeyUp | hasMatches -> loop query ((i - 1 + m) `mod` m) pl+ KeyDown | hasMatches -> loop query ((i + 1) `mod` m) pl+ KeyTab | hasMatches -> loop query ((i + 1) `mod` m) pl+ KeyBackspace | not (T.null query) -> loop (T.init query) 0 pl+ KeyChar c -> loop (T.snoc query c) 0 pl+ k | isQuitKey k -> askErase pl >> pure Nothing+ _ -> loop query i pl+ loop "" 0 0++-- | Directory browser. Enter or Right descends, Left or Backspace goes up,+-- Enter on a file picks it.+askFile :: String -> Int -> IO (Maybe String)+askFile start viewHeight = withTerm Inline (loop start 0 0)+ where+ loop dir idx prev = do+ cwd <- canonicalizePath dir+ listEntries cwd >>= \case+ Left err -> askCommit (dimText (T.pack err)) prev >> pure Nothing+ Right entries -> do+ let count = length entries+ i = max 0 (min idx (count - 1))+ target = entries !! i+ enter = canonicalizePath (cwd <> "/" <> feName target)+ pl <- askRepaint (renderFileFrame cwd entries i viewHeight) prev+ readKey >>= \case+ KeyEnter+ | feIsDir target -> enter >>= \p -> loop p 0 pl+ | otherwise -> do+ full <- enter+ askCommit (wrapAnsi ColorCyan (T.pack full)) pl+ pure (Just full)+ KeyRight+ | feIsDir target -> enter >>= \p -> loop p 0 pl+ | otherwise -> loop cwd i pl+ KeyUp -> loop cwd ((i - 1 + count) `mod` count) pl+ KeyDown -> loop cwd ((i + 1) `mod` count) pl+ KeyTab -> loop cwd ((i + 1) `mod` count) pl+ KeyLeft -> up cwd i pl+ KeyBackspace -> up cwd i pl+ k | isQuitKey k -> askErase pl >> pure Nothing+ _ -> loop cwd i pl+ up cwd i pl = do+ parent <- canonicalizePath (cwd <> "/..")+ if parent /= cwd then loop parent 0 pl else loop cwd i pl++-- | Directories first, then case-insensitive by name, with @..@ on top.+listEntries :: String -> IO (Either String [FileEntry])+listEntries path = do+ exists <- doesPathExist path+ isDir <- doesDirectoryExist path+ if not exists then pure (Left ("not found: " <> path))+ else if not isDir then pure (Left ("not a directory: " <> path))+ else do+ names <- listDirectory path `catch` \(_ :: IOException) -> pure []+ entries <- forM names $ \nm -> FileEntry nm <$> doesDirectoryExist (path <> "/" <> nm)+ pure (Right (FileEntry ".." True : sortOn (\e -> (not (feIsDir e), map toLower (feName e))) entries))++-- | Scrollable pager; @viewHeight@ 0 fills the terminal. q or Esc quits.+askPager :: String -> Int -> Bool -> IO ()+askPager contentS viewHeight lineNumbers = withTerm Inline $ do+ let content = T.pack contentS+ ls = if T.null content then [""] else splitOnChar '\n' content+ (termH, termW) <- getTerminalSize+ let h = if viewHeight > 0 then viewHeight else max 5 (termH - 3)+ maxTop = max 0 (length ls - h)+ loop top prev = do+ let t = max 0 (min top maxTop)+ pl <- askRepaint (renderPagerFrame ls t h termW lineNumbers) prev+ readKey >>= \case+ KeyChar 'q' -> askErase pl+ KeyEscape -> askErase pl+ KeyCtrl 'C' -> askErase pl+ KeyUp -> loop (t - 1) pl+ KeyDown -> loop (t + 1) pl+ KeyEnter -> loop (t + 1) pl+ KeyPageUp -> loop (t - h) pl+ KeyPageDown -> loop (t + h) pl+ KeyChar ' ' -> loop (t + h) pl+ KeyHome -> loop 0 pl+ KeyEnd -> loop maxTop pl+ _ -> loop t pl+ loop 0 0
@@ -1,1087 +1,1135 @@ <div align="right">- <sub><em>part of <a href="https://github.com/mattlianje/d4"><img src="https://raw.githubusercontent.com/mattlianje/d4/master/pix/d4.png" width="23"></a> <a href="https://github.com/mattlianje/d4">d4</a></em></sub>-</div>--<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/layoutz-demo.png" width="750">-</p>--# <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz.png" width="60"> layoutz--**Simple, beautiful CLI output 🪶**--A lightweight, zero-dep lib to build compositional ANSI strings, terminal plots,-and interactive Elm-style TUI's in pure Haskell.--Also in [Scala](https://github.com/mattlianje/layoutz), [OCaml](https://github.com/mattlianje/layoutz/tree/master/layoutz-ocaml)--## Features-- Pure Haskell, zero-dependencies (use `Layoutz.hs` like a header file)-- Elm-style TUIs-- Layout primitives, tables, trees, lists, CJK-aware-- Colors, ANSI styles, rich formatting-- Terminal charts and plots-- Widgets: text input, spinners, progress bars-- Inline raster images via the [kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/)-- One-shot interactive prompts (`askInput`, `askChoose`, `askFilter`, …)-- Drop-in progress `loader`s for build scripts and batch jobs-- Implement `Element` to add your own primitives-- Easy porting to MicroHs--<p align="center">-<img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/showcase.gif" width="650">-<br>-<sub><a href="examples/ShowcaseApp.hs">ShowcaseApp.hs</a></sub>-</p>--Layoutz also lets you easily drop animations into build scripts or any processes that use Stdout:--<p align="center">-<img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/inline-demo.gif" width="650">-<br>-<sub><a href="examples/InlineBar.hs">InlineBar.hs</a></sub>-</p>--## Table of Contents-- [Installation](#installation)-- [Quickstart](#quickstart)-- [Why layoutz?](#why-layoutz)-- [Core Concepts](#core-concepts)-- [Elements](#elements)-- [Border Styles](#border-styles)-- [Charts & Plots](#charts--plots)-- [Colors & Styles](#colors-ansi-support)-- [Inline Images](#inline-images)-- [Custom Elements](#custom-elements)-- [Collections](#collections)-- [Interactive Apps](#interactive-apps)-- [Prompts (Ask)](#prompts-ask)-- [Progress (loader)](#progress-loader)-- [Examples](#examples)-- [Contributing](#contributing)--## Installation--**Add Layoutz on [Hackage](https://hackage.haskell.org/package/layoutz) to your project's `.cabal` file:**-```haskell-build-depends: layoutz-```--All you need:-```haskell-import Layoutz-```--## Quickstart--**(1/3) Static rendering**: pretty, composable strings.--```haskell-import Layoutz--demo = layout- [ center $ row- [ withStyle StyleBold $ text "Layoutz"- , withColor ColorCyan $ underline' "ˆ" $ text "DEMO"- ]- , br- , row- [ statusCard "Users" "1.2K"- , withBorder BorderDouble $ statusCard "API" "UP"- , withColor ColorRed $ withBorder BorderThick $ statusCard "CPU" "23%"- , withStyle StyleReverse $ withBorder BorderRound $ table ["Name", "Role", "Skills"]- [ ["Gegard", "Pugilist", ul ["Armenian", ul ["bad", ul["man"]]]]- , ["Eve", "QA", "Testing"]- ]- ]- ]--putStrLn $ render demo-```--<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/intro-demo.png" width="700">-</p>---**(2/3) Interactive apps** - Build Elm-style TUI's:--```haskell-import Layoutz--data Msg = Inc | Dec--counterApp :: LayoutzApp Int Msg-counterApp = LayoutzApp- { appInit = (0, CmdNone)- , appUpdate = \msg count -> case msg of- Inc -> (count + 1, CmdNone)- Dec -> (count - 1, CmdNone)- , appSubscriptions = \_ -> subKeyPress $ \key -> case key of- KeyChar '+' -> Just Inc- KeyChar '-' -> Just Dec- _ -> Nothing- , appView = \count -> layout- [ section "Counter" [text $ "Count: " <> show count]- , ul ["Press '+' or '-'", "ESC to quit"]- ]- }--main = runApp counterApp-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/counter-demo.gif" width="650">-</p>--**(3/3) Prompts (Ask)**--One-shot CLI prompts (inputs, choosers, filters, file pickers, spinners) that collapse to a single line as you answer them.--```haskell-import Layoutz-import Control.Concurrent (threadDelay)--main :: IO ()-main = do- name <- askInput "Name › " "anonymous" ""- realm <- askChoose "Choose a realm" ["The Shire", "Rivendell", "Mirkwood"] id- packs <- askChooseMany "Pack provisions" ["lembas", "pipe-weed", "rope"] 3 id- member <- askFilter "Search a companion › " ["Bilbo", "Gandalf", "Thorin"] 8 id- riddle <- askWrite "Pose a riddle" "This thing all things devours…" "" "Ctrl-D to save"- quest <- askConfirm "Venture on the quest?" True "Yes" "No"- smaug <- askSpin "Awaking Smaug…" SpinnerDots (threadDelay 1500000 >> pure "ready")- pure ()-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/ask-mini.gif" width="600">- <br>- <sub><a href="examples/AskDemo.hs">AskDemo.hs</a></sub>-</p>--## Why layoutz?-- We have `printf` and [full-blown](https://hackage.haskell.org/package/brick) TUI libraries - but there's a gap in-between-- **layoutz** is a tiny, declarative DSL for structured CLI output-- On the side, it has a little Elm-style runtime + keyhandling DSL to animate your elements, much like a flipbook...- - But you can just use **Layoutz** without any of the TUI stuff--## Core concepts-- Every piece of content is an `Element`-- Elements are **immutable** and **composable** - build complex layouts by combining simple elements-- A `layout` arranges elements **vertically**:-```haskell-layout [elem1, elem2, elem3] -- Joins with "\n"-```-Call `render` on any element to get a string--The power comes from **uniform composition** - since everything has the `Element` typeclass, everything can be combined.--### String Literals-With `OverloadedStrings` enabled, you can use string literals directly:-```haskell-layout ["Hello", "World"] -- Instead of layout [text "Hello", text "World"]-```--> [!NOTE]-> When passing to functions that take polymorphic `Element a` parameters (like `underline'`, `center'`, `pad`), use `text` explicitly:--```haskell-underline' "=" $ text "Title" -- Correct-underline' "=" "Title" -- Ambiguous type error-```--## Border Styles--Applied via `withBorder` to any element with the `HasBorder` typeclass (`box`, `statusCard`, `table`):-```haskell-withBorder BorderRound $ box "Info" ["content"]-withBorder BorderDouble $ statusCard "API" "UP"-withBorder BorderThick $ table ["Name"] [["Alice"]]-```--Write generic code over bordered elements:-```haskell-makeThick :: HasBorder a => a -> a-makeThick = setBorder BorderThick-```--```haskell-BorderNormal -- ┌─┐ (default)-BorderDouble -- ╔═╗-BorderThick -- ┏━┓-BorderRound -- ╭─╮-BorderAscii -- +-+-BorderBlock -- ███-BorderDashed -- ┌╌┐-BorderDotted -- ┌┈┐-BorderInnerHalfBlock -- ▗▄▖-BorderOuterHalfBlock -- ▛▀▜-BorderMarkdown -- |-|-BorderCustom "+" "=" "|" -- Custom border-BorderNone -- No borders-```--## Elements--### Layout--#### Stacking & rows-```haskell-layout ["First", "Second", "Third"] -- vertical--- First--- Second--- Third--row ["Left", "Middle", "Right"] -- horizontal--- Left Middle Right--columns [layout ["A", "B"], layout ["C", "D"]]--- A C--- B D--tightRow [text "A", text "B", text "C"] -- no spacing--- ABC-```--#### Spacing & rules-```haskell-layout [text "Line 1", br, text "Line 2"] -- br is a blank line--hr -- default ──────────...-hr' "~" -- custom char-hr'' "=" 20 -- ====================--vr -- vertical rule, 10 high with │-vr' "║" -- custom char-vr'' "|" 5 -- custom char + height-```--#### Text transforms-```haskell-center $ text "Auto-centered" -- width taken from siblings-center' 20 $ text "TITLE" -- │ TITLE │-alignLeft 20 "Left" -- │Left │-alignRight 20 "Right" -- │ Right│--justify 30 "Spread this out"--- │Spread this out│--wrap 20 "Long text here that should wrap"--- Long text here that--- should wrap--truncate' 15 (text "Very long text that will be cut off") -- Very long te...-truncate'' 20 "…" (text "Custom ellipsis example text here") -- Custom ellipsis exa…--pad 2 $ text "content" -- 2 cells of padding all around--underline $ text "Title" -- Title- -- ─────-underline' "=" $ text "Custom" -- Custom- -- ══════-underlineColored "~" ColorCyan $ text "Fancy"--margin "[error]"- [ text "Ooops!"- , row [text "val result: Int = ", underline' "^" (text "getString()")]- , text "Expected Int, found String"- ]--- [error] Ooops!--- [error] val result: Int = getString()--- [error] ^^^^^^^^^^^--- [error] Expected Int, found String-```--### Content--#### Basics-```haskell-text "hello"-"hello" - with OverloadedStrings--section "Status" [text "All systems operational"]--- === Status ===--- All systems operational-section' "-" "Status" [text "ok"] -- custom glyph-section'' "#" "Report" 5 [text "42"] -- custom glyph + width--kv [("Name", "Alice"), ("Age", "30"), ("City", "NYC")]--- Name: Alice--- Age: 30--- City: NYC-```--#### Boxes, cards & banners-```haskell-box "Status" [text "All systems go"]--- ┌──Status──────────┐--- │ All systems go │--- └──────────────────┘--withBorder BorderDouble $ box "Fancy" [text "Double border"]--- ╔══Fancy═══════════╗--- ║ Double border ║--- ╚══════════════════╝--withBorder BorderRound $ box "Smooth" [text "Rounded corners"]--- ╭──Smooth────────────╮--- │ Rounded corners │--- ╰────────────────────╯--row [ withColor ColorGreen $ statusCard "CPU" "45%"- , withColor ColorCyan $ statusCard "MEM" "2.1G"- ]--- ┌──────┐ ┌───────┐--- │ CPU │ │ MEM │--- │ 45% │ │ 2.1G │--- └──────┘ └───────┘--banner ["System Dashboard"]--- ╔══════════════════╗--- ║ System Dashboard ║--- ╚══════════════════╝-```--Pipe any `HasBorder` element through `withBorder`:-```haskell-withBorder BorderRound $ box "Info" ["content"]-withBorder BorderDouble $ statusCard "API" "UP"-withBorder BorderThick $ table ["Name"] [["Alice"]]-```--#### Lists & trees-```haskell-ul ["Backend", ul ["API", ul ["REST", "GraphQL"], "DB"], "Frontend"]--- • Backend--- ◦ API--- ▪ REST--- ▪ GraphQL--- ◦ DB--- • Frontend--ol ["Setup", ol ["Install deps", ol ["npm", "pip"], "Configure"], "Deploy"]--- 1. Setup--- a. Install deps--- i. npm--- ii. pip--- b. Configure--- 2. Deploy--tree "Project"- [ branch "src" [leaf "main.hs", leaf "test.hs"]- , branch "docs" [leaf "README.md"]- ]--- Project--- ├── src--- │ ├── main.hs--- │ └── test.hs--- └── docs--- └── README.md-```--#### Table-```haskell-table ["Name", "Age", "City"]- [ ["Alice", "30", "New York"]- , ["Bob", "25", ""]- , ["Charlie", "35", "London"]- ]-```-```-┌─────────┬─────┬──────────┐-│ Name │ Age │ City │-├─────────┼─────┼──────────┤-│ Alice │ 30 │ New York │-│ Bob │ 25 │ │-│ Charlie │ 35 │ London │-└─────────┴─────┴──────────┘-```--#### Progress & spinners-```haskell-inlineBar "Download" 0.75--- Download [███████████████─────] 75%--chart [("Web", 10), ("Mobile", 20), ("API", 15)]--- Web │████████████████████────────────────────│ 10--- Mobile │████████████████████████████████████████│ 20--- API │██████████████████████████████──────────│ 15--spinner "Loading" frame SpinnerDots -- ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏-spinner "Loading" frame SpinnerLine -- | / - \-spinner "Loading" frame SpinnerClock -- 🕐 🕑 🕒 🕓 🕔 🕕 🕖 🕗 🕘 🕙 🕚 🕛-spinner "Loading" frame SpinnerBounce -- ⠁ ⠂ ⠄ ⠂-spinner "Loading" frame SpinnerEarth -- 🌍 🌎 🌏-spinner "Loading" frame SpinnerMoon -- 🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘-spinner "Loading" frame SpinnerGrow -- ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ ▉ ▊ ▋ ▌ ▍ ▎-spinner "Loading" frame SpinnerArrow -- ← ↖ ↑ ↗ → ↘ ↓ ↙-```--#### Inline Images--Inline raster images via the [kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).-A `KittyImage` measures exactly `cols`×`rows` cells, so it composes with every other-element: drop it into boxes, rows, tables, `center`, etc.--```haskell-img <- kittyImageFile "pix/sakuraba.png" 35 14 -- PNG sized to 35×14 cells--putStrLn $ render $ row- [ withBorder BorderRound $ box "the gracie hunter" [img]- , box "stats" [kv [("flying", "yes"), ("opponent", "grounded"), ("rules", "PRIDE")]]- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/haskell-kitty-1.png" width="600">-</p>--Build straight from bytes or raw pixels:--```haskell-kittyImage bytes 35 14 -- PNG bytes -> cols rows-kittyRGB pixels w h 18 9 -- raw RGB pxW pxH -> cols rows-kittyRGBA pixels w h 18 9 -- raw RGBA pxW pxH -> cols rows-```--```haskell-let (w, h) = (96, 96)- pixels = [ channel i | i <- [0 .. w * h * 4 - 1] ]- channel i =- let p = i `div` 4; x = p `mod` w; y = p `div` w- in fromIntegral $ case i `mod` 4 of- 0 -> x * 255 `div` w- 1 -> y * 255 `div` h- 2 -> 255 - (x * 255 `div` w)- _ -> 255--putStrLn $ render $ box "gradient" [kittyRGBA pixels w h 18 9]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/haskell-kitty-2.png" width="600">-</p>--Needs a kitty-graphics-capable terminal (kitty, WezTerm, Ghostty). Inside a-`LayoutzApp`, each distinct image is transmitted once and re-placed cheaply on-every frame.--## Charts & Plots--See also [Granite](https://github.com/mchav/granite) for terminal plots in Haskell.--#### Line Plot-```haskell-let sinePoints = [(x, sin x) | x <- [0, 0.1 .. 10.0]]-plotLine 40 10 [Series sinePoints "sine" ColorBrightCyan]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-function-1.png" width="500">-</p>--Multiple series:-```haskell-let sinPts = [(x, sin (x * 0.15) * 5) | x <- [0..50]]- cosPts = [(x, cos (x * 0.15) * 5) | x <- [0..50]]-plotLine 50 12- [ Series sinPts "sin(x)" ColorBrightCyan- , Series cosPts "cos(x)" ColorBrightMagenta- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-function-2.png" width="500">-</p>--#### Pie Chart-```haskell-plotPie 20 10- [ Slice 50 "A" ColorBrightCyan- , Slice 30 "B" ColorBrightMagenta- , Slice 20 "C" ColorBrightYellow- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-pie.png" width="500">-</p>--#### Bar Chart-```haskell-plotBar 40 10- [ BarItem 85 "Mon" ColorBrightCyan- , BarItem 120 "Tue" ColorBrightGreen- , BarItem 95 "Wed" ColorBrightMagenta- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-bar.png" width="500">-</p>--```haskell-plotBar 40 10- [ BarItem 100 "Sales" ColorBrightMagenta- , BarItem 80 "Costs" ColorBrightRed- , BarItem 20 "Profit" ColorBrightCyan- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-bar-custom.png" width="500">-</p>--#### Stacked Bar Chart-```haskell-plotStackedBar 40 10- [ StackedBarGroup [BarItem 30 "Q1" ColorDefault, BarItem 20 "Q2" ColorDefault, BarItem 25 "Q3" ColorDefault] "2022"- , StackedBarGroup [BarItem 35 "Q1" ColorDefault, BarItem 25 "Q2" ColorDefault, BarItem 30 "Q3" ColorDefault] "2023"- , StackedBarGroup [BarItem 40 "Q1" ColorDefault, BarItem 30 "Q2" ColorDefault, BarItem 35 "Q3" ColorDefault] "2024"- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-stacked.png" width="500">-</p>--#### Sparkline-```haskell-plotSparkline [1, 4, 2, 8, 5, 7, 3, 6]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-sparkline.png" width="500">-</p>--#### Heatmap-```haskell-plotHeatmap $ HeatmapData- [ [12, 15, 22, 28, 30, 25, 18]- , [14, 18, 25, 32, 35, 28, 20]- , [10, 13, 20, 26, 28, 22, 15]- ]- ["Mon", "Tue", "Wed"]- ["6am", "9am", "12pm", "3pm", "6pm", "9pm", "12am"]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/chart-heatmap.png" width="500">-</p>--## Colors--Add ANSI colors to any element:--```haskell-layout- [ withColor ColorRed $ text "The quick brown fox..."- , withColor ColorBrightCyan $ text "The quick brown fox..."- , underlineColored "~" ColorRed $ text "The quick brown fox..."- , margin "[INFO]" [withColor ColorCyan $ text "The quick brown fox..."]- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/layoutz-color-2.png" width="700">-</p>---```haskell-ColorBlack-ColorRed-ColorGreen-ColorYellow-ColorBlue-ColorMagenta-ColorCyan-ColorWhite-ColorBrightBlack -- Bright 8-ColorBrightRed-ColorBrightGreen-ColorBrightYellow-ColorBrightBlue-ColorBrightMagenta-ColorBrightCyan-ColorBrightWhite-ColorFull 196 -- 256-color palette (0-255)-ColorTrue 255 128 0 -- 24-bit RGB-ColorDefault -- Conditional no-op-```--### Color Gradients--Create gradients with extended colors:--```haskell-let palette = tightRow $ map (\i -> withColor (ColorFull i) $ text "█") [16, 19..205]- redToBlue = tightRow $ map (\i -> withColor (ColorTrue i 100 (255 - i)) $ text "█") [0, 4..255]- greenFade = tightRow $ map (\i -> withColor (ColorTrue 0 (255 - i) i) $ text "█") [0, 4..255]- rainbow = tightRow $ map colorBlock [0, 4..255]- where- colorBlock i =- let r = if i < 128 then i * 2 else 255- g = if i < 128 then 255 else (255 - i) * 2- b = if i > 128 then (i - 128) * 2 else 0- in withColor (ColorTrue r g b) $ text "█"--putStrLn $ render $ layout [palette, redToBlue, greenFade, rainbow]-```--<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/layoutz-color-1.png" width="700">-</p>---## Styles--Add ANSI styles to any element:--```haskell-layout- [ withStyle StyleBold $ text "The quick brown fox..."- , withColor ColorRed $ withStyle StyleBold $ text "The quick brown fox..."- , withStyle StyleReverse $ withStyle StyleItalic $ text "The quick brown fox..."- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/layoutz-styles-1.png" width="700">-</p>--```haskell-StyleBold-StyleDim-StyleItalic-StyleUnderline-StyleBlink-StyleReverse-StyleHidden-StyleStrikethrough-StyleDefault -- Conditional no-op-StyleBold <> StyleItalic -- Combine with <>-```--**Combining Styles:**--Use `<>` to combine multiple styles at once:--```haskell-layout- [ withStyle (StyleBold <> StyleItalic <> StyleUnderline) $ text "The quick brown fox..."- , withStyle (StyleBold <> StyleReverse) $ text "The quick brown fox..."- ]-```-<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/pix/layoutz-styles-2.png" width="700">-</p>--You can also combine colors and styles:--```haskell-withColor ColorBrightYellow $ withStyle (StyleBold <> StyleItalic) $ text "The quick brown fox..."-```--## Custom Elements--Create your own components by implementing the `Element` typeclass--```haskell-data Square = Square Int--instance Element Square where- renderElement (Square size)- | size < 2 = ""- | otherwise = intercalate "\n" (top : middle ++ [bottom])- where- w = size * 2 - 2- top = "┌" ++ replicate w '─' ++ "┐"- middle = replicate (size - 2) ("│" ++ replicate w ' ' ++ "│")- bottom = "└" ++ replicate w '─' ++ "┘"---- Helper to avoid wrapping with L-square :: Int -> L-square n = L (Square n)---- Use it like any other element-putStrLn $ render $ row- [ square 3- , square 5- , square 7- ]-```-```-┌────┐ ┌────────┐ ┌────────────┐-│ │ │ │ │ │-└────┘ │ │ │ │- │ │ │ │- └────────┘ │ │- │ │- └────────────┘-```--## Collections-```haskell-import Data.List (groupBy, sortOn)-import Data.Function (on)--data User = User { userName :: String, userRole :: String }--users :: [User]-users =- [ User "Alice" "Admin"- , User "Bob" "User"- , User "Tom" "User"- ]--putStrLn $ render $ section "Users by Role"- [ layout- [ box (userRole (head grp)) [ul [text (userName u) | u <- grp]]- | grp <- groupBy ((==) `on` userRole) (sortOn userRole users)- ]- ]-```-```-=== Users by Role ===-┌──Admin──┐-│ • Alice │-└─────────┘-┌──User──┐-│ • Bob │-│ • Tom │-└────────┘-```--## REPL--Drop into GHCi to experiment:-```bash-cabal repl-```--```haskell-λ> :set -XOverloadedStrings-λ> import Layoutz-λ> putStrLn $ render $ center $ box "Hello" ["World!"]-┌──Hello──┐-│ World! │-└─────────┘-λ> putStrLn $ render $ table ["A", "B"] [["1", "2"]]-┌───┬───┐-│ A │ B │-├───┼───┤-│ 1 │ 2 │-└───┴───┘-```--## Interactive Apps--`LayoutzApp` uses the [Elm Architecture](https://guide.elm-lang.org/architecture/) where your-view is a `layoutz` `Element`.--```haskell-data LayoutzApp state msg = LayoutzApp- { appInit :: (state, Cmd msg) -- Initial state + startup command- , appUpdate :: msg -> state -> (state, Cmd msg) -- Pure state transitions- , appSubscriptions :: state -> Sub msg -- Event sources- , appView :: state -> L -- Render to UI- }-```--Three daemon threads coordinate rendering (~30fps), tick/timers, and input capture. State updates flow through `appUpdate` synchronously.--Press **ESC** to exit.--### App Options--Customise how your app runs with `runAppWith` and the `AppOptions` record. Override only the fields you need:--```haskell-runApp app -- Default options-runAppWith defaultAppOptions { optAlignment = AppAlignCenter } app -- Centered in terminal-runInline app -- Animate in-place, no alt screen-```--`runInline` renders the app below existing terminal output without clearing the screen. Useful for embedding progress bars or spinners in build scripts... use `CmdExit` to quit programmatically.--Terminal width is detected once at startup via ANSI cursor position report (zero dependencies).--### Subscriptions--```haskell-subKeyPress (\key -> ...) -- Keyboard input-subEveryMs 100 msg -- Periodic ticks (interval in ms)-subBatch [sub1, sub2, ...] -- Combine subscriptions-```--### Commands--```haskell-CmdNone -- No effect-CmdExit -- Quit the app gracefully-cmdFire (writeFile "log.txt" "entry") -- Fire and forget IO-cmdTask (readFile "data.txt") -- IO that returns a message-cmdAfterMs 500 msg -- Fire a message after delay (ms)-CmdBatch [cmd1, cmd2, ...] -- Combine multiple commands-```--**Example: Logger with file I/O**-```haskell-import Layoutz--data Msg = Log | Saved-data State = State { count :: Int, status :: String }--loggerApp :: LayoutzApp State Msg-loggerApp = LayoutzApp- { appInit = (State 0 "Ready", CmdNone)- , appUpdate = \msg s -> case msg of- Log -> (s { count = count s + 1 },- cmdFire $ appendFile "log.txt" ("Entry " <> show (count s) <> "\n"))- Saved -> (s { status = "Saved!" }, CmdNone)- , appSubscriptions = \_ -> subKeyPress $ \key -> case key of- KeyChar 'l' -> Just Log- _ -> Nothing- , appView = \s -> layout- [ section "Logger" [text $ "Entries: " <> show (count s)]- , text (status s)- , ul ["'l' to log", "ESC to quit"]- ]- }--main = runApp loggerApp-```--### Key Types--```haskell--- Printable-KeyChar Char -- 'a', '1', ' '---- Editing-KeyEnter-KeyBackspace-KeyTab-KeyEscape-KeyDelete---- Navigation-KeyUp-KeyDown-KeyLeft-KeyRight-KeyPageUp-KeyPageDown-KeyHome-KeyEnd---- Modifiers-KeyCtrl Char -- Ctrl+'C', Ctrl+'Q', etc.-KeySpecial String -- Other unrecognized sequences-```--## Prompts (Ask)--You often just want a one-shot CLI prompt (a spinner, a filter, a file picker)-without dropping into "Elm-territory" and thinking about a whole flipbook each time.--**layoutz** offers one-shot interactive actions with the `ask*` family. Each takes-over the tty briefly, returns a value, and leaves a single committed line behind.-`Nothing` means the user cancelled (Esc / Ctrl-C / Ctrl-D).--```haskell-import Layoutz-import Control.Concurrent (threadDelay)--main :: IO ()-main = do- name <- askInput "Name › " "anonymous" ""- ok <- askConfirm "Venture on the quest?" True "Yes" "No"- realm <- askChoose "Choose a realm" ["The Shire", "Rivendell", "Mirkwood", "Lake-town", "Erebor"] id- packs <- askChooseMany "Pack provisions" ["lembas", "pipe-weed", "waybread", "miruvor", "rope"] 3 id- riddle <- askWrite "Pose a multi-line riddle" "This thing all things devours…" "" "Ctrl-D to save"- member <- askFilter "Search > " ["Bilbo", "Balin", "Dwalin", "Thorin", "Gandalf"] 8 id- path <- askFile "." 12- askPager longString 0 True- answer <- askSpin "Awaking Smaug…" SpinnerDots (do threadDelay 1500000; pure (42 :: Int))- pure ()-```--<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/ask-mini.gif" width="650">-</p>--Each `ask*` returns in `IO`... and a `Maybe` if the user can cancel midway:--```haskell-askInput prompt placeholder initial -- IO (Maybe String)-askConfirm question default yes no -- IO Bool-askChoose prompt items render -- IO (Maybe a)-askChooseMany prompt items limit render -- IO (Maybe [a])-askWrite prompt placeholder initial hint -- IO (Maybe String)-askFilter prompt items height render -- IO (Maybe a)-askFile start height -- IO (Maybe String)-askPager content height lineNumbers -- IO ()-askSpin label style task -- IO a-```--## Progress (loader)--Wrap any list with `loader` to get a live progress bar while you process it: map-an `IO` action over each item. Unbounded work gets `loaderStream`, a spinner-with a running count.--```haskell-_ <- loader "Resizing" imageFiles resize-_ <- loader "Inserting" rows insertRow-_ <- loaderStream "Tailing" logLines indexLine-```--Pick a `LoaderStyle` with `loaderStyled` / `loaderStreamStyled`-```-styleBlocks -- (default)-styleBar-styleAscii-styleDots-styleLine-stylePipes-LoaderStyle { .. } -- (custom)-```--```haskell-_ <- loaderStyled styleAscii "Reindexing" docIds reindex-_ <- loaderStyled stylePipes "Crawling" urls fetch-```--Every built-in style, then an unbounded stream:--```haskell-import Layoutz-import Control.Concurrent (threadDelay)--main :: IO ()-main = do- _ <- loaderStyled styleBlocks "Blocks " [1..60] (const (threadDelay 16000))- _ <- loaderStyled styleDots "Dots " [1..60] (const (threadDelay 16000))- _ <- loaderStyled styleLine "Line " [1..60] (const (threadDelay 16000))- _ <- loaderStyled stylePipes "Pipes " [1..60] (const (threadDelay 16000))- _ <- loaderStyled styleBar "Bar " [1..60] (const (threadDelay 16000))- _ <- loaderStyled styleAscii "Ascii " [1..60] (const (threadDelay 16000))- _ <- loaderStream "Streaming" [1..90] (const (threadDelay 45000))- pure ()-```--<p align="center">- <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/loader.gif" width="600">-</p>--## Examples--Small, copy-pasteable snippets for everyday CLI chores.--<details>-<summary>Print a deploy / status summary (<code>section</code> + <code>statusCard</code> + <code>kv</code>)</summary>--```haskell-import Layoutz--main :: IO ()-main = putStrLn $ render $ section "Deploy"- [ row- [ withColor ColorGreen $ statusCard "build" "OK"- , withColor ColorGreen $ statusCard "tests" "142 ✓"- , withColor ColorYellow $ statusCard "deploy" "staging"- ]- , kv [("commit", "a1b2c3d"), ("branch", "master"), ("by", "matt")]- ]-```-</details>--<details>-<summary>Compiler-style error message (<code>margin</code> + <code>underline'</code>)</summary>--```haskell-import Layoutz--main :: IO ()-main = putStrLn $ render $ margin "error:"- [ text "type mismatch"- , row [text "let x: Int = ", underline' "^" (text "getString()")]- , text " expected Int, found String"- ]--- error: type mismatch--- error: let x: Int = getString()--- ^^^^^^^^^^^^--- error: expected Int, found String-```-</details>--<details>-<summary>Render a table straight from records (<code>table</code>)</summary>--```haskell-import Layoutz--data Svc = Svc { svcName :: String, svcStatus :: String, svcCpu :: String }--svcs :: [Svc]-svcs =- [ Svc "api" "up" "23%"- , Svc "db" "up" "61%"- , Svc "cache" "down" "0%"- ]--main :: IO ()-main = putStrLn $ render $ table ["Service", "Status", "CPU"]- [ [text (svcName s), text (svcStatus s), text (svcCpu s)] | s <- svcs ]-```-</details>--<details>-<summary>Progress bar over a batch of work (<code>loader</code>)</summary>--```haskell-import Layoutz-import Control.Concurrent (threadDelay)--main :: IO ()-main = do- let files = ["a.png", "b.png", "c.png"]- _ <- loader "Resizing" files $ \f -> threadDelay 200000 -- your IO per item- putStrLn "done"-```-</details>--<details>-<summary>Gate a destructive action behind a confirm (<code>askConfirm</code>)</summary>--```haskell-import Layoutz--main :: IO ()-main = do- ok <- askConfirm "Drop production table?" False "Yes" "No"- if ok then putStrLn "dropping…" else putStrLn "cancelled"-```-</details>--<details>-<summary>Wrap a slow query in a spinner (<code>askSpin</code>)</summary>--```haskell-import Layoutz-import Control.Concurrent (threadDelay)--main :: IO ()-main = do- rows <- askSpin "Querying…" SpinnerDots runQuery- putStrLn $ render $ section "Result" [text $ show rows <> " rows"]- where- runQuery = do- threadDelay 1500000 -- stand-in for your slow IO- pure (1234 :: Int)-```-</details>--## Contributing--You need [GHC](https://www.haskell.org/ghcup/) (8.10+) and [Cabal](https://www.haskell.org/cabal/).--```bash-make build # build library-make test # run tests-make repl # GHCi with layoutz loaded-make clean # clean build artifacts-```--Fork, make your change, `make test`, open a PR. Keep it zero-dep.--## Inspiration-- Original Scala [layoutz](https://github.com/mattlianje/layoutz)+ <sub><em>part of <a href="https://github.com/mattlianje/cabinet6"><img src="https://raw.githubusercontent.com/mattlianje/cabinet6/master/pix/d4.png" width="20" align="top" hspace="4">c6</a></em></sub>+</div>++# <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz.png" width="60"> layoutz++**Simple, beautiful CLI output**++A lightweight, zero-dep lib to build compositional ANSI strings, terminal plots, and inline or+full-screen Elm-style TUIs in pure Haskell. You can use [Layoutz.hs](https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/Layoutz.hs) like a header file.+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/showcase-raymarcher-loop.gif" width="600">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/ShowcaseApp.hs">ShowcaseApp.hs</a></sub>+</p>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-demo-repl.png" width="600">+</p>++## Features+- Zero dependencies+- Elm-style TUIs: mouse, focus, popups+- Layout primitives: tables, trees, lists+- CJK widths+- Colors, ANSI styles+- Terminal charts and plots+- Widgets: select lists, viewports, buttons, spinners, progress bars+- One-shot prompts, and progress wrappers+- Kitty graphics support+- Custom elements are just functions+- Easy porting to MicroHs++## Installation+[](https://hackage.haskell.org/package/layoutz)+```haskell+build-depends: layoutz+```+Or try it in a REPL:+```bash+cabal repl --build-depends layoutz+```+All you need is one import:+```haskell+import Layoutz+```++## Core concepts+- Everything you draw is a `View m`, `render` gives you back an ANSI String.+- Make a custom element that composes with the built-ins by writing any function that returns a `View`.+- `m` is the message a view sends when it's [clicked](#mouse) or scrolled.+- `View`s are functors, so `fmap ChildMsg` embeds a child view in its parent.++## Of note...+- With LLMs, boilerplate code that formats & "pretty-prints" is cheaper than ever...+- Thus, more than ever, "string formatting code" is spawning, and polluting domain logic.+- Ultimately, layoutz is just a tiny, declarative DSL to combat this.+- On the side, layoutz also has an Elm-style runtime to bring these arbitrary Elements to life: much like a flipbook.+ - The runtime has some little niceties built-in like common cmds for IO, timers, and a key input handler.+- But at the end of the day, you can use layoutz merely to structure Strings (without any of the TUI stuff).++## Build TUIs+Just fill in a **LayoutzApp**, then call `runApp`:+```haskell+data LayoutzApp model msg = LayoutzApp+ { appInit :: (model, Cmd msg)+ , appUpdate :: msg -> model -> (model, Cmd msg)+ , appSubscriptions :: model -> Sub msg+ , appView :: model -> View msg+ }+```+Out of the box you get:+- Adaptive views, viewports and overlays+- Mouse, focus and ready-made widgets+- Commands, subscriptions, timers and key input++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/showcase-tour.gif" width="600">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/ShowcaseApp.hs">ShowcaseApp.hs</a></sub>+</p>++It scales up to fancier things too, like a tiling workspace with splits, zoom, focus and a fuzzy+finder in a short file:++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/tile-finder.gif" width="600">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/TileDemo.hs">TileDemo.hs</a></sub>+</p>++## Draw plots+```haskell+sine = plotLine 50 12 [Series points "sin(x)" ColorBrightCyan]+ where points = [(x, 5 * sin x) | x <- [0, 0.15 .. 7.5]]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/hs-plot.png" width="500">+</p>++## Prompt the user+You often want one-shot CLI prompts with pickers, file pickers, fuzzy-finders, pagers, etc... without dropping+down into Elm-territory to make them. This is why layoutz has the `ask*` helpers.+```haskell+name <- askInput "Name › " "anonymous" ""+realm <- askChoose "Choose a realm" ["The Shire", "Rivendell", "Mirkwood"] id+member <- askFilter "Search a companion › " ["Bilbo", "Gandalf", "Thorin"] 8 id+riddle <- askWrite "Pose a riddle"+ "This thing all things devours…" "" "Ctrl-D to save"+quest <- askConfirm "Venture on the quest?" True "Yes" "No"+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/hs-ask-mini.gif" width="600">+</p>++## Show progress bars+Wrap any list with `loader` for a live bar, or use `loaderStream` for a spinner.+```haskell+_ <- loader "Resizing" files resize+_ <- loaderStream "Tailing" logLines indexLine+n <- askSpin "Awaking Smaug…" SpinnerDots (threadDelay 1500000 >> pure 42)+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/hs-loader.gif" width="600">+</p>+++## Layoutz vs Brick+[Brick](https://github.com/jtdaugherty/brick) is a mighty and tested library,+where you will find more prior art. Layoutz aims to do some things differently:+- One header file with no deps you can easily vendor for yourself+- A simple, familiar Elm-style model (no vty to learn)+ - `update` is a pure function returning `(model, Cmd msg)`, not `EventM` codes+- Styles go on your views and are compositional w/ no "attribute map"+- Inline apps, one-shot prompts are built in++## Performance+Layoutz is fast (5X faster than Go's Bubbletea) and nimble, with a low memory footprint. Methodology and sources in [bench/](https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/bench/README.md)++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/layoutz-hs/bench/results.svg" width="700">+</p>++## Reference++- [Borders](#borders)+- [Elements](#elements)+ - [Layout](#layout)+ - [Content](#content)+- [Custom elements](#custom-elements)+- [Views from data](#views-from-data)+- [Colors](#colors)+- [Styles](#styles)+- [Charts & plots](#charts--plots)+- [Interactive apps](#interactive-apps)+ - [Options](#options)+ - [Resizing](#resizing)+ - [Keys](#keys)+ - [Subscriptions](#subscriptions)+ - [Commands](#commands)+ - [Mouse](#mouse)+ - [Focus](#focus)+ - [Widgets](#widgets)+- [Prompts](#prompts)+- [Progress bars](#progress-bars)++++## Borders++Applied with `border` to `box`, `banner`, `statusCard` and `table` (anything else is left alone):+```haskell+box "Info" ["content"] & border BorderRound+statusCard "API" "UP" & border BorderDouble+table ["Name"] [["Alice"]] & border BorderThick+```++You can partially apply it to make your own shorthands:+```haskell+thick :: View m -> View m+thick = border BorderThick+```++```haskell+BorderNormal -- ┌─┐ (default)+BorderDouble -- ╔═╗+BorderThick -- ┏━┓+BorderRound -- ╭─╮+BorderAscii -- +-++BorderBlock -- ███+BorderDashed -- ┌╌┐+BorderDotted -- ┌┈┐+BorderInnerHalfBlock -- ▗▄▖+BorderOuterHalfBlock -- ▛▀▜+BorderMarkdown -- |-|+BorderCustom "+" "=" "|" -- Custom border+BorderNone -- No borders+```++## Elements++### Layout++#### Stacking & rows+```haskell+vstack ["First", "Second", "Third"]+-- First+-- Second+-- Third++row ["Left", "Middle", "Right"]+-- Left Middle Right++row [vstack ["A", "B"], vstack ["C", "D"]] & gap 2+-- A C+-- B D++row ["A", "B", "C"] & gap 0+-- ABC+```++#### Spacing & rules+```haskell+vstack ["Line 1", br, "Line 2"]++hr -- default ──────────...+hr & glyph "~" -- custom char+hr & glyph "=" & size 20 -- ====================++vr -- vertical rule, 10 high with │+vr & glyph "║" -- custom char+vr & glyph "|" & size 5 -- custom char + height+```++#### Sizing+Views draw at their natural size. `fill` makes one take the room its parent offers: the leftover+width of a `row`, the leftover height of a `vstack`, or the whole terminal at an app's root (see+[Resizing](#resizing)).++```+fill view -- take the room the parent offers+fixedWidth 20 view -- exactly 20 wide: padded or cut+fixedHeight 5 view -- exactly 5 tall+sized (\w h -> view) -- built from the room it gets, redrawn on resize+renderIn 80 24 view -- render with 80x24 of room, like an app's root+width view -- natural size in cells+height view+```++#### Overlays+`overlay base top` draws `top` centred over `base`, for popups and dialogs. Where it covers the+base, it takes the clicks.+```haskell+overlay (screen m & styleDim)+ (box "Quit?" [row [button "yes" Quit, button "no" Stay]])+```++#### Text transforms+```haskell+center "Auto-centered" -- centred against the widest sibling+centerIn 20 "TITLE" -- │ TITLE │+alignLeft 20 "Left" -- │Left │+alignRight 20 "Right" -- │ Right│++justify 30 "Spread this out"+-- │Spread this out│++wrap 20 "Long text here that should wrap"+-- Long text here that+-- should wrap++clip 15 "Very long text that will be cut off" -- Very long te...+clip 20 "Custom ellipsis example text here" & ellipsis "…"+-- Custom ellipsis exa…++pad 2 "content" -- 2 cells of padding all around++underline "Title" -- Title+ -- ─────+underline "Custom" & glyph "=" -- Custom+ -- ======+underline "Fancy" & glyph "~" & accent ColorCyan++vstack+ [ "Ooops!"+ , row ["val result: Int = ", underline "getString()" & glyph "^"]+ , "Expected Int, found String"+ ] & margin "[error]"+-- [error] Ooops!+-- [error] val result: Int = getString()+-- [error] ^^^^^^^^^^^+-- [error] Expected Int, found String+```++### Content++#### Text, sections & key-values+```haskell+text "hello"+"hello" -- same, with OverloadedStrings++section "Status" ["All systems operational"]+-- === Status ===+-- All systems operational+section "Status" ["ok"] & glyph "-" -- --- Status ---+section "Report" ["42"] & glyph "#" & size 5 -- ##### Report #####++kv [("Name", "Alice"), ("Age", "30"), ("City", "NYC")]+-- Name: Alice+-- Age: 30+-- City: NYC+```++#### Boxes, cards & banners+```haskell+box "Status" ["All systems go"]+-- ┌─────Status─────┐+-- │ All systems go │+-- └────────────────┘++box "Fancy" ["Double border"] & border BorderDouble+-- ╔═════Fancy═════╗+-- ║ Double border ║+-- ╚═══════════════╝++box "Smooth" ["Rounded corners"] & border BorderRound+-- ╭─────Smooth──────╮+-- │ Rounded corners │+-- ╰─────────────────╯++row [ statusCard "CPU" "45%" & fg ColorGreen+ , statusCard "MEM" "2.1G" & fg ColorCyan+ ]+-- ┌───────┐ ┌────────┐+-- │ CPU │ │ MEM │+-- │ 45% │ │ 2.1G │+-- └───────┘ └────────┘++banner ["System Dashboard"]+-- ╔══════════════════╗+-- ║ System Dashboard ║+-- ╚══════════════════╝+```++#### Lists & trees+```haskell+ul ["Backend", ul ["API", ul ["REST", "GraphQL"], "DB"], "Frontend"]+-- • Backend+-- ◦ API+-- ▪ REST+-- ▪ GraphQL+-- ◦ DB+-- • Frontend++ol ["Setup", ol ["Install deps", ol ["npm", "pip"], "Configure"], "Deploy"]+-- 1. Setup+-- a. Install deps+-- i. npm+-- ii. pip+-- b. Configure+-- 2. Deploy++tree "Project"+ [ branch "src" [leaf "main.hs", leaf "test.hs"]+ , branch "docs" [leaf "README.md"]+ ]+-- Project+-- ├── src+-- │ ├── main.hs+-- │ └── test.hs+-- └── docs+-- └── README.md+```++#### Table+```haskell+table ["Name", "Age", "City"]+ [ ["Alice", "30", "New York"]+ , ["Bob", "25", ""]+ , ["Charlie", "35", "London"]+ ]+```+```+┌─────────┬─────┬──────────┐+│ Name │ Age │ City │+├─────────┼─────┼──────────┤+│ Alice │ 30 │ New York │+│ Bob │ 25 │ │+│ Charlie │ 35 │ London │+└─────────┴─────┴──────────┘+```++#### Progress & spinners+```haskell+inlineBar "Download" 0.75+-- Download [███████████████─────] 75%++chart [("Web", 10), ("Mobile", 20), ("API", 15)]+-- Web │████████████████████────────────────────│ 10+-- Mobile │████████████████████████████████████████│ 20+-- API │██████████████████████████████──────────│ 15++-- frame is an Int you bump on each tick+spinner "Loading" frame SpinnerDots -- ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏+spinner "Loading" frame SpinnerLine -- | / - \+spinner "Loading" frame SpinnerClock -- 🕐 🕑 🕒 🕓 🕔 🕕 🕖 🕗 🕘 🕙 🕚 🕛+spinner "Loading" frame SpinnerBounce -- ⠁ ⠂ ⠄ ⠂+spinner "Loading" frame SpinnerEarth -- 🌍 🌎 🌏+spinner "Loading" frame SpinnerMoon -- 🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘+spinner "Loading" frame SpinnerGrow -- ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ ▉ ▊ ▋ ▌ ▍ ▎+spinner "Loading" frame SpinnerArrow -- ← ↖ ↑ ↗ → ↘ ↓ ↙+```++#### Inline images++Inline raster images via the [kitty protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/).++```haskell+img <- kittyImageFile "pix/sakuraba.png" 35 14 -- PNG sized to 35×14 cells++putStrLn $ render $ row+ [ box "the gracie hunter" [img] & border BorderRound+ , box "stats"+ [kv [("flying", "yes"), ("opponent", "grounded"), ("rules", "PRIDE")]]+ ]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/haskell-kitty-1.png" width="600">+</p>++Build straight from bytes or raw pixels:++```haskell+kittyImage bytes 35 14 -- PNG bytes -> cols rows+kittyRGB pixels w h 18 9 -- raw RGB pxW pxH -> cols rows+kittyRGBA pixels w h 18 9 -- raw RGBA pxW pxH -> cols rows+```++<details>+<summary>Code</summary>++```haskell+let (w, h) = (96, 96)+ pixels = [ channel i | i <- [0 .. w * h * 4 - 1] ]+ channel i =+ let p = i `div` 4; x = p `mod` w; y = p `div` w+ in fromIntegral $ case i `mod` 4 of+ 0 -> x * 255 `div` w+ 1 -> y * 255 `div` h+ 2 -> 255 - (x * 255 `div` w)+ _ -> 255++putStrLn $ render $ box "gradient" [kittyRGBA pixels w h 18 9]+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/haskell-kitty-2.png" width="600">+</p>++You'll need a terminal that supports kitty graphics (kitty, WezTerm, Ghostty).++## Custom elements++A custom element is just a function that returns a `View`:++```haskell+square :: Int -> View m+square size+ | size < 2 = ""+ | otherwise = vstack (map text (top : middle ++ [bottom]))+ where+ w = size * 2 - 2+ top = "┌" ++ replicate w '─' ++ "┐"+ middle = replicate (size - 2) ("│" ++ replicate w ' ' ++ "│")+ bottom = "└" ++ replicate w '─' ++ "┘"++-- Use it like any other element+putStrLn $ render $ row [square 3, square 5, square 7]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-squares.png" width="600">+</p>++## Views from data+Since views are plain values you can leverage the full power of Haskell's functional collections to generate them:+```haskell+import Data.List (groupBy, sortOn)+import Data.Function (on)++data User = User { userName :: String, userRole :: String }++users :: [User]+users =+ [ User "Alice" "Admin"+ , User "Bob" "User"+ , User "Tom" "User"+ ]++putStrLn $ render $ section "Users by Role"+ [ vstack+ [ box (userRole (head grp)) [ul [text (userName u) | u <- grp]]+ | grp <- groupBy ((==) `on` userRole) (sortOn userRole users)+ ]+ ]+```+```+=== Users by Role ===+┌──Admin──┐+│ • Alice │+└─────────┘+┌──User──┐+│ • Bob │+│ • Tom │+└────────┘+```++## Colors++```haskell+vstack+ [ "The quick brown fox..." & fg ColorRed+ , "The quick brown fox..." & fg ColorBrightCyan+ , underline "The quick brown fox..." & glyph "~" & accent ColorRed+ , "The quick brown fox..." & fg ColorCyan & margin "[INFO]"+ ]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-color-2.png" width="700">+</p>+++```haskell+ColorBlack+ColorRed+ColorGreen+ColorYellow+ColorBlue+ColorMagenta+ColorCyan+ColorWhite+ColorBrightBlack -- ... and the other bright variants+ColorBrightRed+ColorBrightGreen+ColorBrightYellow+ColorBrightBlue+ColorBrightMagenta+ColorBrightCyan+ColorBrightWhite+ColorFull 196 -- 256-color palette (0-255)+ColorTrue 255 128 0 -- 24-bit RGB+ColorDefault -- no color (charts pick one from their palette)+```++### Gradients++<details>+<summary>Code</summary>++```haskell+let strip f xs = row [fg (f i) "█" | i <- xs] & gap 0+ palette = strip ColorFull [16, 19 .. 205]+ redToBlue = strip (\i -> ColorTrue i 100 (255 - i)) [0, 4 .. 255]+ greenFade = strip (\i -> ColorTrue 0 (255 - i) i) [0, 4 .. 255]+ rainbow = strip colorAt [0, 4 .. 255]+ colorAt i =+ let r = if i < 128 then i * 2 else 255+ g = if i < 128 then 255 else (255 - i) * 2+ b = if i > 128 then (i - 128) * 2 else 0+ in ColorTrue r g b++putStrLn $ render $ vstack [palette, redToBlue, greenFade, rainbow]+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-color-1.png" width="700">+</p>++## Styles++```haskell+vstack+ [ "The quick brown fox..." & styleBold+ , "The quick brown fox..." & styleBold & fg ColorRed+ , "The quick brown fox..." & styleItalic & styleReverse+ ]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-styles-1.png" width="700">+</p>++```haskell+styleBold+styleDim+styleItalic+styleUnderline+styleBlink+styleReverse+styleHidden+styleStrikethrough+```++You can chain them:++```haskell+vstack+ [ "The quick brown fox..." & styleBold & styleItalic & styleUnderline+ , "The quick brown fox..." & styleBold & styleReverse+ ]+```+<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-styles-2.png" width="700">+</p>++You can mix colors into the chain too:++```haskell+"The quick brown fox..." & styleBold & styleItalic & fg ColorBrightYellow+```++## Charts & plots++```haskell+plotLine w h [Series points label color]+plotPie w h [Slice value label color]+plotBar w h [BarItem value label color]+plotStackedBar w h [StackedBarGroup [BarItem] label]+plotHeatmap (HeatmapData rows rowLabels colLabels) -- or plotHeatmap' cellW+chart [(label, value)]+plotSparkline [Double]+```++<details>+<summary>Code</summary>++```haskell+sinPts = [(x, sin (x * 0.15) * 5) | x <- [0 .. 60]]+cosPts = [(x, cos (x * 0.15) * 5) | x <- [0 .. 60]]++charts = vstack+ [ row+ [ panel "plotLine"+ [ plotLine 52 10+ [ Series sinPts "sin(x)" ColorBrightCyan+ , Series cosPts "cos(x)" ColorBrightMagenta+ ]+ ]+ , panel "plotPie"+ [ plotPie 32 8+ [ Slice 50 "Liquor" ColorDefault, Slice 20 "Protein" ColorDefault+ , Slice 10 "Water" ColorDefault, Slice 20 "Fun" ColorDefault+ ]+ ]+ ]+ , row+ [ panel "plotBar"+ [ plotBar 42 9+ [ BarItem 100 "Mon" ColorBrightBlue+ , BarItem 120 "Tue" ColorBrightMagenta+ , BarItem 110 "Wed" ColorBrightCyan+ , BarItem 85 "Thu" ColorBrightYellow+ ]+ ]+ , panel "plotStackedBar"+ [ plotStackedBar 42 7+ [ StackedBarGroup (quarters 30 20 25) "2023"+ , StackedBarGroup (quarters 35 25 30) "2024"+ , StackedBarGroup (quarters 40 30 35) "2025"+ ]+ ]+ ]+ , row+ [ panel "plotHeatmap"+ [ plotHeatmap' 5 $ HeatmapData+ [ [12, 15, 22, 28, 30, 25]+ , [14, 18, 25, 32, 35, 28]+ , [10, 13, 20, 26, 28, 22]+ , [16, 20, 27, 31, 30, 33]+ ]+ ["Mon", "Tue", "Wed", "Thu"]+ ["6am", "9am", "12pm", "3pm", "6pm", "9pm"]+ ]+ , vstack+ [ panel "chart" [chart [("Web", 10), ("Mobile", 20), ("API", 15)]]+ , panel "plotSparkline"+ [ plotSparkline [1, 4, 2, 8, 5, 7, 3, 6, 9, 4, 6, 8, 5, 9]+ & fg ColorBrightGreen+ ]+ ]+ ]+ ]++panel title body = box title body & border BorderRound++quarters q1 q2 q3 =+ [ BarItem v q ColorDefault | (v, q) <- zip [q1, q2, q3] ["Q1", "Q2", "Q3"] ]++putStrLn $ render charts+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/pix/layoutz-charts-hs.png" width="700">+</p>++See also [Granite](https://github.com/mchav/granite) for terminal plots in Haskell - which was the+inspiration here.++## Interactive apps++`LayoutzApp` is just a lightweight [TEA](https://guide.elm-lang.org/architecture/) runtime+with 5 green threads and a layoutz `View` as the view.++```haskell+data LayoutzApp model msg = LayoutzApp+ { appInit :: (model, Cmd msg) -- start+ , appUpdate :: msg -> model -> (model, Cmd msg) -- pure+ , appSubscriptions :: model -> Sub msg -- keys, timers+ , appView :: model -> View msg -- draw+ }+```++`sandbox` is a shorthand for little animation apps with no commands or subscriptions:++```haskell+sandbox :: model+ -> (msg -> model -> model)+ -> (model -> View msg)+ -> LayoutzApp model msg+```++### Options++```haskell+runApp app -- full screen, default options+runInline app -- animate in place, no alt screen++-- centred, and returns the final model+run defaultOptions { optAlignment = AppAlignCenter } app+```++```haskell+data Options = Options+ { optAlignment :: AppAlignment -- AppAlignLeft (default), Center, Right+ , optInline :: Bool -- draw under the current output+ , optQuitKeys :: [Key] -- default [KeyEscape, KeyCtrl 'D']+ , optMaxFps :: Int -- frame cap, default 60+ }+```++### Resizing++You often want views that keep their size at rest, but grow and shrink when the terminal+resizes.++This is why layoutz has `fill` and `sized` (see [Sizing](#sizing)). At an app's root, `fill`+takes the whole terminal, and `sized` views are rebuilt from the room they get on every resize.++```haskell+import Layoutz++main :: IO ()+main = runApp $ sandbox () (\_ m -> m) $ \_ ->+ row+ [ box "nav" ["home", "logs", "plots"] & fixedWidth 12+ , box "wave" [sized wave & fill] & fill+ ] & fill+ where+ wave w h = plotLine (w - 6) (h - 4) [Series points "sin" ColorCyan]+ where points = [(x, sin x) | x <- [0, 0.05 .. fromIntegral w / 3]]+```++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/sizing-mini.gif" width="600">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/SizingMini.hs">SizingMini.hs</a></sub>+</p>++### Keys++```haskell+-- Printable+KeyChar Char -- 'a', '1', ' '++-- Editing+KeyEnter+KeyBackspace+KeyTab+KeyEscape+KeyDelete++-- Navigation+KeyUp+KeyDown+KeyLeft+KeyRight+KeyPageUp+KeyPageDown+KeyHome+KeyEnd++-- Modifiers+KeyCtrl Char -- Ctrl+'C', Ctrl+'Q', etc.+KeySpecial String -- Everything else: F-keys, Ctrl-arrows, Alt-keys...+```++### Subscriptions++```haskell+subKeyPress (\key -> ...) -- Keyboard input+subEveryMs 100 msg -- Periodic ticks (interval in ms)+subAnimationFrame Frame -- Every frame, with the time in seconds+subNone -- Nothing+sub1 <> sub2 -- Combine (or mconcat); all handlers see all keys+```++### Commands++```haskell+cmdNone -- No effect+cmdQuit -- Quit, once the other effects ran+cmdFire (writeFile "log.txt" "entry") -- Fire and forget IO+cmdTask (readFile "data.txt") -- IO whose result comes back+cmdAfterMs 500 msg -- Send a message after 500 ms+cmd1 <> cmd2 -- Combine (or mconcat)+executeCmd cmd -- Run the effects now, get the messages (for tests)+```++View, Cmd and Sub are all Functors, so you can embed a child component with `fmap ChildMsg`.++### Mouse++Mouse support usually means parsing escape codes and working out what's under the cursor. ++This is why layoutz has `onClick` and `onScroll` (+ the below functions). Put them on any view, and clicks and scrolls come back as+messages.++```+onClick msg -- left click+onScroll (\notches -> msg) -- wheel: +1 per notch down, -1 up+button "label" msg -- clickable label+clickAt (row, col) view -- what a click would send, no tty+scrollAt 1 (row, col) view -- what a wheel notch would send+```++This example shows you all you need to know about mouse handling (clicks, and scrolls):++```haskell+import Layoutz++data Msg = Inc | Dec | Reset++main :: IO ()+main = runApp $ sandbox (0 :: Int) step $ \n ->+ box "counter" [row [button "-" Dec, display n, button "+" Inc]]+ & onScroll (\d -> if d > 0 then Dec else Inc)+ & onClick Reset+ where+ step Inc = (+ 1)+ step Dec = subtract 1+ step Reset = const 0+```++In the gif, teal is a click and pink is a wheel notch over the number.++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/mouse-mini.gif" width="300">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/MouseMini.hs">MouseMini.hs</a></sub>+</p>++### Focus++If you've written Elm-apps with multiple "panes" or "pages" - you know you need to thread where+you are into your state (with "tab" handling and case to hop tabs in every update and view). This gets tedious... fast.++This is why layoutz has `focusable` and the below functions. You can name a view and the runtime tracks focus for you: Tab and+Shift-Tab cycle, a click focuses.++```+focusable "logs" -- can hold the keyboard: Tab, Shift-Tab, click+focusStyle (border BorderDouble) -- only drawn while focused+onKey (\k -> Just msg) -- keys while focused+cmdFocus "logs" -- move focus from appUpdate+subFocus Focused -- hear about it when focus moves+pressKey (Just "logs") KeyDown view -- what a key would send, no tty+focusOrder view -- the Tab order+```++<details>+<summary>Code</summary>++```haskell+import Layoutz++data Msg = Add Int Int | Next Int | Reset | Focused String++main :: IO ()+main = runApp LayoutzApp+ { appInit = (([0, 0, 0], "a"), cmdNone)+ , appUpdate = \msg (ns, f) -> case msg of+ Add i d -> ((bump i d ns, f), cmdNone)+ Next i -> ((ns, f), cmdFocus (names !! ((i + 1) `mod` 3)))+ Reset -> ((map (const 0) ns, f), cmdNone)+ Focused n -> ((ns, n), cmdNone)+ , appSubscriptions = const (subFocus Focused)+ , appView = \(ns, f) -> vstack+ [ row (zipWith3 pane [0 ..] names ns)+ , text ("focus: " <> f) & styleDim+ ] & onKey (\k -> if k == KeyChar 'r' then Just Reset else Nothing)+ }+ where+ names = ["a", "b", "c"]+ bump i d = zipWith (\j n -> if i == j then n + d else n) [0 ..]+ pane i name n = box name [display n] & fixedWidth 10+ & focusable name+ & focusStyle (fg ColorCyan . border BorderDouble)+ & onKey (\k -> case k of+ KeyUp -> Just (Add i 1)+ KeyDown -> Just (Add i (-1))+ KeyEnter -> Just (Next i)+ _ -> Nothing)+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/focus-mini.gif" width="480">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/FocusMini.hs">FocusMini.hs</a></sub>+</p>++And a slightly more advanced focus demo, with resizing:++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/focus-resize.gif" width="600">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/FocusDemo.hs">FocusDemo.hs</a></sub>+</p>++### Widgets++Another common TUI situation is simply arrowing around a list, or scrolling through a log. The annoying part+is keeping the cursor on screen, which depends on how tall the thing ended up, and `appUpdate` has+no idea.++This is why layoutz has `selectList` and `viewport`. They handle the keys, wheel and clicks, and+work out their next state at draw time, when the size is known.++That state comes back in the+message, so `appUpdate` just stores it.++```+selectList onMove onPick draw list -- arrows, PgUp/PgDn, wheel, click; Enter picks+viewport onScroll state lines -- arrows, PgUp/PgDn, wheel+selectListOf ["api", "worker"] -- a new list+selectedItem list -- Maybe a+viewportBottom -- sticks to the bottom (or viewportTop)+& fill, & fixedHeight n -- room to scroll in+```++<details>+<summary>Example</summary>++```haskell+import Layoutz++data Model = Model (SelectList String) [String] Viewport++data Msg = Moved (SelectList String) | Picked String | Scrolled Viewport++main :: IO ()+main = runApp LayoutzApp+ { appInit = (Model (selectListOf nato) [] viewportBottom, cmdNone)+ , appUpdate = \msg (Model s ls v) -> case msg of+ Moved s' -> (Model s' ls v, cmdNone)+ Picked w -> (Model s (ls <> [w]) v, cmdNone)+ Scrolled v' -> (Model s ls v', cmdNone)+ , appSubscriptions = const subNone+ , appView = \(Model s ls v) -> row+ [ pane "nato" 16 (selectList Moved Picked (pick s) s)+ , pane "picked" 20 (viewport Scrolled v (map text ls))+ ] & fixedHeight 9+ }+ where+ pane name n body = box name [body & fill] & fixedWidth n+ & focusable name+ & focusStyle (fg ColorCyan . border BorderDouble)+ pick s w = text w & if selectedItem s == Just w then styleReverse else id+ nato = words "alfa bravo charlie delta echo foxtrot golf hotel india \+ \juliett kilo lima mike november oscar papa quebec romeo \+ \sierra tango uniform victor whiskey xray yankee zulu"+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/widgets-mini.gif" width="480">+ <br>+ <sub><a href="https://github.com/mattlianje/layoutz/blob/master/layoutz-hs/examples/WidgetsMini.hs">WidgetsMini.hs</a></sub>+</p>++## Prompts++One-shot prompts, no app needed. Each `ask*` takes over the terminal briefly, returns a value,+and leaves a single line behind. `Nothing` means the user cancelled (Esc / Ctrl-C / Ctrl-D).++<details>+<summary>Code</summary>++```haskell+import Layoutz+import Control.Concurrent (threadDelay)++main :: IO ()+main = do+ name <- askInput "Name › " "anonymous" ""+ ok <- askConfirm "Venture on the quest?" True "Yes" "No"+ realm <- askChoose "Choose a realm"+ ["The Shire", "Rivendell", "Mirkwood", "Lake-town", "Erebor"] id+ packs <- askChooseMany "Pack provisions"+ ["lembas", "pipe-weed", "waybread", "miruvor", "rope"] 3 id+ riddle <- askWrite "Pose a multi-line riddle"+ "This thing all things devours…" "" "Ctrl-D to save"+ member <- askFilter "Search > "+ ["Bilbo", "Balin", "Dwalin", "Thorin", "Gandalf"] 8 id+ path <- askFile "." 12+ askPager longString 0 True -- height 0 fills the terminal+ answer <- askSpin "Awaking Smaug…" SpinnerDots+ (threadDelay 1500000 >> pure (42 :: Int))+ pure ()+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/ask-mini.gif" width="650">+</p>++```+askInput prompt placeholder initial -- IO (Maybe String)+askConfirm question default yes no -- IO Bool+askChoose prompt items render -- IO (Maybe a)+askChooseMany prompt items limit render -- IO (Maybe [a])+askWrite prompt placeholder initial hint -- IO (Maybe String)+askFilter prompt items height render -- IO (Maybe a)+askFile start height -- IO (Maybe String)+askPager content height lineNumbers -- IO ()+askSpin label style task -- IO a+```++## Progress bars++```haskell+_ <- loader "Resizing" imageFiles resize+_ <- loader "Inserting" rows insertRow+_ <- loaderStream "Tailing" logLines indexLine+```++Pick a loader style:+```haskell+loaderBlocks -- (default)+loaderBar+loaderAscii+loaderDots+loaderLine+loaderPipes+loaderStyles -- all of the above, as a list+```++```haskell+_ <- loaderStyled loaderAscii "Reindexing" docIds reindex+_ <- loaderStreamStyled loaderPipes "Crawling" urls fetch+```++Or make your own:+```haskell+loaderAscii { lsFill = '#', lsHead = "", lsColor = ColorRed }++data LoaderStyle = LoaderStyle+ { lsFill :: Char -- filled cells+ , lsEmpty :: Char -- empty cells+ , lsOpen :: Text -- left cap, like "["+ , lsClose :: Text -- right cap, like "]"+ , lsHead :: Text -- tip of the fill, like ">"+ , lsSmooth :: Bool -- partial cells at the edge, in eighths+ , lsSpinner :: SpinnerStyle -- used by loaderStreamStyled+ , lsColor :: Color+ }+```++<details>+<summary>All default styles in action</summary>++```haskell+import Layoutz+import Control.Concurrent (threadDelay)++main :: IO ()+main = do+ _ <- loaderStyled loaderBlocks "Blocks " [1..60] (const (threadDelay 16000))+ _ <- loaderStyled loaderDots "Dots " [1..60] (const (threadDelay 16000))+ _ <- loaderStyled loaderLine "Line " [1..60] (const (threadDelay 16000))+ _ <- loaderStyled loaderPipes "Pipes " [1..60] (const (threadDelay 16000))+ _ <- loaderStyled loaderBar "Bar " [1..60] (const (threadDelay 16000))+ _ <- loaderStyled loaderAscii "Ascii " [1..60] (const (threadDelay 16000))+ _ <- loaderStream "Streaming" [1..90] (const (threadDelay 45000))+ pure ()+```++</details>++<p align="center">+ <img src="https://raw.githubusercontent.com/mattlianje/layoutz/refs/heads/master/demos/loader.gif" width="600">+</p>++## Contributing++You need [GHC](https://www.haskell.org/ghcup/) and [Cabal](https://www.haskell.org/cabal/). Layoutz needs text >= 2.1.2, so to use Layoutz.hs as a single file your GHC has to ship with it (9.10.3 does).++```bash+make build # build library+make test # run tests+make repl # GHCi with layoutz loaded+make bench # layoutz vs Bubble Tea, Brick and ratatui+```++Fork, make your change, `make test`, open a PR. Keep it to GHC's boot packages.++## Inspiration+- Original Scala [layoutz](https://github.com/mattlianje/layoutz/tree/master/layoutz-scala)
@@ -0,0 +1,47 @@+{-# LANGUAGE OverloadedStrings #-}++-- | What every program in the bench draws. Frame @k@ changes most numbers.+--+-- Copied in bubbletea/main.go, brick/Main.hs and ratatui/src/main.rs, keep+-- them in sync.+module Dashboard+ ( dashboard+ , dashboardApp+ , Mode (..)+ ) where++import Layoutz++dashboard :: Int -> View m+dashboard k = row+ [ box "Table"+ [ table ["id", "name", "value"]+ [ [text (show i), text ("item" <> show (i + k)), text (show (i * k))] | i <- [1 .. 40 :: Int] ]+ ]+ , vstack+ [ box "Bars"+ [ inlineBar ("b" <> show i) (fromIntegral ((i * k) `mod` 100) / 100) | i <- [1 .. 15 :: Int] ]+ & fg ColorGreen+ , box "Log"+ [ text ("line " <> show (j + k) <> " lorem ipsum dolor sit amet") & fg ColorCyan | j <- [1 .. 20 :: Int] ]+ ]+ ]++-- | 'Idle' only redraws on @+@, 'Busy' also ticks every 10ms.+data Mode = Idle | Busy+ deriving (Eq, Show)++data Msg = Next++dashboardApp :: Mode -> LayoutzApp Int Msg+dashboardApp mode = LayoutzApp+ { appInit = (1, cmdNone)+ , appUpdate = \Next k -> (k + 1, cmdNone)+ , appSubscriptions = \_ -> mconcat+ [ subKeyPress $ \key -> case key of+ KeyChar '+' -> Just Next+ _ -> Nothing+ , if mode == Busy then subEveryMs 10 Next else subNone+ ]+ , appView = dashboard+ }
@@ -0,0 +1,255 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RecordWildCards #-}++{-|+layoutz vs Bubble Tea vs Brick vs ratatui, all drawing Dashboard.hs.++- render: ms per frame, timed inside each program+- the rest: each program running in a 200x60 pty (Pty.hs)++> make bench+> cabal bench --benchmark-options="--bubbletea BIN --brick BIN --ratatui BIN --out bench"++Flags are optional. Writes results.svg and README.md into --out (default: bench).+Runs vary by a few %, only compare rows from the same run.+-}+module Main (main) where++import Control.Exception (evaluate)+import Control.Monad (forM, forM_, replicateM)+import Data.Bifunctor (first, second)+import qualified Data.ByteString.Char8 as BC+import Data.List (sort)+import Data.Maybe (catMaybes)+import Layoutz+import System.Environment (getArgs, getExecutablePath)+import System.Exit (exitFailure)+import System.IO+import System.Process (readProcess)+import Text.Printf (printf)++import Dashboard+import Pty+import Report++main :: IO ()+main = getArgs >>= \case+ -- what the bench spawns for layoutz+ ["--app", "idle"] -> runApp (dashboardApp Idle)+ ["--app", "busy"] -> runApp (dashboardApp Busy)+ args -> maybe usage (uncurry benchmark) (parseArgs args)+ where+ parseArgs = \case+ [] -> Just ([], "bench")+ "--out" : dir : rest -> second (const dir) <$> parseArgs rest+ ('-' : '-' : name) : path : rest+ | name `elem` otherNames -> first (Other name path :) <$> parseArgs rest+ _ -> Nothing+ usage = do+ hPutStrLn stderr "usage: layoutz-bench [--bubbletea PATH] [--brick PATH] [--ratatui PATH] [--out DIR]"+ exitFailure++-- | Another library's dashboard binary.+data Other = Other String FilePath++otherNames :: [String]+otherNames = ["bubbletea", "brick", "ratatui"]++data Subject = Subject+ { subjectName :: String+ , renderTime :: IO Double -- ms per frame+ , program :: FilePath+ , idleArgs :: [String]+ , busyArgs :: [String]+ }++data Results = Results+ { renderMs :: Double+ , idleCpu :: Double -- fraction of one core+ , latencyMs :: [Double]+ , busyCpu :: Double+ , outputKiB :: Double -- per second+ , idleMem :: Memory+ , busyMem :: Memory+ }++screen :: (Int, Int)+screen = (60, 200)++layoutz :: IO Subject+layoutz = do+ self <- getExecutablePath+ pure Subject+ { subjectName = "layoutz"+ , renderTime = layoutzRenderTime+ , program = self+ , idleArgs = ["--app", "idle"]+ , busyArgs = ["--app", "busy"]+ }++-- | The other binaries all take render|idle|busy|version.+other :: Other -> IO Subject+other (Other name path) = do+ version <- unwords . words <$> readProcess path ["version"] ""+ pure Subject+ { subjectName = name <> " " <> version+ , renderTime = read <$> readProcess path ["render"] ""+ , program = path+ , idleArgs = ["idle"]+ , busyArgs = ["busy"]+ }++-- | 100 warmup frames, then time 2000, same as the others.+layoutzRenderTime :: IO Double+layoutzRenderTime = do+ forM_ [1 .. 100] frame+ start <- seconds+ forM_ [1 .. frames] frame+ end <- seconds+ pure ((end - start) * 1000 / fromIntegral frames)+ where+ frames = 2000 :: Int+ (rows, cols) = screen+ frame k = evaluate (length (renderIn cols rows (dashboard k)))++measure :: Subject -> IO Results+measure subject = do+ step "render"+ rendered <- renderTime subject++ step "idle"+ (idle, latencies, idleM) <- withSession screen (program subject) (idleArgs subject) $ \s -> do+ drain s 1 -- startup + first frame+ idle <- cpuDuring s (drain s 5)+ latencies <- replicateM 40 (keypressLatency s)+ m <- memory s+ pure (idle, catMaybes latencies, m)++ step "busy"+ (busy, output, busyM) <- withSession screen (program subject) (busyArgs subject) $ \s -> do+ drain s 1+ before <- bytesWritten s+ start <- seconds+ busy <- cpuDuring s (drain s 5)+ end <- seconds+ after <- bytesWritten s+ m <- memory s+ pure (busy, fromIntegral (after - before) / 1024 / (end - start), m)++ putStrLn "done"+ pure (Results rendered idle latencies busy output idleM busyM)+ where+ step what = putStr (what <> "... ") >> hFlush stdout++cpuDuring :: Session -> IO () -> IO Double+cpuDuring s action = do+ cpu0 <- cpuSeconds s+ t0 <- seconds+ action+ cpu1 <- cpuSeconds s+ t1 <- seconds+ pure ((cpu1 - cpu0) / (t1 - t0))++-- | ms from pressing @+@ to the first byte back.+keypressLatency :: Session -> IO (Maybe Double)+keypressLatency s = do+ drain s 0.1 -- let the last frame finish+ start <- seconds+ press s (BC.pack "+")+ answered <- waitForOutput s 1+ end <- seconds+ drain s 0.05+ pure (if answered then Just ((end - start) * 1000) else Nothing)++benchmark :: [Other] -> FilePath -> IO ()+benchmark others out = do+ hSetBuffering stdout LineBuffering+ subjects <- (:) <$> layoutz <*> traverse other others+ results <- forM subjects $ \subject -> do+ putStr (subjectName subject <> ": ")+ r <- measure subject+ pure (subjectName subject, r)+ putStrLn ""+ putStrLn (render (report results))+ save out Run+ { runSetup = setup+ , runCharts = charts results+ , runHeaders = headers+ , runRows = tableRows results+ }+ forM_ (filter (`notElem` measured) otherNames) $ \name ->+ putStrLn ("\n" <> name <> " was not measured, `make bench` builds it: " <> needs name)+ where+ measured = [ name | Other name _ <- others ]+ needs = \case+ "bubbletea" -> "needs Go 1.21+ (GO=... to pick one)"+ "ratatui" -> "needs cargo (CARGO=... to pick one)"+ _ -> "see the cabal error above"++report :: [(String, Results)] -> View m+report results = vstack+ [ text setup+ , br+ , table headers [ map text r | r <- tableRows results ]+ , br+ , ul (map text notes)+ ]++setup :: String+setup = printf "Dashboard on a %dx%d terminal: 40-row table, 15 bars, 20-line log" cols rows+ where (rows, cols) = screen++headers :: [String]+headers = ["", "render", "idle CPU", "key -> screen (p50 / p90)", "busy CPU", "busy output", "mem idle / busy peak"]++tableRows :: [(String, Results)] -> [[String]]+tableRows results =+ [ [ name+ , printf "%.2f ms" renderMs+ , percent idleCpu+ , printf "%.1f / %.1f ms" (quantile 0.5 latencyMs) (quantile 0.9 latencyMs)+ , percent busyCpu+ , printf "%.0f KiB/s" outputKiB+ , printf "%.1f / %.1f MiB" (residentMiB idleMem) (peakMiB busyMem)+ ]+ | (name, Results{..}) <- results+ ]++-- | One chart per table column.+charts :: [(String, Results)] -> [Chart]+charts results =+ [ panel "render, ms per frame" $ \Results{..} ->+ (renderMs, printf "%.2f ms" renderMs)+ , panel "idle CPU, % of one core" $ \Results{..} ->+ (idleCpu * 100, percent idleCpu)+ , panel "keypress -> screen, ms (p50)" $ \Results{..} ->+ let p50 = quantile 0.5 latencyMs+ in (p50, printf "%.1f ms (p90 %.1f)" p50 (quantile 0.9 latencyMs))+ , panel "busy CPU, % of one core" $ \Results{..} ->+ (busyCpu * 100, percent busyCpu)+ , panel "busy output, KiB/s" $ \Results{..} ->+ (outputKiB, printf "%.0f KiB/s" outputKiB)+ , panel "memory, MiB (busy peak)" $ \Results{..} ->+ (peakMiB busyMem, printf "%.1f MiB" (peakMiB busyMem))+ ]+ where+ panel title f = Chart title [ uncurry (Bar name) (f r) | (name, r) <- results ]++notes :: [String]+notes =+ [ "render: one frame to text (Brick: to vty spans, ratatui: to a cell buffer, neither renders plain text)"+ , "idle CPU: nothing changing"+ , "key -> screen: keypress to first byte of the next frame"+ , "busy: model changes every 10ms, output is bytes the terminal has to parse"+ , "busy: layoutz and Bubble Tea draw at most 60 fps, Brick and ratatui draw every change (~100 fps)"+ , "mem: RSS incl. runtime and binary, peak is the high-water mark while busy"+ , "CPU is % of one core, multi-threaded programs (Go, -threaded GHC) can go over 100%"+ ]++percent :: Double -> String+percent x = printf "%.1f%%" (x * 100)++quantile :: Double -> [Double] -> Double+quantile _ [] = 0 / 0+quantile q xs = sort xs !! min (length xs - 1) (floor (q * fromIntegral (length xs)))
@@ -0,0 +1,136 @@+{-# LANGUAGE ForeignFunctionInterface #-}+{-# LANGUAGE ScopedTypeVariables #-}++-- | Run a program in a pty: read its output, send it keys, check its CPU and+-- memory. Linux only (reads @/proc@).+module Pty+ ( Session+ , withSession+ , drain+ , press+ , waitForOutput+ , cpuSeconds+ , Memory (..)+ , memory+ , bytesWritten+ , seconds+ ) where++import Control.Exception (IOException, bracket, catch)+import Control.Monad (void, when)+import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as BC+import Data.IORef+import Foreign (Ptr, alloca, nullPtr, peek, withArray0, withMany)+import Foreign.C+import GHC.Clock (getMonotonicTimeNSec)+import System.IO+import System.Posix.IO (fdToHandle)+import System.Posix.Process (getProcessStatus)+import System.Posix.Signals (sigKILL, signalProcess)+import System.Posix.Types (Fd (..), ProcessID)++foreign import ccall unsafe "layoutz_bench_spawn"+ c_spawn :: Ptr CString -> CInt -> CInt -> Ptr CInt -> IO CInt++foreign import ccall unsafe "layoutz_bench_clock_ticks"+ c_clockTicks :: IO CLong++data Session = Session+ { sPid :: ProcessID+ , sTerm :: Handle -- master side+ , sWritten :: IORef Int -- total bytes read+ }++-- | Run @program args@ on a @rows@ x @cols@ pty. Sends Ctrl-C at the end,+-- then SIGKILL in case it didn't quit.+withSession :: (Int, Int) -> FilePath -> [String] -> (Session -> IO a) -> IO a+withSession (rows, cols) program args = bracket start stop+ where+ start = do+ (pid, fd) <- spawn+ term <- fdToHandle fd+ hSetBinaryMode term True+ hSetBuffering term NoBuffering+ Session pid term <$> newIORef 0++ spawn =+ withMany withCString (program : args) $ \cargs ->+ withArray0 nullPtr cargs $ \argv ->+ alloca $ \masterPtr -> do+ pid <- c_spawn argv (fromIntegral rows) (fromIntegral cols) masterPtr+ when (pid < 0) $ ioError (userError ("could not start " <> program))+ master <- peek masterPtr+ pure (fromIntegral pid, Fd master)++ stop s = do+ press s (BC.pack "\ETX")+ drain s 0.3+ signalProcess sigKILL (sPid s) `catch` ignore+ void (getProcessStatus True False (sPid s)) `catch` ignore+ hClose (sTerm s) `catch` ignore++ ignore :: IOException -> IO ()+ ignore _ = pure ()++-- | Keep reading for @secs@ seconds.+drain :: Session -> Double -> IO ()+drain s secs = do+ deadline <- (+ secs) <$> seconds+ let loop = do+ now <- seconds+ let left = deadline - now+ when (left > 0) $ do+ more <- readSome s left+ when more loop+ loop++-- | True if anything shows up within @secs@.+waitForOutput :: Session -> Double -> IO Bool+waitForOutput = readSome++press :: Session -> B.ByteString -> IO ()+press s keys = B.hPut (sTerm s) keys `catch` \(_ :: IOException) -> pure ()++-- | Read one chunk if one comes within @secs@. False on timeout or EOF.+readSome :: Session -> Double -> IO Bool+readSome s secs = do+ ready <- hWaitForInput (sTerm s) (max 1 (round (secs * 1000)))+ if not ready+ then pure False+ else do+ chunk <- B.hGetSome (sTerm s) 65536+ modifyIORef' (sWritten s) (+ B.length chunk)+ -- layoutz asks for the cursor position to get the screen size+ when (BC.pack "\ESC[6n" `B.isInfixOf` chunk) $+ press s (BC.pack "\ESC[60;200R")+ pure (not (B.null chunk))+ `catch` \(_ :: IOException) -> pure False++-- | utime + stime so far.+cpuSeconds :: Session -> IO Double+cpuSeconds s = do+ stat <- readFile ("/proc/" <> show (sPid s) <> "/stat")+ ticks <- c_clockTicks+ -- comm can have spaces in it, so split after the closing ")"+ let fields = words (reverse (takeWhile (/= ')') (reverse stat)))+ user = read (fields !! 11)+ system = read (fields !! 12)+ length stat `seq` pure ((user + system) / fromIntegral ticks)++-- | RSS now and peak RSS, in MiB.+data Memory = Memory { residentMiB :: Double, peakMiB :: Double }++memory :: Session -> IO Memory+memory s = do+ status <- lines <$> readFile ("/proc/" <> show (sPid s) <> "/status")+ let kib key = sum [ read n | l <- status, (k : n : _) <- [words l], k == key ] :: Double+ now = kib "VmRSS:"+ peak = kib "VmHWM:"+ length status `seq` pure (Memory (now / 1024) (peak / 1024))++bytesWritten :: Session -> IO Int+bytesWritten = readIORef . sWritten++seconds :: IO Double+seconds = (/ 1e9) . fromIntegral <$> getMonotonicTimeNSec
@@ -0,0 +1,215 @@+-- | Writes @results.svg@ and the results section of @README.md@. Only the+-- text between the two markers is replaced, the rest is hand-written.+module Report+ ( Chart (..)+ , Bar (..)+ , Run (..)+ , save+ ) where++import Control.Exception (IOException, try)+import Data.Char (isSpace)+import Data.List (dropWhileEnd, intercalate, isPrefixOf)+import Data.Version (showVersion)+import System.Directory (createDirectoryIfMissing, doesFileExist)+import System.FilePath ((</>))+import System.Info (fullCompilerVersion)+import System.Process (readProcess)+import Text.Printf (printf)++-- | One small bar chart, one bar per library.+data Chart = Chart+ { chartTitle :: String+ , chartBars :: [Bar]+ }++data Bar = Bar+ { barName :: String+ , barValue :: Double -- sets the length, NaN draws no bar+ , barLabel :: String -- printed after the bar+ }++data Run = Run+ { runSetup :: String+ , runCharts :: [Chart]+ , runHeaders :: [String]+ , runRows :: [[String]]+ }++save :: FilePath -> Run -> IO ()+save dir run = do+ createDirectoryIfMissing True dir+ date <- shell "date" ["+%Y-%m-%d"]+ machine <- describeMachine+ writeFile (dir </> svgFile) (svg (date <> " on " <> intercalate ", " machine) run)+ let page = dir </> "README.md"+ exists <- doesFileExist page+ old <- if exists then readFile page else pure ""+ length old `seq` writeFile page (splice (section date machine run) old)+ putStrLn ("\nSaved " <> page <> " and " <> (dir </> svgFile))++svgFile :: FilePath+svgFile = "results.svg"++-- Markdown --------------------------------------------------------------------++startMarker, endMarker :: String+startMarker = "<!-- results:start, written by `make bench`, edits in here are lost -->"+endMarker = "<!-- results:end -->"++splice :: [String] -> String -> String+splice new old = case break isStart (lines old) of+ (before, _ : rest) | (_, _ : after) <- break isEnd rest ->+ unlines (before <> new <> after)+ _ | null old -> unlines (intro <> new)+ | otherwise -> old <> "\n" <> unlines new+ where+ isStart = ("<!-- results:start" `isPrefixOf`)+ isEnd = (endMarker `isPrefixOf`)+ intro =+ [ "# Benchmarks"+ , ""+ , "layoutz, [Bubble Tea](https://github.com/charmbracelet/bubbletea),"+ , "[Brick](https://github.com/jtdaugherty/brick) and"+ , "[ratatui](https://github.com/ratatui/ratatui) drawing the same dashboard, as"+ , "close as each library allows"+ , "([Dashboard.hs](Dashboard.hs), [bubbletea/main.go](bubbletea/main.go),"+ , "[brick/Main.hs](brick/Main.hs), [ratatui/src/main.rs](ratatui/src/main.rs))."+ , "How it is measured: [Main.hs](Main.hs)."+ , ""+ , "This is not here to \"dunk\" on anyone. Every library here renders a frame in"+ , "under 2 ms, well inside the ~16 ms a 60 Hz screen gives it, so past that point"+ , "the human eye can't tell them apart. They are mature and well tuned, which is"+ , "what makes them good lighthouses: fixed points to steer by as we optimize the"+ , "layoutz runtime."+ , ""+ , "`make bench` (Linux only) re-runs everything and rewrites"+ , "the chart and the table below. Lower is better everywhere."+ , ""+ ]++section :: String -> [String] -> Run -> [String]+section date machine run = concat+ [ [startMarker, "", "Last run: " <> date, ""]+ , map ("- " <>) (machine <> [runSetup run])+ , ["", "", ""]+ , map mdRow (headers : map (const "---") headers : runRows run)+ , ["", endMarker]+ ]+ where+ headers = runHeaders run+ mdRow cells = "| " <> intercalate " | " (map escape cells) <> " |"+ escape = concatMap (\c -> if c == '|' then "\\|" else [c])++-- SVG -------------------------------------------------------------------------++svg :: String -> Run -> String+svg stamp run = unlines $+ [ printf "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"%d\" height=\"%d\" viewBox=\"0 0 %d %d\" font-family=\"-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif\" font-size=\"12\">" width height width height+ , style+ , textAt "title" 0 18 (intercalate " vs " names <> " (lower is better)")+ , textAt "muted" 0 38 (runSetup run)+ , textAt "muted" 0 56 stamp+ ] <> concat (zipWith chart [0 ..] charts) <> ["</svg>"]+ where+ charts = runCharts run+ names = case charts of+ c : _ -> map (takeWhile (/= ' ') . barName) (chartBars c)+ [] -> []+ columns = 2 :: Int+ panelW = 440 :: Int+ gap = 32 :: Int+ top = 84 :: Int+ rowH = 24 :: Int+ barH = 16 :: Int+ mostBars = maximum (1 : map (length . chartBars) charts)+ panelH = 26 + mostBars * rowH + 22+ panelRows = (length charts + columns - 1) `div` columns+ width = columns * panelW + (columns - 1) * gap+ height = top + panelRows * panelH+ nameW = 16 + 7 * maximum (1 : [ length (barName b) | c <- charts, b <- chartBars c ])+ labelW = 120+ barMax = panelW - nameW - labelW++ chart :: Int -> Chart -> [String]+ chart i (Chart title bars) =+ textAt "heading" x (y + 12) title+ : printf "<line class=\"axis\" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\"/>" (x + nameW) (y + 22) (x + nameW) (y + 26 + length bars * rowH)+ : concat (zipWith bar [0 ..] bars)+ where+ x = (i `mod` columns) * (panelW + gap)+ y = top + (i `div` columns) * panelH+ largest = maximum (0 : [ v | Bar _ v _ <- bars, not (isNaN v) ])+ bar :: Int -> Bar -> [String]+ bar j (Bar name value label) =+ [ textAt "name" x (by + 12) name+ , if len > 0+ then printf "<rect class=\"%s\" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"3\"/>" (series name) (x + nameW) by len barH+ else ""+ , textAt "muted" (x + nameW + len + 6) (by + 12) label+ ]+ where+ by = y + 26 + j * rowH+ len | isNaN value || largest <= 0 = 0+ | otherwise = max 2 (round (fromIntegral barMax * value / largest))++ -- same colour per library in every chart+ series name+ | "layoutz" `isPrefixOf` name = "s1"+ | "bubbletea" `isPrefixOf` name = "s2"+ | "brick" `isPrefixOf` name = "s3"+ | "ratatui" `isPrefixOf` name = "s4"+ | otherwise = "s5"++textAt :: String -> Int -> Int -> String -> String+textAt cls x y s = printf "<text class=\"%s\" x=\"%d\" y=\"%d\">%s</text>" cls x y (escapeXml s)++escapeXml :: String -> String+escapeXml = concatMap $ \c -> case c of+ '<' -> "<"+ '>' -> ">"+ '&' -> "&"+ '"' -> """+ _ -> [c]++style :: String+style = unlines+ [ "<style>"+ , " .title { font-size: 15px; font-weight: 600; fill: #0b0b0b }"+ , " .heading { font-weight: 600; fill: #0b0b0b }"+ , " .name { fill: #0b0b0b }"+ , " .muted { fill: #52514e }"+ , " .axis { stroke: #c3c2b7; stroke-width: 1 }"+ , " .s1 { fill: #2a78d6 } .s2 { fill: #eb6834 } .s3 { fill: #1baf7a } .s4 { fill: #6250d6 } .s5 { fill: #8a8984 }"+ , " @media (prefers-color-scheme: dark) {"+ , " .title, .heading, .name { fill: #f0efec }"+ , " .muted { fill: #c3c2b7 }"+ , " .axis { stroke: #52514e }"+ , " .s1 { fill: #3987e5 } .s2 { fill: #d95926 } .s3 { fill: #199e70 } .s4 { fill: #9085e9 } .s5 { fill: #a3a29d }"+ , " }"+ , "</style>"+ ]++-- Machine ---------------------------------------------------------------------++-- | e.g. ["AMD Ryzen 7 5800X (16 threads)", "Linux 5.15.0-56-generic", "GHC 9.10.3"]+describeMachine :: IO [String]+describeMachine = do+ cpuinfo <- either (const "") id <$> (try (readFile "/proc/cpuinfo") :: IO (Either IOException String))+ kernel <- shell "uname" ["-r"]+ let ls = lines cpuinfo+ cpu = case [ trim (drop 1 (dropWhile (/= ':') l)) | l <- ls, "model name" `isPrefixOf` l ] of+ (m : _) -> unwords (words m)+ [] -> "unknown CPU"+ threads = length (filter ("processor" `isPrefixOf`) ls)+ cpuPart | threads > 0 = printf "%s (%d threads)" cpu threads+ | otherwise = cpu+ pure (cpuPart : [ "Linux " <> kernel | not (null kernel) ]+ <> ["GHC " <> showVersion fullCompilerVersion])+ where+ trim = dropWhileEnd isSpace . dropWhile isSpace++-- | Output of a command, "" if it fails.+shell :: FilePath -> [String] -> IO String+shell cmd args = either (const "") (unwords . words)+ <$> (try (readProcess cmd args "") :: IO (Either IOException String))
@@ -0,0 +1,25 @@+#include <pty.h>+#include <stdlib.h>+#include <unistd.h>++/* forkpty + exec argv[0] on a rows x cols terminal. Returns the pid (or -1)+ and puts the master fd in *master. Done in C so the GHC runtime never runs+ in the forked child. */+int layoutz_bench_spawn(char *const argv[], int rows, int cols, int *master)+{+ struct winsize size = { .ws_row = rows, .ws_col = cols };+ pid_t pid = forkpty(master, NULL, NULL, &size);+ if (pid == 0) {+ /* same TERM for everyone */+ setenv("TERM", "xterm-256color", 1);+ unsetenv("COLORTERM");+ execv(argv[0], argv);+ _exit(127);+ }+ return pid;+}++long layoutz_bench_clock_ticks(void)+{+ return sysconf(_SC_CLK_TCK);+}
@@ -1,7 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} {-|-Ask demo - a tour of the one-shot @ask*@ prompts. Each takes over the tty+Ask demo: a tour of the one-shot @ask*@ prompts. Each takes over the tty briefly, returns a value, and leaves a single committed line behind. Run with: cabal run ask-demo@@ -24,30 +24,30 @@ realms :: [String] realms = ["The Shire", "Rivendell", "Mirkwood", "Lake-town", "Erebor"] -gap :: IO ()-gap = putStrLn ""+blank :: IO ()+blank = putStrLn "" main :: IO () main = do putStr "\ESC[2J\ESC[H" _ <- askInput "Name › " "anonymous" ""- gap+ blank _ <- askChoose "Choose a realm" realms id- gap+ blank _ <- askChooseMany "Pack provisions (up to 3)" ["lembas", "pipe-weed", "waybread", "miruvor", "rope", "athelas"] 3 id- gap+ blank _ <- askFilter "Search a companion › " companions 8 id- gap+ blank _ <- askWrite "Pose a riddle" "This thing all things devours…" "" "Ctrl-D to save"- gap+ blank _ <- askFile "." 12- gap+ blank _ <- askConfirm "Venture on the quest?" True "Yes" "No"- gap+ blank askPager roster 8 True- gap+ blank void $ askSpin "Awaking Smaug…" SpinnerDots (threadDelay 1500000 >> pure ("ready" :: String)) where roster = unlines
@@ -0,0 +1,13 @@+module Main where++import Layoutz++main :: IO ()+main = do+ name <- askInput "Name › " "anonymous" ""+ realm <- askChoose "Choose a realm" ["The Shire", "Rivendell", "Mirkwood"] id+ member <- askFilter "Search a companion › " ["Bilbo", "Gandalf", "Thorin"] 8 id+ riddle <- askWrite "Pose a riddle"+ "This thing all things devours…" "" "Ctrl-D to save"+ quest <- askConfirm "Venture on the quest?" True "Yes" "No"+ pure ()
@@ -0,0 +1,69 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Mouse demo: click the buttons or a fruit, scroll the wheel over the list or+over a stepper. Esc quits.+-}++module Main where++import Layoutz++-- A component is just state, messages, update and view.+newtype Stepper = Stepper Int+data StepperMsg = Up | Down++updateStepper :: StepperMsg -> Stepper -> Stepper+updateStepper Up (Stepper n) = Stepper (n + 1)+updateStepper Down (Stepper n) = Stepper (max 0 (n - 1))++stepper :: String -> Stepper -> View StepperMsg+stepper label (Stepper n) =+ row [button "-" Down, text (label <> " " <> show n), button "+" Up]+ & onScroll (\d -> if d > 0 then Down else Up)++data Model = Model+ { workers :: Stepper+ , retries :: Stepper+ , picked :: Int+ , events :: Int+ }++data Msg = Workers StepperMsg | Retries StepperMsg | Pick Int | Nudge Int | Reset++fruits :: [String]+fruits = ["apple", "banana", "cherry", "damson", "elderberry", "fig"]++update :: Msg -> Model -> Model+update msg m = bump $ case msg of+ Workers s -> m { workers = updateStepper s (workers m) }+ Retries s -> m { retries = updateStepper s (retries m) }+ Pick i -> m { picked = i }+ Nudge d -> m { picked = max 0 (min (length fruits - 1) (picked m + d)) }+ Reset -> initial+ where bump m' = m' { events = events m + 1 }++initial :: Model+initial = Model (Stepper 4) (Stepper 2) 0 0++view :: Model -> View Msg+view m = vstack+ [ section "steppers"+ [ Workers <$> stepper "workers" (workers m)+ , Retries <$> stepper "retries" (retries m)+ ]+ , box "fruit" [ vstack (zipWith fruit [0 ..] fruits) & onScroll Nudge ]+ , row [button "reset" Reset, text ("events: " <> show (events m))]+ , text "click, scroll, Esc to quit" & styleDim+ ]+ where+ fruit i name+ | i == picked m = text ("› " <> padTo name) & fg ColorCyan & onClick (Pick i)+ | otherwise = text (" " <> padTo name) & onClick (Pick i)+ padTo s = s <> replicate (12 - length s) ' '++app :: LayoutzApp Model Msg+app = sandbox initial update view++main :: IO ()+main = runApp app
@@ -0,0 +1,37 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Counter demo: '+' and '-' to count, Esc to quit.+-}++module Main where++import Layoutz++data CounterMsg = Inc | Dec++counterApp :: LayoutzApp Int CounterMsg+counterApp = LayoutzApp+ { appInit = (0, cmdNone)+ + , appUpdate = \msg count -> case msg of+ Inc -> (count + 1, cmdNone)+ Dec -> (count - 1, cmdNone)+ + , appSubscriptions = \_state ->+ subKeyPress $ \key -> case key of+ KeyChar '+' -> Just Inc+ KeyChar '-' -> Just Dec+ _ -> Nothing+ + , appView = \count ->+ vstack+ [ section "Counter" [text $ "Count: " <> show count]+ , br+ , ul ["Press '+' or '-'", "Press ESC to quit"]+ ]+ }++main :: IO ()+main = runApp counterApp+
@@ -0,0 +1,42 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Sizing demo: a fixed-width sidebar and a main panel that fill the terminal.+Click a section or scroll over the sidebar; Esc quits.+-}++module Main where++import Layoutz++data Msg = Pick Int | Nudge Int++sections :: [(String, [String])]+sections =+ [ ("Overview", ["3 services up", "1 deploy running", "0 alerts"])+ , ("Services", ["api up 23%", "worker up 61%", "cache down 0%"])+ , ("Deploys", ["#412 api ok", "#413 worker running"])+ , ("Alerts", ["all quiet"])+ ]++update :: Msg -> Int -> Int+update (Pick i) _ = i+update (Nudge d) i = max 0 (min (length sections - 1) (i + d))++view :: Int -> View Msg+view current = vstack+ [ text "layoutz · fill demo" & styleBold+ , row+ [ box "sections" (zipWith item [0 ..] sections) & fixedWidth 18 & onScroll Nudge+ , box title (map text body) & fill+ ] & fill+ , text "click a section · scroll the sidebar · Esc to quit" & styleDim+ ]+ where+ (title, body) = sections !! current+ item i (name, _)+ | i == current = text ("› " <> name) & fg ColorCyan & onClick (Pick i)+ | otherwise = text (" " <> name) & onClick (Pick i)++main :: IO ()+main = runApp (sandbox 0 update view)
@@ -0,0 +1,98 @@+{-# LANGUAGE OverloadedStrings #-}+++module Main where++import Data.Maybe (fromMaybe)+import Layoutz++data Model = Model+ { fighters :: SelectList String+ , logView :: Viewport+ , focused :: String+ }++data Msg = Moved (SelectList String) | Picked String | Scrolled Viewport | Focused String++-- | Strikes a minute at the opening bell, how that changes each minute, and+-- the share that land.+data Pace = Pace Double Double Double++roster :: [(String, Pace)]+roster =+ [ ("Gegard Mousasi", Pace 48 (-0.6) 0.50)+ , ("Rory MacDonald", Pace 62 (-0.9) 0.42)+ , ("Jet Li", Pace 70 (-2.2) 0.55)+ , ("Lyoto Machida", Pace 34 0.2 0.60)+ , ("Anderson Silva", Pace 38 1.3 0.50)+ ]++fighterNames :: [String]+fighterNames = map fst roster++-- | Three five-minute rounds, an exchange every 11 seconds.+fightLog :: String -> [String]+fightLog name =+ [ "R" <> show (1 + secs `div` 300) <> " " <> clock (secs `mod` 300) <> " " <> surname <> " " <> moves !! ((i * 7 + length name) `mod` length moves)+ | i <- [0 .. 79 :: Int], let secs = i * 11 ]+ where+ surname = last (words name)+ clock s = show (s `div` 60) <> ":" <> (if s `mod` 60 < 10 then "0" else "") <> show (s `mod` 60)+ moves =+ [ "jab lands", "low kick, checked", "double leg, stuffed", "right hand lands clean"+ , "clinch, knee to the body", "circles out", "head kick, blocked", "slips the cross, counters"+ , "takes the back", "sprawls, back to the feet" ]++app :: LayoutzApp Model Msg+app = LayoutzApp+ { appInit = (Model (selectListOf fighterNames) viewportBottom "", cmdNone)+ , appUpdate = \msg m -> case msg of+ Moved sl -> (m { fighters = sl, logView = viewportBottom }, cmdNone)+ Picked _ -> (m, cmdFocus "log")+ Scrolled v -> (m { logView = v }, cmdNone)+ Focused n -> (m { focused = n }, cmdNone)+ , appSubscriptions = const (subFocus Focused)+ , appView = view+ }++view :: Model -> View Msg+view m = vstack+ [ text "layoutz · focus demo" & styleBold+ , row+ [ box "fighters" [selectList Moved Picked item (fighters m) & fill]+ & fixedWidth 22 & focusable "fighters" & focusStyle highlight+ , vstack+ [ box "strikes/min · 3 rounds" [paceView] & fixedHeight 13+ , box ("fight log · " <> name) [viewport Scrolled (logView m) (map text (fightLog name)) & fill]+ & fill & focusable "log" & focusStyle highlight+ ] & fill+ ] & fill+ , text ("focus: " <> focused m <> " Tab switch · ↑↓ PgUp/PgDn · Enter → log · Esc quit") & styleDim+ ]+ where+ name = fromMaybe "" (selectedItem (fighters m))+ paceView = maybe (text "") (\p -> sized (paceChart p) & fill) (lookup name roster)+ -- padded so the selected one shows as an even bar+ item s = text (" " <> s <> replicate (longest - length s + 1) ' ')+ & if s == name then styleReverse else id+ longest = maximum (map length fighterNames)+ highlight :: View n -> View n+ highlight = fg ColorCyan . border BorderDouble++-- | Strikes thrown and landed over fifteen minutes, drawn to whatever size it+-- is given.+paceChart :: Pace -> Int -> Int -> View m+paceChart (Pace start fade accuracy) w h = plotLine pw (max 2 (h - 4)) -- the axis, its labels and the legend take 4 rows+ [ Series (curve thrown) "thrown" ColorCyan+ , Series (curve landed) "landed" ColorBrightBlack+ ]+ where+ pw = max 4 (w - 6) -- the y labels ("52.3 │") take 6 columns+ n = 6 * pw -- a few samples per column keeps the steep parts joined up+ curve f = [ (x, f x) | i <- [0 .. n - 1], let x = 15 * fromIntegral i / fromIntegral (n - 1) ]+ -- output drifts over the fight and dips between rounds+ thrown x = start + fade * x + 5 * cos (2 * pi * (x + start) / 5) - 6 * exp (negate ((x - 5) ** 2)) - 6 * exp (negate ((x - 10) ** 2))+ landed x = accuracy * thrown x + 3 * sin (2 * pi * x / 3)++main :: IO ()+main = runApp app
@@ -0,0 +1,31 @@+module Main where++import Layoutz++data Msg = Add Int Int | Next Int | Reset | Focused String++main :: IO ()+main = runApp LayoutzApp+ { appInit = (([0, 0, 0], "a"), cmdNone)+ , appUpdate = \msg (ns, f) -> case msg of+ Add i d -> ((bump i d ns, f), cmdNone)+ Next i -> ((ns, f), cmdFocus (names !! ((i + 1) `mod` 3)))+ Reset -> ((map (const 0) ns, f), cmdNone)+ Focused n -> ((ns, n), cmdNone)+ , appSubscriptions = const (subFocus Focused)+ , appView = \(ns, f) -> vstack+ [ row (zipWith3 pane [0 ..] names ns)+ , text ("focus: " <> f) & styleDim+ ] & onKey (\k -> if k == KeyChar 'r' then Just Reset else Nothing)+ }+ where+ names = ["a", "b", "c"]+ bump i d = zipWith (\j n -> if i == j then n + d else n) [0 ..]+ pane i name n = box name [display n] & fixedWidth 10+ & focusable name+ & focusStyle (fg ColorCyan . border BorderDouble)+ & onKey (\k -> case k of+ KeyUp -> Just (Add i 1)+ KeyDown -> Just (Add i (-1))+ KeyEnter -> Just (Next i)+ _ -> Nothing)
@@ -1,7 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} {-|-Inline loading bar demo — renders a gradient progress bar in-place.+Inline bar demo: a gradient progress bar drawn in place. Run with: cabal run inline-bar -}@@ -22,13 +22,13 @@ update :: Msg -> LoadState -> (LoadState, Cmd Msg) update Tick state- | doneTicks state > 30 = (state, CmdNone) -- finished- | progress state >= 1.0 = (state { doneTicks = doneTicks state + 1 }, CmdNone)+ | doneTicks state > 30 = (state, cmdNone) -- finished+ | progress state >= 1.0 = (state { doneTicks = doneTicks state + 1 }, cmdNone) | otherwise = let next = min 1.0 (progress state + 0.008)- in (state { progress = next }, CmdNone)+ in (state { progress = next }, cmdNone) -view :: LoadState -> L+view :: LoadState -> View m view state = let w = 40 filled = floor (progress state * fromIntegral w) :: Int@@ -37,19 +37,19 @@ r = floor (ratio * 180) + 50 g = floor ((1 - ratio) * 200) + 55 b = 255 :: Int- in withColor (ColorTrue r g b) $ text "█"+ in fg (ColorTrue r g b) $ text "█" ) [0 .. filled - 1] emptyBlocks = replicate (w - filled)- (withColor ColorBrightBlack $ text "░")+ (fg ColorBrightBlack $ text "░") pct = show (floor (progress state * 100) :: Int) ++ "%"- in layout- [ tightRow (barBlocks ++ emptyBlocks)- , withColor ColorBrightCyan $ text $ "Linking... " <> pct+ in vstack+ [ row (barBlocks ++ emptyBlocks) & gap 0+ , fg ColorBrightCyan $ text $ "Linking... " <> pct ] app :: LayoutzApp LoadState Msg app = LayoutzApp- { appInit = (initialState, CmdNone)+ { appInit = (initialState, cmdNone) , appUpdate = update , appSubscriptions = \_ -> subEveryMs 16 Tick , appView = view
@@ -1,8 +1,8 @@ {-# LANGUAGE OverloadedStrings #-} {-|-Inline loading demo - progress bars that render in-place without-clearing the screen. The user prompt and prior output stay visible.+Inline loading demo: progress bars drawn in place, under whatever was+already on screen. Run with: cabal run inline-loading-demo -}@@ -16,11 +16,11 @@ progressBar :: String -> Double -> LayoutzApp S M progressBar label speed = LayoutzApp- { appInit = (S 0.0 0, CmdNone)+ { appInit = (S 0.0 0, cmdNone) , appUpdate = \Tick st ->- if done st > 20 then (st, CmdExit)- else if prog st >= 1.0 then (st { done = done st + 1 }, CmdNone)- else (st { prog = min 1.0 (prog st + speed) }, CmdNone)+ if done st > 20 then (st, cmdQuit)+ else if prog st >= 1.0 then (st { done = done st + 1 }, cmdNone)+ else (st { prog = min 1.0 (prog st + speed) }, cmdNone) , appSubscriptions = \_ -> subEveryMs 16 Tick , appView = \st -> let w = 40@@ -29,12 +29,12 @@ let r' = fromIntegral i / fromIntegral w :: Double r = floor (r' * 180) + 50 g = floor ((1 - r') * 200) + 55- in withColor (ColorTrue r g 255) $ text "█"+ in fg (ColorTrue r g 255) $ text "█" ) [0 .. filled - 1]- empty = replicate (w - filled) (withColor ColorBrightBlack $ text "░")+ empty = replicate (w - filled) (fg ColorBrightBlack $ text "░") pct = show (floor (prog st * 100) :: Int) ++ "%"- in layout [ tightRow (bar ++ empty)- , withColor ColorBrightCyan $ text $ label <> " " <> pct+ in vstack [ row (bar ++ empty) & gap 0+ , fg ColorBrightCyan $ text (label <> " " <> pct) ] }
@@ -0,0 +1,21 @@+import Layoutz+import Control.Concurrent (threadDelay)++files :: [String]+files = ["img-" ++ show i ++ ".png" | i <- [1 .. 80 :: Int]]++resize :: String -> IO ()+resize _ = threadDelay 40000++logLines :: [String]+logLines = ["line " ++ show i | i <- [1 .. 120 :: Int]]++indexLine :: String -> IO ()+indexLine _ = threadDelay 25000++main :: IO ()+main = do+ _ <- loader "Resizing" files resize+ _ <- loaderStream "Tailing" logLines indexLine+ n <- askSpin "Awaking Smaug…" SpinnerDots (threadDelay 1500000 >> pure 42)+ pure ()
@@ -0,0 +1,15 @@+module Main where++import Layoutz++data Msg = Inc | Dec | Reset++main :: IO ()+main = runApp $ sandbox (0 :: Int) step $ \n ->+ box "counter" [row [button "-" Dec, display n, button "+" Inc]]+ & onScroll (\d -> if d > 0 then Dec else Inc)+ & onClick Reset+ where+ step Inc = (+ 1)+ step Dec = subtract 1+ step Reset = const 0
@@ -0,0 +1,36 @@+{-# LANGUAGE OverloadedStrings #-}+import Layoutz++type Model = SelectList (String, Double -> Double)+newtype Msg = Move Model++app :: LayoutzApp Model Msg+app = LayoutzApp+ { appInit = (selectListOf waves, cmdNone)+ , appUpdate = \(Move m) _ -> (m, cmdNone)+ , appSubscriptions = const subNone+ , appView = \m -> row+ [ box "waves" [selectList Move (const (Move m)) (wave m) m]+ & fixedWidth 14+ , box "plot" [sized (plot (selectedItem m)) & fill] & fill ] & gap 0 & fill+ }+ where+ waves =+ [ ("sin", sin)+ , ("sinc", \x -> sin x / x)+ , ("beat", \x -> sin (x / 2) * sin (4 * x))+ , ("damped", \x -> exp (-abs x / 3) * cos (3 * x))+ , ("bell", \x -> exp (-x * x / 4)) ]+ -- the selected wave gets a highlighted bar across the list+ wave m (name, _)+ | Just name == fmap fst (selectedItem m) = text (" " <> take 7 (name <> repeat ' ')) & styleReverse+ | otherwise = text (" " <> name)+ plot Nothing _ _ = ""+ plot (Just (name, f)) w h =+ plotLine (w - 6) (h - 2) [Series [(x, f x) | x <- xs] name ColorCyan]+ where+ n = 40 * w + 1 :: Int+ xs = [2 * pi * (2 * fromIntegral i / fromIntegral n - 1) | i <- [0 .. n]]++main :: IO ()+main = runApp app
@@ -0,0 +1,9 @@+module Main where++import Layoutz++main :: IO ()+main = do+ let sinePoints = [(x, sin x * 5) | x <- [0, 0.15 .. 7.5]]+ putStrLn $ render $+ plotLine 50 12 [Series sinePoints "sin(x)" ColorBrightCyan]
@@ -192,7 +192,7 @@ bC = floor (clampD 0 255 ((nz' * 0.50 + lum * 0.50 + 0.05) * 200 + 30)) :: Int in Pixel ch rC gC bC -renderFrame :: RayState -> L+renderFrame :: RayState -> View m renderFrame s = let theta = rsTheta s phi = rsPhi s@@ -236,7 +236,7 @@ in s { rsMorphTarget = fromIntegral next } -- | Build the visible UI for one frame-viewRay :: RayState -> L+viewRay :: RayState -> View m viewRay s = let fb = renderFrame s targetIdx = (round (rsMorphTarget s) `mod` 3 + 3) `mod` 3@@ -255,53 +255,53 @@ twoPi = 2 * pi :: Double - cameraStats = withColor ColorBrightBlue $ kv+ cameraStats = fg ColorBrightBlue $ kv [ ("th", printf "%.2f" (rsTheta s - twoPi * fromIntegral (floor (rsTheta s / twoPi) :: Int))) , ("ph", printf "%.2f" (rsPhi s)) , ("zoom", printf "%.1f" (rsDist s)) ] - rotateLine = tightRow- [ withColor ColorBrightBlack (text "rotate: ")+ rotateLine = row+ [ fg ColorBrightBlack (text "rotate: ") , if rsAutoRotate s- then withStyle StyleBold (withColor ColorBrightGreen (text "auto"))- else withColor ColorBrightYellow (text "manual")- ]+ then styleBold (fg ColorBrightGreen (text "auto"))+ else fg ColorBrightYellow (text "manual")+ ] & gap 0 - controls = withStyle StyleDim $ layout- [ withColor ColorBrightYellow (text "<-^v> orbit")- , withColor ColorBrightYellow (text "+/- zoom")- , withColor ColorBrightYellow (text "m shape")- , withColor ColorBrightYellow (text "a auto")+ controls = styleDim $ vstack+ [ fg ColorBrightYellow (text "<-^v> orbit")+ , fg ColorBrightYellow (text "+/- zoom")+ , fg ColorBrightYellow (text "m shape")+ , fg ColorBrightYellow (text "a auto") ] - camera = layout+ camera = vstack [ cameraStats , br , rotateLine , br- , withColor ColorBrightYellow (text "~12 fps")- , withColor ColorBrightCyan (plotSparkline sparkData)+ , fg ColorBrightYellow (text "~12 fps")+ , fg ColorBrightCyan (plotSparkline sparkData) , br- , withColor ColorBrightMagenta (kv [("shape", shapeName)])+ , fg ColorBrightMagenta (kv [("shape", shapeName)]) , br- , withColor ColorBrightCyan (spinner "render" (rsTick s `div` 2) SpinnerDots)- , withColor ColorBrightGreen (spinner "scene" (rsTick s `div` 3) SpinnerClock)- , withColor ColorBrightYellow(spinner "light" (rsTick s `div` 2) SpinnerBounce)+ , fg ColorBrightCyan (spinner "render" (rsTick s `div` 2) SpinnerDots)+ , fg ColorBrightGreen (spinner "scene" (rsTick s `div` 3) SpinnerClock)+ , fg ColorBrightYellow(spinner "light" (rsTick s `div` 2) SpinnerBounce) , br , controls ] - cameraBox = withColor ColorBrightMagenta $ setBorder BorderRound $ box "Camera" [camera]+ cameraBox = fg ColorBrightMagenta $ border BorderRound $ box "Camera" [camera] - title = withStyle StyleBold (withColor ColorBrightCyan (text "Ray Marcher"))- in row [layout [title, fb], cameraBox]+ title = styleBold (fg ColorBrightCyan (text "Ray Marcher"))+ in row [vstack [title, fb], cameraBox] rayMarcher :: LayoutzApp RayState RayMsg rayMarcher = LayoutzApp- { appInit = (initialState, CmdNone)- , appUpdate = \msg state -> (updateRay msg state, CmdNone)- , appSubscriptions = \_ -> subBatch+ { appInit = (initialState, cmdNone)+ , appUpdate = \msg state -> (updateRay msg state, cmdNone)+ , appSubscriptions = \_ -> mconcat [ subEveryMs 80 RTick , subKeyPress $ \case KeyLeft -> Just RotL
@@ -0,0 +1,60 @@+{-# LANGUAGE OverloadedStrings #-}+import Layoutz++-- Define layouts+t :: View m+t = table ["Name", "Role", "Status"]+ [ ["Alice", "Engineer", "Online"]+ , ["Eve", "QA", "Away"]+ , [ul ["Gegard", ul ["Mousasi", ul ["was a BAD man"]]], "Fighter", "Nasty"]+ ] & border BorderRound++gradient :: View m+gradient = row (map cell [0, 12 .. 255]) & gap 0+ where+ cell i =+ let r = if i < 128 then i * 2 else 255+ g = if i < 128 then 255 else (255 - i) * 2+ b = if i > 128 then (i - 128) * 2 else 0+ in text "█" & fg (ColorTrue r g b)++-- Nest, compose, combine them+d :: View m+d = vstack+ [ center $ row+ [ text "Layoutz" & underline & glyph "^" & accent ColorBrightMagenta & styleBold+ , "... A Small Demo (ちいさい)" ]+ , row+ [ statusCard "Users" "1.2K" & fg ColorBrightBlue+ , statusCard "API" "UP" & border BorderDouble & fg ColorBrightGreen+ , statusCard "CPU" "23%" & border BorderThick & fg ColorBrightYellow+ , t+ , section "Pugilists"+ [ kv [("Kazushi", "Sakuraba"), ("Jet 李連杰", "Li"), ("Rory", "MacDonald")]+ , gradient+ ]+ ]+ , row+ [ vstack+ [ box "Wrapped" [ wrap 20 "Where there is a will ... Water x Necessaries" ]+ & styleReverse & styleBold & fg ColorBrightMagenta+ , ol [ "Arcole" , "Austerlitz" , ol [ "Iéna" , ol ["Бородино"] ] ] ]+ , vstack+ [ box "Deploy Status"+ [ inlineBar "Build" 1.0+ , inlineBar "Test" 0.8+ , inlineBar "Deploy" 0.3+ ] & fg ColorGreen+ , tree "📁 Project"+ [ branch "src"+ [ leaf "main.hs"+ , leaf "test.hs"+ ]+ ] & fg ColorCyan+ ] & margin "[Haskell!]"+ ]+ ]++-- Get pretty strings w/ render+main :: IO ()+main = putStrLn $ render d
@@ -1,7 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} {-|-Showcase demo – tours every layoutz element and visualization.+Showcase demo: a tour of every layoutz element and chart. Controls: - ←/→ switch scenes (1–8)@@ -96,10 +96,10 @@ update :: Msg -> ShowcaseState -> (ShowcaseState, Cmd Msg) update msg s = case msg of- NextScene -> (s { scene = (scene s + 1) `mod` totalScenes }, CmdNone)- PrevScene -> (s { scene = (scene s - 1 + totalScenes) `mod` totalScenes }, CmdNone)- GoScene n | n >= 0 && n < totalScenes -> (s { scene = n }, CmdNone)- GoScene _ -> (s, CmdNone)+ NextScene -> (s { scene = (scene s + 1) `mod` totalScenes }, cmdNone)+ PrevScene -> (s { scene = (scene s - 1 + totalScenes) `mod` totalScenes }, cmdNone)+ GoScene n | n >= 0 && n < totalScenes -> (s { scene = n }, cmdNone)+ GoScene _ -> (s, cmdNone) Tick -> let -- Text input adding animation@@ -120,55 +120,55 @@ newMorph = if abs mDiff < 0.01 then rayMorphTarget s1 else rayMorph s1 + mDiff * 0.06 in (s1 { tick = tick s1 + 1, ballY = ny, ballVy = vy, ballTrail = trail- , rayMorph = newMorph }, CmdNone)+ , rayMorph = newMorph }, cmdNone) - TypeChar c | not (addingItem s) -> (s { textValue = textValue s ++ [c] }, CmdNone)- TypeChar _ -> (s, CmdNone)+ TypeChar c | not (addingItem s) -> (s { textValue = textValue s ++ [c] }, cmdNone)+ TypeChar _ -> (s, cmdNone) Backspace | not (addingItem s) ->- (s { textValue = if null (textValue s) then "" else init (textValue s) }, CmdNone)- Backspace -> (s, CmdNone)+ (s { textValue = if null (textValue s) then "" else init (textValue s) }, cmdNone)+ Backspace -> (s, cmdNone) SubmitItem | not (addingItem s) && not (null (textValue s)) ->- (s { addingItem = True, addTick = 0 }, CmdNone)- SubmitItem -> (s, CmdNone)+ (s { addingItem = True, addTick = 0 }, cmdNone)+ SubmitItem -> (s, cmdNone) ToggleSelect- | scene s == 4 -> (s { tableSelected = toggleIn (tableRow s) (tableSelected s) }, CmdNone)- | scene s == 7 -> (s { selected = toggleIn (cursor s) (selected s) }, CmdNone)- | otherwise -> (s, CmdNone)+ | scene s == 4 -> (s { tableSelected = toggleIn (tableRow s) (tableSelected s) }, cmdNone)+ | scene s == 7 -> (s { selected = toggleIn (cursor s) (selected s) }, cmdNone)+ | otherwise -> (s, cmdNone) CursorUp- | scene s == 4 -> (s { tableRow = (tableRow s - 1 + length services) `mod` length services }, CmdNone)- | scene s == 7 -> (s { cursor = (cursor s - 1 + 7) `mod` 7 }, CmdNone)- | otherwise -> (s, CmdNone)+ | scene s == 4 -> (s { tableRow = (tableRow s - 1 + length services) `mod` length services }, cmdNone)+ | scene s == 7 -> (s { cursor = (cursor s - 1 + 7) `mod` 7 }, cmdNone)+ | otherwise -> (s, cmdNone) CursorDown- | scene s == 4 -> (s { tableRow = (tableRow s + 1) `mod` length services }, CmdNone)- | scene s == 7 -> (s { cursor = (cursor s + 1) `mod` 7 }, CmdNone)- | otherwise -> (s, CmdNone)+ | scene s == 4 -> (s { tableRow = (tableRow s + 1) `mod` length services }, cmdNone)+ | scene s == 7 -> (s { cursor = (cursor s + 1) `mod` 7 }, cmdNone)+ | otherwise -> (s, cmdNone) AdjustUp- | scene s == 1 -> (s { gravity = min (gravity s + 1) 15 }, CmdNone)- | scene s == 0 -> (s { rayDist = max (rayDist s - 0.25) 2.0 }, CmdNone)- | otherwise -> (s { lineOffset = min (lineOffset s + 1) 10 }, CmdNone)+ | scene s == 1 -> (s { gravity = min (gravity s + 1) 15 }, cmdNone)+ | scene s == 0 -> (s { rayDist = max (rayDist s - 0.25) 2.0 }, cmdNone)+ | otherwise -> (s { lineOffset = min (lineOffset s + 1) 10 }, cmdNone) AdjustDown- | scene s == 1 -> (s { gravity = max (gravity s - 1) 1 }, CmdNone)- | scene s == 0 -> (s { rayDist = min (rayDist s + 0.25) 8.0 }, CmdNone)- | otherwise -> (s { lineOffset = max (lineOffset s - 1) (-10) }, CmdNone)+ | scene s == 1 -> (s { gravity = max (gravity s - 1) 1 }, cmdNone)+ | scene s == 0 -> (s { rayDist = min (rayDist s + 0.25) 8.0 }, cmdNone)+ | otherwise -> (s { lineOffset = max (lineOffset s - 1) (-10) }, cmdNone) - ToggleBarMode -> (s { barMode = (barMode s + 1) `mod` 2 }, CmdNone)+ ToggleBarMode -> (s { barMode = (barMode s + 1) `mod` 2 }, cmdNone) - KickBall -> (s { ballVy = 5.0 }, CmdNone)+ KickBall -> (s { ballVy = 5.0 }, cmdNone) - RayRotL -> (s { rayTheta = rayTheta s - 0.15 }, CmdNone)- RayRotR -> (s { rayTheta = rayTheta s + 0.15 }, CmdNone)- RayRotU -> (s { rayPhi = min (rayPhi s + 0.1) 1.3 }, CmdNone)- RayRotD -> (s { rayPhi = max (rayPhi s - 0.1) (-1.3) }, CmdNone)+ RayRotL -> (s { rayTheta = rayTheta s - 0.15 }, cmdNone)+ RayRotR -> (s { rayTheta = rayTheta s + 0.15 }, cmdNone)+ RayRotU -> (s { rayPhi = min (rayPhi s + 0.1) 1.3 }, cmdNone)+ RayRotD -> (s { rayPhi = max (rayPhi s - 0.1) (-1.3) }, cmdNone) RayNextShape -> let next = (round (rayMorphTarget s) + 1) `mod` 2 :: Int- in (s { rayMorphTarget = fromIntegral next }, CmdNone)+ in (s { rayMorphTarget = fromIntegral next }, cmdNone) bounce :: Double -> Double -> (Double, Double) bounce y vy@@ -180,7 +180,7 @@ -- Subscriptions subscriptions :: ShowcaseState -> Sub Msg-subscriptions s = subBatch+subscriptions s = mconcat [ subEveryMs 80 Tick , subKeyPress $ \key -> case key of KeyRight -> Just NextScene@@ -206,7 +206,7 @@ -- View -view :: ShowcaseState -> L+view :: ShowcaseState -> View m view s = let header = renderHeader s content = case scene s of@@ -220,9 +220,9 @@ 7 -> sceneSelectionsHeatmap s _ -> text "Unknown scene" footer = renderFooter s- in alignLeft sceneWidth $ render $ layout [header, br, content, br, footer]+ in alignLeft sceneWidth $ vstack [header, br, content, br, footer] -renderHeader :: ShowcaseState -> L+renderHeader :: ShowcaseState -> View m renderHeader s = let sceneDots = unwords [ if i == scene s then "●" else "○" | i <- [0..totalScenes-1] ] prefix = " ─── "@@ -230,20 +230,20 @@ suffix = show (scene s + 1) ++ " / " ++ show totalScenes dashCount = max 3 (sceneWidth - length prefix - length title - length suffix - 2) dashes = replicate dashCount '─'- in layout+ in vstack [ br- , tightRow- [ withColor ColorBrightBlack $ text prefix- , withStyle StyleBold $ withColor ColorBrightCyan $ text title- , withColor ColorBrightBlack $ text (" " ++ dashes ++ " ")- , withColor ColorBrightBlack $ text suffix- ]+ , row+ [ fg ColorBrightBlack $ text prefix+ , styleBold $ fg ColorBrightCyan $ text title+ , fg ColorBrightBlack $ text (" " ++ dashes ++ " ")+ , fg ColorBrightBlack $ text suffix+ ] & gap 0 , br- , withStyle StyleBold $ withColor ColorBrightYellow $ text (" " ++ sceneNames !! scene s)+ , styleBold $ fg ColorBrightYellow $ text (" " ++ sceneNames !! scene s) , text (" " ++ sceneDots) ] -renderFooter :: ShowcaseState -> L+renderFooter :: ShowcaseState -> View m renderFooter s = let hints = case scene s of 0 -> " </> scenes wasd orbit +/- zoom Space shape ESC quit"@@ -254,11 +254,11 @@ 6 -> " </> scenes Tab cycle chart mode ESC quit" 7 -> " </> scenes ^/v navigate Space toggle ESC quit" _ -> " </> scenes ESC quit"- in withStyle StyleDim $ withColor ColorBrightBlack $ text hints+ in styleDim $ fg ColorBrightBlack $ text hints -- Scene 2: Physics Game -scenePhysicsGame :: ShowcaseState -> L+scenePhysicsGame :: ShowcaseState -> View m scenePhysicsGame s = let trailPoints = zip (map fromIntegral [0 :: Int ..]) (ballTrail s) gLabel = printf "g = %.2f" (fromIntegral (gravity s) * 0.08 :: Double) :: String@@ -272,78 +272,78 @@ energyBar = "Energy " ++ replicate filled '█' ++ replicate (barW - filled) '░' ++ " " ++ show pct ++ "%" in row- [ layout- [ withColor ColorBrightYellow $ text "Trajectory"+ [ vstack+ [ fg ColorBrightYellow $ text "Trajectory" , plotLine 35 12 [ Series trailPoints "ball" ColorBrightCyan , Series bounds " " ColorBrightBlack ] ]- , withColor ColorBrightMagenta $ withBorder BorderRound $ box "Physics"- [ alignLeft 28 $ render $ layout+ , fg ColorBrightMagenta $ border BorderRound $ box "Physics"+ [ alignLeft 28 $ vstack [ kv [ ("gravity", gLabel), ("velocity", velLabel), ("height", yLabel) ] , br- , withColor ColorBrightGreen $ text energyBar+ , fg ColorBrightGreen $ text energyBar , br- , withColor ColorBrightCyan $ spinner "Simulating" (tick s `div` 3) SpinnerDots- , withStyle StyleBold $ withColor ColorBrightYellow $ text "Press Space to kick ball!"+ , fg ColorBrightCyan $ spinner "Simulating" (tick s `div` 3) SpinnerDots+ , styleBold $ fg ColorBrightYellow $ text "Press Space to kick ball!" ] ] ] -- Scene 1: Ray Marcher -sceneRayMarcher :: ShowcaseState -> L+sceneRayMarcher :: ShowcaseState -> View m sceneRayMarcher s = let fb = renderRayFrame (rayTheta s) (rayPhi s) (rayDist s) (rayMorph s) twoPi = 2 * pi :: Double thetaWrapped = rayTheta s - twoPi * fromIntegral (floor (rayTheta s / twoPi) :: Int)- cameraStats = withColor ColorBrightBlue $ kv- [ ("th", printf "%.2f" thetaWrapped)- , ("ph", printf "%.2f" (rayPhi s))- , ("zoom", printf "%.1f" (rayDist s))+ cameraStats = fg ColorBrightBlue $ kv+ [ ("th", printf "%.2f" thetaWrapped :: String)+ , ("ph", printf "%.2f" (rayPhi s) :: String)+ , ("zoom", printf "%.1f" (rayDist s) :: String) ]- controls = withStyle StyleDim $ layout- [ withColor ColorBrightYellow $ text "wasd orbit"- , withColor ColorBrightYellow $ text "+/- zoom"- , withColor ColorBrightYellow $ text "Space shape"+ controls = styleDim $ vstack+ [ fg ColorBrightYellow $ text "wasd orbit"+ , fg ColorBrightYellow $ text "+/- zoom"+ , fg ColorBrightYellow $ text "Space shape" ]- camera = alignLeft 20 $ render $ layout+ camera = alignLeft 20 $ vstack [ cameraStats , br- , withColor ColorBrightCyan $ spinner "render" (tick s `div` 2) SpinnerDots- , withColor ColorBrightYellow $ spinner "light" (tick s `div` 2) SpinnerBounce+ , fg ColorBrightCyan $ spinner "render" (tick s `div` 2) SpinnerDots+ , fg ColorBrightYellow $ spinner "light" (tick s `div` 2) SpinnerBounce , br , controls ]- cameraBox = withColor ColorBrightMagenta $ withBorder BorderRound $ box "Camera" [camera]+ cameraBox = fg ColorBrightMagenta $ border BorderRound $ box "Camera" [camera] in row [text fb, cameraBox] -- Scene 3: Text Input & Lists -sceneTextInput :: ShowcaseState -> L+sceneTextInput :: ShowcaseState -> View m sceneTextInput s = let inputLine = if addingItem s then- row [ withColor ColorBrightYellow $ spinner "Adding" (addTick s) SpinnerDots- , withColor ColorBrightYellow $ text (" \"" ++ textValue s ++ "\"")+ row [ fg ColorBrightYellow $ spinner "Adding" (addTick s) SpinnerDots+ , fg ColorBrightYellow $ text (" \"" ++ textValue s ++ "\"") ] else- let display = if null (textValue s)- then withColor ColorBrightBlack $ text "Type something..."- else withColor ColorBrightWhite $ text (textValue s)- in tightRow [ withColor ColorBrightCyan $ text "> ", display, withStyle StyleBlink $ text "_" ]+ let shown = if null (textValue s)+ then fg ColorBrightBlack $ text "Type something..."+ else fg ColorBrightWhite $ text (textValue s)+ in row [ fg ColorBrightCyan $ text "> ", shown, styleBlink $ text "_" ] & gap 0 itemColors = [ColorBrightGreen, ColorBrightBlue, ColorBrightMagenta, ColorBrightYellow, ColorBrightCyan] itemList = if null (stItems s) then- withColor ColorBrightBlack $ text " (no items yet)"+ fg ColorBrightBlack $ text " (no items yet)" else- layout $ zipWith (\i item ->- tightRow- [ withColor ColorBrightBlack $ text (" " ++ show (i + 1) ++ ". ")- , withColor (itemColors !! (i `mod` length itemColors)) $ text item- ]+ vstack $ zipWith (\i item ->+ row+ [ fg ColorBrightBlack $ text (" " ++ show (i + 1) ++ ". ")+ , fg (itemColors !! (i `mod` length itemColors)) $ text item+ ] & gap 0 ) [0 :: Int ..] (stItems s) boxW = 32@@ -352,62 +352,62 @@ shortest = if null its then "-" else foldl1 (\a b -> if length a <= length b then a else b) its cnt = length its in row- [ withColor ColorBrightCyan $ withBorder BorderRound $ box "Add Items"- [ alignLeft boxW $ render inputLine+ [ fg ColorBrightCyan $ border BorderRound $ box "Add Items"+ [ alignLeft boxW inputLine , br- , alignLeft boxW $ render $ layout- [ withStyle StyleBold $ text "Items:"+ , alignLeft boxW $ vstack+ [ styleBold $ text "Items:" , itemList ] ]- , withBorder BorderRound $ box "Stats"- [ alignLeft boxW $ render $ layout- [ tightRow [ text "Total items: ", withStyle StyleBold $ withColor ColorBrightCyan $ text (show cnt) ]- , tightRow [ text "Longest: ", withColor ColorBrightMagenta $ text longest ]- , tightRow [ text "Shortest: ", withColor ColorBrightMagenta $ text shortest ]+ , border BorderRound $ box "Stats"+ [ alignLeft boxW $ vstack+ [ row [ text "Total items: ", styleBold $ fg ColorBrightCyan $ text (show cnt) ] & gap 0+ , row [ text "Longest: ", fg ColorBrightMagenta $ text longest ] & gap 0+ , row [ text "Shortest: ", fg ColorBrightMagenta $ text shortest ] & gap 0 ] , br- , alignLeft boxW $ render $+ , alignLeft boxW $ if cnt >= 3- then withStyle StyleBold $ withColor ColorBrightGreen $ text "Nice collection!"- else withColor ColorBrightBlack $ text ("Add " ++ show (3 - cnt) ++ " more...")+ then styleBold $ fg ColorBrightGreen $ text "Nice collection!"+ else fg ColorBrightBlack $ text ("Add " ++ show (3 - cnt) ++ " more...") ] ] -- Scene 4: Borders & Styles -sceneBordersStyles :: ShowcaseState -> L+sceneBordersStyles :: ShowcaseState -> View m sceneBordersStyles _ =- let mkBox (bdr, name, c) = withColor c $ withBorder bdr $ box name [alignLeft 8 name]+ let mkBox (bdr, name, c) = fg c $ border bdr $ box name [alignLeft 8 (text name)] topRow = [ (BorderNormal, "Single", ColorBrightCyan) , (BorderDouble, "Double", ColorBrightMagenta) , (BorderRound, "Round", ColorBrightGreen) ] bottomRow = [ (BorderThick, "Thick", ColorBrightYellow) , (BorderDashed, "Dashed", ColorBrightBlue) , (BorderAscii, "Ascii", ColorBrightWhite) ]- in layout- [ withStyle StyleBold $ withColor ColorBrightYellow $ text "Border Styles"+ in vstack+ [ styleBold $ fg ColorBrightYellow $ text "Border Styles" , row (map mkBox topRow) , row (map mkBox bottomRow) , br- , withStyle StyleBold $ withColor ColorBrightYellow $ text "Text Styles"+ , styleBold $ fg ColorBrightYellow $ text "Text Styles" , row- [ withBorder BorderRound $ box "Standard"- [ withStyle StyleBold $ withColor ColorBrightCyan $ text "Bold"- , withStyle StyleItalic $ withColor ColorBrightMagenta $ text "Italic"- , withStyle StyleUnderline $ withColor ColorBrightGreen $ text "Underline"+ [ border BorderRound $ box "Standard"+ [ styleBold $ fg ColorBrightCyan $ text "Bold"+ , styleItalic $ fg ColorBrightMagenta $ text "Italic"+ , styleUnderline $ fg ColorBrightGreen $ text "Underline" ]- , withBorder BorderRound $ box "Extended"- [ withStyle StyleDim $ withColor ColorBrightYellow $ text "Dim"- , withStyle StyleStrikethrough $ withColor ColorBrightRed $ text "Strikethrough"- , withStyle (StyleBold <> StyleItalic) $ withColor ColorBrightWhite $ text "Bold+Italic"+ , border BorderRound $ box "Extended"+ [ styleDim $ fg ColorBrightYellow $ text "Dim"+ , styleStrikethrough $ fg ColorBrightRed $ text "Strikethrough"+ , styleBold . styleItalic $ fg ColorBrightWhite $ text "Bold+Italic" ] ] ] -- Scene 5: Tables -sceneTables :: ShowcaseState -> L+sceneTables :: ShowcaseState -> View m sceneTables s = let coloredRows = zipWith (\idx (name, status, lat, up) -> let isActive = idx == tableRow s@@ -415,28 +415,28 @@ mark = if isSel then "* " else " " cells = [mark ++ name, status, lat, up] applyStyle- | isActive && isSel = withStyle (StyleBold <> StyleReverse) . withColor ColorBrightGreen- | isActive = withStyle (StyleBold <> StyleReverse) . withColor ColorBrightCyan- | isSel = withColor ColorBrightGreen+ | isActive && isSel = styleBold . styleReverse . fg ColorBrightGreen+ | isActive = styleBold . styleReverse . fg ColorBrightCyan+ | isSel = fg ColorBrightGreen | otherwise = id in map (applyStyle . text) cells ) [0 :: Int ..] services selCount = length (tableSelected s) selInfo = if selCount > 0- then withColor ColorBrightGreen $ text (show selCount ++ " selected")- else withColor ColorBrightBlack $ text "none selected"- in layout- [ withBorder BorderRound $ table ["Service", "Status", "Latency", "Uptime"] coloredRows- , tightRow- [ withColor ColorBrightBlack $ text (" Row " ++ show (tableRow s + 1) ++ "/" ++ show (length services) ++ " | ")+ then fg ColorBrightGreen $ text (show selCount ++ " selected")+ else fg ColorBrightBlack $ text "none selected"+ in vstack+ [ border BorderRound $ table ["Service", "Status", "Latency", "Uptime"] coloredRows+ , row+ [ fg ColorBrightBlack $ text (" Row " ++ show (tableRow s + 1) ++ "/" ++ show (length services) ++ " | ") , selInfo- ]+ ] & gap 0 ] -- Scene 6: Charts & Plots -sceneChartsPlots :: ShowcaseState -> L+sceneChartsPlots :: ShowcaseState -> View m sceneChartsPlots s = let sinPoints = [ (x, sin (x + fromIntegral (tick s) * 0.06) * 4) | i <- [0..100 :: Int], let x = fromIntegral i * 0.08 ]@@ -446,15 +446,15 @@ sign = if intercept' >= 0 then "+" else "-" :: String lineLabel = printf "0.5x %s %.1f" sign (abs intercept') :: String in row- [ layout- [ withColor ColorBrightYellow $ text ("sin(x) & y = " ++ lineLabel ++ " [+/- to shift]")+ [ vstack+ [ fg ColorBrightYellow $ text ("sin(x) & y = " ++ lineLabel ++ " [+/- to shift]") , plotLine 35 12 [ Series sinPoints "sin(x)" ColorBrightCyan , Series linePoints "linear" ColorBrightYellow ] ]- , layout- [ withColor ColorBrightYellow $ text "Revenue Share"+ , vstack+ [ fg ColorBrightYellow $ text "Revenue Share" , plotPie 30 8 [ Slice 45 "Product" ColorBrightCyan , Slice 30 "Services" ColorBrightMagenta@@ -466,7 +466,7 @@ -- Scene 7: Bar Charts & Sparklines -sceneBarChartsSparklines :: ShowcaseState -> L+sceneBarChartsSparklines :: ShowcaseState -> View m sceneBarChartsSparklines s = let sparkData = [ sin (fromIntegral (i + tick s) * 0.3) * 10 + 15 | i <- [0..29 :: Int] ]@@ -494,19 +494,19 @@ , BarItem 25 "Other" ColorBrightMagenta ] "Q4" ] in row- [ layout- [ withColor ColorBrightYellow $ text "Live Signal"- , withColor ColorBrightCyan $ plotSparkline sparkData+ [ vstack+ [ fg ColorBrightYellow $ text "Live Signal"+ , fg ColorBrightCyan $ plotSparkline sparkData ]- , layout- [ withColor ColorBrightYellow $ text (modeName ++ " [Tab to cycle]")+ , vstack+ [ fg ColorBrightYellow $ text (modeName ++ " [Tab to cycle]") , chartElem ] ] -- Scene 8: Selections & Heatmap -sceneSelectionsHeatmap :: ShowcaseState -> L+sceneSelectionsHeatmap :: ShowcaseState -> View m sceneSelectionsHeatmap s = let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] hours = ["6am", "9am", "12pm", "3pm", "6pm", "9pm"]@@ -518,9 +518,9 @@ arrow = if isCur then "> " else " " label = arrow ++ check ++ " " ++ day applyStyle- | isCur && isSel = withStyle StyleBold . withColor ColorBrightGreen- | isCur = withStyle StyleBold . withColor ColorBrightCyan- | isSel = withColor ColorBrightGreen+ | isCur && isSel = styleBold . fg ColorBrightGreen+ | isCur = styleBold . fg ColorBrightCyan+ | isSel = fg ColorBrightGreen | otherwise = id in applyStyle $ text label ) [0 :: Int ..] days@@ -540,13 +540,13 @@ if idx `elem` selected s then r else map (* 0.15) r ) [0 :: Int ..] baseData in row- [ withColor ColorBrightCyan $ withBorder BorderRound $ box "Schedule"- [ layout selectorLines+ [ fg ColorBrightCyan $ border BorderRound $ box "Schedule"+ [ vstack selectorLines , br- , withColor (if selCount > 0 then ColorBrightGreen else ColorBrightBlack) $+ , fg (if selCount > 0 then ColorBrightGreen else ColorBrightBlack) $ text (show selCount ++ " of " ++ show (length days) ++ " active") ]- , withBorder BorderRound $ box "Weekly Activity"+ , border BorderRound $ box "Weekly Activity" [ plotHeatmap' 5 (HeatmapData heatData days hours) ] ] @@ -673,12 +673,12 @@ let hit = vadd ro (vscale rd t) n = calcNormal hit morph diff = max (vdot n rayLightDir) 0.0- fill = max (vdot n rayFillDir) 0.0 * 0.35+ soft = max (vdot n rayFillDir) 0.0 * 0.35 refl = vsub (vscale n (2.0 * vdot n rayLightDir)) rayLightDir spec = (max (vdot refl (vneg rd)) 0.0) ** 32.0 * 0.6 ao = 1.0 - clampD 0.0 0.4 (rayScene (vadd hit (vscale n 0.1)) morph * 5.0) -- Floor keeps hit surfaces above the ramp's whitespace glyphs- lum = clampD 0.0 1.0 (max ((0.12 + diff * 0.7 + fill + spec) * ao) 0.18)+ lum = clampD 0.0 1.0 (max ((0.12 + diff * 0.7 + soft + spec) * ao) 0.18) rampLen = length rayRamp idx = floor (clampD 0 (fromIntegral rampLen - 1) (lum * fromIntegral (rampLen - 1))) :: Int ch = rayRamp !! idx@@ -713,11 +713,11 @@ showcaseApp :: LayoutzApp ShowcaseState Msg showcaseApp = LayoutzApp- { appInit = (initialState, CmdNone)+ { appInit = (initialState, cmdNone) , appUpdate = \msg s -> update msg s , appSubscriptions = subscriptions , appView = view } main :: IO ()-main = runAppWith defaultAppOptions { optAlignment = AppAlignCenter } showcaseApp+main = () <$ run defaultOptions { optAlignment = AppAlignCenter } showcaseApp
@@ -0,0 +1,270 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Simple game: collect gems, avoid devils.++- WASD or arrows move+- R restart+- Esc quit+-}++module Main where++import Layoutz++data GameState = GameState+ { playerX :: Int+ , playerY :: Int+ , items :: [(Int, Int)]+ , score :: Int+ , message :: String+ , gameOver :: Bool+ , level :: Int+ , enemies :: [Enemy]+ , lives :: Int+ , moveCount :: Int -- enemies step every 3rd move+ } deriving (Show)++data Enemy = Enemy+ { enemyX :: Int+ , enemyY :: Int+ } deriving (Show, Eq)++data GameMsg + = MoveUp+ | MoveDown+ | MoveLeft+ | MoveRight+ | Restart+ | Tick+ deriving (Show, Eq)++gameWidth, gameHeight :: Int+gameWidth = 20+gameHeight = 12++-- | Deterministic per level.+generateItems :: Int -> [(Int, Int)]+generateItems lvl =+ let itemCount = 3 + lvl+ positions = [ (x `mod` gameWidth, y `mod` gameHeight) + | i <- [0..itemCount-1]+ , let x = (i * 5 + lvl * 3) `mod` gameWidth+ , let y = (i * 3 + lvl * 2) `mod` gameHeight+ ]+ in take itemCount positions++generateEnemies :: Int -> [Enemy]+generateEnemies lvl =+ let enemyCount = 1 + lvl+ positions = [ Enemy ((i * 7 + lvl) `mod` gameWidth) + ((i * 5 + lvl * 2) `mod` gameHeight)+ | i <- [0..enemyCount-1]+ ]+ in positions++initialState :: GameState+initialState = GameState+ { playerX = gameWidth `div` 2+ , playerY = gameHeight `div` 2+ , items = generateItems 1+ , score = 0+ , message = "Collect all gems! Avoid the devils!"+ , gameOver = False+ , level = 1+ , enemies = generateEnemies 1+ , lives = 3+ , moveCount = 0+ }++moveEnemy :: Enemy -> GameState -> Enemy+moveEnemy enemy state =+ let dx = if playerX state > enemyX enemy then 1+ else if playerX state < enemyX enemy then -1+ else 0+ dy = if playerY state > enemyY enemy then 1+ else if playerY state < enemyY enemy then -1+ else 0+ newX = max 0 (min (gameWidth - 1) (enemyX enemy + dx))+ newY = max 0 (min (gameHeight - 1) (enemyY enemy + dy))+ in Enemy newX newY++processPlayerMove :: GameState -> GameState+processPlayerMove state =+ let playerPos = (playerX state, playerY state)+ newMoveCount = moveCount state + 1+ collectedItem = playerPos `elem` items state+ newItems = filter (/= playerPos) (items state)+ newScore = if collectedItem then score state + 10 else score state+ + newEnemies = if newMoveCount `mod` 3 == 0+ then map (`moveEnemy` state) (enemies state)+ else enemies state+ + hitByEnemy = any (\e -> enemyX e == playerX state && enemyY e == playerY state) newEnemies+ + levelComplete = collectedItem && null newItems+ + in if levelComplete then+ let newLevel = level state + 1+ in state { items = generateItems newLevel+ , score = newScore+ , level = newLevel+ , enemies = generateEnemies newLevel+ , message = "Level " <> show newLevel <> "! More enemies!"+ , moveCount = newMoveCount+ }+ else if hitByEnemy then+ let newLives = lives state - 1+ in if newLives <= 0 then+ state { lives = 0+ , gameOver = True+ , enemies = newEnemies+ , message = "💀 Game Over! Press R to restart"+ , moveCount = newMoveCount+ }+ else+ state { lives = newLives+ , enemies = newEnemies+ , message = "💥 Hit! Lives left: " <> show newLives+ , moveCount = newMoveCount+ }+ else if collectedItem then+ state { items = newItems+ , score = newScore+ , enemies = newEnemies+ , message = "Score: " <> show newScore <> " | Gems left: " <> show (length newItems)+ , moveCount = newMoveCount+ }+ else+ state { enemies = newEnemies+ , message = "Score: " <> show (score state) <> " | Lives: " <> show (lives state) <> " | Level: " <> show (level state)+ , moveCount = newMoveCount+ }++updateGame :: GameMsg -> GameState -> GameState+updateGame msg state+ | gameOver state && msg /= Restart = state+ | otherwise = case msg of+ MoveUp -> + let newY = max 0 (playerY state - 1)+ in processPlayerMove $ state { playerY = newY }+ + MoveDown ->+ let newY = min (gameHeight - 1) (playerY state + 1)+ in processPlayerMove $ state { playerY = newY }+ + MoveLeft ->+ let newX = max 0 (playerX state - 1)+ in processPlayerMove $ state { playerX = newX }+ + MoveRight ->+ let newX = min (gameWidth - 1) (playerX state + 1)+ in processPlayerMove $ state { playerX = newX }+ + Tick ->+ let newMoveCount = moveCount state + 1+ newEnemies = if newMoveCount `mod` 3 == 0+ then map (`moveEnemy` state) (enemies state)+ else enemies state+ hitByEnemy = any (\e -> enemyX e == playerX state && enemyY e == playerY state) newEnemies+ in if hitByEnemy && lives state > 1+ then state { lives = lives state - 1+ , enemies = newEnemies+ , message = "Ouch! Lives left: " <> show (lives state - 1)+ , moveCount = newMoveCount+ }+ else if hitByEnemy+ then state { gameOver = True+ , message = "💀 Game Over! Press R to restart"+ , moveCount = newMoveCount+ }+ else state { enemies = newEnemies+ , moveCount = newMoveCount+ }+ + Restart -> initialState++viewGame :: GameState -> View m+viewGame state =+ let renderCell x y+ | x == playerX state && y == playerY state = "🧙"+ | any (\e -> enemyX e == x && enemyY e == y) (enemies state) = "👹"+ | (x, y) `elem` items state = "💎"+ | otherwise = "⬜"+ + renderRow y = text $ unwords [renderCell x y | x <- [0..gameWidth - 1]]+ + gameBoard = vstack [renderRow y | y <- [0..gameHeight - 1]]+ + hearts = concat (replicate (lives state) "💖")+ stats = vstack+ [ text $ "Score: " <> show (score state)+ , text $ "Lives: " <> hearts+ , text $ "Level: " <> show (level state)+ , text $ "Gems left: " <> show (length (items state))+ ]+ + gameOverSection = if gameOver state+ then section "💀 Game Over"+ [ text $ "Final Score: " <> show (score state)+ , text $ "Reached Level: " <> show (level state)+ , text "Press R to restart!"+ ]+ else text ""+ + controls = section "Controls"+ [ ul [ "🧙 You | 👹 Devil | 💎 Gems"+ , "WASD or Arrow Keys - Move"+ , "R - Restart | ESC - Quit"+ , "Devils move automatically!"+ ]+ ]+ + in vstack+ [ gameBoard+ , br+ , row [section "Stats" [stats], section "Status" [text $ message state]]+ , gameOverSection+ , br+ , controls+ ]++simpleGame :: LayoutzApp GameState GameMsg+simpleGame = LayoutzApp+ { appInit = (initialState, cmdNone)+ + , appUpdate = \msg state -> (updateGame msg state, cmdNone)+ + , appSubscriptions = \_state ->+ mconcat+ [ subEveryMs 100 Tick+ , subKeyPress $ \key -> case key of+ KeyChar 'w' -> Just MoveUp+ KeyChar 'W' -> Just MoveUp+ KeyUp -> Just MoveUp+ + KeyChar 's' -> Just MoveDown+ KeyChar 'S' -> Just MoveDown+ KeyDown -> Just MoveDown+ + KeyChar 'a' -> Just MoveLeft+ KeyChar 'A' -> Just MoveLeft+ KeyLeft -> Just MoveLeft+ + KeyChar 'd' -> Just MoveRight+ KeyChar 'D' -> Just MoveRight+ KeyRight -> Just MoveRight+ + KeyChar 'r' -> Just Restart+ KeyChar 'R' -> Just Restart+ + _ -> Nothing+ ]+ + , appView = viewGame+ }++main :: IO ()+main = runApp simpleGame+
@@ -0,0 +1,14 @@+{-# LANGUAGE OverloadedStrings #-}+module Main where++import Layoutz++main :: IO ()+main = runApp $ sandbox () (\_ m -> m) $ \_ ->+ row+ [ box "nav" ["home", "logs", "plots"] & fixedWidth 12+ , box "wave" [sized wave & fill] & fill+ ] & fill+ where+ wave w h = plotLine (w - 6) (h - 4) [Series points "sin" ColorCyan]+ where points = [(x, sin x) | x <- [0, 0.05 .. fromIntegral w / 3]]
@@ -0,0 +1,63 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Spinner demo: a few spinner styles. Any key advances a frame, Esc quits.+-}++module Main where++import Layoutz++data SpinnerState = SpinnerState+ { frameCount :: Int+ } deriving (Show)++data SpinnerMsg = NextFrame++spinnerDemo :: LayoutzApp SpinnerState SpinnerMsg+spinnerDemo = LayoutzApp+ { appInit = (SpinnerState 0, cmdNone)++ , appUpdate = \msg state -> case msg of+ NextFrame -> (state { frameCount = frameCount state + 1 }, cmdNone)++ , appSubscriptions = \_state ->+ subEveryMs 100 NextFrame++ , appView = \state ->+ vstack+ [ section "Spinner Styles"+ [ text "Spinners animate automatically!"+ , text ""+ , row [ text "Dots: ", spinner "Loading..." (frameCount state) SpinnerDots ]+ , row [ text "Line: ", spinner "Processing" (frameCount state) SpinnerLine ]+ , row [ text "Clock: ", spinner "Working" (frameCount state) SpinnerClock ]+ , row [ text "Bounce: ", spinner "Thinking" (frameCount state) SpinnerBounce ]+ ]+ , br+ , section "Examples"+ [ text "With colors:"+ , fg ColorGreen $ spinner "Success!" (frameCount state) SpinnerDots+ , fg ColorYellow $ spinner "Warning" (frameCount state) SpinnerLine+ , fg ColorRed $ spinner "Error" (frameCount state) SpinnerBounce+ , br+ , text "Without labels:"+ , row+ [ spinner "" (frameCount state) SpinnerDots+ , text " "+ , spinner "" (frameCount state) SpinnerLine+ , text " "+ , spinner "" (frameCount state) SpinnerClock+ , text " "+ , spinner "" (frameCount state) SpinnerBounce+ ]+ ]+ , br+ , text $ "Frame: " <> show (frameCount state)+ , text "Press ESC to quit"+ ]+ }++main :: IO ()+main = runApp spinnerDemo+
@@ -0,0 +1,253 @@+{-# LANGUAGE OverloadedStrings #-}++{-|+Task list demo: pick a task, run it, watch it finish.++- Up/Down or W/S move+- Enter start a task; any key then advances it+- A add a task: type a name, then digits for its duration+- Enter/Tab confirm the new task, Esc to cancel+- Esc quit+-}++module Main where++import Layoutz+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Maybe (fromMaybe)++data TaskState = TaskState+ { tasks :: [String]+ , selected :: Int+ , completed :: Set Int+ , spinFrame :: Int+ , addingTask :: Bool+ , newTaskName :: String+ , newTaskDuration :: String+ , taskDurations :: [(String, Int)]+ , isLoading :: Bool+ , loadProgress :: Int+ , loadingTaskIdx :: Int+ } deriving (Show)++data TaskMsg+ = MoveUp+ | MoveDown+ | StartTask+ | AdvanceProgress+ | ToggleAddTask+ | TypeChar Char+ | TypeDigit Char+ | DeleteChar+ | ConfirmTask+ | CancelAdd+ deriving (Show, Eq)++-- | (name, steps to complete)+initialTasks :: [(String, Int)]+initialTasks =+ [ ("Process data", 15)+ , ("Generate reports", 20)+ , ("Backup files", 12)+ , ("Sync with server", 18)+ , ("Clean temp files", 8)+ , ("Update documentation", 10)+ ]++taskListApp :: LayoutzApp TaskState TaskMsg+taskListApp = LayoutzApp+ { appInit = + ( TaskState+ { tasks = map fst initialTasks+ , selected = 0+ , completed = Set.empty+ , spinFrame = 0+ , addingTask = False+ , newTaskName = ""+ , newTaskDuration = ""+ , taskDurations = initialTasks+ , isLoading = False+ , loadProgress = 0+ , loadingTaskIdx = -1+ }+ , cmdNone+ )+ + , appView = \state ->+ let taskList = zipWith (renderTask state) [0..] (tasks state)+ + completedCount = Set.size (completed state)+ totalCount = length (tasks state)+ + in if addingTask state then+ vstack+ [ section "Task Manager" taskList+ , br+ , box "Add New Task"+ [ text $ "Task name: " <> newTaskName state <> if null (newTaskDuration state) then "_" else ""+ , text $ "Duration (steps): " <> newTaskDuration state <> if not (null (newTaskDuration state)) then "_" else ""+ , br+ , text "Type name (letters), then duration (digits)"+ , text "Enter/Tab to add, ESC to cancel"+ ]+ ]+ else if isLoading state then+ let taskName = tasks state !! loadingTaskIdx state+ duration = fromMaybe 1 (lookup taskName (taskDurations state))+ progress = fromIntegral (loadProgress state) / fromIntegral duration+ in vstack+ [ section "Task Manager" taskList+ , br+ , spinner "Processing..." (spinFrame state) SpinnerDots+ , inlineBar taskName progress+ , text $ "Progress: " <> show (loadProgress state) <> " / " <> show duration+ ]+ else+ vstack+ [ section "Task Manager" taskList+ , br+ , section "Status"+ [ text $ "Completed: " <> show completedCount <> " / " <> show totalCount+ , br+ , if completedCount == totalCount+ then fg ColorGreen $ text "🎉 All tasks completed!"+ else text "Select a task and press Enter to start"+ ]+ , br+ , section "Controls"+ [ ul [ "↑/↓ or W/S - Navigate"+ , "Enter - Start task"+ , "A - Add new task"+ ]+ ]+ ]+ + , appUpdate = \msg state -> (case msg of+ MoveUp | not (addingTask state) && not (isLoading state) ->+ let newSelected = if selected state > 0+ then selected state - 1+ else length (tasks state) - 1+ in state { selected = newSelected }+ + MoveDown | not (addingTask state) && not (isLoading state) ->+ let newSelected = if selected state < length (tasks state) - 1+ then selected state + 1+ else 0+ in state { selected = newSelected }+ + StartTask | not (addingTask state) && not (isLoading state) && not (Set.member (selected state) (completed state)) ->+ state { isLoading = True+ , loadProgress = 0+ , loadingTaskIdx = selected state+ , spinFrame = 0+ , addingTask = False+ }+ + AdvanceProgress | isLoading state ->+ let taskName = tasks state !! loadingTaskIdx state+ duration = fromMaybe 1 (lookup taskName (taskDurations state))+ newProgress = loadProgress state + 1+ in if newProgress >= duration+ then state { isLoading = False+ , loadProgress = 0+ , completed = Set.insert (loadingTaskIdx state) (completed state)+ , spinFrame = spinFrame state + 1+ }+ else state { loadProgress = newProgress+ , spinFrame = spinFrame state + 1+ }+ + ToggleAddTask | not (isLoading state) ->+ state { addingTask = True+ , newTaskName = ""+ , newTaskDuration = ""+ , isLoading = False+ }+ + CancelAdd ->+ state { addingTask = False+ , newTaskName = ""+ , newTaskDuration = ""+ , isLoading = False+ }+ + TypeChar c | addingTask state ->+ state { newTaskName = newTaskName state ++ [c] }+ + TypeDigit d | addingTask state ->+ state { newTaskDuration = newTaskDuration state ++ [d] }+ + DeleteChar | addingTask state ->+ if not (null (newTaskDuration state))+ then state { newTaskDuration = init (newTaskDuration state) }+ else if not (null (newTaskName state))+ then state { newTaskName = init (newTaskName state) }+ else state+ + ConfirmTask | addingTask state && not (null (newTaskName state)) && not (null (newTaskDuration state)) ->+ let duration = read (newTaskDuration state) :: Int+ in state { tasks = tasks state ++ [newTaskName state]+ , taskDurations = taskDurations state ++ [(newTaskName state, duration)]+ , addingTask = False+ , newTaskName = ""+ , newTaskDuration = ""+ , isLoading = False+ }+ + _ -> state+ , cmdNone)+ + , appSubscriptions = \state ->+ if isLoading state then+ mconcat+ [ subEveryMs 100 AdvanceProgress+ , subKeyPress $ \_ -> Nothing+ ]+ else if addingTask state then+ subKeyPress $ \key -> case key of+ KeyEnter -> Just ConfirmTask+ KeyTab -> Just ConfirmTask+ KeyEscape -> Just CancelAdd+ KeyBackspace -> Just DeleteChar+ KeyChar c | c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == ' ' -> Just (TypeChar c)+ KeyChar c | c >= '0' && c <= '9' -> Just (TypeDigit c)+ _ -> Nothing+ else+ subKeyPress $ \key -> case key of+ KeyChar 'w' -> Just MoveUp+ KeyChar 'W' -> Just MoveUp+ KeyUp -> Just MoveUp+ + KeyChar 's' -> Just MoveDown+ KeyChar 'S' -> Just MoveDown+ KeyDown -> Just MoveDown+ + KeyEnter -> Just StartTask+ + KeyChar 'a' -> Just ToggleAddTask+ KeyChar 'A' -> Just ToggleAddTask+ + _ -> Nothing+ }+ where+ renderTask :: TaskState -> Int -> String -> View m+ renderTask state idx task =+ let isSelected = idx == selected state+ isCompleted = Set.member idx (completed state)+ isCurrentlyLoading = isLoading state && idx == loadingTaskIdx state+ + emoji = if isCompleted then "✅"+ else if isCurrentlyLoading then "⚡"+ else "📋"+ marker = if isSelected then "► " else " "+ + taskText = marker <> emoji <> " " <> task+ + in if isSelected+ then fg ColorCyan $ text taskText+ else text taskText++main :: IO ()+main = runApp taskListApp+
@@ -0,0 +1,691 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE ScopedTypeVariables #-}++{-|+Tile demo: a tiling workspace of agent sessions.++Every tile is a chat with an agent. The replies are canned, but the shell+commands the agent runs are real.++- Ctrl-N split the focused tile and open a new session+- Ctrl-W close the focused tile+- Ctrl-F zoom the focused tile (again to unzoom)+- Ctrl-P fuzzy-find sessions, files, symbols and commits+- Tab / click move focus+- Ctrl-D quit++ cabal run tile-demo+ cabal run tile-demo -- --stacked -- first split top/bottom, for tall terminals+-}++module Main where++import Control.Exception (IOException, handle)+import Control.Monad (void)+import Data.Char (isAlphaNum, isLower, isUpper, toLower)+import Data.List (isInfixOf, sortOn, stripPrefix, tails)+import qualified Data.Map.Strict as M+import Data.Maybe (listToMaybe)+import System.Environment (getArgs)+import System.Exit (ExitCode (..))+import System.Process (readProcessWithExitCode)+import Text.Read (readMaybe)+import Layoutz++------------------------------------------------------------------------------+-- Layout tree++data Axis = H | V deriving Eq++-- A split has a resting ratio and the ratio it's currently drawn at. The+-- drawn one eases toward where it should be, which is what animates new+-- tiles and zooming.+data Layout = Tile Int | Split Axis Double Double Layout Layout++leaves :: Layout -> [Int]+leaves (Tile i) = [i]+leaves (Split _ _ _ x y) = leaves x <> leaves y++-- Split tile i in two, new tile second. It starts out at zero size and+-- slides in.+grow :: Axis -> Int -> Int -> Layout -> Layout+grow axis i new = go+ where+ go (Tile j) | j == i = Split axis 0.5 1 (Tile j) (Tile new)+ go (Split a r c x y) = Split a r c (go x) (go y)+ go l = l++-- Remove tile i. Its sibling gets the space.+close :: Int -> Layout -> Layout+close i = go+ where+ go (Split _ _ _ (Tile j) y) | j == i = y+ go (Split _ _ _ x (Tile j)) | j == i = x+ go (Split a r c x y) = Split a r c (go x) (go y)+ go l = l++-- Where a split wants to be. When zoomed, every split above the focused+-- tile opens all the way towards it.+target :: Bool -> Int -> Layout -> Double+target _ _ (Tile _) = 0+target zoomedIn f (Split _ r _ x y)+ | zoomedIn && f `elem` leaves x = 1+ | zoomedIn && f `elem` leaves y = 0+ | otherwise = r++ease :: Double -> Bool -> Int -> Layout -> Layout+ease _ _ _ l@(Tile _) = l+ease dt z f s@(Split a r c x y) = Split a r c' (ease dt z f x) (ease dt z f y)+ where+ t = target z f s+ moved = t + (c - t) * exp (-easeRate * dt)+ c' = if abs (moved - t) < 0.002 then t else moved++easeRate :: Double+easeRate = 14++settled :: Bool -> Int -> Layout -> Bool+settled _ _ (Tile _) = True+settled z f s@(Split _ _ c x y) = c == target z f s && settled z f x && settled z f y++-- Each new split goes the other way from the one it's inside, so tiles+-- spiral inwards like bspwm's dwindle layout.+splitAxis :: Axis -> Int -> Layout -> Axis+splitAxis firstAxis i = go firstAxis+ where+ go a (Tile _) = a+ go _ (Split a _ _ x y)+ | i `elem` leaves x = go (flipAxis a) x+ | otherwise = go (flipAxis a) y++flipAxis :: Axis -> Axis+flipAxis H = V+flipAxis V = H++-- Draw the layout into exactly w by h cells. Tiles squeezed down to nothing+-- still get drawn (at size 0) so they stay in the focus order.+drawLayout :: (Int -> Int -> Int -> View msg) -> Int -> Int -> Layout -> View msg+drawLayout drawTile w h = \case+ Tile i -> drawTile i w h+ Split H _ c x y ->+ let k = cut c w+ in row [drawLayout drawTile k h x, drawLayout drawTile (w - k) h y] & gap 0+ Split V _ c x y ->+ let k = cut c h+ in vstack [drawLayout drawTile w k x, drawLayout drawTile w (h - k) y]+ where+ cut c n = max 0 (min n (round (c * fromIntegral n)))++------------------------------------------------------------------------------+-- Agent sessions++-- Things the agent is going to do+data Step = Think Int | Say String | Run String | Edit String [String]++-- Things already in the transcript+data Entry+ = You String+ | Said String+ | Ran String (Maybe [String]) -- Nothing while the command is running+ | Edited String [String]++data Chat = Chat+ { input :: String+ , past :: [Entry]+ , script :: [Step] -- what the agent still has to do+ , typed :: Int -- how far into the current step it is+ , scrolled :: Int -- lines scrolled back from the bottom+ }++emptyChat :: Chat+emptyChat = Chat { input = "", past = [], script = [], typed = 0, scrolled = 0 }++addEntry :: Entry -> Chat -> Chat+addEntry e c = c { past = past c <> [e] }++-- A session is named after the first thing you asked it+topic :: Chat -> String+topic c = case [ q | You q <- past c ] of+ q : _ -> q+ [] -> "new session"++label :: Int -> Chat -> String+label i c = "#" <> show i <> " " <> topic c++status :: Chat -> String+status c = case script c of+ Think _ : _ -> "thinking"+ Say _ : _ -> "writing"+ Run _ : _ -> "running"+ Edit _ _ : _ -> "editing"+ []+ | null (past c) -> ""+ | otherwise -> "idle"++suggestions :: [String]+suggestions =+ [ "is there a space leak in the stream loop?"+ , "typecheck this with -Wall -Wextra"+ , "what changed lately?"+ ]++replyTo :: String -> [Step]+replyTo q+ | has "leak" =+ [ Think 16+ , Say "Checking how a transcript grows."+ , Run "grep -n -A1 '^addEntry ::' examples/TileDemo.hs"+ , Think 10+ , Say "Probably not a leak: every field gets forced when the tile redraws, so thunks don't pile up. The real cost is past c <> [e], which copies the whole list on every append. A Seq makes that O(1):"+ , Edit "examples/TileDemo.hs"+ [ "+import Data.Sequence (Seq, (|>))"+ , "- , past :: [Entry]"+ , "+ , past :: Seq Entry"+ , "-addEntry e c = c { past = past c <> [e] }"+ , "+addEntry e c = c { past = past c |> e }"+ ]+ , Say "The other uses of past are folds, so they don't change. Want me to apply it?"+ ]+ | has "functor" || has "tolist" =+ [ Think 12+ , Say "Yes. Parameterise the leaf and let GHC derive the rest:"+ , Edit "examples/TileDemo.hs"+ [ "+{-# LANGUAGE DeriveTraversable #-}"+ , "+import Data.Foldable (toList)"+ , "-data Layout = Tile Int | Split Axis Double Double Layout Layout"+ , "+data Layout a = Tile a | Split Axis Double Double (Layout a) (Layout a)"+ , "+ deriving (Functor, Foldable, Traversable)"+ , "-leaves :: Layout -> [Int]"+ , "-leaves (Tile i) = [i]"+ , "-leaves (Split _ _ _ x y) = leaves x <> leaves y"+ , "+leaves :: Layout a -> [a]"+ , "+leaves = toList"+ ]+ , Run "grep -c 'Layout ->' examples/TileDemo.hs"+ , Say "That many signatures become Layout Int. grow and close keep their bodies."+ ]+ | has "wall" || has "warn" || has "typecheck" =+ [ Think 8+ , Run "ghc -fno-code -fforce-recomp -Wall -Wextra -i. examples/TileDemo.hs 2>&1 | tail -4"+ , Say "Clean under -Wall -Wextra."+ ]+ | has "zoom" =+ [ Think 14+ , Say "Let me find where the zoom is animated."+ , Run "grep -n -A8 '^ease ::' examples/TileDemo.hs"+ , Think 8+ , Say "Splits ease toward their target at a rate of 14 per second. Bumping it to 22 makes zooming feel snappier without looking jumpy:"+ , Edit "examples/TileDemo.hs" [" easeRate :: Double", "-easeRate = 14", "+easeRate = 22"]+ , Say "For scale, this whole demo is"+ , Run "wc -l examples/TileDemo.hs"+ ]+ | has "big" || has "size" || has "lines" =+ [ Think 10+ , Say "Counting the library and its examples."+ , Run "wc -l Layoutz.hs examples/*.hs | sort -n | tail -6"+ , Say "The whole library is one file, and only depends on text and containers."+ ]+ | otherwise =+ [ Think 10+ , Say "Here's the recent history of this branch."+ , Run "git log --oneline -8"+ , Run "git diff --stat"+ , Say "Want me to dig into any of these?"+ ]+ where+ has k = k `isInfixOf` map toLower q++-- Move session i's agent along one tick: think, type a few more characters,+-- or start a command (it reports back with ToolDone).+advance :: Int -> Chat -> (Chat, Cmd Msg)+advance i c = case script c of+ Think n : rest+ | typed c < n -> (c { typed = typed c + 1 }, cmdNone)+ | otherwise -> (nextStep rest, cmdNone)+ Say s : rest+ | typed c < length s -> (c { typed = typed c + 3 }, cmdNone)+ | otherwise -> (addEntry (Said s) (nextStep rest), cmdNone)+ Run cmd : _+ | typed c == 0 -> (addEntry (Ran cmd Nothing) (c { typed = 1 }), cmdTask (ToolDone i <$> shell cmd))+ Edit file diff : rest -> (addEntry (Edited file diff) (nextStep rest), cmdNone)+ _ -> (c, cmdNone)+ where+ nextStep rest = c { script = rest, typed = 0 }++-- Fill in the output of the command that's running+toolDone :: [String] -> Chat -> Chat+toolDone out c = case reverse (past c) of+ Ran cmd Nothing : earlier ->+ c { past = reverse (Ran cmd (Just out) : earlier), script = drop 1 (script c), typed = 0 }+ _ -> c++typeKey :: Key -> Chat -> Chat+typeKey k c = case k of+ KeyChar ch -> c { input = input c <> [ch] }+ KeyBackspace -> c { input = take (length (input c) - 1) (input c) }+ KeyEnter+ | not (null (input c)) && null (script c) ->+ (addEntry (You (input c)) c) { input = "", script = replyTo (input c), typed = 0, scrolled = 0 }+ _ -> c++-- Run a command for the agent, stdout and stderr together+shell :: String -> IO [String]+shell cmd = handle (\(e :: IOException) -> pure [show e]) $ do+ (_, out, err) <- readProcessWithExitCode "sh" ["-c", cmd] ""+ pure (lines (out <> err))++-- Run a command for ourselves, nothing if it fails+stdoutOf :: String -> IO [String]+stdoutOf cmd = handle (\(_ :: IOException) -> pure []) $ do+ (code, out, _) <- readProcessWithExitCode "sh" ["-c", cmd] ""+ pure (if code == ExitSuccess then lines out else [])++------------------------------------------------------------------------------+-- Ctrl-P++-- Fuzzy match: the query's letters have to appear in order. Returns a cost+-- (lower is better) and the matched positions for highlighting. Gaps between+-- letters cost, landing on the start of a word is a bonus, and long strings+-- or late starts cost a bit. Every place the first letter shows up is tried.+fuzzy :: String -> String -> Maybe (Int, [Int])+fuzzy [] _ = Just (0, [])+fuzzy q@(q0 : _) s = listToMaybe (sortOn fst candidates)+ where+ chars = zip3 [0 :: Int ..] (map toLower s) (zipWith wordStart (' ' : s) s)+ wordStart prev ch = not (isAlphaNum prev) || (isLower prev && isUpper ch)++ candidates =+ [ match+ | start@((_, ch, _) : _) <- tails chars+ , ch == toLower q0+ , Just match <- [walk (map toLower q) start Nothing 0 []]+ ]++ walk [] _ _ cost hits = Just (cost + length s `div` 10 + min 4 (last hits), reverse hits)+ walk _ [] _ _ _ = Nothing+ walk (c : cs) ((i, ch, isStart) : rest) prev cost hits+ | c == ch = walk cs rest (Just i) (cost + gapCost - startBonus) (i : hits)+ | otherwise = walk (c : cs) rest prev cost hits+ where+ gapCost = maybe 0 (\p -> 2 * (i - p - 1)) prev+ startBonus = if isStart then 3 else 0++-- Something Ctrl-P can find. Picking a session jumps to it, picking anything+-- else mentions it in the focused session.+data Kind = Session Int | File | Symbol | Commit++data Item = Item+ { kind :: Kind+ , key :: String -- the part the query matches against+ , extra :: String -- shown after the key but not matched, e.g. a type+ , tag :: String+ }++data Palette = Palette { query :: String, picked :: Int }++items :: Model -> [Item]+items m = sessions <> index m+ where+ sessions = [ Item (Session i) (label i c) "" (status c) | (i, c) <- M.toList (chats m) ]++matches :: Model -> String -> [(Item, [Int])]+matches m q = map snd (sortOn fst scored)+ where+ scored = [ (cost, (it, hits)) | it <- items m, Just (cost, hits) <- [fuzzy q (key it)] ]++-- Files in the repo, top-level signatures in the library and examples, and+-- the git log+loadIndex :: IO [Item]+loadIndex = do+ files <- stdoutOf "git -C .. ls-files --cached --others --exclude-standard"+ sigs <- stdoutOf "grep -HE \"^[a-z][A-Za-z0-9_']* ::\" Layoutz.hs examples/*.hs"+ commits <- stdoutOf "git log --format='%h %s'"+ pure $ [ Item File f "" "file" | f <- files, not (isScratch f) ]+ <> concatMap symbol sigs+ <> [ Item Commit c "" "commit" | c <- commits ]+ where+ isScratch = any (`elem` "#~") -- editor autosaves and backups++ -- "examples/Foo.hs:bar :: Int" becomes bar, " :: Int", tagged Foo+ symbol l = case break (== ':') l of+ (path, _ : decl) ->+ let (name', ty) = break (== ' ') decl+ in [Item Symbol name' ty (moduleName path)]+ _ -> []++ moduleName = takeWhile (/= '.') . reverse . takeWhile (/= '/') . reverse++------------------------------------------------------------------------------+-- App++data Model = Model+ { layout :: Layout+ , chats :: M.Map Int Chat+ , focus :: Int+ , nextId :: Int+ , zoomed :: Bool+ , palette :: Maybe Palette+ , lastFrame :: Maybe Double -- set while something is animating+ , tick :: Int -- drives the spinners+ , index :: [Item] -- what Ctrl-P searches besides the sessions+ , firstSplit :: Axis+ }++data Msg+ = NewTile+ | CloseTile+ | Zoom+ | Focused String+ | FocusOn Int+ | Frame Double+ | Stream+ | Typed Int Key+ | Scroll Int Int+ | ToolDone Int [String]+ | OpenPalette+ | PaletteKey Key+ | Pick Item+ | Indexed [Item]++initialModel :: Axis -> Model+initialModel axis = Model+ { layout = Tile 0+ , chats = M.singleton 0 emptyChat+ , focus = 0+ , nextId = 1+ , zoomed = False+ , palette = Nothing+ , lastFrame = Nothing+ , tick = 0+ , index = []+ , firstSplit = axis+ }++update :: Msg -> Model -> (Model, Cmd Msg)+update msg m = case msg of+ NewTile ->+ let i = nextId m+ axis = splitAxis (firstSplit m) (focus m) (layout m)+ in ( m { layout = grow axis (focus m) i (layout m)+ , chats = M.insert i emptyChat (chats m)+ , nextId = i + 1+ , focus = i+ , zoomed = False+ }+ , cmdFocus (name i) )++ CloseTile+ | length (leaves (layout m)) == 1 -> (m, cmdNone)+ | otherwise ->+ let layout' = close (focus m) (layout m)+ -- focus the tile before the closed one, or the first if there isn't one+ before = reverse (takeWhile (/= focus m) (leaves (layout m)))+ f = case before <> leaves layout' of+ t : _ -> t+ [] -> 0+ in ( m { layout = layout', chats = M.delete (focus m) (chats m), focus = f, zoomed = False }+ , cmdFocus (name f) )++ Zoom -> (m { zoomed = not (zoomed m) }, cmdNone)++ Focused n -> case stripPrefix "tile" n >>= readMaybe of+ Just i -> (m { focus = i }, cmdNone)+ Nothing -> (m, cmdNone)++ FocusOn i -> (m { focus = i, palette = Nothing }, cmdFocus (name i))++ Frame t ->+ let dt = maybe (1 / 60) (\t0 -> min 0.05 (t - t0)) (lastFrame m)+ layout' = ease dt (zoomed m) (focus m) (layout m)+ done = settled (zoomed m) (focus m) layout'+ in (m { layout = layout', lastFrame = if done then Nothing else Just t }, cmdNone)++ Stream ->+ let stepped = M.mapWithKey advance (chats m)+ in ( m { chats = M.map fst stepped, tick = tick m + 1 }+ , mconcat (map snd (M.elems stepped)) )++ Typed i k -> (onChat i (typeKey k) m, cmdNone)+ Scroll i d -> (onChat i (\c -> c { scrolled = max 0 (scrolled c - d) }) m, cmdNone)+ ToolDone i out -> (onChat i (toolDone out) m, cmdNone)++ OpenPalette -> case palette m of+ Nothing -> (m { palette = Just (Palette "" 0) }, cmdFocus "palette")+ Just _ -> (m { palette = Nothing }, cmdFocus (name (focus m)))++ PaletteKey k -> case palette m of+ Just p -> paletteKey k p m+ Nothing -> (m, cmdNone)++ Pick it ->+ let mention s = onChat (focus m) (\c -> c { input = input c <> s <> " " }) m+ m' = case kind it of+ Session i -> m { focus = i }+ File -> mention ("@" <> key it)+ Symbol -> mention (key it)+ Commit -> mention (takeWhile (/= ' ') (key it)) -- just the hash+ in (m' { palette = Nothing }, cmdFocus (name (focus m')))++ Indexed is -> (m { index = is }, cmdNone)++paletteKey :: Key -> Palette -> Model -> (Model, Cmd Msg)+paletteKey k p m = case k of+ KeyChar ch -> setQuery (query p <> [ch])+ KeyBackspace -> setQuery (take (length (query p) - 1) (query p))+ KeyUp -> move (-1)+ KeyDown -> move 1+ KeyEscape -> (m { palette = Nothing }, cmdFocus (name (focus m)))+ KeyEnter -> case drop (picked p) found of+ (it, _) : _ -> update (Pick it) m+ [] -> (m, cmdNone)+ _ -> (m, cmdNone)+ where+ found = matches m (query p)+ setQuery q = (m { palette = Just (Palette q 0) }, cmdNone)+ move d =+ let i = max 0 (min (length found - 1) (picked p + d))+ in (m { palette = Just p { picked = i } }, cmdNone)++onChat :: Int -> (Chat -> Chat) -> Model -> Model+onChat i f m = m { chats = M.adjust f i (chats m) }++subscriptions :: Model -> Sub Msg+subscriptions m = mconcat+ [ subKeyPress $ \case+ KeyCtrl 'W' -> Just CloseTile+ KeyCtrl 'F' -> Just Zoom+ KeyCtrl 'P' -> Just OpenPalette+ _ -> Nothing+ , subFocus Focused+ , if anyBusy then subEveryMs 30 Stream else subNone+ , if animating then subAnimationFrame Frame else subNone+ ]+ where+ anyBusy = any (not . null . script) (chats m)+ animating = not (settled (zoomed m) (focus m) (layout m))++------------------------------------------------------------------------------+-- View++ink, faint, sky, amber, good, bad, rimOn, rimOff :: Color+ink = ColorTrue 212 216 232+faint = ColorTrue 108 116 148+sky = ColorTrue 122 200 255+amber = ColorTrue 250 200 110+good = ColorTrue 130 220 150+bad = ColorTrue 245 120 120+rimOn = sky+rimOff = ColorTrue 64 70 96++ln :: Color -> String -> View m+ln c s = text s & fg c++name :: Int -> String+name i = "tile" <> show i++view :: Model -> View Msg+view m = sized $ \w h ->+ let tiles = vstack [drawLayout (pane m) w (h - 1) (layout m), statusBar m w]+ in case palette m of+ Nothing -> tiles+ Just p -> overlay (tiles & styleDim) (paletteView m w p)++statusBar :: Model -> Int -> View Msg+statusBar m w = row [text title & styleReverse & fg sky, ln faint hints'] & gap 0+ where+ title = " agents · " <> show (M.size (chats m)) <> (if zoomed m then " · zoomed " else " ")+ hints = " ^N new ^P find ^F zoom ^W close Tab/click focus ^D quit"+ hints' = take (w - length title) (hints <> repeat ' ')++pane :: Model -> Int -> Int -> Int -> View Msg+pane m i w h = case M.lookup i (chats m) of+ Just c | w >= 12 && h >= 4 ->+ let active = focus m == i && null (palette m)+ title = take (w - 6) (" " <> (if active then "● " else "") <> label i c <> " ")+ hint = suggestions !! (i `mod` length suggestions)+ body = chatView active (tick m) hint (w - 4) (h - 2) c+ in box title [vstack body & fg ink]+ & border BorderRound+ & fg (if active then rimOn else rimOff)+ & fixedWidth w & fixedHeight h+ & focusable (name i)+ & onClick (FocusOn i)+ & onKey (tileKey i)+ & onScroll (Scroll i)+ -- too small to draw, but it still needs to be focusable+ _ -> text "" & focusable (name i) & fixedWidth w & fixedHeight h++tileKey :: Int -> Key -> Maybe Msg+tileKey i = \case+ KeyCtrl 'N' -> Just NewTile+ k@(KeyChar _) -> Just (Typed i k)+ KeyBackspace -> Just (Typed i KeyBackspace)+ KeyEnter -> Just (Typed i KeyEnter)+ _ -> Nothing++paletteView :: Model -> Int -> Palette -> View Msg+paletteView m w p =+ box " find " ([header, ln rimOff (replicate innerW '─')] <> rows)+ & border BorderRound+ & fg rimOn+ & fixedWidth (innerW + 4)+ & focusable "palette"+ & onKey (Just . PaletteKey)+ where+ innerW = max 24 (min 76 (w - 10))+ found = matches m (query p)+ count = show (length found) <> "/" <> show (length (items m))+ spaces = max 1 (innerW - 3 - length (query p) - length count)+ header = row [ln sky "› ", ln ink (query p <> "█"), text (replicate spaces ' '), ln faint count] & gap 0++ visible = 12+ top = max 0 (picked p - visible + 1)+ listed+ | null found = [ln faint "nothing matches"]+ | otherwise = zipWith (\n r -> paletteRow innerW (n == picked p) r) [top ..] (take visible (drop top found))+ -- pad to a fixed height so the box doesn't jump around as you type+ rows = take visible (listed <> repeat (text ""))++paletteRow :: Int -> Bool -> (Item, [Int]) -> View Msg+paletteRow innerW isPicked (it, hits) =+ row [marker, letters, padding, ln tagColor (tag it)] & gap 0 & onClick (Pick it)+ where+ room = innerW - length (tag it) - 3+ shown = take room (key it <> extra it)+ marker = if isPicked then ln sky "▌ " else text " "+ letters = row [ ln (shade j) [ch] | (j, ch) <- zip [0 ..] shown ] & gap 0+ padding = text (replicate (room - length shown + 1) ' ')++ shade j+ | j `elem` hits = amber+ | j >= length (key it) = rimOff+ | isPicked = ink+ | otherwise = faint++ tagColor = case kind it of+ Session _ | tag it /= "idle" -> good+ Symbol -> sky+ _ -> faint++spinChar :: Int -> Char+spinChar n = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" !! (n `mod` 10)++-- A session drawn into exactly w by h: transcript, a rule, then the prompt+chatView :: Bool -> Int -> String -> Int -> Int -> Chat -> [View m]+chatView active spin hint w h c =+ shown <> replicate (room - length shown) (text "") <> [ln rimOff (replicate w '─'), prompt]+ where+ room = max 0 (h - 2)+ lines' = if null (past c) then welcome else concatMap entry (past c) <> inProgress+ shown = takeEnd room (dropEnd (scrolled c) lines')+ cursor = if active then "█" else ""+ prompt = row [ln sky "› ", ln ink (takeEnd (w - 3) (input c) <> cursor)] & gap 0++ welcome = map (ln faint) (wrapText w ("Try: " <> hint))++ inProgress = case script c of+ Think _ : _ -> [ln amber (spinChar spin : " thinking")]+ Say s : _ -> map (ln ink) (wrapText w (take (typed c) s <> "▌"))+ _ -> []++ entry = \case+ You s ->+ zipWith (sentLine w) ("› " : repeat " ") (wrapText (w - 3) s) <> [text ""]+ Said s ->+ map (ln ink) (wrapText w s) <> [text ""]+ Ran cmd Nothing ->+ [ln amber (take w (spinChar spin : " bash " <> cmd))]+ Ran cmd (Just out) ->+ ln good (take w ("✓ bash " <> cmd)) : map (ln faint . take w . (" │ " <>)) out <> [text ""]+ Edited file diff ->+ ln sky (take w ("✎ edit " <> file)) : map diffLine diff <> [text ""]++ diffLine l = ln (diffColor l) (take w (" │ " <> l))+ diffColor ('+' : _) = good+ diffColor ('-' : _) = bad+ diffColor _ = faint++-- One line of something you sent, on a highlighted strip the width of the+-- tile. layoutz has no background colour combinator yet, so this writes the+-- SGR codes by hand.+sentLine :: Int -> String -> String -> View m+sentLine w lead s =+ text (sgr "48;2;44;46;64" <> sgr "38;2;122;200;255" <> " " <> lead+ <> sgr "38;2;212;216;232" <> s <> padding <> sgr "0")+ where+ padding = replicate (w - 1 - length lead - length s) ' '+ sgr p = "\ESC[" <> p <> "m"++------------------------------------------------------------------------------+-- Helpers++wrapText :: Int -> String -> [String]+wrapText w = go . words+ where+ go [] = [""]+ go (x : xs) = line (take w x) xs++ line cur [] = [cur]+ line cur (y : ys)+ | length cur + 1 + length y <= w = line (cur <> " " <> y) ys+ | otherwise = cur : line (take w y) ys++takeEnd, dropEnd :: Int -> [a] -> [a]+takeEnd n xs = drop (length xs - n) xs+dropEnd n xs = take (length xs - n) xs++------------------------------------------------------------------------------++app :: Axis -> LayoutzApp Model Msg+app firstAxis = LayoutzApp+ { appInit = (initialModel firstAxis, cmdFocus (name 0) <> cmdTask (Indexed <$> loadIndex))+ , appUpdate = update+ , appSubscriptions = subscriptions+ , appView = view+ }++main :: IO ()+main = do+ args <- getArgs+ let firstAxis = if "--stacked" `elem` args then V else H+ void (run defaultOptions { optQuitKeys = [KeyCtrl 'D'] } (app firstAxis))
@@ -0,0 +1,29 @@+module Main where++import Layoutz++data Model = Model (SelectList String) [String] Viewport++data Msg = Moved (SelectList String) | Picked String | Scrolled Viewport++main :: IO ()+main = runApp LayoutzApp+ { appInit = (Model (selectListOf nato) [] viewportBottom, cmdNone)+ , appUpdate = \msg (Model s ls v) -> case msg of+ Moved s' -> (Model s' ls v, cmdNone)+ Picked w -> (Model s (ls <> [w]) v, cmdNone)+ Scrolled v' -> (Model s ls v', cmdNone)+ , appSubscriptions = const subNone+ , appView = \(Model s ls v) -> row+ [ pane "nato" 16 (selectList Moved Picked (pick s) s)+ , pane "picked" 20 (viewport Scrolled v (map text ls))+ ] & fixedHeight 9+ }+ where+ pane name n body = box name [body & fill] & fixedWidth n+ & focusable name+ & focusStyle (fg ColorCyan . border BorderDouble)+ pick s w = text w & if selectedItem s == Just w then styleReverse else id+ nato = words "alfa bravo charlie delta echo foxtrot golf hotel india \+ \juliett kilo lima mike november oscar papa quebec romeo \+ \sierra tango uniform victor whiskey xray yankee zulu"
@@ -0,0 +1,914 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE LambdaCase #-}++module Main where++import Control.Monad (foldM_, forM_, unless, void, when)+import Control.Monad.ST (ST, runST)+import Data.Array.Base (unsafeAt, unsafeRead, unsafeWrite)+import Data.Array.ST (STUArray, freeze, newArray)+import Data.Array.Unboxed (UArray)+import Data.Bits (shiftL, shiftR, (.&.), (.|.))+import Data.List (inits, isPrefixOf, sortOn)+import qualified Data.Map.Strict as M+import Data.Maybe (isNothing, listToMaybe)+import Data.Ord (Down (..))+import qualified Data.Text.Lazy as TL+import qualified Data.Text.Lazy.Builder as TB+import qualified Data.Text.Lazy.Builder.Int as TB+import GHC.Clock (getMonotonicTime)+import Layoutz (Cmd, Key (..), LayoutzApp (..), Options (..), cmdQuit, cmdTask, defaultOptions, run, sized, subAnimationFrame, subKeyPress, text)++type RGB = Int++rgb :: Int -> Int -> Int -> RGB+rgb r g b = r `shiftL` 16 .|. g `shiftL` 8 .|. b++-- | From @a@ toward @b@, @t@ of the way.+mix :: RGB -> RGB -> Double -> RGB+mix a b t = rgb (channel 16) (channel 8) (channel 0)+ where+ channel s =+ let x = (a `shiftR` s) .&. 255+ y = (b `shiftR` s) .&. 255+ in max 0 (min 255 (round (fromIntegral x + fromIntegral (y - x) * t)))++ground, rim, faint, dim, ink, bright, gold :: RGB+ground = rgb 10 12 22+rim = rgb 92 112 168+faint = rgb 62 70 102+dim = rgb 108 118 156+ink = rgb 196 204 232+bright = rgb 236 240 255+gold = rgb 255 204 122++--------------------------------------------------------------------------------+-- The Ainur++data Node = Node+ { nName :: String+ , nHue :: RGB+ , nWeight :: Double+ , nCard :: Maybe Card -- Nothing for a group+ , nKids :: [Node] -- heaviest first+ , nSlots :: [Slot] -- where each kid sits inside this node+ }++data Card = Card+ { cTitle :: String+ , cKind :: String+ , cFacts :: [(String, String)]+ , cStory :: String+ , cSource :: String+ }++isGroup :: Node -> Bool+isGroup = isNothing . nCard++-- | A group passes its colour down to its cards, and keeps them heaviest+-- first, the order the treemap wants.+group :: String -> RGB -> [Node] -> Node+group name hue members = Node+ { nName = name, nHue = hue, nWeight = sum (map nWeight kids)+ , nCard = Nothing, nKids = kids, nSlots = treemap (map nWeight kids) }+ where kids = sortOn (Down . nWeight) [ k { nHue = hue } | k <- members ]++-- | A card: how much room it gets, then its name, title, kind, facts, story+-- and sources.+card :: Double -> String -> String -> String -> [(String, String)] -> String -> String -> Node+card weight name title kind facts story source = Node+ { nName = name, nHue = rim, nWeight = weight+ , nCard = Just (Card title kind facts story source), nKids = [], nSlots = [] }++-- Weights are an editorial call: the eight Aratar get the most room, the+-- Maiar whom the books barely mention the least.+ainur :: Node+ainur = group "The Ainur" rim+ [ group "Manwë and Varda" (rgb 132 172 255)+ [ card 6 "Manwë" "King of Arda, Lord of the Breath of Arda" "Vala · first of the Aratar"+ [ ("dwells", "Ilmarin, upon Taniquetil")+ , ("spouse", "Varda")+ , ("kin", "brother of Melkor in the thought of Ilúvatar")+ , ("names", "Súlimo") ]+ "Dearest to Ilúvatar, and the one who best understood his purpose. The winds and the upper airs are his, and the hawks and eagles bring him word of everything. Being without evil himself he could not really comprehend it, which is how Melkor talked his way out of the Halls of Mandos."+ "Silmarillion · Valaquenta; Of Fëanor and the Unchaining of Melkor"+ , card 6 "Varda" "Queen of the Stars" "Valië · of the Aratar"+ [ ("dwells", "Ilmarin, with Manwë")+ , ("spouse", "Manwë")+ , ("names", "Elentári; Tintallë the Kindler; Elbereth Gilthoniel to the Sindar") ]+ "She made the stars before the Elves awoke, so starlight was the first thing they ever saw, and they have loved her above all the Valar since. Melkor feared her more than any of them. When Frodo cries out to Elbereth on Weathertop, she is the one he means."+ "Silmarillion · Valaquenta; Fellowship I.12"+ , card 2.6 "Eönwë" "Herald of Manwë" "Maia · banner-bearer of the West"+ [ ("serves", "Manwë") ]+ "None in Arda is his match in arms. He led the host of Valinor in the War of Wrath and kept the last two Silmarils until the sons of Fëanor stole them from his camp. Sauron came to him after the war to beg pardon; Eönwë had no power to grant it, and sent him west to be judged. Sauron did not go."+ "Silmarillion · Valaquenta; Of the Voyage of Eärendil"+ , card 1.6 "Ilmarë" "Handmaid of Varda" "Maia"+ [ ("serves", "Varda") ]+ "Named in the Valaquenta as chief of Varda's handmaidens and hardly anywhere else. Tolkien leaves a good many of the Ainur like this: a name, a place and a dignity, and then they stay in the background, in the light."+ "Silmarillion · Valaquenta"+ ]+ , group "Ulmo" (rgb 84 176 206)+ [ card 6 "Ulmo" "Lord of Waters, King of the Sea" "Vala · of the Aratar"+ [ ("dwells", "the Outer Sea, and the waters under the world")+ , ("spouse", "none")+ , ("people", "Ossë, Uinen, Salmar") ]+ "He keeps no hall in Valinor and seldom comes to its councils. Of all the Valar he never gave up on Middle-earth, and speaks through its springs and rivers to anyone who will listen. He rose out of the sea at Vinyamar to send Tuor to Gondolin."+ "Silmarillion · Valaquenta; Of Tuor and the Fall of Gondolin"+ , card 2.4 "Ossë" "Master of the waves" "Maia · vassal of Ulmo"+ [ ("spouse", "Uinen")+ , ("seas", "those that wash the shores of Middle-earth") ]+ "He delights in storms. For a time Melkor won him over, and Uinen brought him back to Ulmo. He taught the Falathrim of the coasts their seacraft, and it was Ossë who raised the land of Númenor up out of the deep."+ "Silmarillion · Valaquenta; Akallabêth"+ , card 2.2 "Uinen" "Lady of the Seas" "Maia"+ [ ("spouse", "Ossë") ]+ "Her hair lies spread through all the waters under heaven. She loves everything that lives in the salt streams and calms whatever Ossë stirs up. Sailors call on her, and the Númenóreans held her as high as any of the Valar."+ "Silmarillion · Valaquenta"+ , card 1.6 "Salmar" "Maker of the Ulumúri" "Maia"+ [ ("serves", "Ulmo") ]+ "He came into the world with Ulmo and made the great horns on which Ulmo is heard. Whoever hears them never stops longing for the sea afterwards. That is all we are told about him."+ "Silmarillion · Valaquenta"+ ]+ , group "Aulë and Yavanna" (rgb 196 168 108)+ [ card 6 "Aulë" "The Smith" "Vala · of the Aratar"+ [ ("dwells", "his halls in the midst of Valinor")+ , ("spouse", "Yavanna")+ , ("people", "Curumo; Sauron, before his fall") ]+ "Lord of the substances of Arda and of every craft that shapes them. Too impatient to wait for the Children, he made the Seven Fathers of the Dwarves in secret; found out, he raised his hammer to destroy them, and Ilúvatar spared them. The Noldor learned from him, and so, early on, did Sauron."+ "Silmarillion · Valaquenta; Of Aulë and Yavanna"+ , card 6 "Yavanna" "Giver of Fruits, Queen of the Earth" "Valië · of the Aratar"+ [ ("spouse", "Aulë")+ , ("kin", "elder sister of Vána")+ , ("names", "Kementári") ]+ "Everything that grows is hers. She sang the Two Trees out of the green mound Ezellohar. When Aulë confessed the Dwarves she feared for her forests and asked for guardians, and the Shepherds of the Trees were the answer."+ "Silmarillion · Valaquenta; Of Aulë and Yavanna"+ , card 3 "Curumo" "Saruman, chief of the Istari" "Maia · of Aulë's people"+ [ ("names", "Saruman; Curunír, the man of skill") ]+ "Sent with the other Istari to stand against Sauron, and forbidden to meet his power with power. He studied the Enemy's craft until he wanted the Ring for himself, and ended in the Shire, killed on a doorstep by his own servant."+ "Unfinished Tales · The Istari; Return of the King VI.8"+ , card 2.4 "Aiwendil" "Radagast the Brown" "Maia · of Yavanna's people · Istar"+ [ ("dwelt", "Rhosgobel, by the eaves of Mirkwood") ]+ "Yavanna begged Curumo to take him along, and Curumo did, with a bad grace. He grew fonder of birds and beasts than of Elves and Men. The errand he honestly carried for Saruman is what brought Gwaihir to the roof of Orthanc to carry Gandalf off."+ "Unfinished Tales · The Istari; Fellowship II.2"+ ]+ , group "Oromë and Vána" (rgb 116 190 142)+ [ card 6 "Oromë" "The Huntsman, Lord of Forests" "Vala · of the Aratar"+ [ ("spouse", "Vána")+ , ("kin", "brother of Nessa")+ , ("names", "Aldaron; Tauron; Araw to the Sindar") ]+ "Through the long dark he kept riding into Middle-earth on his white horse Nahar, hunting Melkor's creatures, and so he was the one who found the Elves by the water of Cuiviénen. His horn is the Valaróma. The wild white kine near the Sea of Rhûn were said to come from his herds."+ "Silmarillion · Valaquenta; Of the Coming of the Elves; RotK App. A"+ , card 4 "Vána" "The Ever-young" "Valië"+ [ ("spouse", "Oromë")+ , ("kin", "younger sister of Yavanna") ]+ "Flowers open as she passes and birds sing at her coming. Little more is said of her, except through those who served her: Arien kept the golden flowers of her gardens, and Melian was of her people."+ "Silmarillion · Valaquenta"+ , card 2.4 "Arien" "Bearer of the Sun" "Maia · a spirit of fire"+ [ ("carries", "the Sun, the last fruit of Laurelin") ]+ "She tended the golden flowers in the gardens of Vána and watered them with the dew of Laurelin. Melkor had never managed to draw her to him. The Noldor called the Sun Vása, the Heart of Fire."+ "Silmarillion · Of the Sun and Moon"+ , card 2.4 "Tilion" "Steersman of the Moon" "Maia · a hunter of Oromë"+ [ ("carries", "the Moon, the last flower of Telperion") ]+ "A young hunter with a silver bow, who loved silver. He asked for the Moon and was given it. He loved Arien too, and would stray toward her and be scorched, which is why the Moon's path wavers and its face is marked."+ "Silmarillion · Of the Sun and Moon"+ , card 2.4 "Alatar & Pallando" "The Blue Wizards" "Maiar · Istari"+ [ ("names", "Ithryn Luin")+ , ("chosen", "Alatar by Oromë; Pallando went as his friend") ]+ "They went into the East and did not come back, and the West never learned what became of them. Tolkien changed his mind: in one letter they failed and founded secret cults, in later notes they hindered Sauron in the East more than anyone knew."+ "Unfinished Tales · The Istari; Letters 211"+ ]+ , group "The Fëanturi and Nienna" (rgb 162 146 232)+ [ card 6 "Námo" "Mandos, Doomsman of the Valar" "Vala · of the Aratar"+ [ ("dwells", "the Halls of Mandos, in the west of Valinor")+ , ("spouse", "Vairë")+ , ("kin", "brother of Irmo and Nienna") ]+ "He forgets nothing, and knows all that is to come except what Ilúvatar keeps to himself. He speaks the judgements of the Valar, and the Doom of the Noldor was spoken in his voice. He was moved to pity once: by Lúthien, singing to him of her grief and Beren's."+ "Silmarillion · Valaquenta; Of Beren and Lúthien"+ , card 4 "Vairë" "The Weaver" "Valië"+ [ ("spouse", "Námo")+ , ("dwells", "the Halls of Mandos") ]+ "She weaves everything that has ever happened in Time into storied webs. The halls of Mandos widen as the ages pass, and her webs hang on every wall."+ "Silmarillion · Valaquenta"+ , card 4 "Irmo" "Lórien, master of visions and dreams" "Vala"+ [ ("dwells", "the gardens of Lórien")+ , ("spouse", "Estë")+ , ("kin", "brother of Námo and Nienna") ]+ "His gardens are the fairest place in the world and full of spirits; the Valar themselves go there to rest. He and his brother are the Fëanturi, the masters of spirits."+ "Silmarillion · Valaquenta"+ , card 4 "Estë" "The Gentle, healer of hurt and weariness" "Valië"+ [ ("spouse", "Irmo")+ , ("dwells", "an island in the lake Lórellin") ]+ "She dresses in grey and her gift is rest. By day she sleeps on her island in the shaded lake of Lórellin, and the weary of Valinor go to her to be made whole."+ "Silmarillion · Valaquenta"+ , card 6 "Nienna" "Lady of pity and mourning" "Valië · of the Aratar"+ [ ("dwells", "at the western edge of the world")+ , ("kin", "sister of the Fëanturi") ]+ "She grieves for every hurt Melkor did to Arda, and in those who listen to her, grief turns to wisdom. When the Two Trees were dying, Yavanna's song and Nienna's tears drew from them a last flower and a last fruit, and those became the Moon and the Sun."+ "Silmarillion · Valaquenta; Of the Sun and Moon"+ , card 3 "Olórin" "Gandalf, Mithrandir" "Maia · Istar"+ [ ("dwelt", "in Lórien, often at Nienna's house")+ , ("names", "Mithrandir; Tharkûn; Incánus") ]+ "The wisest of the Maiar, who learned pity and patience from Nienna. Asked to go to Middle-earth, he said he was too weak and that he feared Sauron. Manwë said that was all the more reason to go. He came last of the five and was the one who saw the errand through."+ "Unfinished Tales · The Istari"+ , card 3 "Melian" "Queen of Doriath" "Maia"+ [ ("spouse", "Elwë Thingol")+ , ("child", "Lúthien") ]+ "Nightingales sang about her in the gardens of Lórien. Elwë heard her in the woods of Nan Elmoth and the two of them stood there, silent, while the trees grew tall. Her Girdle kept Doriath hidden for an age, and was lifted when Thingol died and she left Middle-earth."+ "Silmarillion · Of Thingol and Melian; Of the Ruin of Doriath"+ ]+ , group "Tulkas and Nessa" (rgb 232 156 112)+ [ card 4 "Tulkas" "Astaldo, the Valiant" "Vala"+ [ ("spouse", "Nessa") ]+ "Last of the Valar to come into Arda, drawn by the noise of the first war, and Melkor fled from his laughter. He fights bare-handed and needs no horse. No use at all in a council, but the friend you want in a fight. He wrestled Melkor down to be bound in the chain Angainor."+ "Silmarillion · Valaquenta; Ainulindalë; Of the Coming of the Elves"+ , card 4 "Nessa" "The Dancer" "Valië"+ [ ("spouse", "Tulkas")+ , ("kin", "sister of Oromë") ]+ "Quick as an arrow. The deer follow her through the wild and cannot keep up. She dances on the lawns of Valmar, which are always green."+ "Silmarillion · Valaquenta"+ ]+ , group "The Fallen" (rgb 214 92 92)+ [ card 6 "Melkor" "Morgoth, the Black Foe of the World" "Ainu · once the mightiest of them"+ [ ("kin", "brother of Manwë in the thought of Ilúvatar")+ , ("names", "Morgoth Bauglir, the Constrainer") ]+ "He was given the greatest share of power and knowledge, and wanted above all to bring into being things of his own. Failing that, he set out to master or ruin what others made. Fëanor named him Morgoth after he killed Finwë and took the Silmarils. He is not counted among the Valar."+ "Silmarillion · Ainulindalë; Valaquenta; Of the Flight of the Noldor"+ , card 3 "Sauron" "Mairon, Gorthaur, Annatar" "Maia · once of Aulë's people"+ [ ("served", "Melkor") ]+ "He began by loving order and design and came to love only his own will, imposed on everything. Morgoth's lieutenant in the First Age; in the Second, Annatar, Lord of Gifts, who taught the smiths of Eregion and in secret forged the One Ring. Unlike his master he never wanted the world destroyed. He wanted it his."+ "Silmarillion · Valaquenta; Of the Rings of Power"+ , card 2.2 "Gothmog" "Lord of Balrogs" "Maia · a Valarauko"+ [ ("served", "Melkor") ]+ "High-captain of Angband. He struck down Fëanor and slew Fingon, and at the fall of Gondolin he fought Ecthelion of the Fountain, and the two of them went down together into the fountain in the King's square."+ "Silmarillion · Of the Fifth Battle; Of Tuor and the Fall of Gondolin"+ , card 2.2 "Durin's Bane" "The Balrog of Moria" "Maia · a Valarauko"+ [ ("served", "Melkor") ]+ "It fled the ruin of Angband and hid at the roots of the mountains. The Dwarves of Khazad-dûm, mining too deep after mithril, woke it; it killed two of their kings and emptied the city. Gandalf broke the bridge beneath it, they fell together, and fought all the way up to the peak of Zirakzigil."+ "Fellowship II.5; Two Towers III.5; RotK App. A"+ ]+ , group "Of no known kind" (rgb 168 176 198)+ [ card 2.8 "Tom Bombadil" "Eldest, master of wood, water and hill" "of no known kind"+ [ ("dwells", "by the Withywindle, in the Old Forest")+ , ("spouse", "Goldberry") ]+ "He remembers the first raindrop and the first acorn. The Ring has no hold on him: he puts it on and does not vanish. Readers have made him a Maia, a Vala, Eru, the spirit of Arda itself. Tolkien wrote that even a mythology needs some enigmas, and left him one on purpose."+ "Fellowship I.7; Letters 144"+ , card 1.8 "Goldberry" "The River-daughter" "of no known kind"+ [ ("spouse", "Tom Bombadil")+ , ("kin", "daughter of the River-woman of the Withywindle") ]+ "Some read her as a Maia of the waters, some as the turning of the seasons. The books never say what she is, and she does not seem to mind."+ "Fellowship I.7; The Adventures of Tom Bombadil"+ , card 2.4 "Ungoliant" "Gloomweaver" "of no known kind"+ [ ("child", "the last of her brood was Shelob") ]+ "The Eldar did not know where she came from; some said she was a spirit Melkor corrupted before the world began. With him she killed the Two Trees and drank their light, then turned on him for the jewels, and only his Balrogs saved him."+ "Silmarillion · Of the Darkening of Valinor; Of the Flight of the Noldor"+ ]+ ]++--------------------------------------------------------------------------------+-- A card, set like a page++data Role = Name | Title | Kind | Label | Value | Story | Source deriving Eq++-- | How wide a card's text runs when there's room.+measure :: Int+measure = 58++wrap :: Int -> String -> [String]+wrap width = go . words+ where+ go [] = []+ go (w : ws) = let (line, rest) = fill w ws in line : go rest+ fill line (w : ws) | length line + 1 + length w <= width = fill (line ++ " " ++ w) ws+ fill line ws = (line, ws)++-- | A card's lines at a given width, each a run of pieces in some role.+setCard :: Int -> Node -> Card -> [[(Role, String)]]+setCard width n c =+ [[(Name, nName n)], [(Title, cTitle c)], [], [(Kind, cKind c)]]+ ++ concatMap fact (cFacts c)+ ++ [[]] ++ [ [(Story, l)] | l <- wrap width (cStory c) ]+ ++ [[]] ++ [ [(Source, l)] | l <- wrap width (cSource c) ]+ where+ fact (label, value) = case wrap (width - labelWidth) value of+ first : more -> [(Label, pad label), (Value, first)] : [ [(Label, pad ""), (Value, l)] | l <- more ]+ [] -> []+ labelWidth = 10+ pad s = s ++ replicate (labelWidth - length s) ' '++roleColour :: RGB -> Role -> RGB+roleColour hue = \case+ Name -> bright+ Title -> mix hue bright 0.3+ Kind -> dim+ Label -> faint+ Value -> ink+ Story -> ink+ Source -> dim++regular, bold, italic :: Int+regular = 0+bold = 1+italic = 2++roleStyle :: Role -> Int+roleStyle = \case+ Name -> bold+ Kind -> italic+ Source -> italic+ _ -> regular++--------------------------------------------------------------------------------+-- Squarified treemap (Bruls, Huizing and van Wijk)++-- | Part of a parent's inner area, as fractions of it.+data Slot = Slot !Double !Double !Double !Double++-- | Every group is laid out as if it filled a screen this much wider than+-- tall, in square units (a cell is about half as wide as it is tall).+aspect :: Double+aspect = 1.9++treemap :: [Double] -> [Slot]+treemap [] = []+treemap weights = [ Slot (x / aspect) y (w / aspect) h | (x, y, w, h) <- squarify areas (0, 0, aspect, 1) ]+ where areas = map (* (aspect / sum weights)) weights++type Box = (Double, Double, Double, Double)++-- | Lay areas (largest first) into a box, a strip at a time along its+-- shorter side, adding to each strip while that makes its worst tile less+-- skinny.+squarify :: [Double] -> Box -> [Box]+squarify [] _ = []+squarify (a : others) box@(_, _, w, h) = placed ++ squarify rest box'+ where+ side = min w h+ (strip, rest) = grow [a] others+ grow acc (next : more) | worst (next : acc) <= worst acc = grow (next : acc) more+ grow acc more = (reverse acc, more)+ worst acc = let s = sum acc in max (side * side * maximum acc / (s * s)) (s * s / (side * side * minimum acc))+ (placed, box') = layStrip strip box++layStrip :: [Double] -> Box -> ([Box], Box)+layStrip strip (x, y, w, h)+ | w >= h = let cw = total / h in (zipWith (\o a -> (x, y + o, cw, a / cw)) (offsets cw) strip, (x + cw, y, w - cw, h))+ | otherwise = let rh = total / w in (zipWith (\o a -> (x + o, y, a / rh, rh)) (offsets rh) strip, (x, y + rh, w, h - rh))+ where+ total = sum strip+ offsets d = scanl (+) 0 (map (/ d) strip)++--------------------------------------------------------------------------------+-- Geometry++-- | A rectangle on screen, in cells, before rounding.+data Rect = Rect !Double !Double !Double !Double++-- | Which kid to take at each level, from the top.+type Path = [Int]++nodeAt :: Path -> Node+nodeAt = foldl (\n i -> nKids n !! i) ainur++place :: Rect -> Slot -> Rect+place (Rect x y w h) (Slot a b c d) = Rect (x + a * w) (y + b * h) (c * w) (d * h)++-- | The area that puts a slot at this rectangle.+unplace :: Rect -> Slot -> Rect+unplace (Rect x y w h) (Slot a b c d) = Rect (x - a * pw) (y - b * ph) pw ph+ where pw = w / c; ph = h / d++-- | Inside a box's border, and the box around such an inside.+inside, around :: Rect -> Rect+inside (Rect x y w h) = Rect (x + 1) (y + 1) (w - 2) (h - 2)+around (Rect x y w h) = Rect (x - 1) (y - 1) (w + 2) (h + 2)++-- | Where a node lands when the top is at @r@.+descend :: Rect -> Path -> Rect+descend = go ainur+ where+ go _ r [] = r+ go n r (i : is) = go (nKids n !! i) (place (inside r) (nSlots n !! i)) is++-- | Where the top must be for the node at @path@ to land on @r@.+rootFor :: Path -> Rect -> Rect+rootFor path r = foldr up r (zip (scanl (\n i -> nKids n !! i) ainur path) path)+ where up (parent, i) inner = around (unplace inner (nSlots parent !! i))++-- | A card keeps a column of air to its right and a row below, once it's+-- big enough to spare them.+cardArea :: Rect -> Rect+cardArea (Rect x y w h) = Rect x y (w - spare w) (h - spare h)+ where spare d = if d >= 4 then 1 else 0++nearest :: Double -> Int+nearest v = floor (v + 0.5)++-- | Rounded to whole cells: left, top, right, bottom (the last two exclusive).+cells :: Rect -> (Int, Int, Int, Int)+cells (Rect x y w h) = (nearest x, nearest y, nearest (x + w), nearest (y + h))++--------------------------------------------------------------------------------+-- Motion++-- | Between two rectangles the way a camera zooms: about the one point that+-- stays put, the size changing by the same factor each moment, so it reads+-- as moving closer rather than as a box stretching.+zoom :: Double -> Rect -> Rect -> Rect+zoom t (Rect x0 y0 w0 h0) (Rect x1 y1 w1 h1) = Rect x y w h+ where+ (x, w) = axis x0 w0 x1 w1+ (y, h) = axis y0 h0 y1 h1+ axis a0 s0 a1 s1+ | abs (k - 1) < 1e-4 = (a0 + (a1 - a0) * t, s0 + (s1 - s0) * t)+ | otherwise = (p + (a0 - p) * k ** t, s0 * k ** t)+ where+ k = s1 / s0+ p = (a1 - a0 * k) / (1 - k) -- the point that stays put++lerpSlot :: Double -> Slot -> Slot -> Slot+lerpSlot t (Slot a b c d) (Slot a' b' c' d') = Slot (l a a') (l b b') (l c c') (l d d')+ where l p q = p + (q - p) * t++clamp01 :: Double -> Double+clamp01 = max 0 . min 1++-- | Most of the way at once, then settling.+easeOut :: Double -> Double+easeOut t = 1 - (1 - t) ^ (5 :: Int)++-- | The camera's curve: 'easeOut' with a little constant speed mixed in, so+-- it comes in to land instead of crawling. A crawl is invisible in itself,+-- but the odd cell it still crosses is not: a tile rounding a column wider+-- re-wraps its text a beat after everything looked still. With this the last+-- cells go by at about one a frame, and then it stops.+land :: Double -> Double+land t = (easeOut t + 0.15 * t) / 1.15++zoomTime, hurriedTime, openingTime, glideTime, fadeTime, oneFrame :: Double+zoomTime = 0.22+hurriedTime = 0.11+openingTime = 0.5+glideTime = 0.12+fadeTime = 0.1+oneFrame = 1 / 60++-- | Into a kid, or back out of it. Either way the camera holds on the kid,+-- moving it between where it sits in its group and filling the screen.+data Move = Move+ { mvKid :: Path+ , mvInto :: Bool+ , mvLength :: Double+ , mvStart :: Maybe Double -- once it reaches the front of the queue+ }++--------------------------------------------------------------------------------+-- The app++data Model = Model+ { mAt :: Path -- where the camera is, or is heading+ , mSelected :: Int -- the selected kid, when that's a group+ , mRemembered :: M.Map Path Int -- what was selected in each group, for coming back+ , mMoves :: [Move] -- camera moves still to play+ , mNow :: Double+ , mOpenedAt :: Maybe Double -- when the opening zoom began+ , mFocusWas :: (Path, Int) -- where focus was, to fade from+ , mFocusMovedAt :: Double+ , mOutlineFrom :: Slot -- where the selection outline set off from+ , mOutlineMovedAt :: Double+ , mOutlineLitAt :: Double -- when it last faded in+ }++data Msg+ = Frame Double -- an animation frame, at its time+ | Pressed Key+ | PressedAt Key Double -- the same key, stamped with the time++start :: Model+start = Model+ { mAt = [], mSelected = 0, mRemembered = M.empty, mMoves = [], mNow = 0, mOpenedAt = Nothing+ , mFocusWas = ([], 0), mFocusMovedAt = 0+ , mOutlineFrom = Slot 0 0 0 0, mOutlineMovedAt = 0, mOutlineLitAt = 0 }++app :: LayoutzApp Model Msg+app = LayoutzApp+ { appInit = (start, mempty)+ , appUpdate = update+ , appSubscriptions = \m -> subKeyPress (Just . Pressed) <> (if moving m then subAnimationFrame Frame else mempty)+ , appView = \m -> sized (\w h -> text (TL.unpack (scene m (max 30 w) (max 8 h))))+ }++update :: Msg -> Model -> (Model, Cmd Msg)+update msg m = case msg of+ Frame t -> (frame t m, mempty)+ Pressed (KeyChar 'q') -> (m, cmdQuit)+ -- Stamping the key first means whatever it starts starts now, not back at+ -- the last frame, which may have been a while ago.+ Pressed key -> (m, cmdTask (PressedAt key <$> getMonotonicTime))+ -- Drawn one frame in, so the first frame after a press already moves.+ PressedAt key t -> ((advance (navigate key (advance m { mNow = t }))) { mNow = t + oneFrame }, mempty)++frame :: Double -> Model -> Model+frame t m = case mOpenedAt m of+ Nothing -> m { mNow = t, mOpenedAt = Just t, mOutlineLitAt = t + openingTime }+ Just _ -> advance m { mNow = max t (mNow m) }++here :: Model -> Node+here m = nodeAt (mAt m)++-- | How far along something started at @t0@ is, on a curve.+since :: (Double -> Double) -> Model -> Double -> Double -> Double+since curve m t0 duration = curve (clamp01 ((mNow m - t0) / duration))++-- | Anything still on its way. Frames are only asked for until it has all+-- arrived, so a still screen costs nothing.+moving :: Model -> Bool+moving m = case mOpenedAt m of+ Nothing -> True+ Just t0 -> not (null (mMoves m)) || mNow m < maximum+ [ t0 + openingTime, mFocusMovedAt m + fadeTime+ , mOutlineMovedAt m + glideTime, mOutlineLitAt m + fadeTime ]++-- | The node the camera holds on, where it is on screen, and where the+-- move under way takes it from and to, if one is.+camera :: Model -> Rect -> (Path, Rect, Maybe (Rect, Rect))+camera m screen = case (mMoves m, mOpenedAt m) of+ (Move kid into duration started : _, _) ->+ let sits = place (inside screen) (nSlots (nodeAt (init kid)) !! last kid)+ t = maybe 0 (\t0 -> since land m t0 duration) started+ in if into then travel kid t sits screen else travel kid t screen sits+ ([], Nothing) -> ([], speck, Nothing)+ ([], Just t0) -> travel (mAt m) (since land m t0 openingTime) speck screen+ where+ travel held t from to = (held, zoom t from to, if t < 1 then Just (from, to) else Nothing)+ Rect x y w h = screen+ speck = Rect (x + w / 2 - 2) (y + h / 2 - 1) 4 2++selectedSlot :: Model -> Slot+selectedSlot m = nSlots (here m) !! mSelected m++-- | Where the selection outline is, gliding toward the selected tile.+outlineNow :: Model -> Slot+outlineNow m = lerpSlot (since easeOut m (mOutlineMovedAt m) glideTime) (mOutlineFrom m) (selectedSlot m)++-- | Start the move at the front of the queue, or retire it once it's done.+-- When the last one stops the selection lights up, so nothing moves after.+advance :: Model -> Model+advance m = case mMoves m of+ [] -> m+ mv : rest -> case mvStart mv of+ Nothing -> advance m { mMoves = mv { mvStart = Just (mNow m) } : rest }+ Just t0+ | mNow m < t0 + mvLength mv -> m+ | next : more <- rest -> m { mMoves = next { mvStart = Just (t0 + mvLength mv) } : more }+ | otherwise -> lightUp m { mMoves = [] }++-- | The outline fades in where it belongs. Growing it from the middle would+-- sweep its edges across the text just as everything else settled.+lightUp :: Model -> Model+lightUp m+ | isGroup (here m) = m { mOutlineFrom = selectedSlot m, mOutlineMovedAt = mNow m, mOutlineLitAt = mNow m }+ | otherwise = m++-- | Queue a move. Keys pressed while one is under way hurry the rest along,+-- so quick fingers never wait on the animation.+enqueue :: Move -> Model -> Model+enqueue mv m = m { mMoves = case mMoves m of+ [] -> [mv]+ cur : rest -> hurry cur : map quick rest ++ [quick mv] }+ where+ hurry c = case mvStart c of+ Just t0 -> let ran = mNow m - t0 in c { mvLength = max ran (min (mvLength c) (ran + 0.06)) }+ Nothing -> quick c+ quick c = c { mvLength = hurriedTime }++-- | Note where focus was, so the change can fade in.+refocus :: Model -> Model+refocus m = m { mFocusWas = (mAt m, mSelected m), mFocusMovedAt = mNow m }++navigate :: Key -> Model -> Model+navigate key m = case key of+ KeyUp -> arrow (0, -1)+ KeyDown -> arrow (0, 1)+ KeyLeft -> arrow (-1, 0)+ KeyRight -> arrow (1, 0)+ KeyEnter | isGroup (here m) -> enter (mSelected m) m+ KeyEscape -> leave m+ KeyBackspace -> leave m+ _ -> m+ where+ -- In a group the outline glides on from wherever it is. On an open card+ -- the camera steps back out and into the neighbour.+ arrow dir+ | isGroup (here m) = maybe m select (neighbour dir (here m) (mSelected m))+ | null (mAt m) = m+ | otherwise = maybe m (\i -> enter i (leave m)) (neighbour dir (nodeAt (init (mAt m))) (last (mAt m)))+ select i = (refocus m) { mSelected = i, mOutlineFrom = outlineNow m, mOutlineMovedAt = mNow m }++enter :: Int -> Model -> Model+enter i m = enqueue (Move kid True zoomTime Nothing) (refocus m)+ { mAt = kid+ , mSelected = M.findWithDefault 0 kid (mRemembered m)+ , mRemembered = M.insert (mAt m) i (mRemembered m) }+ where kid = mAt m ++ [i]++leave :: Model -> Model+leave m+ | null (mAt m) = m+ | otherwise = enqueue (Move (mAt m) False zoomTime Nothing) (refocus m)+ { mAt = init (mAt m), mSelected = last (mAt m) }++-- | The nearest kid in a direction, between centres, in square units.+neighbour :: (Double, Double) -> Node -> Int -> Maybe Int+neighbour (dx, dy) n from = snd <$> listToMaybe (sortOn fst candidates)+ where+ slots = nSlots n+ centre (Slot x y w h) = ((x + w / 2) * aspect, y + h / 2)+ (cx, cy) = centre (slots !! from)+ candidates =+ [ (along + 2.5 * abs across, i)+ | (i, s) <- zip [0 ..] slots, i /= from+ , let (ox, oy) = centre s+ along = (ox - cx) * dx + (oy - cy) * dy+ across = (ox - cx) * dy - (oy - cy) * dx+ , along > 1e-3 ]++--------------------------------------------------------------------------------+-- A grid of cells to draw into, then turned into one ANSI string++data Grid s = Grid+ { gWidth, gHeight :: !Int+ , gClip :: !(Int, Int, Int, Int) -- left, top, right, bottom; the last two exclusive+ , gChars :: STUArray s Int Char+ , gFg, gBg :: STUArray s Int RGB+ , gStyle :: STUArray s Int Int+ }++type Frozen = (UArray Int Char, UArray Int RGB, UArray Int RGB, UArray Int Int)++newGrid :: Int -> Int -> ST s (Grid s)+newGrid w h = Grid w h (0, 0, w, h) <$> new ' ' <*> new ink <*> new ground <*> new regular+ where new value = newArray (0, w * h - 1) value++freezeGrid :: Grid s -> ST s Frozen+freezeGrid g = (,,,) <$> freeze (gChars g) <*> freeze (gFg g) <*> freeze (gBg g) <*> freeze (gStyle g)++colsIn, rowsIn :: Grid s -> Int -> Int -> [Int]+colsIn g a b = let (x0, _, x1, _) = gClip g in [max a x0 .. min b x1 - 1]+rowsIn g a b = let (_, y0, _, y1) = gClip g in [max a y0 .. min b y1 - 1]++inClip :: Grid s -> Int -> Int -> Bool+inClip g x y = let (x0, y0, x1, y1) = gClip g in x >= x0 && y >= y0 && x < x1 && y < y1++index :: Grid s -> Int -> Int -> Int+index g x y = y * gWidth g + x++-- | A character in a colour and style, over whatever background is there.+put :: Grid s -> Int -> Int -> Char -> RGB -> Int -> ST s ()+put g x y c fg st = when (inClip g x y) $ do+ unsafeWrite (gChars g) (index g x y) c+ unsafeWrite (gFg g) (index g x y) fg+ unsafeWrite (gStyle g) (index g x y) st++charAt :: Grid s -> Int -> Int -> ST s (Maybe Char)+charAt g x y+ | inClip g x y = Just <$> unsafeRead (gChars g) (index g x y)+ | otherwise = pure Nothing++tintBg :: Grid s -> Int -> Int -> (RGB -> RGB) -> ST s ()+tintBg g x y f = when (inClip g x y) $+ unsafeRead (gBg g) (index g x y) >>= unsafeWrite (gBg g) (index g x y) . f++fillRect :: Grid s -> Int -> Int -> Int -> Int -> RGB -> ST s ()+fillRect g x0 y0 x1 y1 bg = forM_ (rowsIn g y0 y1) $ \y -> forM_ (colsIn g x0 x1) $ \x -> do+ unsafeWrite (gChars g) (index g x y) ' '+ unsafeWrite (gBg g) (index g x y) bg+ unsafeWrite (gStyle g) (index g x y) regular++-- | Text, cut off at @right@. Returns the column after it.+write :: Grid s -> Int -> Int -> Int -> String -> RGB -> Int -> ST s Int+write g x0 y right str fg st = go x0 str+ where+ go !x (c : cs) | x < right = put g x y c fg st >> go (x + 1) cs+ go x _ = pure x++-- | A rounded outline. With @keepTitle@ its top edge goes around any text+-- already there, the way a title sits in a border.+outline :: Grid s -> Bool -> Int -> Int -> Int -> Int -> RGB -> ST s ()+outline g keepTitle x0 y0 x1 y1 colour = do+ let xr = x1 - 1+ yb = y1 - 1+ edge = maybe False (`elem` " ─╭╮")+ forM_ (colsIn g (x0 + 1) xr) $ \x -> do+ this <- charAt g x y0+ left <- charAt g (x - 1) y0+ right <- charAt g (x + 1) y0+ when (not keepTitle || this == Just '─' || (this == Just ' ' && edge left && edge right)) $+ put g x y0 '─' colour regular+ put g x yb '─' colour regular+ forM_ (rowsIn g (y0 + 1) yb) $ \y -> put g x0 y '│' colour regular >> put g xr y '│' colour regular+ put g x0 y0 '╭' colour regular >> put g xr y0 '╮' colour regular+ put g x0 yb '╰' colour regular >> put g xr yb '╯' colour regular++-- | The grid as lines of text. The pen (foreground, background, style) only+-- changes where it has to, and a space has no foreground to change.+toAnsi :: Int -> Int -> Frozen -> TL.Text+toAnsi width height (chars, fgs, bgs, styles) = TB.toLazyText (foldMap line [0 .. height - 1])+ where+ line y = cellsFrom (y * width) (y * width + width) (-1) (-1) (-1)+ <> (if y < height - 1 then TB.singleton '\n' else mempty)+ cellsFrom :: Int -> Int -> RGB -> RGB -> Int -> TB.Builder+ cellsFrom !i !end !fg !bg !st+ | i >= end = str "\ESC[0m"+ | otherwise = change <> TB.singleton c <> cellsFrom (i + 1) end fg' bg' st'+ where+ c = unsafeAt chars i+ f = unsafeAt fgs i+ b = unsafeAt bgs i+ s = unsafeAt styles i+ blank = c == ' '+ (change, fg', bg', st')+ | not blank && s /= st = (pen (reset s <> colour 38 f <> str ";" <> colour 48 b), f, b, s)+ | not blank && f /= fg && b /= bg = (pen (colour 38 f <> str ";" <> colour 48 b), f, b, st)+ | b /= bg = (pen (colour 48 b), fg, b, st)+ | not blank && f /= fg = (pen (colour 38 f), f, bg, st)+ | otherwise = (mempty, fg, bg, st)+ str = TB.fromString+ pen p = str "\ESC[" <> p <> str "m"+ reset s = str "0;" <> (if s .&. bold /= 0 then str "1;" else mempty) <> (if s .&. italic /= 0 then str "3;" else mempty)+ colour :: Int -> RGB -> TB.Builder+ colour layer c = TB.decimal layer <> str ";2;" <> TB.decimal (c `shiftR` 16) <> str ";"+ <> TB.decimal ((c `shiftR` 8) .&. 255) <> str ";" <> TB.decimal (c .&. 255)++--------------------------------------------------------------------------------+-- Drawing++-- | How the map is drawn this frame.+data Look = Look+ { lWidth :: Int+ , lRecede :: Path -> Double -- how far a node has faded back+ , lLit :: Maybe Path -- the selected tile, once the camera has stopped+ , lEnds :: Maybe (Rect, Rect) -- where the top starts and ends the move under way+ }++scene :: Model -> Int -> Int -> TL.Text+scene m width height = toAnsi width height $ runST $ do+ g <- newGrid width height+ let screen = Rect 1 1 (fromIntegral width - 2) (fromIntegral height - 3)+ (held, heldAt, ends) = camera m screen+ top = rootFor held heldAt+ settled = null (mMoves m) && maybe False (\t0 -> mNow m >= t0 + openingTime) (mOpenedAt m)+ showOutline = settled && isGroup (here m)+ look = Look+ { lWidth = width+ , lRecede = recede m+ , lLit = if showOutline then Just (mAt m ++ [mSelected m]) else Nothing+ , lEnds = fmap (\(a, b) -> (rootFor held a, rootFor held b)) ends }+ mapArea = g { gClip = (0, 1, width, height - 1) }+ drawNode mapArea look [] ainur top+ when showOutline $ drawSelection mapArea m (descend top (mAt m))+ drawPath g m+ drawHints g m+ freezeGrid g++-- | How far a node fades back. Outside the open group it fades most; inside,+-- everything but the selection a little.+recede :: Model -> Path -> Double+recede m p = from + (to - from) * since easeOut m (mFocusMovedAt m) fadeTime+ where+ from = fadeFor (mFocusWas m)+ to = fadeFor (mAt m, mSelected m)+ fadeFor (at, sel)+ | p `isPrefixOf` at = 0+ | at `isPrefixOf` p = if isGroup (nodeAt at) && p !! length at /= sel then 0.22 else 0+ | otherwise = 0.65++drawNode :: Grid s -> Look -> Path -> Node -> Rect -> ST s ()+drawNode g look path n r@(Rect x y w h)+ | x + w < 0 || y + h < 0 || x > fromIntegral (gWidth g) || y > fromIntegral (gHeight g) = pure ()+ | c1 - c0 < 1 || r1 - r0 < 1 = pure ()+ | Just c <- nCard n = drawCard g look path n c (cardArea r)+ | otherwise = drawGroup g look path n r+ where (c0, r0, c1, r1) = cells r++drawGroup :: Grid s -> Look -> Path -> Node -> Rect -> ST s ()+drawGroup g look path n r = do+ let (c0, r0, c1, r1) = cells r+ tone shade = mix shade ground (lRecede look path)+ hue = nHue n+ fillRect g c0 r0 c1 r1 (tone (mix ground hue 0.04))+ if c1 - c0 >= 4 && r1 - r0 >= 3+ then do+ outline g False c0 r0 c1 r1 (tone (mix ground hue 0.5))+ -- the outermost box goes unnamed: the path along the top names it+ unless (null path) $+ void (write g (c0 + 2) r0 (c1 - 2) (" " ++ nName n ++ " ") (tone (mix hue bright 0.35)) bold)+ forM_ (zip3 [0 ..] (nKids n) (nSlots n)) $ \(i, kid, slot) ->+ drawNode g look (path ++ [i]) kid (place (inside r) slot)+ else void (write g c0 r0 c1 (nName n) (tone (mix hue ground 0.3)) regular)++-- | A card is set as a page, centred once there's room. A small tile shows+-- only the name and title; the rest comes up as it grows, wrapped to fit.+--+-- While the camera moves, the card keeps the page it has at the bigger end+-- of the move, so nothing reflows on the way. Its corner rides along at+-- the same place in the tile, so the text goes wherever the tile goes, never+-- back. Anything that doesn't fit yet is cut off at the tile's edges.+drawCard :: Grid s -> Look -> Path -> Node -> Card -> Rect -> ST s ()+drawCard g look path n c area@(Rect x y w h) = do+ let (c0, r0, c1, r1) = cells area+ cols = c1 - c0+ tone shade = mix shade ground (lRecede look path)+ lit = lLit look == Just path+ bg = tone (mix ground (nHue n) (if lit then 0.15 else 0.08))+ (shown, left, top) = case lEnds look of+ Nothing -> let s = settle n c area in (sShown s, nearest (sLeft s), nearest (sTop s))+ Just (topA, topB) ->+ let ra@(Rect xa ya wa ha) = cardArea (descend topA path)+ rb@(Rect xb yb wb hb) = cardArea (descend topB path)+ a = settle n c ra+ b = settle n c rb+ in ( sShown (if wb > wa then b else a)+ , ride (xa, wa, sLeft a) (xb, wb, sLeft b) (x, w)+ , ride (ya, ha, sTop a) (yb, hb, sTop b) (y, h) )+ right = c1 - 1+ clarity = clamp01 (fromIntegral (cols - 30) / 24)+ headline role = role == Name || role == Title+ colour role+ | headline role = tone (roleColour (nHue n) role)+ | otherwise = tone (mix bg (roleColour (nHue n) role) clarity)+ fit s | length s <= right - left = s+ | otherwise = take (max 0 (right - left - 1)) s ++ "…"+ (x0, y0, x1, y1) = gClip g+ page = g { gClip = (max x0 (c0 + 1), max y0 r0, min x1 right, min y1 r1) }+ fillRect g c0 r0 c1 r1 bg+ forM_ (zip [top ..] shown) $ \(row, pieces) ->+ foldM_ (\col (role, s) -> write page col row right (if headline role then fit s else s) (colour role) (roleStyle role))+ left pieces++-- | How a card sits in a tile once the camera has stopped: the lines it+-- shows, and the corner of the block they make, before rounding. Kept+-- unrounded so a corner held against the tile's edge rounds with that edge+-- all the way through a move, rather than a cell outside it now and then.+data Setting = Setting { sShown :: [[(Role, String)]], sLeft, sTop :: Double }++settle :: Node -> Card -> Rect -> Setting+settle n c area@(Rect x y w h) = Setting shown left top+ where+ (c0, r0, c1, r1) = cells area+ cols = c1 - c0+ rows = r1 - r0+ -- wrapped in steps of four, so a tile a column wider than another+ -- still sets the same page+ width = max 16 (min measure ((cols - 3) `div` 4 * 4))+ page = setCard width n c+ shown = if cols < 30 || rows < 6 then take 2 page else page+ -- centred on where the tile really is rather than on its rounded size+ left = max (x + 1) (x + (w - fromIntegral width) / 2)+ top = max y (y + (h - fromIntegral (length shown)) / 2)++-- | A point in a tile that moves from @pa@ to @pb@ as the tile goes from+-- @(xa, wa)@ to @(xb, wb)@, kept at the same fraction of the tile plus the+-- same offset. The camera moves every such point one way only, so this one+-- never turns back.+ride :: (Double, Double, Double) -> (Double, Double, Double) -> (Double, Double) -> Int+ride (xa, wa, pa) (xb, wb, pb) (x, w)+ | abs (wb - wa) < 1e-9 = nearest (x + offA)+ | otherwise = nearest (x + f * w + offA - f * wa)+ where+ offA = pa - xa+ f = (pb - xb - offA) / (wb - wa)++-- | A gold outline around the selected tile, with a soft glow, fading in.+drawSelection :: Grid s -> Model -> Rect -> ST s ()+drawSelection g m groupRect = when (x1 - x0 >= 2 && y1 - y0 >= 2) $ do+ forM_ [y0 - 1 .. y1] $ \y -> forM_ [x0 - 2 .. x1 + 1] $ \x -> do+ let dx = max (x0 - x) (x - x1 + 1)+ dy = max (y0 - y) (y - y1 + 1)+ glow | dx <= 0 && dy <= 0 = 0+ | dx <= 1 && dy <= 1 = 0.09+ | otherwise = 0.035+ when (glow > 0) $ tintBg g x y (\b -> mix b gold (glow * lit))+ outline g True x0 y0 x1 y1 (mix ground gold lit)+ where+ area = place (inside groupRect) (outlineNow m)+ tile = if isGroup (nKids (here m) !! mSelected m) then area else cardArea area+ (x0, y0, x1, y1) = cells tile+ lit = since easeOut m (mOutlineLitAt m) fadeTime++-- | Where we are, along the top.+drawPath :: Grid s -> Model -> ST s ()+drawPath g m = foldM_ crumb 2 (zip [1 ..] names)+ where+ names = [ nName (nodeAt p) | p <- inits (mAt m) ]+ crumb x (i, name)+ | i == length names = write g x 0 (gWidth g) name bright bold+ | otherwise = write g x 0 (gWidth g) name dim regular >>= \x' -> write g x' 0 (gWidth g) " › " faint regular++-- | What the keys do, along the bottom.+drawHints :: Grid s -> Model -> ST s ()+drawHints g m = void (write g 2 (gHeight g - 1) (gWidth g) hints faint regular)+ where+ hints | isGroup (here m) = "arrows move enter open esc back q quit"+ | otherwise = "arrows next esc back q quit"++main :: IO ()+main = void (run defaultOptions { optQuitKeys = [KeyCtrl 'D'] } app)
@@ -1,34 +1,40 @@ cabal-version: 3.0 name: layoutz-version: 0.4.0.0-synopsis: Simple, beautiful CLI output-description: Zero-dep, compositional terminal output+version: 1.0.0.0+synopsis: Terminal UIs, layouts and plots: Elm-style TUIs in pure Haskell+description:+ Build terminal UIs and nice CLI output from small compositional views+ .+ Zero-dep and a single module, so you can+ also just drop Layoutz.hs into your project. homepage: https://github.com/mattlianje/layoutz bug-reports: https://github.com/mattlianje/layoutz/issues license: Apache-2.0 license-file: LICENSE author: Matthieu Court maintainer: matthieu.court@protonmail.com-copyright: 2025 Matthieu Court-category: Text+copyright: 2025-2026 Matthieu Court+category: Terminal, TUI, User Interfaces, Text build-type: Simple extra-source-files: README.md++extra-doc-files: CHANGELOG.md- pix/*.png source-repository head type: git location: https://github.com/mattlianje/layoutz- subdir: hs library exposed-modules: Layoutz build-depends: base >= 4.7 && < 5- , text- , containers- , directory+ , text >= 2.1.2 && < 2.2+ , containers >= 0.5 && < 0.9+ , directory >= 1.2 && < 1.4+ if !os(windows)+ build-depends: unix >= 2.7 && < 2.9 hs-source-dirs: . default-language: Haskell2010 ghc-options: -Wall@@ -37,14 +43,37 @@ main-is: AskDemo.hs build-depends: base >= 4.7 && < 5 , layoutz+ , text hs-source-dirs: examples default-language: Haskell2010 ghc-options: -Wall +executable ask-mini+ main-is: AskMini.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010++executable plot-demo+ main-is: PlotDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010++executable loader-demo+ main-is: LoaderDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ executable inline-bar main-is: InlineBar.hs build-depends: base >= 4.7 && < 5 , layoutz+ , text hs-source-dirs: examples default-language: Haskell2010 ghc-options: -Wall@@ -53,26 +82,145 @@ main-is: InlineLoadingDemo.hs build-depends: base >= 4.7 && < 5 , layoutz+ , text hs-source-dirs: examples default-language: Haskell2010 ghc-options: -Wall +executable click-demo+ main-is: ClickDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable fill-demo+ main-is: FillDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable focus-demo+ main-is: FocusDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable sizing-mini+ main-is: SizingMini.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable mouse-mini+ main-is: MouseMini.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable focus-mini+ main-is: FocusMini.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable widgets-mini+ main-is: WidgetsMini.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable napkin-demo+ main-is: NapkinDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall+ executable showcase-app main-is: ShowcaseApp.hs build-depends: base >= 4.7 && < 5 , layoutz+ , text hs-source-dirs: examples default-language: Haskell2010 ghc-options: -Wall +executable zoom-demo+ main-is: ZoomDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ , text+ , containers+ , array+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall -O2+ executable raymarcher main-is: RayMarcher.hs build-depends: base >= 4.7 && < 5 , layoutz+ , text hs-source-dirs: examples default-language: Haskell2010 ghc-options: -Wall -O2 +executable counter-demo+ main-is: CounterDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable readme-demo+ main-is: ReadmeDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable simple-game+ main-is: SimpleGame.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable spinner-demo+ main-is: SpinnerDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall++executable task-list-demo+ main-is: TaskListDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ , containers+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall+ test-suite layoutz-tests type: exitcode-stdio-1.0 main-is: Test.hs@@ -84,3 +232,35 @@ hs-source-dirs: test default-language: Haskell2010 ghc-options: -Wall++-- layoutz vs Bubble Tea, Brick and ratatui: `make bench`. Linux only.+benchmark layoutz-bench+ type: exitcode-stdio-1.0+ main-is: Main.hs+ other-modules: Dashboard+ , Pty+ , Report+ hs-source-dirs: bench+ c-sources: bench/cbits/pty.c+ extra-libraries: util+ build-depends: base >= 4.7 && < 5+ , layoutz+ , bytestring+ , directory+ , filepath+ , process+ , unix+ default-language: Haskell2010+ ghc-options: -Wall -O2+ if !os(linux)+ buildable: False++executable tile-demo+ main-is: TileDemo.hs+ build-depends: base >= 4.7 && < 5+ , layoutz+ , containers+ , process+ hs-source-dirs: examples+ default-language: Haskell2010+ ghc-options: -Wall -O2 -threaded
binary file changed (618801 → absent bytes)
binary file changed (304237 → absent bytes)
binary file changed (274337 → absent bytes)
binary file changed (410493 → absent bytes)
binary file changed (284801 → absent bytes)
binary file changed (502408 → absent bytes)
binary file changed (914713 → absent bytes)
binary file changed (886788 → absent bytes)
binary file changed (911917 → absent bytes)
binary file changed (927538 → absent bytes)
binary file changed (488692 → absent bytes)
binary file changed (247185 → absent bytes)
binary file changed (220737 → absent bytes)
@@ -3,20 +3,22 @@ import Test.Tasty import Test.Tasty.HUnit import Layoutz-import Data.List (isInfixOf)-import qualified Data.Text as T+import Data.List (isInfixOf, inits) import Data.IORef (newIORef, readIORef, writeIORef)+import Data.Maybe (fromMaybe) --- Helper to strip ANSI codes for testing stripAnsiTest :: String -> String stripAnsiTest [] = [] stripAnsiTest ('\ESC':'[':rest) = stripAnsiTest (dropAfterM rest)- where + where dropAfterM [] = [] dropAfterM ('m':xs) = xs dropAfterM (_:xs) = dropAfterM xs stripAnsiTest (c:rest) = c : stripAnsiTest rest +renderS :: View m -> String+renderS = render+ main :: IO () main = defaultMain tests @@ -25,7 +27,6 @@ [ basicElementTests , visualFeatureTests , dataVisualizationTests- , renderTextTests , containerTests , layoutTests , dimensionTests@@ -34,26 +35,31 @@ , styleTests , commandTests , visualizationTests- , columnsTruncateBannerTests+ , gapClipBannerTests+ , eventTests+ , sizingTests+ , focusTests+ , widgetTests+ , inputTests ] --- columns / truncate / banner-columnsTruncateBannerTests :: TestTree-columnsTruncateBannerTests = testGroup "Columns, Truncate & Banner"- [ testCase "columns places elements side by side" $- render (columns [layout ["A", "B"], layout ["C", "D"]]) @?= "A C\nB D"+-- gap / clip / banner+gapClipBannerTests :: TestTree+gapClipBannerTests = testGroup "Gap, Clip & Banner"+ [ testCase "gap 2 places stacks side by side" $+ render (row [vstack ["A", "B"], vstack ["C", "D"]] & gap 2) @?= "A C\nB D" - , testCase "columns' custom spacing" $- render (columns' 1 [layout ["A"], layout ["B"]]) @?= "A B"+ , testCase "gap sets row spacing" $+ render (row [vstack ["A"], vstack ["B"]] & gap 1) @?= "A B" - , testCase "truncate' leaves short text untouched" $- render (truncate' 15 (text "short")) @?= "short"+ , testCase "clip leaves short text untouched" $+ render (clip 15 (text "short")) @?= "short" - , testCase "truncate' cuts long text with default ellipsis" $- render (truncate' 15 (text "Very long text that will be cut off")) @?= "Very long te..."+ , testCase "clip cuts long text with the default ellipsis" $+ render (clip 15 (text "Very long text that will be cut off")) @?= "Very long te..." - , testCase "truncate'' custom ellipsis" $- render (truncate'' 20 "…" (text "Custom ellipsis example text here")) @?= "Custom ellipsis exa…"+ , testCase "clip with a custom ellipsis" $+ render (text "Custom ellipsis example text here" & clip 20 & ellipsis "…") @?= "Custom ellipsis exa…" , testCase "banner is a titleless double-bordered box" $ render (banner ["System Dashboard"]) @?= "╔══════════════════╗\n║ System Dashboard ║\n╚══════════════════╝"@@ -72,27 +78,13 @@ render (underline $ text "Test") @?= "Test\n────" , testCase "underline custom" $- render (underline' "=" $ text "Test") @?= "Test\n===="+ render (text "Test" & underline & glyph "=") @?= "Test\n====" , testCase "center default width" $- -- center now uses smart auto-centering, test within a layout context- render (layout [text "wide content here to establish context width", center $ text "Test"]) @?= "wide content here to establish context width\n Test "+ render (vstack [text "wide content here to establish context width", center $ text "Test"]) @?= "wide content here to establish context width\n Test " , testCase "center custom width" $- render (center' 10 $ text "Test") @?= " Test "- ]---- renderText tests-renderTextTests :: TestTree-renderTextTests = testGroup "renderText"- [ testCase "renderText returns Text, not String" $- renderText (text "Hello World") @?= T.pack "Hello World"-- , testCase "renderText matches render" $- renderText (text "Test") @?= T.pack (render (text "Test"))-- , testCase "renderText on composed layout" $- renderText (layout [text "A", text "B"]) @?= T.pack "A\nB"+ render (centerIn 10 $ text "Test") @?= " Test " ] -- Visual feature tests@@ -102,44 +94,44 @@ render hr @?= "──────────────────────────────────────────────────" , testCase "horizontal rule custom char" $- render (hr' "=") @?= "=================================================="+ render (hr & glyph "=") @?= "==================================================" , testCase "horizontal rule custom width" $- render (hr'' "-" 10) @?= "----------"+ render (hr & glyph "-" & size 10) @?= "----------" , testCase "vertical rule default" $- length (lines $ render vr) @?= 10+ length (lines $ renderS vr) @?= 10 , testCase "vertical rule custom char" $- head (lines $ render $ vr' "║") @?= "║"+ head (lines $ renderS $ vr & glyph "║") @?= "║" , testCase "vertical rule custom height" $- length (lines $ render $ vr'' "|" 5) @?= 5+ length (lines $ renderS $ vr & glyph "|" & size 5) @?= 5 , testCase "padding" $- lines (render $ pad 2 $ text "Test") @?= [" ", " ", " Test ", " ", " "]+ lines (renderS $ pad 2 $ text "Test") @?= [" ", " ", " Test ", " ", " "] , testCase "margin custom" $- render (margin ">>>" [text "Line 1", text "Line 2"]) @?= ">>> Line 1\n>>> Line 2"+ render (vstack [text "Line 1", text "Line 2"] & margin ">>>") @?= ">>> Line 1\n>>> Line 2" , testCase "margin error" $- render (margin "[error]" [text "Error message"]) @?= "[error] Error message"+ render (vstack [text "Error message"] & margin "[error]") @?= "[error] Error message" ] -- Data visualization tests dataVisualizationTests :: TestTree dataVisualizationTests = testGroup "Data Visualization" [ testCase "inline bar 0%" $- "Test [────────────────────] 0%" `elem` lines (render $ inlineBar "Test" 0.0) @?= True+ "Test [────────────────────] 0%" `elem` lines (renderS $ inlineBar "Test" 0.0) @?= True , testCase "inline bar 50%" $- "Test [██████████──────────] 50%" `elem` lines (render $ inlineBar "Test" 0.5) @?= True+ "Test [██████████──────────] 50%" `elem` lines (renderS $ inlineBar "Test" 0.5) @?= True , testCase "inline bar 100%" $- "Test [████████████████████] 100%" `elem` lines (render $ inlineBar "Test" 1.0) @?= True+ "Test [████████████████████] 100%" `elem` lines (renderS $ inlineBar "Test" 1.0) @?= True , testCase "chart" $- "Task │████████████████████████████████████████│ 50" `elem` lines (render $ chart [("Task", 50.0)]) @?= True+ "Task │████████████████████████████████████████│ 50" `elem` lines (renderS $ chart [("Task", 50.0)]) @?= True , testCase "key-value pairs" $ render (kv [("Key", "Value")]) @?= "Key: Value"@@ -149,16 +141,16 @@ containerTests :: TestTree containerTests = testGroup "Containers" [ testCase "status card default border" $- length (lines $ render $ statusCard "API" "UP") @?= 4+ length (lines $ renderS $ statusCard "API" "UP") @?= 4 , testCase "status card double border" $- "╔═══════╗" `elem` lines (render $ withBorder BorderDouble $ statusCard "API" "UP") @?= True+ "╔═══════╗" `elem` lines (renderS $ border BorderDouble $ statusCard "API" "UP") @?= True , testCase "box default border" $- "┌──Title──┐" `elem` lines (render $ box "Title" [text "Content"]) @?= True+ "┌──Title──┐" `elem` lines (renderS $ box "Title" [text "Content"]) @?= True , testCase "box double border" $- "╔══Title══╗" `elem` lines (render $ withBorder BorderDouble $ box "Title" [text "Content"]) @?= True+ "╔══Title══╗" `elem` lines (renderS $ border BorderDouble $ box "Title" [text "Content"]) @?= True ] -- Layout tests@@ -168,31 +160,34 @@ render (ul [text "Item 1", text "Item 2"]) @?= "• Item 1\n• Item 2" , testCase "unordered list nested" $- " ◦ Sub 1" `elem` lines (render $ ul [text "Item 1", ul [text "Sub 1", text "Sub 2"]]) @?= True+ " ◦ Sub 1" `elem` lines (renderS $ ul [text "Item 1", ul [text "Sub 1", text "Sub 2"]]) @?= True , testCase "ordered list single level" $ render (ol [text "First", text "Second"]) @?= "1. First\n2. Second" , testCase "ordered list nested with letters" $- " a. Nested" `elem` lines (render $ ol [text "Item 1", ol [text "Nested", text "Also nested"]]) @?= True+ " a. Nested" `elem` lines (renderS $ ol [text "Item 1", ol [text "Nested", text "Also nested"]]) @?= True , testCase "ordered list triple nested with roman numerals" $- " i. Deep" `elem` lines (render $ ol [text "L1", ol [text "L2", ol [text "Deep"]]]) @?= True+ " i. Deep" `elem` lines (renderS $ ol [text "L1", ol [text "L2", ol [text "Deep"]]]) @?= True , testCase "table basic" $- "│ A │ B │" `elem` lines (render $ table ["A", "B"] [[text "1", text "2"]]) @?= True+ "│ A │ B │" `elem` lines (renderS $ table ["A", "B"] [[text "1", text "2"]]) @?= True , testCase "tree structure" $- "Root" `elem` lines (render $ tree "Root" [leaf "Child"]) @?= True+ "Root" `elem` lines (renderS $ tree "Root" [leaf "Child"]) @?= True , testCase "section" $- "=== Title ===" `elem` lines (render $ section "Title" [text "Content"]) @?= True+ "=== Title ===" `elem` lines (renderS $ section "Title" [text "Content"]) @?= True - , testCase "row layout" $+ , testCase "row spacing" $ render (row [text "A", text "B"]) @?= "A B" - , testCase "layout composition" $- render (layout [text "Line 1", text "Line 2"]) @?= "Line 1\nLine 2"+ , testCase "settings reach through colour" $+ render (hr & fg ColorRed & size 5) @?= render (hr & size 5 & fg ColorRed)++ , testCase "vstack composition" $+ render (vstack [text "Line 1", text "Line 2"]) @?= "Line 1\nLine 2" , testCase "align left" $ render (alignLeft 10 "Hi") @?= "Hi "@@ -214,48 +209,48 @@ width (text "Hello") @?= 5 , testCase "height calculation" $- height (layout [text "Line 1", text "Line 2"]) @?= 2+ height (vstack [text "Line 1", text "Line 2"]) @?= 2 ] -- Color tests colorTests :: TestTree colorTests = testGroup "Colors"- [ testCase "render includes ANSI codes" $- "\ESC[31m" `isInfixOf` render (withColor ColorRed $ text "Hello") @?= True+ [ testCase "renderS includes ANSI codes" $+ "\ESC[31m" `isInfixOf` renderS (fg ColorRed $ text "Hello") @?= True - , testCase "render includes reset code" $- "\ESC[0m" `isInfixOf` render (withColor ColorRed $ text "Hello") @?= True+ , testCase "renderS includes reset code" $+ "\ESC[0m" `isInfixOf` renderS (fg ColorRed $ text "Hello") @?= True , testCase "colored element width ignores ANSI codes" $- width (withColor ColorRed $ text "Hello") @?= 5+ width (fg ColorRed $ text "Hello") @?= 5 , testCase "colored status card maintains structure" $- let colored = render $ withColor ColorGreen $ withBorder BorderDouble $ statusCard "API" "UP"+ let colored = renderS $ fg ColorGreen $ border BorderDouble $ statusCard "API" "UP" strippedLines = map stripAnsiTest (lines colored) in "╔═══════╗" `elem` strippedLines @?= True , testCase "colored box maintains structure" $- let colored = render $ withColor ColorBlue $ box "Title" [text "Content"]+ let colored = renderS $ fg ColorBlue $ box "Title" [text "Content"] strippedLines = map stripAnsiTest (lines colored) in "┌──Title──┐" `elem` strippedLines @?= True , testCase "nested colors work" $- "\ESC[32m" `isInfixOf` render (withColor ColorRed $ layout [withColor ColorGreen $ text "Hi"]) @?= True+ "\ESC[32m" `isInfixOf` renderS (fg ColorRed $ vstack [fg ColorGreen $ text "Hi"]) @?= True , testCase "bright colors use correct codes" $- "\ESC[91m" `isInfixOf` render (withColor ColorBrightRed $ text "Hi") @?= True+ "\ESC[91m" `isInfixOf` renderS (fg ColorBrightRed $ text "Hi") @?= True , testCase "color with borders both work" $- let colored = render $ withColor ColorYellow $ withBorder BorderThick $ statusCard "Test" "OK"+ let colored = renderS $ fg ColorYellow $ border BorderThick $ statusCard "Test" "OK" strippedLines = map stripAnsiTest (lines colored) in "┏━━━━━━━━┓" `elem` strippedLines @?= True , testCase "colored underline includes ANSI codes" $- "\ESC[31m" `isInfixOf` render (underlineColored "=" ColorRed $ text "Title") @?= True+ "\ESC[31m" `isInfixOf` renderS (text "Title" & underline & glyph "=" & accent ColorRed) @?= True , testCase "colored underline maintains structure" $- let underlined = render $ underlineColored "=" ColorRed $ text "Test"- strippedLines = map stripAnsiTest (lines underlined)+ let rendered = renderS $ accent ColorRed . glyph "=" . underline $ text "Test"+ strippedLines = map stripAnsiTest (lines rendered) in "====" `elem` strippedLines @?= True ] @@ -263,29 +258,29 @@ extendedColorTests :: TestTree extendedColorTests = testGroup "Extended Colors" [ testCase "256-color palette (ColorFull)" $- "\ESC[38;5;" `isInfixOf` render (withColor (ColorFull 196) $ text "Red") @?= True+ "\ESC[38;5;" `isInfixOf` renderS (fg (ColorFull 196) $ text "Red") @?= True , testCase "256-color clamping max" $- "\ESC[38;5;255" `isInfixOf` render (withColor (ColorFull 300) $ text "Clamped") @?= True+ "\ESC[38;5;255" `isInfixOf` renderS (fg (ColorFull 300) $ text "Clamped") @?= True , testCase "256-color clamping min" $- "\ESC[38;5;0" `isInfixOf` render (withColor (ColorFull (-10)) $ text "Clamped") @?= True+ "\ESC[38;5;0" `isInfixOf` renderS (fg (ColorFull (-10)) $ text "Clamped") @?= True , testCase "RGB true color (ColorTrue)" $- "\ESC[38;2;" `isInfixOf` render (withColor (ColorTrue 255 100 50) $ text "RGB") @?= True+ "\ESC[38;2;" `isInfixOf` renderS (fg (ColorTrue 255 100 50) $ text "RGB") @?= True , testCase "RGB true color full spec" $- "\ESC[38;2;255;100;50" `isInfixOf` render (withColor (ColorTrue 255 100 50) $ text "RGB") @?= True+ "\ESC[38;2;255;100;50" `isInfixOf` renderS (fg (ColorTrue 255 100 50) $ text "RGB") @?= True , testCase "RGB color clamping" $- "\ESC[38;2;255;255;0" `isInfixOf` render (withColor (ColorTrue 300 300 (-10)) $ text "Clamped") @?= True+ "\ESC[38;2;255;255;0" `isInfixOf` renderS (fg (ColorTrue 300 300 (-10)) $ text "Clamped") @?= True - , testCase "tightRow renders without spaces" $- stripAnsiTest (render $ tightRow [withColor ColorRed $ text "A", withColor ColorGreen $ text "B"]) @?= "AB"+ , testCase "gap 0 renders without spaces" $+ stripAnsiTest (renderS $ row [fg ColorRed $ text "A", fg ColorGreen $ text "B"] & gap 0) @?= "AB" - , testCase "tightRow vs row spacing" $- let tightResult = stripAnsiTest (render $ tightRow [text "A", text "B"])- normalResult = render $ row [text "A", text "B"]+ , testCase "gap 0 vs default spacing" $+ let tightResult = stripAnsiTest (renderS $ row [text "A", text "B"] & gap 0)+ normalResult = renderS $ row [text "A", text "B"] in (tightResult == "AB" && normalResult == "A B") @?= True ] @@ -293,68 +288,71 @@ styleTests :: TestTree styleTests = testGroup "Styles" [ testCase "bold style" $- "\ESC[1m" `isInfixOf` render (withStyle StyleBold $ text "Bold") @?= True+ "\ESC[1m" `isInfixOf` renderS (styleBold $ text "Bold") @?= True , testCase "italic style" $- "\ESC[3m" `isInfixOf` render (withStyle StyleItalic $ text "Italic") @?= True+ "\ESC[3m" `isInfixOf` renderS (styleItalic $ text "Italic") @?= True - , testCase "combined styles with <>" $- let combined = render $ withStyle (StyleBold <> StyleItalic) $ text "Fancy"- in ("\ESC[1;3m" `isInfixOf` combined || "\ESC[3;1m" `isInfixOf` combined) @?= True+ , testCase "stacked styles merge into one SGR" $+ renderS (text "Fancy" & styleBold & styleItalic) @?= "\ESC[1;3mFancy\ESC[0m" , testCase "triple combined styles" $- let combined = render $ withStyle (StyleBold <> StyleItalic <> StyleUnderline) $ text "Very Fancy"+ let combined = renderS $ (styleBold . styleItalic . styleUnderline) $ text "Very Fancy" hasAll = "\ESC[" `isInfixOf` combined && "1" `isInfixOf` combined && "3" `isInfixOf` combined && "4" `isInfixOf` combined in hasAll @?= True , testCase "style with color both work" $- let styled = render $ withColor ColorRed $ withStyle StyleBold $ text "Important"+ let styled = renderS $ fg ColorRed $ styleBold $ text "Important" in ("\ESC[31m" `isInfixOf` styled && "\ESC[1m" `isInfixOf` styled) @?= True , testCase "style maintains element width" $- width (withStyle StyleBold $ text "Hello") @?= 5+ width (styleBold $ text "Hello") @?= 5 , testCase "combined style maintains structure" $- let styled = render $ withStyle (StyleBold <> StyleReverse) $ box "Title" [text "Content"]+ let styled = renderS $ (styleBold . styleReverse) $ box "Title" [text "Content"] strippedLines = map stripAnsiTest (lines styled) in "┌──Title──┐" `elem` strippedLines @?= True , testCase "wrap text at word boundaries" $- let wrapped = render $ wrap 10 "This is a very long text"+ let wrapped = renderS $ wrap 10 "This is a very long text" wrappedLines = lines wrapped in length wrappedLines > 1 @?= True , testCase "wrap preserves words" $- "This is a" `isInfixOf` render (wrap 10 "This is a test") @?= True+ "This is a" `isInfixOf` renderS (wrap 10 "This is a test") @?= True ] -- Command execution tests commandTests :: TestTree commandTests = testGroup "Commands"- [ testCase "CmdNone produces Nothing" $ do- result <- executeCmd (CmdNone :: Cmd String)- result @?= Nothing+ [ testCase "cmdNone produces nothing" $ do+ result <- executeCmd (cmdNone :: Cmd String)+ result @?= [] , testCase "cmdFire executes IO without message" $ do ref <- newIORef (0 :: Int) result <- executeCmd (cmdFire $ writeIORef ref 42 :: Cmd String) val <- readIORef ref- result @?= Nothing+ result @?= [] val @?= 42 , testCase "cmdTask executes IO and returns message" $ do result <- executeCmd (cmdTask $ pure "hello" :: Cmd String)- result @?= Just "hello"+ result @?= ["hello"] - , testCase "CmdBatch executes all commands" $ do+ , testCase "<> runs effects in order" $ do ref <- newIORef (0 :: Int)- _ <- executeCmd (CmdBatch [cmdFire $ writeIORef ref 1, cmdFire $ writeIORef ref 2] :: Cmd String)+ _ <- executeCmd (cmdFire (writeIORef ref 1) <> cmdFire (writeIORef ref 2) :: Cmd String) val <- readIORef ref- val @?= 2 -- Last write wins+ val @?= 2 - , testCase "CmdBatch returns first Just message" $ do- result <- executeCmd (CmdBatch [CmdRun (pure Nothing), cmdTask (pure "first"), cmdTask (pure "second")] :: Cmd String)- result @?= Just "first"+ , testCase "<> delivers every message" $ do+ result <- executeCmd (mconcat [cmdFire (pure ()), cmdTask (pure "first"), cmdTask (pure "second")] :: Cmd String)+ result @?= ["first", "second"]++ , testCase "fmap maps messages" $ do+ result <- executeCmd (length <$> cmdTask (pure ("four" :: String)))+ result @?= [4] ] -- Visualization primitive tests@@ -362,30 +360,25 @@ visualizationTests = testGroup "Visualizations" [ testGroup "Renames" [ testCase "ColorDefault produces no ANSI wrapping" $- render (withColor ColorDefault $ text "Hello") @?= "Hello"-- , testCase "StyleDefault produces no style wrapping" $- render (withStyle StyleDefault $ text "Hello") @?= "Hello"+ render (fg ColorDefault $ text "Hello") @?= "Hello" - , testCase "StyleDefault is Monoid mempty" $- render (withStyle mempty $ text "Hello") @?= "Hello" ] , testGroup "Sparkline" [ testCase "sparkline output length matches input" $- length (render $ plotSparkline [1,2,3,4,5]) @?= 5+ length (renderS $ plotSparkline [1,2,3,4,5]) @?= 5 , testCase "sparkline empty input" $ render (plotSparkline []) @?= "" , testCase "sparkline constant values use middle block" $- all (== '▄') (render $ plotSparkline [5,5,5]) @?= True+ all (== '▄') (renderS $ plotSparkline [5,5,5]) @?= True , testCase "sparkline max value is full block" $- last (render $ plotSparkline [0,0,10]) @?= '█'+ last (renderS $ plotSparkline [0,0,10]) @?= '█' , testCase "sparkline min value is lowest block" $- head (render $ plotSparkline [0,5,10]) @?= '▁'+ head (renderS $ plotSparkline [0,5,10]) @?= '▁' ] , testGroup "Line Plot"@@ -396,23 +389,23 @@ render (plotLine 20 5 [Series [] "empty" ColorBrightCyan]) @?= "No data" , testCase "plotLine contains y-axis" $- "│" `isInfixOf` render (plotLine 20 5 [Series [(0,0),(1,1)] "test" ColorBrightCyan]) @?= True+ "│" `isInfixOf` renderS (plotLine 20 5 [Series [(0,0),(1,1)] "test" ColorBrightCyan]) @?= True , testCase "plotLine contains x-axis" $- "─" `isInfixOf` render (plotLine 20 5 [Series [(0,0),(1,1)] "test" ColorBrightCyan]) @?= True+ "─" `isInfixOf` renderS (plotLine 20 5 [Series [(0,0),(1,1)] "test" ColorBrightCyan]) @?= True , testCase "plotLine multi-series has legend" $- let r = render $ plotLine 20 5+ let r = renderS $ plotLine 20 5 [ Series [(0,0),(1,1)] "A" ColorBrightCyan , Series [(0,1),(1,0)] "B" ColorBrightRed ] in ("A" `isInfixOf` r && "B" `isInfixOf` r) @?= True , testCase "plotLine single series no legend" $- let r = render $ plotLine 20 5 [Series [(0,0),(1,1)] "only" ColorBrightCyan]+ let r = renderS $ plotLine 20 5 [Series [(0,0),(1,1)] "only" ColorBrightCyan] in not ("●" `isInfixOf` stripAnsiTest r) @?= True , testCase "plotLine contains braille characters" $- let r = stripAnsiTest $ render $ plotLine 30 8 [Series [(x, sin x) | x <- [0,0.1..6.28]] "sin" ColorBrightCyan]+ let r = stripAnsiTest $ renderS $ plotLine 30 8 [Series [(x, sin x) | x <- [0,0.1..6.28]] "sin" ColorBrightCyan] in any (\c -> c >= '⠀' && c <= '⣿') r @?= True ] @@ -421,16 +414,16 @@ render (plotPie 10 5 []) @?= "No data" , testCase "plotPie legend has percentages" $- let r = render $ plotPie 15 6 [Slice 75 "Big" ColorBrightCyan, Slice 25 "Small" ColorBrightMagenta]+ let r = renderS $ plotPie 15 6 [Slice 75 "Big" ColorBrightCyan, Slice 25 "Small" ColorBrightMagenta] in ("75%" `isInfixOf` stripAnsiTest r && "25%" `isInfixOf` stripAnsiTest r) @?= True , testCase "plotPie legend has labels" $- let r = stripAnsiTest $ render $ plotPie 15 6+ let r = stripAnsiTest $ renderS $ plotPie 15 6 [Slice 50 "Alpha" ColorBrightCyan, Slice 50 "Beta" ColorBrightMagenta] in ("Alpha" `isInfixOf` r && "Beta" `isInfixOf` r) @?= True , testCase "plotPie contains braille characters" $- let r = stripAnsiTest $ render $ plotPie 20 8+ let r = stripAnsiTest $ renderS $ plotPie 20 8 [Slice 60 "A" ColorBrightCyan, Slice 40 "B" ColorBrightMagenta] in any (\c -> c >= '⠀' && c <= '⣿') r @?= True ]@@ -440,19 +433,19 @@ render (plotBar 20 5 []) @?= "No data" , testCase "plotBar contains y-axis" $- "│" `isInfixOf` render (plotBar 20 5 [BarItem 10 "A" ColorBrightCyan]) @?= True+ "│" `isInfixOf` renderS (plotBar 20 5 [BarItem 10 "A" ColorBrightCyan]) @?= True , testCase "plotBar contains bar labels" $- let r = stripAnsiTest $ render $ plotBar 30 5+ let r = stripAnsiTest $ renderS $ plotBar 30 5 [BarItem 10 "Mon" ColorBrightCyan, BarItem 20 "Tue" ColorBrightGreen] in ("Mon" `isInfixOf` r && "Tue" `isInfixOf` r) @?= True , testCase "plotBar contains block characters" $- let r = stripAnsiTest $ render $ plotBar 20 5 [BarItem 100 "X" ColorBrightCyan]+ let r = stripAnsiTest $ renderS $ plotBar 20 5 [BarItem 100 "X" ColorBrightCyan] in any (\c -> c `elem` ("▁▂▃▄▅▆▇█" :: String)) r @?= True , testCase "plotBar y-axis shows max value" $- let r = stripAnsiTest $ render $ plotBar 30 5 [BarItem 50 "A" ColorBrightCyan]+ let r = stripAnsiTest $ renderS $ plotBar 30 5 [BarItem 50 "A" ColorBrightCyan] in "50" `isInfixOf` r @?= True ] @@ -461,21 +454,35 @@ render (plotStackedBar 20 5 []) @?= "No data" , testCase "plotStackedBar contains group labels" $- let r = stripAnsiTest $ render $ plotStackedBar 30 5+ let r = stripAnsiTest $ renderS $ plotStackedBar 30 5 [ StackedBarGroup [BarItem 10 "X" ColorDefault] "G1" , StackedBarGroup [BarItem 20 "X" ColorDefault] "G2" ] in ("G1" `isInfixOf` r && "G2" `isInfixOf` r) @?= True , testCase "plotStackedBar multi-segment has legend" $- let r = stripAnsiTest $ render $ plotStackedBar 30 5+ let r = stripAnsiTest $ renderS $ plotStackedBar 30 5 [ StackedBarGroup [BarItem 10 "Sales" ColorDefault, BarItem 5 "Tax" ColorDefault] "Q1" ] in ("Sales" `isInfixOf` r && "Tax" `isInfixOf` r) @?= True , testCase "plotStackedBar single segment no legend" $- let r = stripAnsiTest $ render $ plotStackedBar 30 5+ let r = stripAnsiTest $ renderS $ plotStackedBar 30 5 [ StackedBarGroup [BarItem 10 "Only" ColorDefault] "Q1" , StackedBarGroup [BarItem 20 "Only" ColorDefault] "Q2" ] in not ("█ Only" `isInfixOf` r) @?= True++ , testCase "plotStackedBar legend uses explicit segment colors" $+ let r = renderS $ plotStackedBar 30 5+ [ StackedBarGroup [ BarItem 10 "Red" ColorRed+ , BarItem 5 "Blue" ColorBlue ] "Q1" ]+ in ( "\ESC[31m█\ESC[0m Red" `isInfixOf` r+ && "\ESC[34m█\ESC[0m Blue" `isInfixOf` r) @?= True++ , testCase "plotStackedBar legend falls back to palette color" $+ let r = renderS $ plotStackedBar 30 5+ [ StackedBarGroup [ BarItem 10 "A" ColorDefault+ , BarItem 5 "B" ColorDefault ] "Q1" ]+ in ( "\ESC[96m█\ESC[0m A" `isInfixOf` r+ && "\ESC[95m█\ESC[0m B" `isInfixOf` r) @?= True ] , testGroup "Heatmap"@@ -483,26 +490,264 @@ render (plotHeatmap (HeatmapData [] [] [])) @?= "No data" , testCase "plotHeatmap contains row labels" $- let r = stripAnsiTest $ render $ plotHeatmap+ let r = stripAnsiTest $ renderS $ plotHeatmap (HeatmapData [[1,2],[3,4]] ["Row1","Row2"] ["C1","C2"]) in ("Row1" `isInfixOf` r && "Row2" `isInfixOf` r) @?= True , testCase "plotHeatmap contains column labels" $- let r = stripAnsiTest $ render $ plotHeatmap+ let r = stripAnsiTest $ renderS $ plotHeatmap (HeatmapData [[1,2],[3,4]] ["R1","R2"] ["ColA","ColB"]) in ("ColA" `isInfixOf` r && "ColB" `isInfixOf` r) @?= True , testCase "plotHeatmap contains ANSI background codes" $- "\ESC[48;5;" `isInfixOf` render (plotHeatmap+ "\ESC[48;5;" `isInfixOf` renderS (plotHeatmap (HeatmapData [[10,90]] ["R"] ["A","B"])) @?= True , testCase "plotHeatmap contains gradient legend" $- let r = stripAnsiTest $ render $ plotHeatmap+ let r = stripAnsiTest $ renderS $ plotHeatmap (HeatmapData [[0,100]] ["R"] ["A","B"]) in ("0" `isInfixOf` r && "100" `isInfixOf` r) @?= True , testCase "plotHeatmap' custom cell width" $- let r = render $ plotHeatmap' 10 (HeatmapData [[1]] ["R"] ["C"])- in length r > length (render $ plotHeatmap (HeatmapData [[1]] ["R"] ["C"])) @?= True+ let r = renderS $ plotHeatmap' 10 (HeatmapData [[1]] ["R"] ["C"])+ in length r > length (renderS $ plotHeatmap (HeatmapData [[1]] ["R"] ["C"])) @?= True ] ]++data TMsg = Inc | Dec | Outer | Scrolled Int | Wrap TMsg+ deriving (Eq, Show)++eventTests :: TestTree+eventTests = testGroup "Events"+ [ testCase "click lands on the button under the cell" $ do+ let v = row [button "-" Dec, text " 3 ", button "+" Inc]+ clickAt (0, 1) v @?= Just Dec+ clickAt (0, 9) v @?= Just Inc+ clickAt (0, 5) v @?= Nothing++ , testCase "innermost handler wins, outer catches the rest" $ do+ let v = onClick Outer (box "" [button "+" Inc])+ clickAt (1, 3) v @?= Just Inc+ clickAt (0, 0) v @?= Just Outer+ clickAt (1, 0) v @?= Just Outer++ , testCase "overlay centres the top view and its clicks win where it covers" $ do+ let v = overlay (onClick Outer (vstack ["abcdefg", "hijklmn", "opqrstu"])) (onClick Inc "x")+ render v @?= "abcdefg\nhijxlmn\nopqrstu"+ clickAt (1, 3) v @?= Just Inc+ clickAt (1, 0) v @?= Just Outer+ clickAt (0, 3) v @?= Just Outer++ , testCase "overlay blanks a wide character it cuts in half" $+ render (overlay (text "日本語") (text "x")) @?= "日x 語" -- 本 lost its right half++ , testCase "scroll bubbles past click-only children" $ do+ let v = onScroll Scrolled (vstack [button "a" Inc, "b"])+ scrollAt 1 (0, 1) v @?= Just (Scrolled 1)+ scrollAt (-1) (1, 0) v @?= Just (Scrolled (-1))+ clickAt (0, 1) v @?= Just Inc++ , testCase "regions follow centring, colour and table cells" $ do+ clickAt (1, 9) (vstack [text (replicate 20 '-'), center (button "ok" Inc)]) @?= Just Inc+ clickAt (1, 2) (vstack [text (replicate 20 '-'), center (button "ok" Inc)]) @?= Nothing+ clickAt (0, 1) (fg ColorRed (button "x" Inc)) @?= Just Inc+ clickAt (3, 3) (table ["A"] [[button "go" Inc]]) @?= Just Inc++ , testCase "fmap re-targets messages for embedded components" $+ clickAt (0, 1) (fmap Wrap (button "x" Inc)) @?= Just (Wrap Inc)++ , testCase "handler-free views mix into views that send messages" $+ clickAt (1, 1) (vstack [text "title", button "x" Inc]) @?= Just Inc++ , testCase "handlers don't change the rendering" $ do+ render (row [button "-" Dec, "x"]) @?= render (row [styleReverse " - ", "x"])+ width (onClick Inc (box "t" ["abc"])) @?= width (box "t" ["abc"])+ ]++sizingTests :: TestTree+sizingTests = testGroup "Sizing"+ [ testCase "fill takes the leftover width of an row" $+ lines (renderIn 20 3 (row ["ab", box "" ["x"] & fill]))+ @?= [ "ab ┌───────────────┐"+ , " │ x │"+ , " └───────────────┘" ]++ , testCase "fill takes the leftover height of a vstack" $+ lines (renderIn 7 5 (vstack ["top", box "" ["x"] & fill]))+ @?= [ "top"+ , "┌─────┐"+ , "│ x │"+ , "│ │"+ , "└─────┘" ]++ , testCase "fill shares the room between fills" $+ map length (lines (renderIn 21 3 (row [box "" ["a"] & fill, box "" ["b"] & fill])))+ @?= [21, 21, 21]++ , testCase "without room, fill changes nothing" $+ render (box "" ["x"] & fill) @?= render (box "" ["x"])++ , testCase "fixedWidth pads or cuts to the width" $ do+ map length (lines (render (box "" ["x"] & fixedWidth 9))) @?= [9, 9, 9]+ render (text "abcdef" & fixedWidth 3) @?= "abc"++ , testCase "a fixed-width sidebar spans the row's height" $+ lines (renderIn 20 4 (row [box "" ["a"] & fixedWidth 5, box "" ["b"] & fill] & fill))+ @?= [ "┌───┐ ┌────────────┐"+ , "│ a │ │ b │"+ , "│ │ │ │"+ , "└───┘ └────────────┘" ]++ , testCase "rules stretch under fill" $+ render (row [hr & fill] & fixedWidth 6) @?= "──────"++ , testCase "clicks cover the stretched area" $+ clickAt (1, 12) (row ["ab", box "" ["x"] & fill & onClick Inc] & fixedWidth 20) @?= Just Inc++ , testCase "clip and pad keep clicks" $ do+ clickAt (0, 1) (clip 3 (button "long" Inc)) @?= Just Inc+ clickAt (1, 2) (pad 1 (button "x" Inc)) @?= Just Inc+ ]++focusTests :: TestTree+focusTests = testGroup "Focus"+ [ testCase "Tab order is screen order" $+ focusOrder (vstack [text "a" & focusable "one", row [text "b" & focusable "two", text "c" & focusable "three"]])+ @?= ["one", "two", "three"]++ , testCase "keys go to the focused view" $ do+ let v = vstack [ text "a" & onKey (const (Just Inc)) & focusable "one"+ , text "b" & onKey (const (Just Dec)) & focusable "two" ]+ pressKey (Just "one") (KeyChar 'x') v @?= Just Inc+ pressKey (Just "two") (KeyChar 'x') v @?= Just Dec+ pressKey Nothing (KeyChar 'x') v @?= Nothing++ , testCase "onKey outside focusable still belongs to it" $ do+ let v = text "a" & focusable "one" & onKey (const (Just Inc))+ pressKey (Just "one") KeyEnter v @?= Just Inc+ pressKey Nothing KeyEnter v @?= Nothing++ , testCase "the focused view gets first pick, the rest gets what it leaves" $ do+ let quitOn k = if k == KeyChar 'q' then Just Outer else Nothing+ v = vstack [text "a" & onKey (\k -> if k == KeyEnter then Just Inc else Nothing) & focusable "one"]+ & onKey quitOn+ pressKey (Just "one") KeyEnter v @?= Just Inc+ pressKey (Just "one") (KeyChar 'q') v @?= Just Outer++ , testCase "focusStyle doesn't show without focus" $+ render (text "x" & focusable "a" & focusStyle styleBold) @?= "x"+ ]++widgetTests :: TestTree+widgetTests = testGroup "Widgets"+ [ testCase "selectList draws a cursor" $+ lines (stripAnsiTest (render (fruits (selectListOf ["a", "b", "c"]))))+ @?= ["› a", " b", " c"]++ , testCase "selectList moves with keys, clicks and the wheel" $ do+ let sl = selectListOf ["a", "b", "c"]+ movedTo = fmap selectedItem+ movedTo (pressKey Nothing KeyDown (fruits sl)) @?= Just (Just "b")+ movedTo (pressKey Nothing KeyEnd (fruits sl)) @?= Just (Just "c")+ movedTo (clickAt (2, 1) (fruits sl)) @?= Just (Just "c")+ movedTo (scrollAt 1 (0, 0) (fruits sl)) @?= Just (Just "b")++ , testCase "selectList keeps the cursor in sight" $ do+ let sl = iterate (press KeyDown) (selectListOf (map show [1 .. 6 :: Int])) !! 4+ selectedItem sl @?= Just "5"+ map stripAnsiTest (lines (renderIn 6 2 (fruits sl & fill))) @?= [" 4 █", "› 5 │"]++ , testCase "viewport shows a window with a scrollbar" $+ lines (render (numbers viewportTop)) @?= ["1 █", "2 │", "3 │"]++ , testCase "viewport scrolls and sticks to the bottom" $ do+ let down = scrolled KeyDown viewportTop+ end = scrolled KeyEnd viewportTop+ lines (render (numbers down)) @?= ["2 █", "3 │", "4 │"]+ end @?= viewportBottom+ lines (render (numbers end)) @?= ["8 │", "9 │", "10█"]+ lines (render (numbers (scrolled KeyUp end))) @?= ["7 │", "8 █", "9 │"]++ , testCase "viewport cuts lines wider than its room" $+ lines (renderIn 5 2 (viewport id viewportTop (map text ["abcdefgh", "ij", "klmnop"]) & fill))+ @?= ["abcd█", "ij │"]++ , testCase "sized gets the room it is drawn in" $ do+ let dims = sized (\w h -> text (show w <> "x" <> show h))+ lines (renderIn 7 3 (box "" [dims & fill] & fill)) @?= ["┌─────┐", "│ 3x1 │", "└─────┘"]+ render dims @?= "80x24"+ ]+ where+ fruits sl = selectList id (const sl) text sl+ press k sl = fromMaybe sl (pressKey Nothing k (fruits sl))+ numbers vp = viewport id vp (map (text . show) [1 .. 10 :: Int]) & fixedHeight 3+ scrolled k vp = fromMaybe vp (pressKey Nothing k (numbers vp))++-- parseInput+inputTests :: TestTree+inputTests = testGroup "Input parsing"+ [ testCase "each known sequence parses on its own" $+ mapM_ (\(bytes, want) -> (bytes, parseInput bytes) @?= (bytes, Just (want, ""))) sequences++ , testCase "every strict prefix of a sequence needs more input" $+ mapM_ (\p -> (p, parseInput p) @?= (p, Nothing))+ [ p | (bytes, _) <- sequences, p <- init (inits bytes) ]++ , testCase "back to back sequences split apart" $+ parseAll (concatMap fst sequences) @?= map snd sequences++ , testCase "leftover input comes back untouched" $+ parseInput "\ESC[Axyz" @?= Just (InputKey KeyUp, "xyz")++ , testCase "a lone ESC waits for the caller to decide" $+ parseInput "\ESC" @?= Nothing++ , testCase "nothing to parse" $+ parseInput "" @?= Nothing++ , testCase "modified keys we don't know are not Esc" $+ parseAll "\ESC[1;5A\ESC[15~" @?= [key (KeySpecial "[1;5A"), key (KeySpecial "[15~")]++ , testCase "a row-1 position report is modified F3, not a resize" $+ parseAll "\ESC[1;2R" @?= [key (KeySpecial "[1;2R")]++ , testCase "a broken mouse report is a special key" $+ parseAll "\ESC[<0;10M" @?= [key (KeySpecial "[<0;10")]+ ]+ where+ key = InputKey+ parseAll str = case parseInput str of+ Just (i, rest) -> i : parseAll rest+ Nothing -> []+ sequences =+ [ ("a", key (KeyChar 'a'))+ , (" ", key (KeyChar ' '))+ , ("é", key (KeyChar 'é'))+ , ("\r", key KeyEnter)+ , ("\n", key KeyEnter)+ , ("\t", key KeyTab)+ , ("\DEL", key KeyBackspace)+ , ("\b", key KeyBackspace)+ , ("\SOH", key (KeyCtrl 'A'))+ , ("\ETX", key (KeyCtrl 'C'))+ , ("\ESC[A", key KeyUp)+ , ("\ESC[B", key KeyDown)+ , ("\ESC[C", key KeyRight)+ , ("\ESC[D", key KeyLeft)+ , ("\ESC[H", key KeyHome)+ , ("\ESC[F", key KeyEnd)+ , ("\ESC[Z", key KeyBackTab)+ , ("\ESC[1~", key KeyHome)+ , ("\ESC[3~", key KeyDelete)+ , ("\ESC[4~", key KeyEnd)+ , ("\ESC[5~", key KeyPageUp)+ , ("\ESC[6~", key KeyPageDown)+ , ("\ESCOH", key KeyHome)+ , ("\ESCOF", key KeyEnd)+ , ("\ESCOP", key (KeySpecial "OP"))+ , ("\ESCx", key (KeySpecial "x"))+ , ("\ESC[<0;10;5M", InputMouse (MouseEvent 0 (4, 9) True))+ , ("\ESC[<0;10;5m", InputMouse (MouseEvent 0 (4, 9) False))+ , ("\ESC[<65;1;1M", InputMouse (MouseEvent 65 (0, 0) True))+ , ("\ESC[60;200R", InputSize 60 200)+ ]