tui

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: BSD-3-Clause Imports: 5 Imported by: 3 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

tui

Immediate-mode widget toolkit on top of the terminal cell buffer. No retained widget tree, no framework loop: the application owns a []terminal.Cell buffer and all state; tui provides regions, layout math, render functions, and plain-struct state helpers. Every frame is a full logical redraw — the terminal diff layer keeps actual output minimal.

Core concept: Region

A Region is a bounds-checked rectangular view over a cell slice. All drawing goes through regions; coordinates are region-relative. Sub-regions nest and clip to parent bounds, so widgets cannot draw outside their allotted area.

w, h := term.Size()
cells := make([]terminal.Cell, w*h)
root := tui.NewRegion(cells, w, 0, 0, w, h)

panel := root.Sub(2, 1, 40, 10) // clipped view
inner := panel.Inset(1)         // shrink 1 cell on all sides

Out-of-bounds writes are silently dropped — no bounds management needed in widget code.

Quick start

term := terminal.New()
term.Init()
defer term.Fini()

w, h := term.Size()
cells := make([]terminal.Cell, w*h)

list := tui.NewScrollState(len(items), h-2)
list.Selection = 0

for {
    root := tui.NewRegion(cells, w, 0, 0, w, h)
    root.Fill(color.Gunmetal)

    root.Box(tui.LineRounded, color.SteelBlue)
    content := root.Inset(1)
    content.List(buildItems(items), list.Selection, list.Offset, tui.ListOpts{
        CursorBg: color.DarkSlate,
    })
    content.ScrollBar(content.W-1, list.Offset, list.Visible, list.Total,
        color.IronGray)

    term.Flush(cells, w, h)

    ev := term.PollEvent()
    switch ev.Type {
    case terminal.EventKey:
        switch ev.Key {
        case terminal.KeyUp:
            list.SelectPrev()
        case terminal.KeyDown:
            list.SelectNext()
        case terminal.KeyEscape:
            return
        }
    case terminal.EventResize:
        w, h = ev.Width, ev.Height
        cells = make([]terminal.Cell, w*h)
        list.SetVisible(h - 2)
    }
}

Layout

cols := tui.SplitH(root, 0.3, 0.7)          // ratio split, normalized
rows := tui.SplitV(cols[1], 0.5, 0.5)
side, main := tui.SplitHFixed(root, 24)     // fixed left width
top, rest := tui.SplitVFixed(root, 3)       // fixed top height
dlg := tui.Center(root, 50, 12)             // centered sub-region

The last ratio segment absorbs rounding remainder — no gaps.

Text and style

r.Text(x, y, "label", fg, bg, terminal.AttrNone)
r.TextCenter(y, "title", fg, bg, terminal.AttrBold)
r.TextRight(y, "hint", fg, bg, terminal.AttrDim)
lines := r.TextBlock(x, y, longText, fg, bg, attr) // word-wrapped, returns line count
r.TextStyled(x, y, s, tui.Style{Fg: fg, Bg: bg, Attr: attr})

String utilities operate on rune counts: RuneLen, Truncate / TruncateLeft / TruncateMiddle (ellipsis variants), PadLeft / PadRight / PadCenter, WrapText (at line breaks and spaces; a path or key longer than the line breaks after ., ,, :, /, [ or ]).

Style{Fg, Bg, Attr} bundles cell appearance; most widget option structs accept it.

Widgets

Widgets are stateless render functions (mostly Region methods). Application state lives in plain structs passed by pointer. Available renderers:

boxes and lines (Box, BoxFilled, HLine, VLine — single, double, rounded, heavy, dashed and ASCII line types), List, Table, Tree, TabBar, KeyValue / KeyValueWrap, Progress / ProgressV / Gauge / Spinner, ProgressOverlay, Sparkline / SparklineV, Input / TextField, Editor, Modal / Overlay / ConfirmDialog, ScrollBar / ScrollIndicator, masonry layout.

Representative patterns below; remaining widgets follow the same opts-struct + state-struct shape — read the source for full options.

Theme and form controls

A Theme is one Style per role (Text, Muted, Accent, Selected, Input, Cursor, Error, Border) plus the Glyphs widgets draw. A role's Attr may carry color bits, a palette index or the terminal's own color, so an application builds one theme per color tier and every control draws alike in each: DefaultTheme is dark true color, Theme16 uses the ANSI 16 on the terminal's own background, MonoTheme uses attributes alone, and ThemeFor(term.ColorMode()) picks among them. A selection always changes a glyph (a radio mark, a pointer, the focus mark), so it reads without color. A reverse-video Selected with no color of its own (Theme16, MonoTheme) keeps the terminal's own foreground in every cell drawn on it, so the cursor row is one bar. GlyphsUnicode, GlyphsCP437 (text consoles) and GlyphsASCII (outside UTF-8) are the glyph sets; Glyphs.Line is the line type of frames, rules and wires.

th := tui.DefaultTheme
root.FillStyle(th.Text) // the panel the controls draw on

value, rows := form.Field(y, 10, tui.Field{Label: "port", Required: true,
    Help: "TCP port to listen on", Error: portErr}, focus.Index == 0, th)
value.TextInput(port, "8080", focus.Index == 0, th) // the default as placeholder
y += rows

value, rows = form.Field(y, 10, tui.Field{Label: "format"}, focus.Index == 1, th)
value.Radio(0, 0, []string{"raw", "txt", "json"}, format, th) // ○ raw  ● txt  ○ json
y += rows

form.Group(y, "tls", "on, pinned", tlsOpen, focus.Index == 2, th)
  • Focus is the focus ring: HandleKey moves it on Tab and Shift+Tab.
  • Field draws the focus mark, the label, the required mark, and the error, or the help while focused, wrapped, and returns the region for the value. The label leaves the value at least half the row; label width 0 stacks the label above the value, for narrow screens.
  • TextInput draws a TextFieldState, its placeholder muted while empty, scrolled to the cursor with a muted … where text is out of view. TextFieldState.Accept filters typed and pasted runes (AcceptInteger, AcceptNumber); Paste inserts an EventPaste's text with line breaks as spaces and control characters dropped.
  • Radio draws radio buttons in a row, the chosen one marked; too wide, it shows the chosen one and its neighbours. StepChoice moves it on Left and Right.
  • Toggle draws an on/off switch.
  • Group draws a foldable group's header, and its summary while folded.
  • OptionListState and OptionList filter options by what is typed, matching name or hint regardless of case. Hints sit beside the names, or, narrow, the cursor's hint wraps below them; Rows(w) is the height to size a dialog by. With Menu there is no filter and Pick finds an option by its Key, shown before its name.
  • Frame fills a region, borders it with its title, and returns the inside; sized with Center to what it holds, a dialog ends on its last line.
  • Rule draws a line with a title and a hint, dropping the hint first.
  • Wires lay lines on a grid by the arms that meet in each cell (H, V), and DrawWires draws every junction, tee and crossing joined.
Scrollable list with scrollbar
items := make([]tui.ListItem, 0, len(files))
for _, f := range files {
    items = append(items, tui.ListItem{
        Icon: '▸', IconFg: color.Amber,
        Text: f.Name, TextStyle: tui.Style{Fg: terminal.LightGray},
    })
}
r.List(items, state.Selection, state.Offset, tui.ListOpts{CursorBg: color.DarkSlate})
r.ScrollBar(r.W-1, state.Offset, state.Visible, state.Total, color.IronGray)
Modal dialog
dlg := tui.Center(root, 50, 12)
content := dlg.Modal(tui.ModalOpts{
    Title:    "Settings",
    Border:   tui.LineDouble,
    BorderFg: color.SteelBlue,
    TitleFg:  terminal.White,
    Bg:       color.DarkSlate,
})
content.TextBlock(0, 0, body, fg, color.DarkSlate, terminal.AttrNone)

Modal fills, borders, titles, and returns the content region. Overlay adds fullscreen/floating/shadow variants; ConfirmDialog adds yes/no buttons with focus state.

Progress overlay
prog := tui.NewProgressState(tui.DefaultProgressOpts("Indexing", "Scanning...",
    tui.ProgressDeterminate))

// per frame:
prog.Tick()
prog.SetProgress(done / total)
if prog.Visible {
    root.ProgressOverlay(prog.Opts)
}

Five progress types (spinner, determinate, indeterminate, pulse, dots), eight spinner styles, eight bar styles, seven frame styles — combinable via opts.

Multi-line editor
ed := tui.NewEditorState(initialText)

// input:
if ev.Type == terminal.EventKey {
    ed.HandleKey(ev.Key, ev.Rune, ev.Modifiers) // full emacs-style bindings built in
}

// render:
r.Editor(ed, tui.EditorOpts{LineNumbers: true, Border: tui.LineSingle, Focused: true})
text := ed.Value()

TextFieldState + TextField provide the single-line equivalent (placeholder, prefix, password mask, max length).

State helpers

Pure logic, no rendering — usable independently:

  • ScrollState — item-index scrolling with selection (SelectNext/Prev, EnsureVisible, PageUp/Down, AtTop/AtBottom)
  • ViewportScroll — row-based content scrolling with viewport clipping (ClipToViewport maps content rows to visible rows, EnsureRange keeps a range in view); Region.Window draws content taller than the region off screen and shows the rows in view
  • TreeState + TreeExpansion + TreeBuilder — cursor/scroll, expand/collapse keyed state, hierarchical → flat visible-node list
  • EditorState, TextFieldState — text content, cursor, scroll, key handling
  • MasonryState — multi-column layout calculation over a viewport
  • Free functions: AdjustScroll, ClampScroll, ClampCursor, ScrollPercent, PageDelta

Notes

  • Width calculations count runes, one column each, as Flush draws a wide or joining rune as U+FFFD.
  • Zero-value color.RGB in style fields generally means "inherit" (widget default or row background) — check specific widget docs. A zero background with no Bg color bits is transparent: the cell keeps the background beneath it, bits and all.
  • Mouse hit testing: TabBar returns []TabBounds; other widgets require application-side geometry from the regions used.

