tui

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 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.

Documentation

Overview

Package tui builds full-screen terminal applications from widgets: lists and tables that filter as you type, text fields and editors, switches, radio buttons and check lists, dialogs and menus, panels, tabs and pages, a key legend and a help screen, and a status bar.

Where package pick asks one question in the lines below the cursor, a tui application takes the whole screen until it quits, the way lazygit, k9s or htop do.

Applications

An App shows a tree of widgets: New takes its root, App.Run takes the terminal over (raw mode, the alternate screen, bracketed paste, the mouse with WithMouse) and puts it back however the run ends, also on a panic or a signal. Every change is drawn into a grid of cells and only the cells that changed are written.

list := tui.NewList(func(t Ticket) []tui.Span { ... }).SetColumns(...)
list.OnSelect = open
root := tui.VBox(tui.Grow(tui.NewPanel("Tickets", list)), tui.Fit(tui.NewLegend()))
app := tui.New(root)
app.Keymap().Bind("quit", app.Quit, "q")
if err := app.Run(); errors.Is(err, tui.ErrNotATerminal) { ... }

The application and its widgets belong to the goroutine that runs it. Work that blocks, such as a request to an API, runs through App.Go, which hands its result back to that goroutine; App.Busy shows a spinner meanwhile and App.Notify a message afterwards.

Widgets

A Widget draws itself into a Canvas. What else it does it says by the interfaces it implements: Focusable takes the focus and keys, Container holds other widgets, Bindings has keys of its own, Paster takes pasted text, Clicker takes the mouse and Sizer tells layouts its size. Any type can be a widget; the ones here are building blocks:

Keys

A key goes first to the widget with the focus, then up the tree to the widgets around it, and last to the application's Keymap. A widget that takes text, such as a field, or a list while its filter is open, gets characters before any binding, so typing "q" into a field does not quit. Tab and Shift-Tab move the focus, Esc closes the topmost layer, Ctrl-C quits and "?" or F1 shows every binding that applies.

The widgets know the keys other terminal programs taught their users:

↑ ↓  k j            move                      vim, less, lazygit, k9s
g G  home end       first, last               vim, less
ctrl+u ctrl+d       half a page               vim, less
pgup pgdown         page                      everywhere
/   n N             filter or search, matches vim, less, k9s
enter               open, choose              everywhere
space               mark, toggle              lazygit, mutt, ranger
esc                 back, cancel, clear       everywhere
tab shift+tab       next, previous field      forms, lazygit panes
?   f1              help                      lazygit, k9s, htop
ctrl+a ctrl+e ...   line editing              readline, emacs

The Legend shows the bindings of the focused widget first and those around it after, cut to the width of the screen; bindings marked Hidden show only in the help.

Text

Text drawn with a Canvas is made safe there: control characters and escape sequences are left out, so text from a server cannot move the cursor or recolor the screen. Widgets that take text from elsewhere (labels, list cells, titles) also fold it onto one line or wrap it. Colors are styles of package theme, given with each Span; Theme holds the styles of the widgets, derived from the active theme of package theme.

Tests

Headless runs an application without a terminal: keys go in, the screen comes out as text. Applications built from the package can test their screens the same way the package tests its widgets.

Platforms

On Unix, a resize is picked up at once (SIGWINCH), Ctrl-Z can hand the terminal to the shell (App.Suspend), and the read that waits for keys is ended when the application quits. On Windows the size is polled, Ctrl-Break and closing the console put the terminal back before the process ends with status 1, there is no suspend, and the read waits for one more key before it ends; that key is dropped.

Example

A table of tickets with a filter and a legend, driven by keys in a headless run.

package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/tui"
)

func main() {
	type ticket struct{ id, title string }
	list := tui.NewList(func(t ticket) []tui.Span {
		return []tui.Span{{Text: t.id}, {Text: t.title}}
	}).SetColumns(tui.Column{Title: "ID"}, tui.Column{Title: "TITLE", Grow: 1})
	list.SetItems([]ticket{
		{"m-1", "Mail bounces"},
		{"m-2", "Backup restore"},
		{"m-3", "Mail quota"},
	})
	opened := ""
	list.OnSelect = func(t ticket) { opened = t.id }

	app := tui.New(tui.VBox(tui.Grow(list), tui.Fit(tui.NewLegend())))
	app.Keymap().Bind("quit", app.Quit, "q")

	// app.Run() would take the terminal; a headless run draws into memory.
	h := tui.NewHeadless(app, 40, 6)
	h.Press("/")
	h.Type("mail")
	h.Press("enter", "j", "enter")
	fmt.Println(h.Screen())
	fmt.Println("opened", opened)
}
Output:
  ID  TITLE
  m-1 Mail bounces
  m-3 Mail quota

/mail
↑/k move  ⏎ open  space mark  ? more
opened m-3

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	BorderRounded = Border{"╭", "─", "╮", "│", "│", "╰", "─", "╯"}
	BorderSingle  = Border{"┌", "─", "┐", "│", "│", "└", "─", "┘"}
	BorderDouble  = Border{"╔", "═", "╗", "║", "║", "╚", "═", "╝"}
	BorderThick   = Border{"┏", "━", "┓", "┃", "┃", "┗", "━", "┛"}
	BorderASCII   = Border{"+", "-", "+", "|", "|", "+", "-", "+"}
)

The borders a box can have.

View Source
var ErrInputClosed = errors.New("tui: input closed")

ErrInputClosed is what App.Run returns when the terminal went away before the application quit.

View Source
var ErrNotATerminal = errors.New("tui: not a terminal")

ErrNotATerminal is what App.Run returns when its input or output is not a terminal.

Functions

func KeyLabel

func KeyLabel(name string) string

KeyLabel is the short form of a key name for the legend: "↑" for "up", "⏎" for "enter", "^s" for "ctrl+s". Names it does not shorten come back as they are.

Types

type Align

type Align int

Align is the horizontal alignment of text.

const (
	AlignLeft Align = iota
	AlignCenter
	AlignRight
)

Alignments.

type App

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

App runs a full-screen application: it takes the terminal over, draws the widget tree for every change and hands keys, pastes and the mouse to the widgets.

Everything about the application, its widgets included, belongs to the goroutine that runs it. Work that blocks, such as a request, goes through App.Go; other goroutines reach the application through App.Post.

func New

func New(root Widget, opts ...Option) *App

New returns an application that shows root.

func (*App) ActiveBindings

func (a *App) ActiveBindings() []*Binding

ActiveBindings returns the bindings that apply now, the focused widget's first, each key once: what the legend shows. While a text field has the focus, the bindings of its parents to plain characters are left out, since the field takes those keys.

func (*App) Busy

func (a *App) Busy(text string) (done func())

Busy shows text with a spinner in the status bar until the function it returns is called: around work started with Go.

func (*App) Choose

func (a *App) Choose(title string, options []string, selected int, onChoose func(i int))

Choose shows options in a layer to pick one from, filtering as you type after "/". onChoose is called with the index of the option picked.

func (*App) Close

func (a *App) Close(w Widget)

Close closes the layer showing w, and the layers above it.

func (*App) Confirm

func (a *App) Confirm(title, message string, onYes func())

Confirm asks a yes/no question in a dialog: Enter on Yes or "y" answers yes, Esc or "n" no. onYes is called for yes, nothing for no.

func (*App) EditText

func (a *App) EditText(title, value string, onSave func(text string)) *TextArea

EditText edits text of several lines in a dialog: Ctrl-S saves, Esc cancels. onSave is called with the text.

func (*App) Focus

func (a *App) Focus(w Focusable)

Focus gives the focus to w, which must be part of the topmost layer.

func (*App) FocusNext

func (a *App) FocusNext(delta int)

FocusNext moves the focus to the next focusable widget of the topmost layer, by delta steps: 1 forward, -1 back.

func (*App) Focused

