Apache-2.0 licensed by Matthieu Court
Maintained by [email protected]
This version can be pinned in stack with:layoutz-1.0.0.0@sha256:595e58a51bbd4faff3aa04769ae8f9806b5fd8c91065c52ae01ec4a0ca5db72d,8001

Module documentation for 1.0.0.0

Used by 1 package in nightly-2026-12-02(full list with versions):

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 like a header file.

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

Hackage

build-depends: layoutz

Or try it in a REPL:

cabal repl --build-depends layoutz

All you need is one import:

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 or scrolled.
  • Views 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:

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

It scales up to fancier things too, like a tiling workspace with splits, zoom, focus and a fuzzy finder in a short file:

Draw plots

sine = plotLine 50 12 [Series points "sin(x)" ColorBrightCyan]
  where points = [(x, 5 * sin x) | x <- [0, 0.15 .. 7.5]]

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.

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"

Show progress bars

Wrap any list with loader for a live bar, or use loaderStream for a spinner.

_ <- loader "Resizing" files resize
_ <- loaderStream "Tailing" logLines indexLine
n <- askSpin "Awaking Smaug…" SpinnerDots (threadDelay 1500000 >> pure 42)

Layoutz vs Brick

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/

Reference

Borders

Applied with border to box, banner, statusCard and table (anything else is left alone):

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:

thick :: View m -> View m
thick = border BorderThick
BorderNormal                  -- ┌─┐ (default)
BorderDouble                  -- ╔═╗
BorderThick                   -- ┏━┓
BorderRound                   -- ╭─╮
BorderAscii                   -- +-+
BorderBlock                   -- ███
BorderDashed                  -- ┌╌┐
BorderDotted                  -- ┌┈┐
BorderInnerHalfBlock          -- ▗▄▖
BorderOuterHalfBlock          -- ▛▀▜
BorderMarkdown                -- |-|
BorderCustom "+" "=" "|"      -- Custom border
BorderNone                    -- No borders

Elements

Layout

Stacking & rows

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

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).

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.

overlay (screen m & styleDim)
        (box "Quit?" [row [button "yes" Quit, button "no" Stay]])

Text transforms

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

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

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

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

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

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.

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")]]
  ]

Build straight from bytes or raw pixels:

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
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]

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:

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]

Views from data

Since views are plain values you can leverage the full power of Haskell’s functional collections to generate them:

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

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]"
  ]
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

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]

Styles

vstack
  [ "The quick brown fox..." & styleBold
  , "The quick brown fox..." & styleBold & fg ColorRed
  , "The quick brown fox..." & styleItalic & styleReverse
  ]
styleBold
styleDim
styleItalic
styleUnderline
styleBlink
styleReverse
styleHidden
styleStrikethrough

You can chain them:

vstack
  [ "The quick brown fox..." & styleBold & styleItalic & styleUnderline
  , "The quick brown fox..." & styleBold & styleReverse
  ]

You can mix colors into the chain too:

"The quick brown fox..." & styleBold & styleItalic & fg ColorBrightYellow

Charts & plots

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]
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

See also Granite for terminal plots in Haskell - which was the inspiration here.

Interactive apps

LayoutzApp is just a lightweight TEA runtime with 5 green threads and a layoutz View as the view.

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:

sandbox :: model
        -> (msg -> model -> model)
        -> (model -> View msg)
        -> LayoutzApp model msg

Options

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
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). At an app’s root, fill takes the whole terminal, and sized views are rebuilt from the room they get on every resize.

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]]

Keys

-- 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

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

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):

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.

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
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)

And a slightly more advanced focus demo, with resizing:

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
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"

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).

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 ()
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

_ <- loader "Resizing" imageFiles resize
_ <- loader "Inserting" rows insertRow
_ <- loaderStream "Tailing" logLines indexLine

Pick a loader style:

loaderBlocks -- (default)
loaderBar
loaderAscii
loaderDots
loaderLine
loaderPipes
loaderStyles -- all of the above, as a list
_ <- loaderStyled loaderAscii "Reindexing" docIds reindex
_ <- loaderStreamStyled loaderPipes "Crawling" urls fetch

Or make your own:

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
  }
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 ()

Contributing

You need GHC and 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).

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

Changes

Changelog

[1.0.0.0] - 2026-12-02

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

Added

  • Inline raster images via the kitty graphics protocol: kittyImage, kittyImageFile, kittyRGB, kittyRGBA. Images measure exactly cols×rows cells, so they compose with boxes, rows, tables, etc.
  • One-shot ask* prompts that collapse to a single line once answered
  • Progress loaders for wrapping work in build scripts and batch jobs: loader, loaderStream, and their *Styled variants

[0.3.4.0] - 2026-03-31

Added

  • renderText :: Element a => a -> Text for rendering directly to Data.Text.Text.
  • Unit tests for renderText.

Changed

  • Added text as an explicit dep on boot (stil technically zero dep by GHC standards)
  • But easy to comment out renderText for porting to MicroHs

[0.3.3.0] - 2026-03-14

Added

  • runAppFinal: like runApp but returns the final application state.
  • runAppWithFinal: like runAppWith but returns the final application state.
  • runInline: renders app inline without alt-screen, for embedded spinners/progress bars.
  • New InlineLoadingDemo example.

[0.3.2.0] - 2026-03-11

Added

  • CmdExit command for graceful app shutdown from within appUpdate.
  • cmdIsExit helper to check if a command tree contains an exit.

Fixed

  • Haddock markup errors.
  • SpinnerDemo.hs example.

[0.3.1.0] - 2026-03-01

Changed

  • Documentation tweaks and Haddock polish.

[0.3.0.0] - 2026-03-01

Added

  • TUI runtime (LayoutzApp, Elm Architecture style event loop).
  • Keyboard input handling (Key, readKey).
  • Commands (Cmd, cmdFire, cmdTask, cmdAfterMs).
  • Subscriptions (Sub, subKeyPress, subEveryMs).
  • AppOptions and AppAlignment for layout customization.
  • Spinner animations (SpinnerDots, SpinnerLine, SpinnerClock, SpinnerBounce).
  • Visualization primitives: plotSparkline, plotLine, plotPie, plotBar, plotStackedBar, plotHeatmap.
  • Braille-based line and pie chart rendering.
  • 256-color and RGB true-color support (ColorFull, ColorTrue).
  • Text styles with Semigroup combining (StyleBold <> StyleItalic).
  • tightRow for gapless horizontal layouts.
  • wrap for word-boundary text wrapping.
  • Ordered lists (ol) with nested numbering (arabic, alpha, roman).

[0.1.0.0] - 2026-02-27

Added

  • Initial Haskell port of layoutz.
  • Core DSL: text, layout, box, row, center, ul, table, kv, tree.
  • Border styles: normal, double, thick, round, ASCII, block, dashed, dotted, half-block, markdown, custom.
  • withBorder, withColor, withStyle combinators.
  • ANSI-aware width calculation (charWidth, visibleLength).
  • hr, vr, pad, margin, chart, section, alignLeft/alignRight/alignCenter/justify.
  • OverloadedStrings support for L.