Documentation

Index

Constants

View Source
const (
	IconExpanded  = '▼'
	IconCollapsed = '▶'
	IconBullet    = '•'
)

ExpandIcon chars

Variables

View Source
var (
	GlyphsUnicode = Glyphs{Focus: '▌', Pointer: '▸', Folded: '▸', Unfolded: '▾', On: '●', Off: '○', Required: '*'}
	GlyphsCP437   = Glyphs{Focus: '▌', Pointer: '►', Folded: '►', Unfolded: '▼', On: '•', Off: '○', Required: '*'}
	GlyphsASCII   = Glyphs{Focus: '>', Pointer: '>', Folded: '+', Unfolded: '-', On: '*', Off: '-', Required: '*', Line: LineASCII}
)
View Source
var DefaultTheme = Theme{
	Text:     Style{Fg: color.RGB{R: 200, G: 200, B: 200}, Bg: color.RGB{R: 20, G: 20, B: 30}},
	Muted:    Style{Fg: color.RGB{R: 120, G: 125, B: 140}},
	Accent:   Style{Fg: color.RGB{R: 80, G: 160, B: 220}, Attr: terminal.AttrBold},
	Selected: Style{Bg: color.RGB{R: 40, G: 45, B: 65}},
	Input:    Style{Bg: color.RGB{R: 30, G: 30, B: 50}},
	Cursor:   Style{Fg: color.RGB{R: 20, G: 20, B: 30}, Bg: color.RGB{R: 200, G: 200, B: 200}},
	Error:    Style{Fg: color.RGB{R: 255, G: 80, B: 80}},
	Border:   Style{Fg: color.RGB{R: 60, G: 80, B: 100}},
	Glyphs:   GlyphsUnicode,
}

DefaultTheme is a dark theme for true color and 256-color terminals

View Source
var MonoTheme = Theme{
	Text:     Style{Attr: own | terminal.AttrBgDefault},
	Muted:    Style{Attr: own | terminal.AttrDim},
	Accent:   Style{Attr: own | terminal.AttrBold},
	Selected: Style{Attr: own | terminal.AttrReverse},
	Input:    Style{Attr: own | terminal.AttrUnderline},
	Cursor:   Style{Attr: own | terminal.AttrReverse},
	Error:    Style{Attr: own | terminal.AttrBold | terminal.AttrUnderline},
	Border:   Style{Attr: own},
	Glyphs:   GlyphsUnicode,
}

MonoTheme draws with attributes alone in the terminal's own colors: the theme for ColorModeNone, and one that reads on any terminal

View Source
var SparklineChars = []rune{'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'}

SparklineChars provides 8-level vertical resolution

View Source
var Theme16 = Theme{
	Text:     Style{Attr: own | terminal.AttrBgDefault},
	Muted:    ansi(color.ANSIBrightBlack, 0),
	Accent:   ansi(color.ANSICyan, terminal.AttrBold),
	Selected: Style{Attr: own | terminal.AttrReverse},
	Input:    Style{Attr: own | terminal.AttrUnderline},
	Cursor:   Style{Attr: own | terminal.AttrReverse},
	Error:    ansi(color.ANSIRed, terminal.AttrBold),
	Border:   Style{Attr: own},
	Glyphs:   GlyphsUnicode,
}

Theme16 uses the ANSI 16 colors alone, in the terminal's own shades, on its own background: the theme for ColorMode16, a text console's

View Source
var ToastColors = map[ToastSeverity]struct{ Fg, Bg, Icon color.RGB }{
	ToastInfo: {
		Fg:   color.RGB{R: 200, G: 200, B: 200},
		Bg:   color.RGB{R: 40, G: 40, B: 50},
		Icon: color.RGB{R: 100, G: 150, B: 255},
	},
	ToastSuccess: {
		Fg:   color.RGB{R: 220, G: 255, B: 220},
		Bg:   color.RGB{R: 30, G: 60, B: 30},
		Icon: color.RGB{R: 80, G: 220, B: 80},
	},
	ToastWarning: {
		Fg:   color.RGB{R: 255, G: 240, B: 200},
		Bg:   color.RGB{R: 60, G: 50, B: 20},
		Icon: color.RGB{R: 255, G: 200, B: 60},
	},
	ToastError: {
		Fg:   color.RGB{R: 255, G: 220, B: 220},
		Bg:   color.RGB{R: 60, G: 25, B: 25},
		Icon: color.RGB{R: 255, G: 80, B: 80},
	},
}

ToastColors default colors per severity

View Source
var ToastIcons = map[ToastSeverity]rune{
	ToastInfo:    'ℹ',
	ToastSuccess: '✓',
	ToastWarning: '⚠',
	ToastError:   '✗',
}

ToastIcons for severity levels

Functions

func AcceptInteger added in v0.2.0

func AcceptInteger(r rune) bool

AcceptInteger takes the runes of a decimal integer

func AcceptNumber added in v0.2.0

func AcceptNumber(r rune) bool

AcceptNumber takes the runes of a decimal number, exponent included

func AdjustScroll

func AdjustScroll(cursor, scroll, visible, total int) int

AdjustScroll returns new scroll offset keeping cursor visible

func BreakpointH

func BreakpointH(w int, breakpoints ...int) int

BreakpointH returns index of first breakpoint <= w, returns len(breakpoints) if w is less than all breakpoints

func BreakpointV

func BreakpointV(h int, breakpoints ...int) int

BreakpointV returns index of first breakpoint <= h

func CalculateColumnWidths

func CalculateColumnWidths(availableW int, headers []string, rows [][]string, opts TableOpts) []int

CalculateColumnWidths computes optimal column widths for given data Returns widths that fit within availableW, respecting fixed widths in opts

func ClampCursor

func ClampCursor(cursor, total int) int

ClampCursor ensures cursor is within valid range

func ClampScroll

func ClampScroll(scroll, visible, total int) int

ClampScroll ensures scroll offset is within valid range

func Columns

func Columns(availableW, itemW, gap int) int

Columns calculates how many columns fit in width

func DividerPositions

func DividerPositions(regionW, n, gap int) []int

DividerPositions returns X coordinates for vertical dividers between equal columns Use with VLine to draw dividers in gaps created by SplitHEqual

func ExpandIconRune

func ExpandIconRune(expanded bool) rune

ExpandIconRune returns appropriate expand/collapse indicator

func FindFirstChildIndex

func FindFirstChildIndex(nodes []TreeNode, idx int) int

FindFirstChildIndex returns index of first child for node at idx, or -1 if none

func FindNextSiblingIndex

func FindNextSiblingIndex(nodes []TreeNode, idx int) int

FindNextSiblingIndex returns index of next sibling at same depth, or -1

func FindParentIndex

func FindParentIndex(nodes []TreeNode, idx int) int

FindParentIndex returns index of parent node for node at idx, or -1 if root

func FindPrevSiblingIndex

func FindPrevSiblingIndex(nodes []TreeNode, idx int) int

FindPrevSiblingIndex returns index of previous sibling at same depth, or -1

func FitOrScroll

func FitOrScroll(contentH, availableH int) bool

FitOrScroll returns true if content exceeds available height

func FormatCoverageSuffix

func FormatCoverageSuffix(count, total int) string

FormatCoverageSuffix returns a suffix string for TreeNode.Suffix

func HDividerPositions

func HDividerPositions(regionH, n, gap int) []int

HDividerPositions returns Y coordinates for horizontal dividers between equal rows

func PadCenter

func PadCenter(s string, width int) string

PadCenter centers string within width

func PadLeft

func PadLeft(s string, width int) string

PadLeft left-pads string with spaces to width

func PadRight

func PadRight(s string, width int) string

PadRight pads string with spaces to width

func PageDelta

func PageDelta(visible int) int

PageDelta returns recommended page scroll amount

func RepeatRune

func RepeatRune(r rune, n int) string

RepeatRune returns a string of n repeated runes, for string repeat use strings.Repeat

func RuneLen

func RuneLen(s string) int

RuneLen returns s's width in cells, a rune each: Flush draws every rune in one column, a wide or joining one as U+FFFD

func ScrollPercent

func ScrollPercent(scroll, visible, total int) int

ScrollPercent returns scroll position as 0-100 percentage

func StepChoice added in v0.2.0

func StepChoice(key terminal.Key, r rune, chosen, n int) (int, bool)

StepChoice moves a choice among n options on Left or Right (h, l), stopping at either end, and reports whether it moved

func Truncate

func Truncate(s string, maxLen int) string

Truncate truncates string with … suffix if exceeds maxLen

func TruncateLeft

func TruncateLeft(s string, maxLen int) string

TruncateLeft truncates with … prefix, keeps end of string

func TruncateMiddle

func TruncateMiddle(s string, maxLen int) string

TruncateMiddle keeps start and end, … in middle

func WrapText

func WrapText(s string, width int) []string

WrapText wraps text to fit width: at each line break, at spaces, or, in a word longer than a line, after its last '.', ',', ':', '/', '[' or ']' that fits (a path or a key such as a[0].b); a word without one is cut. Returns slice of lines, each no longer than width.

Types

type AlertOpts

type AlertOpts struct {
	Title   string
	Message string
	Button  string // Default "OK"
	Style   ConfirmStyle
}

AlertOpts configures single-button alert dialog

type Align

type Align uint8

Align specifies text alignment within a column

const (
	AlignLeft Align = iota
	AlignRight
	AlignCenter
)

type BarAlign

type BarAlign uint8

BarAlign specifies status bar alignment mode

const (
	BarAlignRight      BarAlign = iota // Pack sections from right
	BarAlignLeft                       // Pack sections from left
	BarAlignDistribute                 // Evenly space sections
	BarAlignCenter                     // Center all sections as a group
)

type BarOpts

type BarOpts struct {
	Separator string // Between sections, default " │ "
	SepStyle  Style  // Separator styling
	Bg        color.RGB
	Align     BarAlign
	Padding   int // Left/right padding, default 1
}

BarOpts configures status bar rendering

func DefaultBarOpts