func (a *App) Focused() Focusable

Focused returns the widget with the focus, nil if none can take it.

func (*App) Go

func (a *App) Go(work func() func())

Go runs work on a goroutine of its own and the function it returns back on the application's goroutine, where it may change widgets:

app.Go(func() func() {
	tickets, err := client.List(ctx, query) // blocks
	return func() { list.SetItems(tickets); ... }
})

A panic in work is raised again on the application's goroutine, where Run puts the terminal back before the program ends.

func (*App) HandleKey

func (a *App) HandleKey(k Key) bool

HandleKey hands k to the widgets as a key typed: the bindings on the focus path from the focused widget up, the focused widget, Tab and Esc of the layer, and the application's bindings. It reports whether anything took the key.

func (*App) Keymap

func (a *App) Keymap() *Keymap

Keymap returns the bindings of the whole application. They apply when no widget on the focus path took the key, and not while a layer is pushed. Ctrl-C quits and "?" shows the help unless WithoutHelp was given.

func (*App) Layers

func (a *App) Layers() int

Layers reports how many layers are pushed over the root widget.

func (*App) Menu

func (a *App) Menu(title string, items []MenuItem)

Menu shows actions to pick one from, as a context menu: ↑/↓ and Enter, or the key of an item. The menu closes before the action runs.

func (*App) Notify

func (a *App) Notify(level Level, text string)

Notify shows text in the status bar for a few seconds.

func (*App) Notifyf

func (a *App) Notifyf(level Level, format string, args ...any)

Notifyf is Notify with a format.

func (*App) Pop

func (a *App) Pop()

Pop closes the topmost layer. The root widget is never closed.

func (*App) Post

func (a *App) Post(fn func())

Post runs fn on the application's goroutine. It may be called from any goroutine; fn may change widgets, and the screen is redrawn after it.

func (*App) Prompt

func (a *App) Prompt(title, label, value string, onSubmit func(text string)) *Input

Prompt asks for a line of text in a dialog. Enter submits it, Esc cancels. onSubmit is called with the text.

func (*App) Push

func (a *App) Push(w Widget, opts LayerOptions)

Push shows w over everything else, until Esc or Pop closes it. Keys go to the layer only.

func (*App) Quit

func (a *App) Quit()

Quit ends Run once the current event is handled.

func (*App) QuitWith

func (a *App) QuitWith(err error)

QuitWith ends Run, which then returns err.

func (*App) Root

func (a *App) Root() Widget

Root returns the widget the application shows.

func (*App) Run

func (a *App) Run() error

Run takes the terminal over and runs the application until Quit, and puts the terminal back as it found it before returning, also on a panic and on a signal that ends the process. It returns ErrNotATerminal where input or output is not a terminal.

func (*App) SetRoot

func (a *App) SetRoot(w Widget)

SetRoot shows w instead of the root widget, with the focus on its first focusable widget.

func (*App) ShowHelp

func (a *App) ShowHelp()

ShowHelp shows every binding that applies now, grouped, in a layer.

func (*App) Size

func (a *App) Size() (width, height int)

Size is the size of the screen in cells.

func (*App) Status

func (a *App) Status() (notice *Notice, busy string)

Status returns the notice to show now, if any, and what the application is busy with, with a spinner frame for it: what a StatusBar draws.

func (*App) Suspend

func (a *App) Suspend()

Suspend hands the terminal back to the shell, as Ctrl-Z does in other programs, and takes it again once the shell continues the program. It does nothing where the system has no job control.

func (*App) Theme

func (a *App) Theme() Theme

Theme returns the styles the widgets draw with.

type Binding

type Binding struct {
	// Keys are the names of the keys, as [Key.String] names them: "j",
	// "down", "ctrl+s", "shift+tab", "?".
	Keys []string
	// Help says what the keys do, in a word or two: "open", "move".
	Help string
	// Group is the heading the binding is listed under in the help.
	Group string
	// Hidden keeps the binding out of the legend; the help still lists it.
	Hidden bool
	// Enabled, when set, reports whether the binding applies now. A binding
	// that does not apply neither takes its keys nor shows.
	Enabled func() bool
	// Action is what the keys do.
	Action func()
}

Binding binds keys to an action.

func (*Binding) Hide

func (b *Binding) Hide() *Binding

Hide keeps the binding out of the legend and returns it.

func (*Binding) InGroup

func (b *Binding) InGroup(group string) *Binding

InGroup sets the heading of the binding in the help and returns it.

func (*Binding) Label

func (b *Binding) Label() string

Label is how the legend shows the keys: the short forms of the first two, joined by "/".

func (*Binding) When

func (b *Binding) When(enabled func() bool) *Binding

When makes the binding apply only while enabled reports true, and returns it.

type Bindings

type Bindings interface {
	Keymap() *Keymap
}

Bindings is a widget with keys of its own. The keymap is asked while the widget or one inside it has the focus, before the widget's HandleKey, and its bindings show in the legend.

type Border

type Border struct {
	TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight string
}

Border is the set of characters a box is drawn with.

type Box

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

Box lays its children out in a column, one below the other, or in a row, side by side.

func HBox

func HBox(items ...Item) *Box

HBox returns a box that puts its children side by side from left to right.

func VBox

func VBox(items ...Item) *Box

VBox returns a box that stacks its children from top to bottom.

func (*Box) Add

func (b *Box) Add(items ...Item)

Add appends children.

func (*Box) Children

func (b *Box) Children() []Widget

Children returns the children shown.

func (*Box) Draw

func (b *Box) Draw(c Canvas)

Draw draws the children.

func (*Box) Gap

func (b *Box) Gap(n int) *Box

Gap sets the number of blank cells between children and returns the box.

func (*Box) Hidden

func (b *Box) Hidden(w Widget) bool

Hidden reports whether a child is hidden.

func (*Box) SetHidden

func (b *Box) SetHidden(w Widget, hidden bool)

SetHidden hides a child, or shows it again: a hidden child takes no room, is not drawn and cannot have the focus.

func (*Box) Size

func (b *Box) Size(width, height int) (int, int)

Size is the sum of the children along the axis of the box and the largest of them across it.

type Button

type Button struct {

	// OnPress is called when the button is pressed.
	OnPress func()
	// contains filtered or unexported fields
}

Button does something when pressed with Enter, Space or a click.

func NewButton

func NewButton(label string, onPress func()) *Button

NewButton returns a button.

func (*Button) CanFocus

func (b *Button) CanFocus() bool

CanFocus reports whether the button is enabled.

func (*Button) Draw

func (b *Button) Draw(c Canvas)

Draw draws the button.

func (*Button) HandleKey

func (b *Button) HandleKey(Key) bool

HandleKey takes no other keys.

func (*Button) HandleMouse

func (b *Button) HandleMouse(m Mouse) bool

HandleMouse presses the button on a click.

func (*Button) Keymap

func (b *Button) Keymap() *Keymap

Keymap returns the keys of the button.

func (*Button) Press

func (b *Button) Press()

Press calls OnPress.

func (*Button) SetDisabled

func (b *Button) SetDisabled(disabled bool) *Button

SetDisabled keeps the button from taking the focus.

func (*Button) SetLabel

func (b *Button) SetLabel(label string)

SetLabel sets the label.

func (*Button) Size

func (b *Button) Size(width, _ int) (int, int)

Size is the width of the label and its brackets, and one line.

type Canvas

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

Canvas is a rectangle of the screen a widget draws into. Drawing outside it is clipped. Coordinates are relative to its top left corner.

func (Canvas) App

func (c Canvas) App() *App

App is the application the canvas belongs to.

func (Canvas) Box

func (c Canvas) Box(border Border, style theme.Style, title, footer Line) Canvas

Box draws border around the canvas in style, with title on its top edge and footer on its bottom edge, right-aligned, and returns the canvas inside it.

func (Canvas) Draw

func (c Canvas) Draw(w Widget)

