tui

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package tui is a minimal, dependency-free terminal UI toolkit: screen lifecycle, keyboard decoding, styling, and a couple of widgets. It uses only the standard library plus golang.org/x/term. The dashboard is built on top of it so terminal plumbing lives in exactly one place.

Index

Constants

This section is empty.

Variables

View Source
var ColorEnabled = true

ColorEnabled gates all SGR styling. Set false for dumb terminals / NO_COLOR.

Functions

func Bar added in v0.2.0

func Bar(pct float64, width int) string

Bar renders a "[████····]" usage bar of the given inner width, coloured by threshold (see ThreshColor). pct is clamped to 0..100. It is a generic widget: callers that need non-threshold colouring compose their own.

func Blue

func Blue(s string) string

func Bold

func Bold(s string) string

func Box

func Box(title string, content []string, width, innerHeight int) []string

Box frames content in a titled border. It always returns exactly innerHeight+2 lines, each exactly width columns wide (by visible width). Content is padded/truncated to innerHeight rows and to the inner width using visible-width math, so embedded colour/reverse codes keep their alignment.

func ClampAll added in v0.1.2

func ClampAll(lines []string, w, h int) []string

ClampAll caps lines to at most h rows and clamps each to w visible columns.

func ClampLine

func ClampLine(s string, width int) string

ClampLine ensures a possibly-styled line never exceeds width visible columns, preserving escape sequences and closing colour at the cut.

func ColumnCount added in v0.2.0

func ColumnCount(width, minColWidth, gap, max int) int

ColumnCount picks how many columns of content to lay out for a terminal of the given width, given the minimum usable width of one column. It never returns more than max, and always at least 1. This centralises the responsive breakpoint decision so views share one rule.

func Columns added in v0.2.0

func Columns(blocks [][]string, gap int) []string

Columns places blocks side by side, each padded to its own widest visible line, separated by gap spaces. It generalises Join to any number of blocks and is the building block for responsive multi-column layouts. Blocks may differ in line count; the last column is not right-padded.

func ColumnsDivided added in v0.2.0

func ColumnsDivided(cols [][]string, colWidth int, divider string) []string

ColumnsDivided lays column blocks across a fixed total width by padding every column to colWidth and joining them with divider (e.g. a dim vertical bar), so the columns fill the available width and are visually separated. Shorter columns are padded with blank cells, keeping the divider continuous top to bottom. Use this (over Columns) when you want equal, width-filling columns.

func Cyan

func Cyan(s string) string

func Dim

func Dim(s string) string

func FirstLine added in v0.1.2

func FirstLine(s string) string

FirstLine returns s up to the first newline (the whole string when there is none) — for collapsing multi-line errors onto one row.

func Gauge added in v0.2.0

func Gauge(label string, pct float64, width int, suffix string) string

Gauge renders "LABEL [bar] NN% suffix" — a labelled, threshold-coloured usage bar. width is the inner bar width.

func Green

func Green(s string) string

func HSlice

func HSlice(s string, hoff int) string

HSlice drops the first hoff visible columns of a plain string (for horizontal scrolling). Input must be plain text (no SGR).

func HumanBytes added in v0.2.0

func HumanBytes(b float64) string

HumanBytes formats a byte count with a binary (1024) unit suffix.

func HumanDuration added in v0.2.0

func HumanDuration(sec float64) string

HumanDuration formats a number of seconds as "Nd Nh Nm" (dropping the day field under 24h).

func Join

func Join(left, right []string, gap int) []string

Join places two blocks side by side: the left block is padded to its widest line, then a gap, then the right block. Handles differing line counts and preserves any styling in the left block (visible-width padding).

func Magenta

func Magenta(s string) string

func Pad

func Pad(s string, width int) string

Pad left-aligns a plain string into exactly width columns.

func PadLeft

func PadLeft(s string, width int) string

PadLeft right-aligns a plain string into exactly width columns (for numbers).

func PadVisible

func PadVisible(s string, width int) string

PadVisible pads a possibly-styled string to exactly width visible columns, preserving SGR sequences. Truncates (with ClampLine) when too long.

func Red

func Red(s string) string

Foreground colours and attributes.

func RenderHelp added in v0.2.0

func RenderHelp(sections []HelpSection) []string

RenderHelp renders help sections as aligned "key description" rows beneath dim section titles — the body of a full-screen help overlay. Keys are padded to a common width across all sections so the descriptions line up.

func Reverse

func Reverse(s string) string

func SetColorMode added in v0.1.2

func SetColorMode(mode string)

SetColorMode sets ColorEnabled from an explicit mode ("always"/"never"); for anything else it auto-detects from NO_COLOR, TERM, and whether stdout is a terminal. Terminal-capability detection lives here so callers don't repeat it.

func SparkCells added in v0.2.0

func SparkCells(v []float64) string

SparkCells renders each value (0..100) as a block character coloured by its own threshold — for per-entity levels (e.g. per-core CPU) where each cell's colour should reflect that cell, unlike Sparkline which colours the whole run by the latest value.

func Sparkline added in v0.2.0

func Sparkline(v []float64, width int) string

Sparkline renders values (each 0..100) as a compact block-character trend, coloured by the latest value. Returns a dim placeholder when empty. Only the most recent width values are shown.

func StripSGR

func StripSGR(s string) string

StripSGR removes ANSI escape sequences, leaving plain text.

func TabBar