func DefaultBarOpts() BarOpts

DefaultBarOpts returns sensible defaults

type BarSection

type BarSection struct {
	Label      string
	Value      string
	LabelStyle Style
	ValueStyle Style
	Priority   int // Higher = survives truncation
}

BarSection represents one segment of a status bar

type BarStyle

type BarStyle uint8

BarStyle defines progress bar appearance

const (
	BarStyleBlock   BarStyle = iota // █░
	BarStyleShade                   // ▓▒░
	BarStyleArrow                   // =>-
	BarStyleDot                     // ●○
	BarStyleBracket                 // [###   ]
	BarStylePipe                    // |===  |
	BarStyleThin                    // ━╺
	BarStyleThick                   // ▰▱
)

type Button

type Button struct {
	Label   string
	Key     string // Keyboard hint (e.g., "Ctrl+S")
	Focused bool
}

Button defines a single button in a button bar

type ButtonBarOpts

type ButtonBarOpts struct {
	Align BarAlign
	Gap   int
	Style ButtonStyle
}

ButtonBarOpts configures button bar rendering

type ButtonStyle

type ButtonStyle struct {
	LabelFg color.RGB
	LabelBg color.RGB
	KeyFg   color.RGB
	FocusFg color.RGB
	FocusBg color.RGB
	Bg      color.RGB
}

ButtonStyle defines button bar colors

func DefaultButtonStyle

func DefaultButtonStyle() ButtonStyle

DefaultButtonStyle returns default button colors with dark background

func DefaultButtonStyleFrom

func DefaultButtonStyleFrom(bg color.RGB) ButtonStyle

DefaultButtonStyleFrom returns default button colors using the given background

type CheckState

type CheckState uint8

CheckState represents checkbox visual state

const (
	CheckNone    CheckState = iota // [ ]
	CheckPartial                   // [o]
	CheckFull                      // [x]
	CheckPlus                      // [+]
)

type ConfirmOpts

type ConfirmOpts struct {
	Title       string
	Message     string
	YesLabel    string // Default "Yes"
	NoLabel     string // Default "No"
	Destructive bool   // Style Yes as warning
	Style       ConfirmStyle
}

ConfirmOpts configures confirmation dialog

type ConfirmResult

type ConfirmResult uint8

ConfirmResult represents dialog outcome

const (
	ConfirmPending ConfirmResult = iota
	ConfirmYes
	ConfirmNo
	ConfirmCancel
)

type ConfirmState

type ConfirmState struct {
	FocusYes bool // true = Yes focused, false = No focused
	Result   ConfirmResult
}

ConfirmState holds confirmation dialog state

func NewConfirmState

func NewConfirmState(defaultYes bool) *ConfirmState

NewConfirmState creates dialog state with default selection

func (*ConfirmState) Cancel

func (c *ConfirmState) Cancel()

Cancel cancels the dialog

func (*ConfirmState) Confirm

func (c *ConfirmState) Confirm()

Confirm selects currently focused button

func (*ConfirmState) HandleKey

func (c *ConfirmState) HandleKey(key terminal.Key, r rune) bool

HandleKey processes input, returns true if dialog should close

func (*ConfirmState) SelectNo

func (c *ConfirmState) SelectNo()

SelectNo directly selects No

func (*ConfirmState) SelectYes

func (c *ConfirmState) SelectYes()

SelectYes directly selects Yes

func (*ConfirmState) Toggle

func (c *ConfirmState) Toggle()

Toggle switches focus between Yes and No

type ConfirmStyle

type ConfirmStyle struct {
	BorderFg      color.RGB
	TitleFg       color.RGB
	MessageFg     color.RGB
	Bg            color.RGB
	ButtonFg      color.RGB
	ButtonBg      color.RGB
	ButtonFocusFg color.RGB
	ButtonFocusBg color.RGB
	DestructiveFg color.RGB
	DestructiveBg color.RGB
}

ConfirmStyle defines dialog colors

func DefaultConfirmStyle

func DefaultConfirmStyle() ConfirmStyle

DefaultConfirmStyle returns default dialog colors

type Coverage

type Coverage struct {
	Count int
	Total int
}

Coverage represents count/total for display in tree nodes

func (Coverage) IsAll

func (c Coverage) IsAll() bool

IsAll returns true if count equals total and total is positive

func (Coverage) IsNone

func (c Coverage) IsNone() bool

IsNone returns true if count is zero

func (Coverage) IsPartial

func (c Coverage) IsPartial() bool

IsPartial returns true if count is between zero and total (exclusive)

func (Coverage) String

func (c Coverage) String() string

String returns coverage as "count/total", "[ALL]", or empty string if total is zero

type DocBlock

type DocBlock struct {
	Kind DocKind
	Key  string // DocEntry only
	Text string
}

DocBlock is one logical unit of a document

type DocKind

type DocKind uint8

DocKind classifies a document block

const (
	DocSection DocKind = iota // Section header with an inline rule
	DocEntry                  // Key + description in aligned columns
	DocPara                   // Wrapped paragraph across the document width
	DocGap                    // One blank row
)

type DocOpts

type DocOpts struct {
	HeaderStyle Style
	KeyStyle    Style
	TextStyle   Style
	RuleStyle   Style
	Rule        LineType // Header rule; LineNone draws the header alone
	KeyWidth    int      // Fixed key column, 0 = measured from the entries
	KeyMaxW     int      // Cap for the measured key column, 0 = 40% of width
	MinTextW    int      // Text column narrower than this stacks every entry
	Gap         int      // Columns between key and text, minimum 1
	Indent      int      // Left indent of section content
	StackIndent int      // Indent of a stacked description
	SectionGap  int      // Blank rows before a section header
	MaxWidth    int      // Document width cap, 0 = region width
	Center      bool     // Center the document when the cap applies
}

DocOpts configures document layout and rendering Layout-affecting fields must not change between Layout and Doc

type DocState

type DocState struct {
	Viewport *ViewportScroll
	// contains filtered or unexported fields
}

DocState holds a laid-out document and its scroll position

func NewDocState

func NewDocState() *DocState

NewDocState creates document state

func (*DocState) Layout

func (d *DocState) Layout(blocks []DocBlock, width int, opts DocOpts)

Layout flattens blocks into rows for the given width; the row count becomes the viewport content height. Entries stack when the text column is too narrow, and an over-long key stacks on its own rather than truncating.

func (*DocState) SetViewport

func (d *DocState) SetViewport(h int)

SetViewport updates viewport height

type EditorOpts

type EditorOpts struct {
	LineNumbers  bool
	LineNumWidth int // 0 = auto-size
	WrapLines    bool
	Border       LineType
	Focused      bool
	Style        EditorStyle
}

EditorOpts configures editor rendering

type EditorState

type EditorState struct {
	Lines      []string
	CursorLine int
	CursorCol  int
	ScrollX    int
	ScrollY    int
	ViewportW  int // Updated during render
	ViewportH  int // Updated during render
}

EditorState holds multi-line text editor state

func NewEditorState

func NewEditorState(initial string) *EditorState

NewEditorState creates initialized editor state

func (*EditorState) AdjustScroll

func (e *EditorState) AdjustScroll(viewportW, viewportH int)

AdjustScroll updates scroll to keep cursor visible

func (*EditorState) Clear

func (e *EditorState) Clear()

Clear empties the editor

func (*EditorState) CurrentLine

func (e *EditorState) CurrentLine() string

CurrentLine returns current line text

func (*EditorState) DeleteBackward

func (e *EditorState) DeleteBackward() bool

DeleteBackward deletes character before cursor or merges lines

func (*EditorState) DeleteForward

func (e *EditorState) DeleteForward() bool

DeleteForward deletes character at cursor or merges with next line

func (*EditorState) DeleteLine

func (e *EditorState) DeleteLine() bool

DeleteLine removes current line

func (*EditorState) DeleteToEndOfLine

func (e *EditorState) DeleteToEndOfLine() bool

DeleteToEndOfLine deletes from cursor to end of line

func (*EditorState) DeleteToStartOfLine

func (e *EditorState) DeleteToStartOfLine() bool

DeleteToStartOfLine deletes from start to cursor

func (*EditorState) DeleteWordBackward

func (e *EditorState) DeleteWordBackward() bool

DeleteWordBackward deletes word before cursor

func (*EditorState) DeleteWordForward

func (e *EditorState) DeleteWordForward() bool

DeleteWordForward deletes word after cursor

func (*EditorState) HandleKey

func (e *EditorState) HandleKey(key terminal.Key, r rune, mod terminal.Modifier) bool

HandleKey processes keyboard input, returns true if state changed

func (*EditorState) Insert

func (e *EditorState) Insert(r rune)

Insert adds a rune at cursor position

func (*EditorState) InsertNewline

func (e *EditorState) InsertNewline()

InsertNewline splits current line at cursor

func (*EditorState) InsertString

func (e *EditorState) InsertString(s string)

InsertString adds string at cursor, handling newlines

func (*EditorState) LineCount

func (e *EditorState) LineCount() int

LineCount returns number of lines

func (*EditorState) MoveDown

func (e *EditorState) MoveDown()

MoveDown moves cursor to next line

func (*EditorState) MoveLeft

func (e *EditorState) MoveLeft()

MoveLeft moves cursor left, wrapping to previous line

func (*EditorState) MoveRight

func (e *EditorState) MoveRight()

MoveRight moves cursor right, wrapping to next line

func (*EditorState) MoveToEnd

func (e *EditorState) MoveToEnd()

MoveToEnd moves cursor to end of document

func (*EditorState) MoveToLineEnd

func (e *EditorState) MoveToLineEnd()

MoveToLineEnd moves cursor to end of line

func (*EditorState) MoveToLineStart

func (e *EditorState) MoveToLineStart()

MoveToLineStart moves cursor to start of line

func (*EditorState) MoveToStart

func (e *EditorState) MoveToStart()

MoveToStart moves cursor to start of document

func (*EditorState) MoveUp

func (e *EditorState) MoveUp()