Draw draws w into the canvas and remembers where, for the mouse.

func (Canvas) Fill

func (c Canvas) Fill(style theme.Style)

Fill paints every cell of the canvas blank in style.

func (Canvas) FillRow

func (c Canvas) FillRow(x, y int, style theme.Style)

FillRow paints row y blank in style, from x to the right edge.

func (Canvas) Focused

func (c Canvas) Focused(w Widget) bool

Focused reports whether w has the focus.

func (Canvas) HasFocus

func (c Canvas) HasFocus(w Widget) bool

HasFocus reports whether w or a widget inside it has the focus.

func (Canvas) Height

func (c Canvas) Height() int

Height is how many rows high the canvas is.

func (Canvas) Line

func (c Canvas) Line(x, y int, l Line) int

Line draws a line at x, y and returns how many cells it took.

func (Canvas) ShowCursor

func (c Canvas) ShowCursor(x, y int)

ShowCursor puts the terminal's cursor at x, y of the canvas, where a text field wants it. The cursor is hidden in every frame that does not ask for it.

func (Canvas) Sub

func (c Canvas) Sub(x, y, w, h int) Canvas

Sub returns the part of c at x, y of size w×h, clipped to c.

func (Canvas) Text

func (c Canvas) Text(x, y int, s string, style theme.Style) int

Text draws s at x, y in style and returns how many cells it took. It is clipped at the right edge of the canvas; control characters are left out.

func (Canvas) Theme

func (c Canvas) Theme() Theme

Theme is the theme to draw with.

func (Canvas) VScrollbar

func (c Canvas) VScrollbar(x, offset, height, total int)

VScrollbar draws a scroll bar into the column x of the canvas, for a view of height rows starting at offset of total rows. Nothing is drawn when everything fits.

func (Canvas) Width

func (c Canvas) Width() int

Width is how many cells wide the canvas is.

func (Canvas) WithStyle

func (c Canvas) WithStyle(base theme.Style) Canvas

WithStyle returns c with base as the style everything drawn in it starts from: spans drawn into it add their own style on top.

type CheckList

type CheckList struct {

	// OnChange is called with the index of the option checked or
	// unchecked; with -1 after "a" and "n".
	OnChange func(i int)
	// contains filtered or unexported fields
}

CheckList chooses any number of several options, as checkboxes. Space or Enter checks the option under the cursor, "a" checks all, "n" none.

func NewCheckList

func NewCheckList(options []string) *CheckList

NewCheckList returns a check list with nothing checked.

func (*CheckList) CanFocus

func (l *CheckList) CanFocus() bool

CanFocus reports whether the list is enabled.

func (*CheckList) Checked

func (l *CheckList) Checked() []bool

Checked reports which options are checked.

func (*CheckList) Draw

func (l *CheckList) Draw(c Canvas)

Draw draws the options.

func (*CheckList) HandleKey

func (l *CheckList) HandleKey(Key) bool

HandleKey takes no other keys.

func (*CheckList) HandleMouse

func (l *CheckList) HandleMouse(m Mouse) bool

HandleMouse checks the option clicked.

func (*CheckList) Keymap

func (l *CheckList) Keymap() *Keymap

Keymap returns the keys of the list.

func (*CheckList) SetChecked

func (l *CheckList) SetChecked(i int, on bool)

SetChecked checks or unchecks the option of index i without calling OnChange.

func (*CheckList) SetDisabled

func (l *CheckList) SetDisabled(disabled bool) *CheckList

SetDisabled keeps the list from taking the focus.

func (*CheckList) SetHorizontal

func (l *CheckList) SetHorizontal(h bool) *CheckList

SetHorizontal lays the options out in a row.

func (*CheckList) Size

func (l *CheckList) Size(width, height int) (int, int)

Size is the options laid out.

func (*CheckList) Toggle

func (l *CheckList) Toggle(i int)

Toggle checks or unchecks the option of index i and calls OnChange.

func (*CheckList) Values

func (l *CheckList) Values() []string

Values returns the options checked.

type Clicker

type Clicker interface {
	HandleMouse(m Mouse) bool
}

Clicker is a widget that takes mouse events in the rectangle it was drawn into. X and Y of the event are relative to that rectangle.

type Column

type Column struct {
	// Title is the header of the column.
	Title string
	// Width is the width of the column in cells. Zero sizes the column to
	// its widest cell among the rows, unless Grow is set.
	Width int
	// Grow makes the column share the room the other columns leave, by
	// weight, like [GrowBy].
	Grow int
	// Min is the narrowest the column gets when room is short.
	Min int
	// Align aligns the cells.
	Align Align
}

Column is a column of a list shown as a table.

type Container

type Container interface {
	Widget
	Children() []Widget
}

Container is a widget that holds others. Children returns the ones shown now, in the order the focus moves through them.

type Dialog

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

Dialog is a box with a title around a body and a row of buttons, for a layer pushed with App.Push.

func NewDialog

func NewDialog(title string, body Widget, buttons ...*Button) *Dialog

NewDialog returns a dialog.

func (*Dialog) Children

func (d *Dialog) Children() []Widget

Children returns the body and the buttons.

func (*Dialog) Draw

func (d *Dialog) Draw(c Canvas)

Draw draws the box, the body and the buttons, right-aligned.

func (*Dialog) SetFooter

func (d *Dialog) SetFooter(s string) *Dialog

SetFooter sets the muted text on the bottom edge, such as the keys.

func (*Dialog) SetWidth

func (d *Dialog) SetWidth(w int) *Dialog

SetWidth sets the width of the dialog in cells, where the body would otherwise decide.

func (*Dialog) Size

func (d *Dialog) Size(width, height int) (int, int)

Size is the body, the buttons and the box.

type Focusable

type Focusable interface {
	Widget
	// CanFocus reports whether the widget takes the focus now: a disabled
	// field does not.
	CanFocus() bool
	// HandleKey is given a key the bindings of the widget did not take, and
	// reports whether it used it. A text field takes the characters typed
	// into it this way.
	HandleKey(k Key) bool
}

Focusable is a widget that can take the focus. Tab and Shift-Tab move the focus between the focusable widgets of a screen in the order a walk of the widget tree finds them.

type Focuser

type Focuser interface {
	FocusChanged(focused bool)
}

Focuser is a widget that wants to know when it gains or loses the focus.

type Form

type Form struct {

	// OnSubmit is called on Ctrl-S, and by a button that calls Submit,
	// when no field reports an error.
	OnSubmit func()
	// contains filtered or unexported fields
}

Form lays fields out under each other, each with its label in a column on the left and, for a field whose Err reports an error, the error under it. Tab and Shift-Tab move between the fields, Ctrl-S submits.

Example

A form in a dialog, with a field that must not stay empty.

package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/tui"
)

func main() {
	name := tui.NewInput()
	name.Validate = func(s string) error {
		if s == "" {
			return fmt.Errorf("a name is required")
		}
		return nil
	}
	name.SetValue("")
	notify := tui.NewSwitch("by email", true)
	form := tui.NewForm().Add("Name", name).Add("Notify", notify)
	form.OnSubmit = func() { fmt.Println("saved", name.Value(), notify.Value()) }

	h := tui.NewHeadless(tui.New(form), 30, 4)
	fmt.Println(h.Screen())
	h.Type("Ada")
	h.Press("tab", "space", "ctrl+s")
}
Output:
  Name
        a name is required

Notify  by email  ON
saved Ada false

func NewForm

func NewForm() *Form

NewForm returns an empty form.

func (*Form) Add

func (f *Form) Add(label string, w Widget) *Form

Add adds a field with its label.

func (*Form) AddButtons

func (f *Form) AddButtons(buttons ...*Button) *Form

AddButtons adds buttons in a row at the bottom.

func (*Form) AddHint

func (f *Form) AddHint(label string, w Widget, hint string) *Form