func TabBar(tabs []string, active, width int) string

TabBar renders a single-line tab selector, highlighting the active tab.

func ThreshColor added in v0.1.2

func ThreshColor(s string, pct float64) string

ThreshColor colours s by a 0–100 utilisation percentage: >=90 red, >=70 yellow, else green. The single source for gauge/stat colour thresholds.

func Truncate

func Truncate(s string, max int) string

Truncate trims a plain (no-SGR) string to max visible runes, adding an ellipsis when it has to cut.

func VisibleWidth

func VisibleWidth(s string) int

VisibleWidth returns the display width of s, ignoring SGR escape sequences.

func Yellow

func Yellow(s string) string

Types

type Event

type Event struct {
	Type EventType
	Key  Key
	Rune rune
}

Event is a decoded input event.

func Decode

func Decode(b []byte) (Event, int)

Decode decodes the first event from b and returns the bytes consumed (>=1 when b is non-empty). Exported for unit testing.

type EventType

type EventType int

EventType classifies a loop event.

const (
	EventKey EventType = iota
	EventQuit
)

type HelpSection added in v0.2.0

type HelpSection struct {
	Title string
	Keys  [][2]string // each entry is {key, description}
}

HelpSection is a titled group of key bindings for a help overlay.

type Key

type Key int

Key names non-rune keys.

const (
	KeyRune Key = iota
	KeyUp
	KeyDown
	KeyLeft
	KeyRight
	KeyTab
	KeyShiftTab
	KeyEnter
	KeyEsc
	KeyBackspace
	KeyPgUp
	KeyPgDn
	KeyHome
	KeyEnd
	KeyCtrlD
	KeyCtrlU
)

type List

type List struct {
	Header   string // optional column header (not selectable)
	Rows     []string
	Selected int
	// contains filtered or unexported fields
}

List is a selectable set of pre-formatted plain-text rows with a moving cursor. The caller formats row columns; List handles selection highlight and keeping the cursor visible. For non-selectable scrolling use Pager.

func (*List) Bottom

func (l *List) Bottom()

func (*List) Move

func (l *List) Move(d int)

Move shifts the selection by d (negative = up).

func (*List) Render

func (l *List) Render(width, height int) []string

Render returns at most height lines (including any header) each clamped to width, with the current row shown in reverse video.

func (*List) SetRows

func (l *List) SetRows(rows []string)

SetRows replaces the rows, keeping the selection in range.

func (*List) Top

func (l *List) Top()

Top/Bottom jump the selection to the ends.

type Pager added in v0.1.2

type Pager struct {
	Rows []string
	// contains filtered or unexported fields
}

Pager is a scrollable, non-selectable view of pre-formatted rows — used for overlays like the detail/logs view. The scroll offset is authoritative (no hidden cursor); its upper bound is clamped lazily in Window/Render so callers may ScrollBottom/ScrollTo freely.

func (*Pager) Len added in v0.1.2

func (p *Pager) Len() int

func (*Pager) Offset added in v0.1.2

func (p *Pager) Offset() int

Offset/Len expose scroll state for callers that render rows themselves (e.g. a pager that adds search highlighting and horizontal scrolling).

func (*Pager) Render added in v0.1.2

func (p *Pager) Render(width, height int) []string

Render returns the visible rows for the given viewport, each padded to width.

func (*Pager) ScrollBottom added in v0.1.2

func (p *Pager) ScrollBottom()

func (*Pager) ScrollBy added in v0.1.2

func (p *Pager) ScrollBy(d int)

ScrollBy shifts the viewport by d rows (negative = up); the lower bound is clamped here, the upper bound in Window.

func (*Pager) ScrollTo added in v0.1.2

func (p *Pager) ScrollTo(i int)

func (*Pager) ScrollTop added in v0.1.2

func (p *Pager) ScrollTop()

func (*Pager) Window added in v0.1.2

func (p *Pager) Window(height int) (start, end int)

Window clamps the offset for the given viewport height and returns the [start,end) range of rows that should be displayed.

type Reader

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

Reader decodes terminal input into Events. In raw mode an escape sequence is usually delivered in a single Read, which this relies on; any leftover bytes are buffered for the next call.

func NewReader

func NewReader(in *os.File) *Reader

NewReader builds a Reader over the given file (normally os.Stdin).

func (*Reader) ReadEvent

func (r *Reader) ReadEvent() (Event, error)

ReadEvent blocks until one event can be decoded.

type Screen

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

Screen owns the terminal lifecycle: alternate screen buffer, raw mode, cursor visibility, size queries, and idempotent restoration. Using the alternate buffer means the dashboard never pollutes scrollback and the user's prior content + scroll position are restored on exit.

func NewScreen

func NewScreen() (*Screen, error)

NewScreen enters the alternate screen, hides the cursor, and puts the terminal into raw mode. Call Close (deferred) to restore.

func (*Screen) Close

func (s *Screen) Close()

Close restores the terminal. Safe to call more than once.

func (*Screen) Draw

func (s *Screen) Draw(lines []string)

Draw paints a frame given as already-laid-out lines. It homes the cursor, erases each line's tail, then erases anything below the last line so a shorter frame leaves no residue. No full clear -> no flicker.

func (*Screen) Size

func (s *Screen) Size() (w, h int)

Size returns the current terminal dimensions, freshly queried so resizes are always picked up. Falls back to 80x24 if the query fails.

Jump to

Keyboard shortcuts

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