MoveUp moves cursor to previous line

func (*EditorState) MoveWordLeft

func (e *EditorState) MoveWordLeft()

MoveWordLeft moves cursor to previous word boundary

func (*EditorState) MoveWordRight

func (e *EditorState) MoveWordRight()

MoveWordRight moves cursor to next word boundary

func (*EditorState) PageDown

func (e *EditorState) PageDown()

PageDown moves cursor down by half viewport

func (*EditorState) PageUp

func (e *EditorState) PageUp()

PageUp moves cursor up by half viewport

func (*EditorState) SetValue

func (e *EditorState) SetValue(s string)

SetValue replaces all content and resets cursor

func (*EditorState) Value

func (e *EditorState) Value() string

Value returns all lines joined with newlines

type EditorStyle

type EditorStyle struct {
	TextFg        color.RGB
	TextBg        color.RGB
	CursorFg      color.RGB
	CursorBg      color.RGB
	LineNumFg     color.RGB
	LineNumBg     color.RGB
	CurrentLineBg color.RGB
	BorderFg      color.RGB
}

EditorStyle defines editor colors

func DefaultEditorStyle

func DefaultEditorStyle() EditorStyle

DefaultEditorStyle returns default colors

type Field added in v0.2.0

type Field struct {
	Label    string
	Required bool
	Help     string // shown under the field while it has focus
	Error    string // shown under the field, in place of Help
}

Field labels one form row

type Focus added in v0.2.0

type Focus struct {
	Index, Len int
}

Focus is a focus ring over a form's controls, numbered 0 to Len-1

func (*Focus) HandleKey added in v0.2.0

func (f *Focus) HandleKey(key terminal.Key, mod terminal.Modifier) bool

HandleKey moves focus on Tab and Shift+Tab, wrapping, and reports whether it moved

type FormField

type FormField struct {
	Label string
	State *TextFieldState
}

FormField pairs a label with an editable text field

type FormOpts

type FormOpts struct {
	LabelWidth int
	Spacing    int
	Style      FormStyle
}

FormOpts configures form rendering

type FormState

type FormState struct {
	Fields []FormField
	Focus  int
}

FormState holds state for a multi-field form with focus tracking

func NewFormState

func NewFormState(labels ...string) *FormState

NewFormState creates a form with labeled fields initialized to empty values

func (*FormState) Clear

func (f *FormState) Clear()

Clear empties all fields in the form

func (*FormState) CurrentField

func (f *FormState) CurrentField() *TextFieldState

CurrentField returns the TextFieldState of the focused field, or nil

func (*FormState) FocusNext

func (f *FormState) FocusNext()

FocusNext moves focus to the next field, wrapping around

func (*FormState) FocusPrev

func (f *FormState) FocusPrev()

FocusPrev moves focus to the previous field, wrapping around

func (*FormState) HandleKey

func (f *FormState) HandleKey(key terminal.Key, r rune, mod terminal.Modifier) bool

HandleKey processes keyboard input for form navigation and field editing, returns true if state changed

func (*FormState) SetValue

func (f *FormState) SetValue(idx int, val string)

SetValue replaces the text of the field at idx

func (*FormState) Value

func (f *FormState) Value(idx int) string

Value returns the text value of the field at idx

type FormStyle

type FormStyle struct {
	LabelFg  color.RGB
	FieldFg  color.RGB
	FieldBg  color.RGB
	FocusBg  color.RGB
	CursorFg color.RGB
	CursorBg color.RGB
	Bg       color.RGB
}

FormStyle defines form colors

func DefaultFormStyle

func DefaultFormStyle() FormStyle

DefaultFormStyle returns default form colors

type Glyphs added in v0.2.0

type Glyphs struct {
	Focus    rune     // beside the focused control
	Pointer  rune     // the cursor row of a list
	Folded   rune     // a closed group
	Unfolded rune     // an open group
	On, Off  rune     // a toggle
	Required rune     // after a required field's label
	Line     LineType // frames, rules and wires
}

Glyphs are the marks widgets draw; a selection always changes a glyph, so it reads without color. A text console's font takes GlyphsCP437, a terminal outside UTF-8 GlyphsASCII.

type InputOpts

type InputOpts struct {
	Label    string
	LabelFg  color.RGB
	Text     string
	Cursor   int // Cursor position in text (rune index)
	CursorBg color.RGB
	TextFg   color.RGB
	Bg       color.RGB
}

InputOpts configures single-line input field

type LineType

type LineType uint8

LineType specifies box drawing character style

const (
	LineSingle  LineType = iota // ┌─┐│└┘
	LineDouble                  // ╔═╗║╚╝
	LineRounded                 // ╭─╮│╰╯
	LineHeavy                   // ┏━┓┃┗┛
	LineNone                    // spaces (invisible border with padding)
	LineASCII                   // +-+|++, for a terminal outside UTF-8
	LineDashed                  // ╭╌╮╎╰╯
)

type ListItem

type ListItem struct {
	Indent    int  // Left padding in cells
	Icon      rune // Expand indicator or bullet, 0 = none
	IconFg    color.RGB
	Check     CheckState // CheckNone to skip checkbox
	CheckFg   color.RGB
	Text      string
	TextStyle Style
}

ListItem represents a single row in a scrollable list

type ListOpts

type ListOpts struct {
	CursorBg  color.RGB
	DefaultBg color.RGB
	IconWidth int // Width reserved for icon, default 2
}

ListOpts configures list rendering

type MasonryItem

type MasonryItem struct {
	Key    string
	Height int
	Data   any
}

MasonryItem represents a single item in masonry layout

type MasonryLayout

type MasonryLayout struct {
	X, Y, W, H int
	Item       MasonryItem
}

MasonryLayout holds calculated position for an item

type MasonryOpts

type MasonryOpts struct {
	Columns     int
	GapX        int // Columns between masonry columns
	GapY        int // Rows between stacked items
	MinColW     int
	Breakpoints map[int]int
}

MasonryOpts configures masonry layout

func DefaultMasonryOpts

func DefaultMasonryOpts() MasonryOpts

DefaultMasonryOpts returns sensible defaults

type MasonryRenderFunc

type MasonryRenderFunc func(region Region, layout MasonryLayout, contentOffset int)

MasonryRenderFunc renders a single item

type MasonryState

type MasonryState struct {
	Viewport *ViewportScroll
	Layouts  []MasonryLayout
}

MasonryState manages masonry layout with viewport scroll

func NewMasonryState

func NewMasonryState() *MasonryState

NewMasonryState creates masonry state

func (*MasonryState) CalculateLayout

func (m *MasonryState) CalculateLayout(items []MasonryItem, width int, opts MasonryOpts)

CalculateLayout computes item positions

func (*MasonryState) ScrollIndicator

func (m *MasonryState) ScrollIndicator() string

ScrollIndicator renders scroll position indicator for masonry

func (*MasonryState) SetViewport

func (m *MasonryState) SetViewport(h int)

SetViewport updates viewport height

type ModalOpts

type ModalOpts struct {
	Title    string
	Hint     string // Right-aligned hint text
	Border   LineType
	BorderFg color.RGB
	TitleFg  color.RGB
	HintFg   color.RGB
	Bg       color.RGB
}

ModalOpts configures modal overlay rendering

type Option added in v0.2.0

type Option struct {
	Name string // what is chosen
	Hint string // a line about it
	Key  rune   // in a menu, the key that picks it at once
}

Option is one entry of an option list

type OptionListState added in v0.2.0

type OptionListState struct {
	Options []Option
	Filter  TextFieldState
	Cursor  int  // index into Matches
	Scroll  int  // first match shown
	Menu    bool // no filter; Pick finds an option by its Key
}

OptionListState filters options by the text typed into it, matching name or hint regardless of case, and keeps a cursor on the matches. A menu has no filter: each option's Key picks it.

func NewOptionListState added in v0.2.0

func NewOptionListState(options []Option) *OptionListState

NewOptionListState creates a list showing every option

func (*OptionListState) Chosen added in v0.2.0

func (s *OptionListState) Chosen() (int, bool)

Chosen returns the index in Options of the option under the cursor, and false when nothing matches

func (*OptionListState) HandleKey added in v0.2.0

func (s *OptionListState) HandleKey(key terminal.Key, r rune, mod terminal.Modifier) bool

HandleKey moves the cursor on Up and Down, or edits the filter, and reports whether anything changed

func (*OptionListState) Matches added in v0.2.0

func (s *OptionListState) Matches() []int

Matches returns the indices of the options the filter matches, in order, keeping the cursor on one of them

func (*OptionListState) Paste added in v0.2.0

func (s *OptionListState) Paste(text string) bool

Paste adds pasted text to the filter

func (*OptionListState) Pick added in v0.2.1

func (s *OptionListState) Pick(r rune) (int, bool)

Pick returns the index in Options of the option whose Key is r

func (*OptionListState) Rows added in v0.2.1

func (s *OptionListState) Rows(w int) int

Rows returns the rows the list takes at width w to show every option: the filter, a row each, and the cursor's hint where it does not fit beside them

type OverlayOpts

type OverlayOpts struct {
	Style   OverlayStyle
	Title   string
	Border  LineType
	Bg      color.RGB
	Fg      color.RGB // Border and title color
	TitleBg color.RGB // Title bar background, zero = same as Fg
	TitleFg color.RGB // Title text color, zero = same as Bg

	// Modal/Floating positioning (ignored for Fullscreen)
	Width  int // 0 = 80% of region
	Height int // 0 = 80% of region
	X, Y   int // Offset from center, 0 = centered

	// Shadow for Floating style
	ShadowColor color.RGB
}

OverlayOpts configures overlay rendering

func DefaultOverlayOpts

func DefaultOverlayOpts(title string) OverlayOpts

DefaultOverlayOpts returns sensible defaults for modal overlay

func FullscreenOverlayOpts

func FullscreenOverlayOpts(title string) OverlayOpts

FullscreenOverlayOpts returns opts for fullscreen overlay with title bar

type OverlayResult