AddHint adds a field with its label and a muted line under it that says what it takes.

func (*Form) Children

func (f *Form) Children() []Widget

Children returns the fields and the buttons.

func (*Form) Draw

func (f *Form) Draw(c Canvas)

Draw draws the fields, their labels, errors and hints, and the buttons.

func (*Form) Err

func (f *Form) Err() error

Err returns the first error a field reports, nil when there is none.

func (*Form) Keymap

func (f *Form) Keymap() *Keymap

Keymap returns the keys of the form.

func (*Form) Size

func (f *Form) Size(width, height int) (int, int)

Size is the fields with their labels, a blank line between them, and the buttons.

func (*Form) Submit

func (f *Form) Submit()

Submit calls OnSubmit unless a field reports an error.

type Headless

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

Headless runs an application without a terminal, one step at a time, for tests: keys go in, and the screen comes out as text.

h := tui.NewHeadless(app, 80, 24)
h.Type("versand")
h.Press("enter")
if !strings.Contains(h.Screen(), "m-5705118") { ... }

func NewHeadless

func NewHeadless(app *App, width, height int) *Headless

NewHeadless returns a headless run of app on a screen of width×height cells, drawn once.

func (*Headless) Click

func (h *Headless) Click(x, y int)

Click clicks the left button at x, y.

func (*Headless) Cursor

func (h *Headless) Cursor() (x, y int)

Cursor returns where the terminal's cursor is, -1, -1 where it is hidden.

func (*Headless) Draw

func (h *Headless) Draw()

Draw draws a frame, after the application was changed from outside a key, such as by pushing a layer.

func (*Headless) Feed

func (h *Headless) Feed(data string)

Feed hands raw bytes to the application as the terminal would send them, escape sequences included.

func (*Headless) Lines

func (h *Headless) Lines() []string

Lines returns the rows of the screen as text, trailing spaces cut.

func (*Headless) Paste

func (h *Headless) Paste(text string)

Paste pastes text in one piece.

func (*Headless) Press

func (h *Headless) Press(keys ...string)

Press presses keys, named as ParseKey reads them, one after the other. It panics on a name ParseKey does not know, since that is a mistake in the test.

func (*Headless) Quit

func (h *Headless) Quit() (bool, error)

Quit reports whether the application asked to quit, and with what error.

func (*Headless) Resize

func (h *Headless) Resize(width, height int)

Resize changes the size of the screen.

func (*Headless) Screen

func (h *Headless) Screen() string

Screen returns the screen as text, rows joined by "\n", trailing blank rows cut.

func (*Headless) Settle

func (h *Headless) Settle(timeout time.Duration)

Settle waits for the work started with App.Go to end, up to timeout, and runs what it and App.Post handed to the application.

func (*Headless) Type

func (h *Headless) Type(text string)

Type types text, character by character.

func (*Headless) Wheel

func (h *Headless) Wheel(x, y, n int)

Wheel turns the wheel at x, y: up for a negative n, down for a positive one, |n| steps.

type Input

type Input struct {

	// OnChange is called with the text after every change.
	OnChange func(text string)
	// OnSubmit is called with the text when Enter is pressed.
	OnSubmit func(text string)
	// Validate checks the text after every change; the error it returns is
	// what Err reports, and what a Form shows under the field.
	Validate func(text string) error
	// contains filtered or unexported fields
}

Input is a one-line text field. It edits by grapheme cluster, so an emoji or a letter with an accent is one character, and knows the keys of a shell's line editor:

←/→ ctrl+b/f          character left/right
alt+←/→ ctrl+←/→      word left/right (also alt+b/f)
home/end ctrl+a/e     start/end
backspace delete      delete a character (also ctrl+h/d)
ctrl+w alt+backspace  delete the word before the cursor
alt+d                 delete the word after the cursor
ctrl+u ctrl+k         delete to the start/end
ctrl+z ctrl+y         undo/redo
enter                 submit, where OnSubmit is set

With suggestions set, the rest of the first suggestion that starts with what was typed shows after the cursor; → or End at the end of the text takes it, ctrl+n and ctrl+p go through the others.

func NewInput

func NewInput() *Input

NewInput returns an empty text field.

func (*Input) CanFocus

func (in *Input) CanFocus() bool

CanFocus reports whether the field is enabled.

func (*Input) Draw

func (in *Input) Draw(c Canvas)

Draw draws the field across its width.

func (*Input) Err

func (in *Input) Err() error

Err returns what Validate said about the text, nil when it is fine.

func (*Input) HandleKey

func (in *Input) HandleKey(k Key) bool

HandleKey edits the text.

func (*Input) HandleMouse

func (in *Input) HandleMouse(m Mouse) bool

HandleMouse puts the cursor where the field was clicked.

func (*Input) HandlePaste

func (in *Input) HandlePaste(text string) bool

HandlePaste inserts pasted text, its line breaks as spaces.

func (*Input) Keymap

func (in *Input) Keymap() *Keymap

Keymap returns the keys of the field.

func (*Input) SetDisabled

func (in *Input) SetDisabled(disabled bool) *Input

SetDisabled keeps the field from taking the focus.

func (*Input) SetLimit

func (in *Input) SetLimit(n int) *Input

SetLimit sets the most characters the field takes, 0 for no limit.

func (*Input) SetPlaceholder

func (in *Input) SetPlaceholder(s string) *Input

SetPlaceholder sets the text shown, muted, while the field is empty.

func (*Input) SetSecret

func (in *Input) SetSecret(secret bool) *Input

SetSecret shows every character as a bullet, for a password or a token.

func (*Input) SetSuggest

func (in *Input) SetSuggest(fn func(text string) []string) *Input

SetSuggest sets where suggestions for the text come from; nil for none.

func (*Input) SetValue

func (in *Input) SetValue(s string)

SetValue replaces the text and puts the cursor at its end. OnChange is not called.

func (*Input) Size

func (in *Input) Size(width, _ int) (int, int)

Size is the width it is given and one line.

func (*Input) TakesText

func (in *Input) TakesText() bool

TakesText reports that the field takes typed characters.

func (*Input) Value

func (in *Input) Value() string

Value returns the text.

type Item

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

Item is a child of a Box and the way it is sized.

func Fit

func Fit(w Widget) Item

Fit sizes w to what it asks for as a Sizer; a widget that is none gets one row in a column and its text width in a row, or 0.

func Fixed

func Fixed(n int, w Widget) Item

Fixed sizes w to n cells: rows in a column, columns in a row.

func Grow

func Grow(w Widget) Item

Grow sizes w to share the room the other children leave with the other growing children, equally.

func GrowBy

func GrowBy(weight int, w Widget) Item

GrowBy is Grow with a weight: a child of weight 2 gets twice the room of one of weight 1.

type Key

type Key struct {
	Code KeyCode
	// Rune is the character typed, for KeyRune: the letter of Ctrl-S is
	// 's' with ModCtrl.
	Rune rune
	Mod  Mod
}

Key is one keypress.

func ParseKey

func ParseKey(name string) (Key, error)

ParseKey reads a key name as Key.String writes it: "ctrl+s", "alt+x", "shift+tab", "f5", "space", "enter", "a", "+".

func (Key) Printable

func (k Key) Printable() bool

Printable reports whether the key types its rune into a text field: a character without Ctrl or Alt.

func (Key) String

func (k Key) String() string

String names the key the way bindings name it: modifiers first, in the order ctrl, alt, shift, joined by "+", then the key: "ctrl+s", "shift+tab", "alt+enter", "f5", "space", "a", "A", "?".

type KeyCode

type KeyCode int

KeyCode says which key was pressed. A key that types a character is KeyRune, with the character in Key.Rune.

const (
	KeyRune KeyCode = iota
	KeyEnter
	KeyTab
	KeyBackspace
	KeyEscape
	KeyUp
	KeyDown
	KeyLeft
	KeyRight
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyInsert
	KeyDelete
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
)

