packages feed

layoutz-1.0.0.0: README.md

<div align="right">
  <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
[![Hackage](https://img.shields.io/hackage/v/layoutz)](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)