type OverlayResult struct {
	Outer   Region // Full overlay bounds (including border/title)
	Content Region // Inner content area
	TitleY  int    // Y position of title bar in Outer, -1 if no title
}

OverlayResult contains regions returned by Overlay rendering

type OverlayState

type OverlayState struct {
	Visible bool
	Opts    OverlayOpts
	Data    any // Application-specific state
}

OverlayState manages overlay visibility and content state

func NewOverlayState

func NewOverlayState(opts OverlayOpts) *OverlayState

NewOverlayState creates hidden overlay state

func (*OverlayState) Hide

func (o *OverlayState) Hide()

Hide makes overlay invisible

func (*OverlayState) Show

func (o *OverlayState) Show()

Show makes overlay visible

func (*OverlayState) Toggle

func (o *OverlayState) Toggle()

Toggle switches visibility

type OverlayStyle

type OverlayStyle uint8

OverlayStyle specifies overlay appearance

const (
	OverlayFullscreen  OverlayStyle = iota // No border, fills region
	OverlayModal                           // Centered box with border
	OverlayFloating                        // Positioned box with shadow
	OverlayBorderTitle                     // Title embedded in top border line
)

type PaneOpts

type PaneOpts struct {
	Title    string
	Border   LineType
	BorderFg color.RGB
	Bg       color.RGB
	TitleFg  color.RGB
}

PaneOpts configures pane rendering

type ProgressOverlayOpts

type ProgressOverlayOpts struct {
	Title        string
	Message      string
	Type         ProgressType
	Style        ProgressStyle
	SpinnerStyle SpinnerStyle
	BarStyle     BarStyle
	Progress     float64 // 0.0-1.0 for determinate
	Frame        int     // Animation frame counter
	ShowPercent  bool    // Show percentage text
	ShowETA      string  // Optional ETA string
	Width        int     // Overlay width, 0 = auto
	Cancelable   bool    // Show cancel hint
	CancelKey    string  // e.g., "Esc"
	Fg           color.RGB
	Bg           color.RGB
	BarFg        color.RGB
	BarBg        color.RGB
	AccentFg     color.RGB // Spinner/highlight color
}

ProgressOverlayOpts configures progress overlay

func DefaultProgressOpts

func DefaultProgressOpts(title, message string, ptype ProgressType) ProgressOverlayOpts

DefaultProgressOpts returns sensible defaults

type ProgressState

type ProgressState struct {
	Visible  bool
	Opts     ProgressOverlayOpts
	Frame    int
	Progress float64
}

ProgressState manages progress overlay state

func NewProgressState

func NewProgressState(opts ProgressOverlayOpts) *ProgressState

NewProgressState creates progress overlay state

func (*ProgressState) Complete

func (p *ProgressState) Complete()

Complete marks progress as done

func (*ProgressState) Dismiss

func (p *ProgressState) Dismiss()

Dismiss hides the progress overlay

func (*ProgressState) SetETA

func (p *ProgressState) SetETA(eta string)

SetETA updates ETA string

func (*ProgressState) SetMessage

func (p *ProgressState) SetMessage(msg string)

SetMessage updates message text

func (*ProgressState) SetProgress

func (p *ProgressState) SetProgress(pct float64)

SetProgress updates progress value (0.0-1.0)

func (*ProgressState) Show

func (p *ProgressState) Show()

Show displays the progress overlay

func (*ProgressState) Tick

func (p *ProgressState) Tick()

Tick advances animation frame

type ProgressStyle

type ProgressStyle uint8

ProgressStyle defines visual appearance

const (
	ProgressStyleMinimal ProgressStyle = iota // Text only
	ProgressStyleBox                          // Single border
	ProgressStyleDouble                       // Double border
	ProgressStyleRounded                      // Rounded border
	ProgressStyleShadow                       // Box with shadow
	ProgressStyleNeon                         // Bright colors
	ProgressStyleRetro                        // Block characters
)

type ProgressType

type ProgressType uint8

ProgressType specifies progress indicator variant

const (
	ProgressSpinner       ProgressType = iota // Animated spinner
	ProgressDeterminate                       // Bar with percentage
	ProgressIndeterminate                     // Marquee animation
	ProgressPulse                             // Pulsing bar
	ProgressDots                              // Animated dots
)

type Region

type Region struct {
	Cells  []terminal.Cell
	TotalW int // Total width of the underlying cell buffer
	X, Y   int // Absolute position in cell buffer
	W, H   int // Region dimensions
}

Region represents a rectangular area within a cell buffer All coordinates are relative to the region's origin

func Center

func Center(outer Region, w, h int) Region

Center returns a centered region of given size within outer

func GridLayout

func GridLayout(r Region, cols, rows, gapX, gapY int) []Region

GridLayout returns a grid of equally sized regions

func NewRegion

func NewRegion(cells []terminal.Cell, totalW, x, y, w, h int) Region

NewRegion creates a region referencing a cell slice with bounds

func SplitH

func SplitH(r Region, ratios ...float64) []Region

SplitH splits region horizontally by ratios (0.0-1.0)

func SplitHEqual

func SplitHEqual(r Region, n, gap int) []Region

SplitHEqual splits region into n equal-width columns gap specifies spacing between columns (e.g., 1 for divider lines) Returns n regions positioned with gaps between them

func SplitHFixed

func SplitHFixed(r Region, leftW int) (left, right Region)

SplitHFixed splits with fixed left width, rest to right

func SplitV

func SplitV(r Region, ratios ...float64) []Region

SplitV splits region vertically by ratios (0.0-1.0)

func SplitVEqual

func SplitVEqual(r Region, n, gap int) []Region

SplitVEqual splits region into n equal-height rows gap specifies spacing between rows

func SplitVFixed

func SplitVFixed(r Region, topH int) (top, bottom Region)

SplitVFixed splits with fixed top height, rest to bottom

func (Region) AlertDialog

func (r Region) AlertDialog(opts AlertOpts) Region

AlertDialog renders single-button alert, returns true when dismissed

func (Region) Bounds

func (r Region) Bounds() (x, y, w, h int)

Bounds returns absolute position and dimensions

func (Region) Box

func (r Region) Box(line LineType, fg color.RGB)

Box draws border around region edge

func (Region) BoxClipped

func (r Region) BoxClipped(line LineType, fg color.RGB, totalH, off int)

BoxClipped draws the visible slice of a box whose logical height is totalH, with off rows scrolled past its top edge. Rows outside the box are skipped, so a partially visible box keeps its sides and grows no false edges.

func (Region) BoxFilled

func (r Region) BoxFilled(line LineType, fg, bg color.RGB)

BoxFilled draws border and fills interior with background

func (Region) BoxStyle added in v0.2.1

func (r Region) BoxStyle(line LineType, s Style)

BoxStyle draws a border around the region's edge in a theme's style

func (Region) ButtonBar

func (r Region) ButtonBar(y int, buttons []Button, opts ButtonBarOpts)

ButtonBar renders a row of buttons with labels and keyboard hints at row y

func (Region) Card

func (r Region) Card(title string, line LineType, fg color.RGB) Region

Card draws titled border and returns inner content region

func (Region) Cell

func (r Region) Cell(x, y int, ch rune, fg, bg color.RGB, attr terminal.Attr)

Cell sets a single cell with bounds checking. A zero-value bg (color.RGB{}) with no Bg color bits in attr is transparent: the existing cell's background is preserved, bits and all. Establish a base background first (Fill, or pre-initialized cell buffer). For a literal black background use CellOpaque or Fill(color.RGB{}).

func (Region) CellOpaque

func (r Region) CellOpaque(x, y int, ch rune, fg, bg color.RGB, attr terminal.Attr)

CellOpaque sets a single cell writing bg verbatim, including zero (black). Used by base-layer operations (Fill) that must be able to write any color.

func (Region) Checkbox

func (r Region) Checkbox(x, y int, state CheckState, fg color.RGB)

Checkbox draws a checkbox indicator

func (Region) Clear

func (r Region) Clear()

Clear fills region with spaces and zero colors

func (Region) ConfirmDialog

func (r Region) ConfirmDialog(state *ConfirmState, opts ConfirmOpts) Region

ConfirmDialog renders confirmation dialog centered in region Returns content region for additional content if needed

func (Region) Divider

func (r Region) Divider(y int, label string, line LineType, fg color.RGB)

Divider draws horizontal line with optional centered label

func (Region) Doc

func (r Region) Doc(d *DocState, opts DocOpts)

Doc renders the visible window of a laid-out document

func (Region) DrawWires added in v0.2.1

func (r Region) DrawWires(g Wires, line LineType, s Style)

DrawWires draws every cell of the grid that has arms, in the line type

func (Region) Editor

func (r Region) Editor(state *EditorState, opts EditorOpts) int

Editor renders multi-line editor and returns content height used

func (Region) Field added in v0.2.0

func (r Region) Field(y, labelW int, f Field, focused bool, th Theme) (Region, int)

Field draws a form row at y: the focus mark, the label in a column labelW wide with the required mark, and below, the error, or the help while focused, wrapped. The label column leaves the value half the row; labelW 0 stacks the label on its own row and the value under it, indented. It returns the region for the value, where the caller draws a TextInput, Radio or Toggle, and the rows it used.

func (Region) Fill

func (r Region) Fill(bg color.RGB)

Fill fills entire region with background color. Opaque by definition: Fill establishes the base layer, so bg is written verbatim (including zero/black) rather than treated as transparent.

func (Region) FillStyle added in v0.2.0

func (r Region) FillStyle(s Style)

FillStyle fills the region with spaces in s, opaque as Fill is; a theme's Text fills the panel its widgets draw on

func (Region) Form

func (r Region) Form(state *FormState, opts FormOpts) int

Form renders a multi-field form with labels and editable text fields, returns height used

func (Region) Frame added in v0.2.1

func (r Region) Frame(title string, th Theme) Region

Frame fills the region with the theme's text style and draws its border in Glyphs.Line, the title on the top edge, and returns the inside with a column of padding each side. Callers size it to its content, with Center.