The keys a terminal reports.

type Keyed

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

Keyed wraps a widget and gives it keys of its own, such as the keys of a screen that apply whichever of its widgets has the focus.

func NewKeyed

func NewKeyed(child Widget) *Keyed

NewKeyed returns child with an empty keymap.

func (*Keyed) Children

func (k *Keyed) Children() []Widget

Children returns the widget inside.

func (*Keyed) Draw

func (k *Keyed) Draw(c Canvas)

Draw draws the widget inside.

func (*Keyed) Keymap

func (k *Keyed) Keymap() *Keymap

Keymap returns the keys.

func (*Keyed) Size

func (k *Keyed) Size(width, height int) (int, int)

Size is the size of the widget inside.

type Keymap

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

Keymap is an ordered set of bindings. The first binding of a key wins.

func NewKeymap

func NewKeymap() *Keymap

NewKeymap returns an empty keymap.

func (*Keymap) Add

func (m *Keymap) Add(bindings ...*Binding)

Add adds bindings to the keymap.

func (*Keymap) Bind

func (m *Keymap) Bind(help string, action func(), keys ...string) *Binding

Bind binds keys to action, with help for the legend, and returns the binding to be refined further:

km.Bind("open", open, "enter")
km.Bind("refresh", reload, "r", "ctrl+r").InGroup("List")

func (*Keymap) Bindings

func (m *Keymap) Bindings() []*Binding

Bindings returns the bindings that apply now, in order.

func (*Keymap) Lookup

func (m *Keymap) Lookup(k Key) *Binding

Lookup returns the binding that applies to k, or nil.

func (*Keymap) Unbind

func (m *Keymap) Unbind(key string)

Unbind removes every binding of key.

type Label

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

Label shows lines of text. It takes no focus.

func NewDynamic

func NewDynamic(fn func() []Line) *Label

NewDynamic returns a label whose lines fn makes for every frame, such as a header with a count.

func NewLabel

func NewLabel(text string, style theme.Style) *Label

NewLabel returns a label of text in one style. The text is made safe to show with term.Plain, so text from elsewhere can be passed as it is.

func NewLines

func NewLines(lines ...Line) *Label

NewLines returns a label of styled lines.

func (*Label) Draw

func (l *Label) Draw(c Canvas)

Draw draws the lines, cut or wrapped to the width.

func (*Label) SetAlign

func (l *Label) SetAlign(a Align) *Label

SetAlign aligns the lines.

func (*Label) SetLines

func (l *Label) SetLines(lines ...Line)

SetLines replaces the lines.

func (*Label) SetText

func (l *Label) SetText(text string, style theme.Style)

SetText replaces the text.

func (*Label) SetWrap

func (l *Label) SetWrap(wrap bool) *Label

SetWrap makes lines wider than the label wrap rather than be cut.

func (*Label) Size

func (l *Label) Size(width, height int) (int, int)

Size is the widest line and the number of lines.

type LayerOptions

type LayerOptions struct {
	// Width and Height are the size of the layer in cells. Zero takes what
	// the widget asks for as a [Sizer], or else two thirds of the screen.
	// The layer is centered and never larger than the screen.
	Width, Height int
	// NoEscape keeps Esc from closing the layer, for a layer that binds Esc
	// itself or must be answered.
	NoEscape bool
	// Focus is the widget that takes the focus, the first one that can
	// when nil.
	Focus Focusable
	// OnClose is called once the layer is closed, however that happens.
	OnClose func()
}

LayerOptions shape a layer pushed with App.Push.

type Legend

type Legend struct{}

Legend shows the keys that apply now and what they do, on one line: the focused widget's first, then those of the widgets around it and of the application. What does not fit is left out, behind "? more" when the help is bound.

func NewLegend

func NewLegend() *Legend

NewLegend returns a legend.

func (*Legend) Draw

func (*Legend) Draw(c Canvas)

Draw draws the keys.

func (*Legend) Size

func (*Legend) Size(width, _ int) (int, int)

Size is one line.

type Level

type Level int

Level is the severity of a notice.

const (
	LevelInfo Level = iota
	LevelSuccess
	LevelWarning
	LevelError
)

The levels of a notice.

type Line

type Line []Span

Line is a line of text made of spans.

func Text

func Text(s string, style theme.Style) Line

Text returns a line of s in one style.

func TruncateLine

func TruncateLine(l Line, width int) Line

TruncateLine cuts a line to width cells, ending it in an ellipsis in the style of the span that was cut.

func WrapLine

func WrapLine(l Line, width int) []Line

WrapLine breaks a line into lines of at most width cells, at spaces where it can and inside a word where the word is wider than a line. Styles carry over to the lines they continue on. A width below 1 is taken as 1.

func WrapText

func WrapText(text string, width int, style theme.Style) []Line

WrapText breaks text, which may hold line breaks, into lines of at most width cells, in one style. The text is made safe to show first with term.Plain, so text from elsewhere can be passed as it is.

func (Line) String

func (l Line) String() string

String is the text of the line without its styles.

func (Line) Width

func (l Line) Width() int

Width is how many cells the line takes up.

type List

type List[T any] struct {

	// OnSelect is called with the item Enter was pressed on.
	OnSelect func(item T)
	// OnCursor is called with the item under the cursor whenever it
	// changes, such as for a preview.
	OnCursor func(item T)
	// OnFilter is called with the filter after every change, for a list
	// whose rows come from a search on a server. Leave Match unset then, so
	// the list does not filter the rows itself as well.
	OnFilter func(filter string)
	// OnEnd is called when the cursor comes within a page of the last row,
	// to load more rows.
	OnEnd func()
	// contains filtered or unexported fields
}

List shows rows to choose from, as a list or as a table with a header, and filters them as you type. It is generic over the type of its items: the cells of a row come from a function of the item.

↑/↓ k/j               move
pgup/pgdown ctrl+b/f  page up/down
ctrl+u/d              half a page up/down
g/G home/end          first/last row
enter                 choose the row (OnSelect)
space                 mark the row, for an action on several
ctrl+a                mark every row shown, or none if all are marked
/                     filter; enter keeps the filter, esc clears it
esc                   clear the filter, else the marks

func NewList

func NewList[T any](cells func(item T) []Span) *List[T]

NewList returns a list whose rows cells makes from its items.

func (*List[T]) AppendItems

func (l *List[T]) AppendItems(items ...T)

AppendItems adds items at the end, as a page loaded after OnEnd. The cursor and the marks stay.

func (*List[T]) CanFocus

func (l *List[T]) CanFocus() bool

CanFocus reports whether the list takes the focus.

func (*List[T]) ClearMarks

func (l *List[T]) ClearMarks()

ClearMarks removes every mark.

func (*List[T]) Cursor

func (l *List[T]) Cursor() int

Cursor returns the index of the row under the cursor among the rows shown.

func (*List[T]) Draw

func (l *List[T]) Draw(c Canvas)

Draw draws the header, the rows in view, the scroll bar and the filter line.

func (*List[T]) Filter

func (l *List[T]) Filter() string

Filter returns the filter.

func (*List[T]) Filtering

func (l *List[T]) Filtering() bool

Filtering reports whether the filter line is open for typing.

func (*List[T]) HandleKey

func (l *List[T]) HandleKey(k Key) bool

HandleKey edits the filter while its line is open.

func (*List[T]) HandleMouse

func (l *List[T]) HandleMouse(m Mouse) bool

HandleMouse moves the cursor to the row clicked, and scrolls with the wheel.

func (*List[T]) HandlePaste

func (l *List[T]) HandlePaste(text string) bool

HandlePaste takes pasted text into the filter while its line is open.

func (*List[T]) Items

func (l *List[T]) Items() []T

Items returns every item, those filtered out included.

func (*List[T]) Keymap

func (l *List[T]) Keymap() *Keymap

Keymap returns the keys of the list.

func (*List[T]) Marked

func (l *List[T]) Marked() []T

Marked returns the marked items, or the item under the cursor when none is marked: what an action on several items acts on.

func (*List[T]) Move

func (l *List[T]) Move(n int)

Move moves the cursor n rows down, or up for a negative n.

func (*List[T]) Position

func (l *List[T]) Position() string

Position is where the cursor is, as "3/20", or "3/20 of 52541" with a total set.

func (*List[T]) Selected

func (l *List[T]) Selected() (T, bool)

Selected returns the item under the cursor, and false when there is none.

func (*List[T]) SetColumns

func (l *List[T]) SetColumns(columns ...Column) *List[T]

SetColumns shows the list as a table with these columns, one per cell.

func (*List[T]) SetCursor

func (l *List[T]) SetCursor(i int)

SetCursor puts the cursor on the row of index i among the rows shown.

func (*List[T]) SetDisabled

func (l *List[T]) SetDisabled(disabled bool) *List[T]

SetDisabled keeps the list from taking the focus.

func (*List[T]) SetEmpty

func (l *List[T]) SetEmpty(text string) *List[T]

SetEmpty sets what the list says when there are no rows.

func (*List[T]) SetFilter

func (l *List[T]) SetFilter(s string)

SetFilter sets the filter.

func (*List[T]) SetItems

func (l *List[T]) SetItems(items []T)

SetItems replaces the items. The cursor stays on the row it was on where it can, and the marks go.

func (*List[T]) SetLoading

func (l *List[T]) SetLoading(loading bool)

SetLoading shows that rows are being loaded.

func (*List[T]) SetMatch

func (l *List[T]) SetMatch(fn func(item T) string) *List[T]

SetMatch sets the text the filter is matched against, the cells otherwise. A nil fn leaves filtering to OnFilter.

func (*List[T]) SetRowStyle

func (l *List[T]) SetRowStyle(fn func(item T) theme.Style) *List[T]

SetRowStyle sets a style for whole rows, such as a muted one for closed tickets.

func (*List[T]) SetTotal

func (l *List[T]) SetTotal(n int)

SetTotal sets how many items there are in all, where the list holds only the first of them, for the position to show "20/52541".

func (*List[T]) Shown

func (l *List[T]) Shown() []T

Shown returns the items the filter lets through, in order.

func (*List[T]) TakesText

func (l *List[T]) TakesText() bool

TakesText reports whether the filter line takes typed characters now.

type MenuItem struct {
	// Key is the key that picks the item at once, such as "a"; optional.
	Key string
	// Label says what the item does.
	Label string
	// Action is what it does.
	Action func()
	// Disabled shows the item muted and keeps it from being picked.
	Disabled bool
	// Separator draws a line instead of an item.
	Separator bool
}

MenuItem is an entry of a menu.

type Mod

type Mod uint8

Mod is the set of modifier keys held with a key.

const (
	ModShift Mod = 1 << iota
	ModAlt
	ModCtrl
)

The modifiers a terminal reports. Shift is reported only for keys that type no character: a shifted letter arrives as the capital letter.

type Mouse

type Mouse struct {
	X, Y   int
	Button MouseButton
	Action MouseAction
	Mod    Mod
}

Mouse is a mouse event, in cells from the top left corner of the screen, 0-based.

type MouseAction

type MouseAction int

MouseAction is what happened with the button.

const (
	MousePress MouseAction = iota
	MouseRelease
	MouseMotion
)

Mouse actions.

type MouseButton

type MouseButton int

MouseButton is the button of a mouse event.

const (
	MouseNone MouseButton = iota
	MouseLeft
	MouseMiddle
	MouseRight
	MouseWheelUp
	MouseWheelDown
)

The buttons a terminal reports. A wheel turned is a press of WheelUp or WheelDown.

type Notice

type Notice struct {
	Level Level
	Text  string
	// contains filtered or unexported fields
}

Notice is a message shown in the status bar for a while.

type Option

type Option func(*App)

Option configures an App.

func WithMouse

func WithMouse() Option

WithMouse turns the mouse on: clicks focus widgets and reach Clickers, the wheel scrolls. Text can then be selected with Shift held, in most terminals.

func WithTerminal

func WithTerminal(in, out *os.File) Option

WithTerminal makes the application run on in and out rather than on os.Stdin and os.Stdout. Both must be the same terminal.

func WithTheme

func WithTheme(t Theme) Option

WithTheme sets the styles the widgets draw with; DefaultTheme otherwise.

func WithoutHelp

func WithoutHelp() Option

WithoutHelp leaves out the "?" binding that shows the help.

type Padded

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

Padded draws a widget with blank cells around it.

func Pad

func Pad(child Widget, top, right, bottom, left int) *Padded

Pad returns child with blank cells around it, in CSS order: top, right, bottom, left.

func (*Padded) Children

func (p *Padded) Children() []Widget

Children returns the widget inside.

func (*Padded) Draw

func (p *Padded) Draw(c Canvas)

Draw draws the widget inside the padding.

func (*Padded) Size

func (p *Padded) Size(width, height int) (int, int)

Size is the size of the widget inside and the padding.

type Pages

type Pages struct {

	// OnChange is called with the name of the page shown after Show.
	OnChange func(name string)
	// contains filtered or unexported fields
}

Pages shows one of several widgets at a time, by name: the screens of an application, such as a list and the detail of one row.

func NewPages

func NewPages() *Pages

NewPages returns an empty set of pages.

func (*Pages) Add

func (p *Pages) Add(name string, w Widget)

Add adds a page; the first page added is shown first.

func (*Pages) Children

func (p *Pages) Children() []Widget

Children returns the page shown.

func (*Pages) Current

func (p *Pages) Current() string

Current returns the name of the page shown.

func (*Pages) Draw

func (p *Pages) Draw(c Canvas)

Draw draws the page shown.

func (*Pages) Names

func (p *Pages) Names() []string

Names returns the names of the pages in the order they were added.

func (*Pages) Page

func (p *Pages) Page(name string) Widget

Page returns the widget of a page.

func (*Pages) Show

func (p *Pages) Show(name string)

Show shows the page of name.

type Panel

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

Panel draws a border around a widget, with a title and a footer on it. The border takes the theme's FocusBorder while the widget, or one inside it, has the focus.

func NewPanel

func NewPanel(title string, child Widget) *Panel

NewPanel returns a panel around child with a title.

func (*Panel) Child

func (p *Panel) Child() Widget

Child returns the widget inside the panel.

func (*Panel) Children

func (p *Panel) Children() []Widget

Children returns the widget inside the panel.

func (*Panel) Draw

func (p *Panel) Draw(c Canvas)

Draw draws the border and the widget inside it.

func (*Panel) SetBorder

func (p *Panel) SetBorder(b Border)

SetBorder sets the characters of the border.

func (*Panel) SetFooter

func (p *Panel) SetFooter(l Line)

SetFooter sets what the bottom edge shows on its right, such as a position.

func (*Panel) SetPadding

func (p *Panel) SetPadding(n int)

SetPadding sets the blank columns inside the border on either side.

func (*Panel) SetTitle

func (p *Panel) SetTitle(title string)

SetTitle sets the title, drawn in the theme's Title style.

func (*Panel) SetTitleLine

func (p *Panel) SetTitleLine(l Line)

SetTitleLine sets a title of several styles, such as a title and a count.

func (*Panel) Size

func (p *Panel) Size(width, height int) (int, int)

Size is the size of the widget inside and the border.

type Paste

type Paste struct {
	Text string
	// contains filtered or unexported fields
}

Paste is text pasted into the terminal in one piece, with bracketed paste on. Line breaks are "\n"; every other control character but the tab is left out.

type Paster

type Paster interface {
	HandlePaste(text string) bool
}

Paster is a widget that takes pasted text while it has the focus.