func (Region) Gauge

func (r Region) Gauge(x, y, w int, value, max int, fg, bg color.RGB)

Gauge draws labeled gauge with percentage

func (Region) Group added in v0.2.0

func (r Region) Group(y int, title, summary string, open, focused bool, th Theme)

Group draws a foldable group's header at y: the focus mark, the Folded or Unfolded glyph and the title, and while folded, a muted summary of what it holds

func (Region) HLine

func (r Region) HLine(y int, line LineType, fg color.RGB)

HLine draws horizontal line across region width at row y

func (Region) Height

func (r Region) Height() int

Height returns region height

func (Region) Input

func (r Region) Input(y int, opts InputOpts)

Input renders labeled text input field on row y, handling cursor display and horizontal scrolling

func (Region) Inset

func (r Region) Inset(n int) Region

Inset returns a region shrunk by n cells on all sides

func (Region) KeyValue

func (r Region) KeyValue(y int, key, value string, keyStyle, valStyle Style, sep rune)

KeyValue renders right-aligned key, separator and left-aligned value on row y, sizing the key column to this row alone

func (Region) KeyValueColumn

func (r Region) KeyValueColumn(y, keyW int, key, value string, keyStyle, valStyle Style, sep rune)

KeyValueColumn renders a key-value row against an explicit key column, so a set of rows aligns on the separator; keyW <= 0 sizes the column to this row

func (Region) KeyValueWrap

func (r Region) KeyValueWrap(y int, key, value string, keyStyle, valStyle Style, sep rune) int

KeyValueWrap renders a key with its value wrapped into the value column, returning the number of lines used

key: value text that is
     long and wraps to
     next line

func (Region) List

func (r Region) List(items []ListItem, cursor, scroll int, opts ListOpts) int

List renders scrollable list items within region, returns number of rows rendered

func (Region) Masonry

func (r Region) Masonry(state *MasonryState, render MasonryRenderFunc)

Masonry renders visible items via callback

func (Region) MeasureKeyValueWrap

func (r Region) MeasureKeyValueWrap(key, value string) int

MeasureKeyValueWrap returns the line count KeyValueWrap needs, for layout pre-calculation. Shares the column split with the renderer, so the two agree.

func (Region) Modal

func (r Region) Modal(opts ModalOpts) Region

Modal fills region with background, draws border with title/hint, returns content region

func (Region) OptionList added in v0.2.0

func (r Region) OptionList(s *OptionListState, th Theme)

OptionList draws the filter on the first row, a menu none, and the matches below, the cursor row marked with the pointer on the Selected background and a menu's keys before the names in the accent style. Hints sit muted beside the names or, where that column would be narrower than 16, the cursor's hint wraps onto the list's last rows.

func (Region) Overlay

func (r Region) Overlay(opts OverlayOpts) OverlayResult

Overlay renders an overlay and returns content region for caller to populate Caller should render content into result.Content after this call

func (Region) Pane

func (r Region) Pane(opts PaneOpts) Region

Pane draws bordered pane with optional title, returns content region Content region is inside border, below title row if present

func (Region) Progress

func (r Region) Progress(x, y, w int, pct float64, fg, bg color.RGB)

Progress draws horizontal progress bar (0.0-1.0)

func (Region) ProgressOverlay

func (r Region) ProgressOverlay(opts ProgressOverlayOpts) Region

ProgressOverlay renders centered progress overlay

func (Region) ProgressV

func (r Region) ProgressV(x, y, h int, pct float64, fg, bg color.RGB)

ProgressV draws vertical progress bar (fills bottom-up)

func (Region) QuickStatusBar

func (r Region) QuickStatusBar(y int, pairs [][2]string, labelFg, valueFg, bg color.RGB)

QuickStatusBar renders simple label:value pairs right-aligned

func (Region) Radio added in v0.2.1

func (r Region) Radio(x, y int, options []string, chosen int, th Theme) int

Radio draws options as radio buttons in a row at (x, y): the chosen one with the On glyph in the accent style, the rest with Off, muted ("○ raw ● txt ○ json"); chosen -1 marks none. Where the row does not fit, it shows the options around the chosen one, a muted '…' where others are hidden. It returns the columns it drew.

func (Region) Rule added in v0.2.1

func (r Region) Rule(y int, title, hint string, th Theme)

Rule draws a line across row y, the title at its third column and the hint muted at its end. The title keeps its room: the hint is dropped where both do not fit.

func (Region) ScrollBar

func (r Region) ScrollBar(x int, offset, visible, total int, fg color.RGB)

ScrollBar draws a vertical scrollbar track with thumb in a single color

func (Region) ScrollBarStyled

func (r Region) ScrollBarStyled(x int, offset, visible, total int, opts ScrollBarOpts)

ScrollBarStyled draws a vertical scrollbar at column x with explicit styling

func (Region) ScrollIndicator

func (r Region) ScrollIndicator(y int, offset, visible, total int, fg color.RGB)

ScrollIndicator draws compact indicator text (Top/Bot/XX%)

func (Region) Sparkline

func (r Region) Sparkline(x, y, width int, values []float64, opts SparklineOpts)

Sparkline renders an inline graph of values, values are mapped to 8-level block characters

func (Region) SparklineV

func (r Region) SparklineV(x, y, height int, values []float64, opts SparklineOpts)

SparklineV renders vertical sparkline (bottom to top)

func (Region) Spinner

func (r Region) Spinner(x, y int, frame int, fg color.RGB)

Spinner draws spinner character based on frame counter

func (Region) StatusBar

func (r Region) StatusBar(y int, sections []BarSection, opts BarOpts)

StatusBar renders horizontal status bar on row y

func (Region) Sub

func (r Region) Sub(x, y, w, h int) Region

Sub returns a nested region with coordinates relative to parent, result is clipped to parent bounds

func (Region) TabBar

func (r Region) TabBar(y int, titles []string, active int, opts TabBarOpts) []TabBounds

TabBar renders horizontal tab strip at row y Returns bounds of each tab for hit testing / navigation

func (Region) TabBarCentered

func (r Region) TabBarCentered(y int, titles []string, active int, opts TabBarOpts) []TabBounds

TabBarCentered renders tab bar centered horizontally

func (Region) Table

func (r Region) Table(headers []string, rows [][]string, opts TableOpts)

Table renders a table with headers and rows

func (Region) Text

func (r Region) Text(x, y int, s string, fg, bg color.RGB, attr terminal.Attr)

Text renders text at position, truncates at region edge

func (Region) TextBlock

func (r Region) TextBlock(x, y int, text string, fg, bg color.RGB, attr terminal.Attr) int

TextBlock renders wrapped text within region bounds, returns number of lines rendered

func (Region) TextBlockStyled

func (r Region) TextBlockStyled(x, y int, text string, style Style) int

TextBlockStyled renders wrapped text using Style struct, returns number of lines rendered

func (Region) TextCenter

func (r Region) TextCenter(y int, s string, fg, bg color.RGB, attr terminal.Attr)

TextCenter renders text centered on row

func (Region) TextField

func (r Region) TextField(state *TextFieldState, opts TextFieldOpts) int

TextField renders text field and returns content height used

func (Region) TextInput added in v0.2.0

func (r Region) TextInput(state *TextFieldState, placeholder string, focused bool, th Theme)

TextInput draws state's text on r's first row, or, empty, the placeholder muted: a default shows what an empty value means. Focused, it draws on the Input background with the cursor, scrolling to keep the cursor in view; a muted '…' marks text out of view.

func (Region) TextRight

func (r Region) TextRight(y int, s string, fg, bg color.RGB, attr terminal.Attr)

TextRight renders text right-aligned on row

func (Region) TextStyled

func (r Region) TextStyled(x, y int, s string, style Style)

TextStyled renders text using Style struct

func (Region) TitledPane

func (r Region) TitledPane(title string, titleFg, bg color.RGB) Region

TitledPane fills region with background, draws centered title at top, returns content region Content region starts at row 1 with full width

func (Region) TitledPaneFocused

func (r Region) TitledPaneFocused(title string, titleFg, bg, focusBg color.RGB, focused bool) Region

TitledPaneFocused is TitledPane with focus-dependent background

func (Region) Toast

func (r Region) Toast(opts ToastOpts) Region

Toast renders a toast message overlay Returns the region occupied by the toast for hit testing

func (Region) Toggle added in v0.2.0

func (r Region) Toggle(x, y int, on bool, th Theme) int

Toggle draws a switch at (x, y): the On glyph and "on" in the accent style, or the Off glyph and "off" muted, and returns the columns it drew

func (Region) Tree

func (r Region) Tree(nodes []TreeNode, cursor, scroll int, opts TreeOpts) int

Tree renders hierarchical tree nodes within region, returns number of rows rendered Nodes must be pre-flattened (only visible/expanded nodes included)

func (Region) VLine

func (r Region) VLine(x int, line LineType, fg color.RGB)

VLine draws vertical line across region height at column x

func (Region) Width

func (r Region) Width() int

Width returns region width

func (Region) Window added in v0.2.1

func (r Region) Window(h int, v *ViewportScroll, bg Style, draw func(Region))

Window shows content h rows tall through the region, from v's offset: draw paints a buffer as wide as the region and h tall, filled with bg, and the rows in view are copied. Window sets v's heights; a caller keeping a row in view sets them first and calls EnsureRange.

type ScrollBarOpts

type ScrollBarOpts struct {
	ThumbFg  color.RGB
	TrackFg  color.RGB
	Bg       color.RGB // Zero inherits the existing cell background
	Thumb    rune      // 0 = '█'
	Track    rune      // 0 = '░'
	HideIdle bool      // Draw nothing when content fits the viewport
}

ScrollBarOpts configures scrollbar rendering

type ScrollState

type ScrollState struct {
	Offset    int // First visible item index
	Total     int // Total item count
	Visible   int // Visible item count (viewport height)
	Selection int // Currently selected item, -1 if none
}

ScrollState tracks scroll position for a scrollable container

func NewScrollState

func NewScrollState(total, visible int) *ScrollState