type RadioGroup

type RadioGroup struct {

	// OnChange is called with the index of the option chosen.
	OnChange func(i int)
	// contains filtered or unexported fields
}

RadioGroup chooses one of several options, as radio buttons in a column or a row. Space or Enter chooses the option under the cursor.

func NewRadioGroup

func NewRadioGroup(options []string, selected int) *RadioGroup

NewRadioGroup returns a radio group with the option of index selected chosen; -1 for none.

func (*RadioGroup) CanFocus

func (r *RadioGroup) CanFocus() bool

CanFocus reports whether the group is enabled.

func (*RadioGroup) Draw

func (r *RadioGroup) Draw(c Canvas)

Draw draws the options.

func (*RadioGroup) HandleKey

func (r *RadioGroup) HandleKey(Key) bool

HandleKey takes no other keys.

func (*RadioGroup) HandleMouse

func (r *RadioGroup) HandleMouse(m Mouse) bool

HandleMouse chooses the option clicked.

func (*RadioGroup) Keymap

func (r *RadioGroup) Keymap() *Keymap

Keymap returns the keys of the group.

func (*RadioGroup) Select

func (r *RadioGroup) Select(i int)

Select chooses the option of index i and calls OnChange.

func (*RadioGroup) Selected

func (r *RadioGroup) Selected() int

Selected returns the index of the option chosen, -1 for none.

func (*RadioGroup) SetDisabled

func (r *RadioGroup) SetDisabled(disabled bool) *RadioGroup

SetDisabled keeps the group from taking the focus.

func (*RadioGroup) SetHorizontal

func (r *RadioGroup) SetHorizontal(h bool) *RadioGroup

SetHorizontal lays the options out in a row.

func (*RadioGroup) SetSelected

func (r *RadioGroup) SetSelected(i int)

SetSelected chooses the option of index i without calling OnChange.

func (*RadioGroup) Size

func (r *RadioGroup) Size(width, height int) (int, int)

Size is the options laid out.

func (*RadioGroup) Value

func (r *RadioGroup) Value() string

Value returns the option chosen, "" for none.

type Resize

type Resize struct {
	Width, Height int
}

Resize says the terminal changed size.

type Select

type Select struct {

	// OnChange is called with the index of the option chosen.
	OnChange func(i int)
	// contains filtered or unexported fields
}

Select is a field that shows one of several options and, on Enter or Space, opens a list to choose another from, which filters as you type.

func NewSelect

func NewSelect(title string, options []string, selected int) *Select

NewSelect returns a select with the option of index selected shown; -1 for none.

func (*Select) CanFocus

func (s *Select) CanFocus() bool

CanFocus reports whether the select is enabled.

func (*Select) Draw

func (s *Select) Draw(c Canvas)

Draw draws the option shown and an arrow.

func (*Select) HandleKey

func (s *Select) HandleKey(Key) bool

HandleKey takes no other keys.

func (*Select) HandleMouse

func (s *Select) HandleMouse(m Mouse) bool

HandleMouse opens the list on a click.

func (*Select) Keymap

func (s *Select) Keymap() *Keymap

Keymap returns the keys of the select.

func (*Select) Open

func (s *Select) Open()

Open opens the list of options in a layer.

func (*Select) Selected

func (s *Select) Selected() int

Selected returns the index of the option shown, -1 for none.

func (*Select) SetDisabled

func (s *Select) SetDisabled(disabled bool) *Select

SetDisabled keeps the select from taking the focus.

func (*Select) SetSelected

func (s *Select) SetSelected(i int)

SetSelected shows the option of index i without calling OnChange.

func (*Select) Size

func (s *Select) Size(width, _ int) (int, int)

Size is the widest option and the arrow, and one line.

func (*Select) Value

func (s *Select) Value() string

Value returns the option shown, "" for none.

type Sizer

type Sizer interface {
	Size(width, height int) (w, h int)
}

Sizer is a widget that tells layouts how big it wants to be in a space of width×height cells. A layout gives a child of size [Auto] what it asks for, if there is room.

type Spacer

type Spacer struct{}

Spacer is an empty widget that takes room.

func (Spacer) Draw

func (Spacer) Draw(Canvas)

Draw draws nothing.

type Span

type Span struct {
	Text  string
	Style theme.Style
}

Span is a piece of text in one style.

func Badge

func Badge(s string, style theme.Style) Span

Badge returns s as a badge: padded with a space on either side, for a style with a background, such as a label or a priority.

type StatusBar

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

StatusBar is the line at the bottom of an application: a notice from App.Notify, or what App.Busy says it is busy with, or else text of its own on the left, and text on the right.

func NewStatusBar

func NewStatusBar(left, right func() Line) *StatusBar

NewStatusBar returns a status bar. left and right make the text on either side for every frame; either may be nil.

func (*StatusBar) Draw

func (s *StatusBar) Draw(c Canvas)

Draw draws the bar.

func (*StatusBar) Size

func (*StatusBar) Size(width, _ int) (int, int)

Size is one line.

type Tabs

type Tabs struct {
	*Pages
	// contains filtered or unexported fields
}

Tabs shows pages with a row of their titles above them. Ctrl-Right and Ctrl-Left, or "]" and "[" where no text field has the focus, switch between them, and so do Alt-1 to Alt-9.

func NewTabs

func NewTabs() *Tabs

NewTabs returns empty tabs.

func (*Tabs) AddTab

func (t *Tabs) AddTab(name, title string, w Widget)

AddTab adds a page with the title its tab shows.

func (*Tabs) Draw

func (t *Tabs) Draw(c Canvas)

Draw draws the tab row and the page shown.

func (*Tabs) Keymap

func (t *Tabs) Keymap() *Keymap

Keymap returns the keys that switch tabs.

type TextArea

type TextArea struct {

	// OnChange is called with the text after every change.
	OnChange func(text string)
	// contains filtered or unexported fields
}

TextArea is a multi-line text field, such as the body of a message. Lines wider than the field wrap at spaces. It takes the keys of Input and these:

enter                 new line
↑/↓                   line up/down, as wrapped
pgup/pgdown           page up/down
ctrl+home/ctrl+end    start/end of the text

Tab is left to move the focus, so a TextArea in a form behaves like the other fields.

func NewTextArea

func NewTextArea() *TextArea

NewTextArea returns an empty text area.

func (*TextArea) CanFocus

func (t *TextArea) CanFocus() bool

CanFocus reports whether the field is enabled.

func (*TextArea) Draw

func (t *TextArea) Draw(c Canvas)

Draw draws the visible rows and a scroll bar where the text does not fit.

func (*TextArea) HandleKey

func (t *TextArea) HandleKey(k Key) bool

HandleKey edits the text.

func (*TextArea) HandleMouse

func (t *TextArea) HandleMouse(m Mouse) bool

HandleMouse puts the cursor where the field was clicked, and scrolls with the wheel.

func (*TextArea) HandlePaste

func (t *TextArea) HandlePaste(text string) bool

HandlePaste inserts pasted text, its lines included.

func (*TextArea) Keymap

func (t *TextArea) Keymap() *Keymap

Keymap returns the keys of the field.

func (*TextArea) Len

func (t *TextArea) Len() int

Len is how many characters the text holds, line breaks counted: what a counter such as "120/8000" shows.

func (*TextArea) Limit

func (t *TextArea) Limit() int

Limit is the most characters the field takes, 0 for no limit.

func (*TextArea) SetDisabled

func (t *TextArea) SetDisabled(disabled bool) *TextArea

SetDisabled keeps the field from taking the focus.

func (*TextArea) SetLimit

func (t *TextArea) SetLimit(n int) *TextArea

SetLimit sets the most characters the field takes, line breaks counted, 0 for no limit.

func (*TextArea) SetPlaceholder

func (t *TextArea) SetPlaceholder(s string) *TextArea

SetPlaceholder sets the text shown, muted, while the field is empty.

func (*TextArea) SetValue

func (t *TextArea) SetValue(s string)

SetValue replaces the text and puts the cursor at its end. OnChange is not called.

func (*TextArea) TakesText

func (t *TextArea) TakesText() bool

TakesText reports that the field takes typed characters.

func (*TextArea) Value

func (t *TextArea) Value() string

Value returns the text.

type Theme

type Theme struct {
	// Text is ordinary text.
	Text theme.Style
	// Muted is text that recedes: hints, placeholders, empty states.
	Muted theme.Style
	// Title is the title of a panel or dialog.
	Title theme.Style
	// Border is the border of a panel; FocusBorder of the panel holding
	// the focus.
	Border      theme.Style
	FocusBorder theme.Style
	// Header is the header row of a table.
	Header theme.Style
	// Cursor is the row under the cursor of a focused list; Cursor
	// without focus, CursorBlurred.
	Cursor        theme.Style
	CursorBlurred theme.Style
	// Marked is a row marked for a bulk action, and the mark in front of
	// it.
	Marked theme.Style
	// Key is a key in the legend and the help, KeyHelp what it does.
	Key     theme.Style
	KeyHelp theme.Style
	// Accent marks something worth noticing, such as the active tab.
	Accent theme.Style
	// Match is the part of a row a filter matched.
	Match theme.Style
	// Field is a text field, FieldFocused one that has the focus.
	Field        theme.Style
	FieldFocused theme.Style
	// On and Off are the two states of a switch.
	On  theme.Style
	Off theme.Style
	// Info, Success, Warning and Error color messages by severity.
	Info    theme.Style
	Success theme.Style
	Warning theme.Style
	Error   theme.Style
	// Scrollbar is the track of a scroll bar, ScrollThumb its thumb.
	Scrollbar   theme.Style
	ScrollThumb theme.Style
	// StatusBar is the line at the bottom of the screen.
	StatusBar theme.Style
	// Dialog is the background of a dialog or a menu.
	Dialog theme.Style
}

Theme is the set of styles the widgets draw with. Every field is a theme.Style; an empty one draws in the terminal's own colors.

func DefaultTheme

func DefaultTheme() Theme

DefaultTheme is ThemeFrom of the active theme of package theme.

func ThemeFrom

func ThemeFrom(t theme.Theme) Theme

ThemeFrom derives the styles of the widgets from a theme of package theme, so a tool that installed its own with theme.Use gets matching widgets. Backgrounds, which package theme has no roles for, use the reverse video of the terminal, so they read on dark and light backgrounds alike.

type Toggle

type Toggle struct {

	// OnChange is called with the new value after every flip.
	OnChange func(on bool)
	// contains filtered or unexported fields
}

Toggle is a yes/no value: a checkbox, "[x] Label", or a switch, "Label ON". Space or Enter flips it.

func NewCheckbox

func NewCheckbox(label string, on bool) *Toggle

NewCheckbox returns a toggle drawn as a checkbox.

func NewSwitch

func NewSwitch(label string, on bool) *Toggle

NewSwitch returns a toggle drawn as a switch.

func (*Toggle) CanFocus

func (t *Toggle) CanFocus() bool

CanFocus reports whether the toggle is enabled.

func (*Toggle) Draw

func (t *Toggle) Draw(c Canvas)

Draw draws the toggle.

func (*Toggle) Flip

func (t *Toggle) Flip()

Flip turns the toggle on or off and calls OnChange.

func (*Toggle) HandleKey

func (t *Toggle) HandleKey(Key) bool

HandleKey takes no other keys.

func (*Toggle) HandleMouse

func (t *Toggle) HandleMouse(m Mouse) bool

HandleMouse flips the toggle on a click.

func (*Toggle) Keymap

func (t *Toggle) Keymap() *Keymap

Keymap returns the keys of the toggle.

func (*Toggle) SetDisabled

func (t *Toggle) SetDisabled(disabled bool) *Toggle

SetDisabled keeps the toggle from taking the focus.

func (*Toggle) SetLabel

func (t *Toggle) SetLabel(label string)

SetLabel sets the label.

func (*Toggle) SetValue

func (t *Toggle) SetValue(on bool)

SetValue sets the value without calling OnChange.

func (*Toggle) Size

func (t *Toggle) Size(width, _ int) (int, int)

Size is the width of the label and the box, and one line.

func (*Toggle) Value

func (t *Toggle) Value() bool

Value reports whether the toggle is on.

type Viewport

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

Viewport shows lines that may not fit and scrolls through them, with a scroll bar on the right. Lines wider than the viewport wrap. It knows the keys of a pager:

↑/↓ k/j               line up/down
pgup/pgdown ctrl+b/f  page up/down (also space)
ctrl+u/d              half a page up/down
g/G home/end          top/bottom
/                     search; n/N next/previous match

With follow on, the view stays at the bottom while lines are added, as a log does, until it is scrolled up.

func NewViewport

func NewViewport() *Viewport

NewViewport returns an empty viewport.

func (*Viewport) Append

func (v *Viewport) Append(lines ...Line)

Append adds lines at the end.

func (*Viewport) CanFocus

func (v *Viewport) CanFocus() bool

CanFocus reports whether the viewport takes the focus.

func (*Viewport) Draw

func (v *Viewport) Draw(c Canvas)

Draw draws the visible lines, the scroll bar and the search line.

func (*Viewport) HandleKey

func (v *Viewport) HandleKey(k Key) bool

HandleKey edits the search line while it is open.

func (*Viewport) HandleMouse

func (v *Viewport) HandleMouse(m Mouse) bool

HandleMouse scrolls with the wheel.

func (*Viewport) HandlePaste

func (v *Viewport) HandlePaste(text string) bool

HandlePaste takes pasted text into the search line while it is open.

func (*Viewport) Keymap

func (v *Viewport) Keymap() *Keymap

Keymap returns the keys of the viewport.

func (*Viewport) Position

func (v *Viewport) Position() string

Position is how far the view is scrolled, as "Top", "Bot", "All" or a percentage, the way less and vim show it.

func (*Viewport) ScrollBottom

func (v *Viewport) ScrollBottom()

ScrollBottom scrolls to the last line.

func (*Viewport) ScrollBy

func (v *Viewport) ScrollBy(n int)

ScrollBy scrolls n rows down, or up for a negative n.

func (*Viewport) ScrollToLine

func (v *Viewport) ScrollToLine(n int)

ScrollToLine scrolls so that line n, counted in the lines given rather than as wrapped, is at the top.

func (*Viewport) ScrollTop

func (v *Viewport) ScrollTop()

ScrollTop scrolls to the first line.

func (*Viewport) SetDisabled

func (v *Viewport) SetDisabled(disabled bool) *Viewport

SetDisabled keeps the viewport from taking the focus, for text that is only shown.

func (*Viewport) SetFollow

func (v *Viewport) SetFollow(follow bool) *Viewport

SetFollow keeps the view at the bottom as lines are added.

func (*Viewport) SetLines

func (v *Viewport) SetLines(lines []Line)

SetLines replaces the lines. The view keeps its position, or stays at the bottom with follow on.

func (*Viewport) SetText

func (v *Viewport) SetText(text string, style theme.Style)

SetText replaces the lines with text in one style.

func (*Viewport) TakesText

func (v *Viewport) TakesText() bool

TakesText reports whether the search line takes typed characters now.

type Widget

type Widget interface {
	Draw(c Canvas)
}

Widget is anything drawn on the screen. Draw is called for every frame, with a canvas of the size the layout gave the widget; it must not block.

What else a widget does it says by the interfaces it implements: Focusable to take the focus and keys, Container to hold other widgets, Bindings to bind keys, Paster to take pasted text, Clicker to take the mouse and Sizer to tell layouts how big it wants to be.

Jump to

Keyboard shortcuts

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