NewScrollState creates initialized scroll state

func (*ScrollState) AtBottom

func (s *ScrollState) AtBottom() bool

AtBottom returns true if scrolled to bottom

func (*ScrollState) AtTop

func (s *ScrollState) AtTop() bool

AtTop returns true if scrolled to top

func (*ScrollState) Clamp

func (s *ScrollState) Clamp()

Clamp ensures offset is within valid range

func (*ScrollState) EnsureVisible

func (s *ScrollState) EnsureVisible(pos int)

EnsureVisible adjusts offset to make item at pos visible

func (*ScrollState) PageDown

func (s *ScrollState) PageDown()

PageDown scrolls down by half visible height

func (*ScrollState) PageUp

func (s *ScrollState) PageUp()

PageUp scrolls up by half visible height

func (*ScrollState) ScrollBy

func (s *ScrollState) ScrollBy(delta int)

ScrollBy adjusts offset by delta, clamping to valid range

func (*ScrollState) ScrollTo

func (s *ScrollState) ScrollTo(pos int)

ScrollTo sets offset to specific position

func (*ScrollState) Select

func (s *ScrollState) Select(idx int)

Select sets selection and ensures it's visible

func (*ScrollState) SelectNext

func (s *ScrollState) SelectNext()

SelectNext moves selection down

func (*ScrollState) SelectPrev

func (s *ScrollState) SelectPrev()

SelectPrev moves selection up

func (*ScrollState) SetTotal

func (s *ScrollState) SetTotal(total int)

SetTotal updates total count and reclamps

func (*ScrollState) SetVisible

func (s *ScrollState) SetVisible(visible int)

SetVisible updates visible count and reclamps

type SparklineOpts

type SparklineOpts struct {
	Min, Max float64 // Range bounds, auto-scale if both 0
	Style    Style
}

SparklineOpts configures sparkline rendering

type SpinnerStyle

type SpinnerStyle uint8

SpinnerStyle defines spinner animation type

const (
	SpinnerBraille SpinnerStyle = iota // ⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏
	SpinnerDots                        // ⣾⣽⣻⢿⡿⣟⣯⣷
	SpinnerLine                        // |/-\
	SpinnerBlock                       // ▖▘▝▗
	SpinnerCircle                      // ◐◓◑◒
	SpinnerArc                         // ◜◠◝◞◡◟
	SpinnerBounce                      // ⠁⠂⠄⠂
	SpinnerGrow                        // ▁▃▄▅▆▇█▇▆▅▄▃
)

type Style

type Style struct {
	Fg   color.RGB
	Bg   color.RGB
	Attr terminal.Attr
}

Style bundles foreground, background, and attributes for text rendering. Attr's color bits say how to read Fg and Bg: terminal.AttrFg256 a palette index in R, terminal.AttrFgDefault the terminal's own color.

func DefaultStyle

func DefaultStyle(fg color.RGB) Style

DefaultStyle returns style with zero values (transparent bg)

func (Style) IsZero

func (s Style) IsZero() bool

IsZero returns true if style has no colors or attributes set

func (Style) On added in v0.2.0

func (s Style) On(bg Style) Style

On returns s drawn on bg: s's foreground, bg's background (s's own where bg's is transparent), and the attributes of both. On a reverse bg with no color of its own, s keeps only its background, with the terminal's own foreground and bg's styles: a reversed cell's background is its foreground (a console's keeps its intensity), so mixed styles would break the bar.

type TabBarOpts

type TabBarOpts struct {
	ActiveStyle   Style
	InactiveStyle Style
	Separator     string // Between tabs, default " │ "
	Padding       int    // Horizontal padding inside each tab, default 1
}

TabBarOpts configures tab bar rendering

func DefaultTabBarOpts

func DefaultTabBarOpts() TabBarOpts

DefaultTabBarOpts returns sensible defaults

type TabBounds

type TabBounds struct {
	X, W int
}

TabBounds stores position and size of a rendered tab

type TableOpts

type TableOpts struct {
	ColWidths    []int   // Fixed widths per column, 0 = auto
	ColAligns    []Align // Alignment per column, default AlignLeft
	HeaderStyle  Style
	RowStyle     Style
	AltRowStyle  Style    // Alternating row style, zero = same as RowStyle
	ColSeparator rune     // Between columns, 0 = space
	RowSeparator LineType // Between rows, LineNone = no separator
}

TableOpts configures table rendering

func DefaultTableOpts

func DefaultTableOpts() TableOpts

DefaultTableOpts returns sensible defaults

type TextFieldOpts

type TextFieldOpts struct {
	Placeholder string   // Shown when empty
	Prefix      string   // Left prompt (e.g., "> ")
	Mask        rune     // Password mask, 0 = none
	MaxLen      int      // Max runes, 0 = unlimited
	Border      LineType // Border style, LineNone = no border
	Focused     bool     // Show cursor and accept input
	Style       TextFieldStyle
}

TextFieldOpts configures text field rendering

type TextFieldState

type TextFieldState struct {
	Text   []rune
	Cursor int // Positions before which cursor sits (0 = before first char)
	Scroll int // First visible rune index

	// Accept, when set, filters the runes typed or pasted: AcceptInteger
	// and AcceptNumber make a typed field
	Accept func(rune) bool
}

TextFieldState holds editable text field state

func NewTextFieldState

func NewTextFieldState(initial string) *TextFieldState

NewTextFieldState creates initialized text field state

func (*TextFieldState) AdjustScroll

func (t *TextFieldState) AdjustScroll(viewportW int)

AdjustScroll updates scroll to keep the cursor visible within viewport width, and the viewport filled up to the end of the text

func (*TextFieldState) Clear

func (t *TextFieldState) Clear()

Clear empties the field

func (*TextFieldState) DeleteBackward

func (t *TextFieldState) DeleteBackward() bool

DeleteBackward removes rune before cursor

func (*TextFieldState) DeleteForward

func (t *TextFieldState) DeleteForward() bool

DeleteForward removes rune at cursor

func (*TextFieldState) DeleteToEnd

func (t *TextFieldState) DeleteToEnd() bool

DeleteToEnd removes from cursor to end

func (*TextFieldState) DeleteToStart

func (t *TextFieldState) DeleteToStart() bool

DeleteToStart removes from start to cursor

func (*TextFieldState) DeleteWordBackward

func (t *TextFieldState) DeleteWordBackward() bool

DeleteWordBackward removes word before cursor

func (*TextFieldState) DeleteWordForward

func (t *TextFieldState) DeleteWordForward() bool

DeleteWordForward removes word after cursor

func (*TextFieldState) HandleKey

func (t *TextFieldState) HandleKey(key terminal.Key, r rune, mod terminal.Modifier) bool

HandleKey processes keyboard input, returns true if state changed

func (*TextFieldState) Insert

func (t *TextFieldState) Insert(r rune)

Insert adds rune at cursor position

func (*TextFieldState) InsertString

func (t *TextFieldState) InsertString(s string)

InsertString adds string at cursor position

func (*TextFieldState) MoveLeft

func (t *TextFieldState) MoveLeft()

MoveLeft moves cursor left

func (*TextFieldState) MoveRight

func (t *TextFieldState) MoveRight()

MoveRight moves cursor right

func (*TextFieldState) MoveToEnd

func (t *TextFieldState) MoveToEnd()

MoveToEnd moves cursor to end

func (*TextFieldState) MoveToStart

func (t *TextFieldState) MoveToStart()

MoveToStart moves cursor to beginning

func (*TextFieldState) MoveWordLeft

func (t *TextFieldState) MoveWordLeft()

MoveWordLeft moves cursor to previous word boundary

func (*TextFieldState) MoveWordRight

func (t *TextFieldState) MoveWordRight()

MoveWordRight moves cursor to next word boundary

func (*TextFieldState) Paste added in v0.2.0

func (t *TextFieldState) Paste(s string) bool

Paste inserts pasted text at the cursor: a line break or tab becomes a space, and other control characters and runes Accept refuses are dropped. It reports whether anything was inserted.

func (*TextFieldState) SetValue

func (t *TextFieldState) SetValue(s string)

SetValue replaces text and moves cursor to end

func (*TextFieldState) Value

func (t *TextFieldState) Value() string

Value returns current text as string

type TextFieldStyle

type TextFieldStyle struct {
	TextFg        color.RGB
	TextBg        color.RGB
	CursorFg      color.RGB
	CursorBg      color.RGB
	PlaceholderFg color.RGB
	PrefixFg      color.RGB
	BorderFg      color.RGB
}

TextFieldStyle defines text field colors

func DefaultTextFieldStyle

func DefaultTextFieldStyle() TextFieldStyle

DefaultTextFieldStyle returns default colors

type Theme

type Theme struct {
	Text     Style // values and body text; its Bg is the panel's
	Muted    Style // labels, hints, placeholders and defaults, help lines
	Accent   Style // marks: focus, the chosen option, a required field
	Selected Style // the cursor row of a list
	Input    Style // the background of the field being edited
	Cursor   Style // the text cursor
	Error    Style // errors
	Border   Style // boxes and rules
	Glyphs   Glyphs
}

Theme styles the widgets that take one. Each role is a Style whose Attr may carry color bits (a palette index, the terminal's own color), so one theme per color tier, mono included, draws every widget alike. A role with a zero Bg and no Bg bits draws on whatever is beneath it.

func ThemeFor added in v0.2.0

func ThemeFor(mode terminal.ColorMode) Theme

ThemeFor returns the theme for a color mode: DefaultTheme with 256 colors or more, Theme16 with 16, MonoTheme with none

type ToastOpts

type ToastOpts struct {
	Message    string
	Severity   ToastSeverity
	Position   ToastPosition
	Style      ToastStyle
	ShowIcon   bool
	MinWidth   int // Minimum width for floating toasts, 0 = auto
	MaxWidth   int // Maximum width, 0 = region width
	Padding    int // Horizontal padding, default 1
	MarginX    int // Margin from edge for floating positions
	MarginY    int // Margin from edge for floating positions
	CustomFg   color.RGB
	CustomBg   color.RGB
	CustomIcon color.RGB
}

ToastOpts configures toast rendering

func DefaultToastOpts

func DefaultToastOpts(message string, severity ToastSeverity) ToastOpts

DefaultToastOpts returns sensible defaults

type ToastPosition

type ToastPosition uint8

ToastPosition specifies where toast renders

const (
	ToastBottom      ToastPosition = iota // Full-width bar at bottom
	ToastTop                              // Full-width bar at top
	ToastBottomRight                      // Floating box bottom-right
	ToastBottomLeft                       // Floating box bottom-left
	ToastTopRight                         // Floating box top-right
	ToastTopLeft                          // Floating box top-left
	ToastCenter                           // Centered floating box
)

type ToastSeverity

type ToastSeverity uint8

ToastSeverity defines message type for styling

const (
	ToastInfo    ToastSeverity = iota // Default, neutral
	ToastSuccess                      // Green, positive
	ToastWarning                      // Yellow, caution
	ToastError                        // Red, failure
)

type ToastState

type ToastState struct {
	Visible    bool
	Opts       ToastOpts
	FramesLeft int // Countdown to auto-dismiss, -1 = persistent
}

ToastState manages toast lifecycle

func NewToastState

func NewToastState(opts ToastOpts, frames int) *ToastState

NewToastState creates a toast that auto-dismisses after frames Use frames=-1 for persistent toast

func (*ToastState) Dismiss

func (t *ToastState) Dismiss()

Dismiss hides the toast

func (*ToastState) Show

func (t *ToastState) Show(opts ToastOpts, frames int)

Show displays a new toast

func (*ToastState) Tick

func (t *ToastState) Tick() bool

Tick decrements frame counter, returns true if toast should dismiss

type ToastStyle

type ToastStyle uint8

ToastStyle defines visual appearance

const (
	ToastStyleMinimal ToastStyle = iota // No border, just text
	ToastStyleBar                       // Full-width background bar
	ToastStyleBox                       // Bordered box
	ToastStyleRounded                   // Rounded border box
	ToastStyleDouble                    // Double-line border
	ToastStyleShadow                    // Box with shadow effect
)

type TreeBuilder

type TreeBuilder struct {
	// contains filtered or unexported fields
}

TreeBuilder helps construct flattened visible node list from hierarchical data

func NewTreeBuilder

func NewTreeBuilder(expansion *TreeExpansion) *TreeBuilder

NewTreeBuilder creates a builder with expansion state

func (*TreeBuilder) Add

func (b *TreeBuilder) Add(node TreeNode, parentExpanded bool)

Add adds a node if visible (parent expanded) parentExpanded should be true for root-level nodes

func (*TreeBuilder) MarkLastSiblings

func (b *TreeBuilder) MarkLastSiblings()

MarkLastSiblings sets IsLast flag on nodes that are last at their depth Call after all nodes added, before rendering

func (*TreeBuilder) Nodes

func (b *TreeBuilder) Nodes() []TreeNode

Nodes returns accumulated visible nodes

func (*TreeBuilder) Reset

func (b *TreeBuilder) Reset()

Reset clears accumulated nodes

type TreeExpansion

type TreeExpansion struct {
	State map[string]bool
}

TreeExpansion manages expand/collapse state

func NewTreeExpansion

func NewTreeExpansion() *TreeExpansion

NewTreeExpansion creates initialized expansion state

func (*TreeExpansion) Clear

func (e *TreeExpansion) Clear()

Clear removes all expansion state

func (*TreeExpansion) Collapse

func (e *TreeExpansion) Collapse(key string)

Collapse sets key to collapsed

func (*TreeExpansion) CollapseAll

func (e *TreeExpansion) CollapseAll()

CollapseAll collapses all keys

func (*TreeExpansion) Expand

func (e *TreeExpansion) Expand(key string)

Expand sets key to expanded

func (*TreeExpansion) ExpandAll

func (e *TreeExpansion) ExpandAll(keys []string)

ExpandAll expands all provided keys

func (*TreeExpansion) IsExpanded

func (e *TreeExpansion) IsExpanded(key string) bool

IsExpanded returns expansion state for key

func (*TreeExpansion) SetExpanded

func (e *TreeExpansion) SetExpanded(key string, expanded bool)

SetExpanded sets expansion state for key

func (*TreeExpansion) Toggle

func (e *TreeExpansion) Toggle(key string) bool

Toggle toggles expansion state for key

type TreeLineMode

type TreeLineMode uint8

TreeLineMode specifies connector line rendering

const (
	TreeLinesNone   TreeLineMode = iota // Indent only, no lines
	TreeLinesSimple                     // │ continuation, └ for last
)

type TreeNode

type TreeNode struct {
	Key        string // Unique identifier for expansion state
	Label      string // Display text
	Icon       rune   // Custom icon, 0 = auto (▶/▼ for expandable, • for leaf)
	IconFg     color.RGB
	Expandable bool       // Has children
	Expanded   bool       // Currently expanded
	Depth      int        // Nesting level (0 = root)
	Check      CheckState // Optional checkbox, CheckNone to skip
	CheckFg    color.RGB
	Style      Style // Text styling
	IsLast     bool  // Last sibling at this depth (for tree lines)
	Data       any   // Application payload

	Suffix      string    // Secondary text after label (e.g., "(5 files)")
	SuffixStyle Style     // Styling for suffix, zero = dimmed version of Style
	Badge       rune      // Icon between checkbox and label (e.g., '★'), 0 = none
	BadgeFg     color.RGB // Badge color
}

TreeNode represents a node in a hierarchical tree

type TreeOpts

type TreeOpts struct {
	CursorBg    color.RGB
	DefaultBg   color.RGB
	IndentWidth int // Cells per depth, default 2
	IconWidth   int // Width for icon column, default 2
	LineMode    TreeLineMode
	LineFg      color.RGB
}

TreeOpts configures tree rendering

func DefaultTreeOpts

func DefaultTreeOpts() TreeOpts

DefaultTreeOpts returns sensible defaults

type TreeState

type TreeState struct {
	Cursor  int
	Scroll  int
	Visible int // Viewport height
}

TreeState manages navigation state for a tree

func NewTreeState

func NewTreeState(visible int) *TreeState

NewTreeState creates initialized tree state

func (*TreeState) AdjustScroll

func (t *TreeState) AdjustScroll(total int)

AdjustScroll ensures cursor is visible

func (*TreeState) JumpEnd

func (t *TreeState) JumpEnd(total int)

JumpEnd moves cursor to last item

func (*TreeState) JumpStart

func (t *TreeState) JumpStart()

JumpStart moves cursor to first item

func (*TreeState) MoveCursor

func (t *TreeState) MoveCursor(delta, total int)

MoveCursor adjusts cursor position by delta

func (*TreeState) PageDown

func (t *TreeState) PageDown(total int)

PageDown scrolls down by half viewport

func (*TreeState) PageUp

func (t *TreeState) PageUp(total int)

PageUp scrolls up by half viewport

func (*TreeState) SetVisible

func (t *TreeState) SetVisible(visible int)

SetVisible updates viewport height

type ViewportScroll

type ViewportScroll struct {
	Offset    int // Row offset from top of content
	ContentH  int // Total content height in rows
	ViewportH int // Visible viewport height
}

ViewportScroll manages row-based scroll for content regions Distinct from ScrollState which is item-index based

func NewViewportScroll

func NewViewportScroll() *ViewportScroll

NewViewportScroll creates viewport scroll state

func (*ViewportScroll) CanScroll

func (v *ViewportScroll) CanScroll() bool

CanScroll returns true if content exceeds viewport

func (*ViewportScroll) ClipToViewport

func (v *ViewportScroll) ClipToViewport(y, h int) (viewY, viewH, contentOffset int, visible bool)

ClipToViewport maps content coordinates to viewport coordinates Returns viewY (in viewport), viewH (visible height), contentOffset (rows clipped from top) visible=false if entirely outside viewport

func (*ViewportScroll) End

func (v *ViewportScroll) End()

End scrolls to bottom

func (*ViewportScroll) EnsureRange

func (v *ViewportScroll) EnsureRange(y, h int)

EnsureRange scrolls the least distance that brings a content row range into view; a range taller than the viewport is top-aligned

func (*ViewportScroll) Home

func (v *ViewportScroll) Home()

Home scrolls to top

func (*ViewportScroll) IsVisible

func (v *ViewportScroll) IsVisible(y, h int) bool

IsVisible returns true if content row range intersects viewport

func (*ViewportScroll) MaxOffset

func (v *ViewportScroll) MaxOffset() int

MaxOffset returns maximum valid scroll offset

func (*ViewportScroll) PageDown

func (v *ViewportScroll) PageDown()

PageDown scrolls down by viewport height

func (*ViewportScroll) PageUp

func (v *ViewportScroll) PageUp()

PageUp scrolls up by viewport height

func (*ViewportScroll) ScrollBy

func (v *ViewportScroll) ScrollBy(delta int)

ScrollBy adjusts offset by delta

func (*ViewportScroll) ScrollTo

func (v *ViewportScroll) ScrollTo(pos int)

ScrollTo sets absolute offset

func (*ViewportScroll) SetDimensions

func (v *ViewportScroll) SetDimensions(contentH, viewportH int)

SetDimensions updates content and viewport heights, clamps offset

type Wires added in v0.2.1

type Wires struct {
	W    int
	Arms []uint8
}

Wires are lines on a grid, each cell holding the arms that meet there: up 1, right 2, down 4, left 8. Wherever lines branch or cross, the cell draws the junction, whatever order they were laid in.

func NewWires added in v0.2.1

func NewWires(w, h int) Wires

NewWires creates an empty grid w by h

func (Wires) H added in v0.2.1

func (g Wires) H(y, x0, x1 int)

H lays a wire along row y between columns x0 and x1

func (Wires) V added in v0.2.1

func (g Wires) V(x, y0, y1 int)

V lays a wire down column x between rows y0 and y1

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL