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:
- Layout: VBox, HBox (children sized Grow, GrowBy, Fixed or Fit), Panel, Pages, Tabs, Pad, Spacer, Keyed
- Text: Label, Viewport (a scrolling, searchable pager), Badge
- Input: Input, TextArea, Toggle (checkbox or switch), RadioGroup, CheckList, Select, Button, Form
- Choosing: List (a list or a table, with a filter, marks and pages loaded on demand)
- Layers: Dialog, App.Push, App.Confirm, App.Prompt, App.Choose, App.Menu, App.EditText
- Chrome: Legend, StatusBar, the help on "?"
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 ¶
- Variables
- func KeyLabel(name string) string
- type Align
- type App
- func (a *App) ActiveBindings() []*Binding
- func (a *App) Busy(text string) (done func())
- func (a *App) Choose(title string, options []string, selected int, onChoose func(i int))
- func (a *App) Close(w Widget)
- func (a *App) Confirm(title, message string, onYes func())
- func (a *App) EditText(title, value string, onSave func(text string)) *TextArea
- func (a *App) Focus(w Focusable)
- func (a *App) FocusNext(delta int)
- func (a *App) Focused() Focusable
- func (a *App) Go(work func() func())
- func (a *App) HandleKey(k Key) bool
- func (a *App) Keymap() *Keymap
- func (a *App) Layers() int
- func (a *App) Menu(title string, items []MenuItem)
- func (a *App) Notify(level Level, text string)
- func (a *App) Notifyf(level Level, format string, args ...any)
- func (a *App) Pop()
- func (a *App) Post(fn func())
- func (a *App) Prompt(title, label, value string, onSubmit func(text string)) *Input
- func (a *App) Push(w Widget, opts LayerOptions)
- func (a *App) Quit()
- func (a *App) QuitWith(err error)
- func (a *App) Root() Widget
- func (a *App) Run() error
- func (a *App) SetRoot(w Widget)
- func (a *App) ShowHelp()
- func (a *App) Size() (width, height int)
- func (a *App) Status() (notice *Notice, busy string)
- func (a *App) Suspend()
- func (a *App) Theme() Theme
- type Binding
- type Bindings
- type Border
- type Box
- type Button
- func (b *Button) CanFocus() bool
- func (b *Button) Draw(c Canvas)
- func (b *Button) HandleKey(Key) bool
- func (b *Button) HandleMouse(m Mouse) bool
- func (b *Button) Keymap() *Keymap
- func (b *Button) Press()
- func (b *Button) SetDisabled(disabled bool) *Button
- func (b *Button) SetLabel(label string)
- func (b *Button) Size(width, _ int) (int, int)
- type Canvas
- func (c Canvas) App() *App
- func (c Canvas) Box(border Border, style theme.Style, title, footer Line) Canvas
- func (c Canvas) Draw(w Widget)
- func (c Canvas) Fill(style theme.Style)
- func (c Canvas) FillRow(x, y int, style theme.Style)
- func (c Canvas) Focused(w Widget) bool
- func (c Canvas) HasFocus(w Widget) bool
- func (c Canvas) Height() int
- func (c Canvas) Line(x, y int, l Line) int
- func (c Canvas) ShowCursor(x, y int)
- func (c Canvas) Sub(x, y, w, h int) Canvas
- func (c Canvas) Text(x, y int, s string, style theme.Style) int
- func (c Canvas) Theme() Theme
- func (c Canvas) VScrollbar(x, offset, height, total int)
- func (c Canvas) Width() int
- func (c Canvas) WithStyle(base theme.Style) Canvas
- type CheckList
- func (l *CheckList) CanFocus() bool
- func (l *CheckList) Checked() []bool
- func (l *CheckList) Draw(c Canvas)
- func (l *CheckList) HandleKey(Key) bool
- func (l *CheckList) HandleMouse(m Mouse) bool
- func (l *CheckList) Keymap() *Keymap
- func (l *CheckList) SetChecked(i int, on bool)
- func (l *CheckList) SetDisabled(disabled bool) *CheckList
- func (l *CheckList) SetHorizontal(h bool) *CheckList
- func (l *CheckList) Size(width, height int) (int, int)
- func (l *CheckList) Toggle(i int)
- func (l *CheckList) Values() []string
- type Clicker
- type Column
- type Container
- type Dialog
- type Focusable
- type Focuser
- type Form
- func (f *Form) Add(label string, w Widget) *Form
- func (f *Form) AddButtons(buttons ...*Button) *Form
- func (f *Form) AddHint(label string, w Widget, hint string) *Form
- func (f *Form) Children() []Widget
- func (f *Form) Draw(c Canvas)
- func (f *Form) Err() error
- func (f *Form) Keymap() *Keymap
- func (f *Form) Size(width, height int) (int, int)
- func (f *Form) Submit()
- type Headless
- func (h *Headless) Click(x, y int)
- func (h *Headless) Cursor() (x, y int)
- func (h *Headless) Draw()
- func (h *Headless) Feed(data string)
- func (h *Headless) Lines() []string
- func (h *Headless) Paste(text string)
- func (h *Headless) Press(keys ...string)
- func (h *Headless) Quit() (bool, error)
- func (h *Headless) Resize(width, height int)
- func (h *Headless) Screen() string
- func (h *Headless) Settle(timeout time.Duration)
- func (h *Headless) Type(text string)
- func (h *Headless) Wheel(x, y, n int)
- type Input
- func (in *Input) CanFocus() bool
- func (in *Input) Draw(c Canvas)
- func (in *Input) Err() error
- func (in *Input) HandleKey(k Key) bool
- func (in *Input) HandleMouse(m Mouse) bool
- func (in *Input) HandlePaste(text string) bool
- func (in *Input) Keymap() *Keymap
- func (in *Input) SetDisabled(disabled bool) *Input
- func (in *Input) SetLimit(n int) *Input
- func (in *Input) SetPlaceholder(s string) *Input
- func (in *Input) SetSecret(secret bool) *Input
- func (in *Input) SetSuggest(fn func(text string) []string) *Input
- func (in *Input) SetValue(s string)
- func (in *Input) Size(width, _ int) (int, int)
- func (in *Input) TakesText() bool
- func (in *Input) Value() string
- type Item
- type Key
- type KeyCode
- type Keyed
- type Keymap
- type Label
- type LayerOptions
- type Legend
- type Level
- type Line
- type List
- func (l *List[T]) AppendItems(items ...T)
- func (l *List[T]) CanFocus() bool
- func (l *List[T]) ClearMarks()
- func (l *List[T]) Cursor() int
- func (l *List[T]) Draw(c Canvas)
- func (l *List[T]) Filter() string
- func (l *List[T]) Filtering() bool
- func (l *List[T]) HandleKey(k Key) bool
- func (l *List[T]) HandleMouse(m Mouse) bool
- func (l *List[T]) HandlePaste(text string) bool
- func (l *List[T]) Items() []T
- func (l *List[T]) Keymap() *Keymap
- func (l *List[T]) Marked() []T
- func (l *List[T]) Move(n int)
- func (l *List[T]) Position() string
- func (l *List[T]) Selected() (T, bool)
- func (l *List[T]) SetColumns(columns ...Column) *List[T]
- func (l *List[T]) SetCursor(i int)
- func (l *List[T]) SetDisabled(disabled bool) *List[T]
- func (l *List[T]) SetEmpty(text string) *List[T]
- func (l *List[T]) SetFilter(s string)
- func (l *List[T]) SetItems(items []T)
- func (l *List[T]) SetLoading(loading bool)
- func (l *List[T]) SetMatch(fn func(item T) string) *List[T]
- func (l *List[T]) SetRowStyle(fn func(item T) theme.Style) *List[T]
- func (l *List[T]) SetTotal(n int)
- func (l *List[T]) Shown() []T
- func (l *List[T]) TakesText() bool
- type MenuItem
- type Mod
- type Mouse
- type MouseAction
- type MouseButton
- type Notice
- type Option
- type Padded
- type Pages
- type Panel
- func (p *Panel) Child() Widget
- func (p *Panel) Children() []Widget
- func (p *Panel) Draw(c Canvas)
- func (p *Panel) SetBorder(b Border)
- func (p *Panel) SetFooter(l Line)
- func (p *Panel) SetPadding(n int)
- func (p *Panel) SetTitle(title string)
- func (p *Panel) SetTitleLine(l Line)
- func (p *Panel) Size(width, height int) (int, int)
- type Paste
- type Paster
- type RadioGroup
- func (r *RadioGroup) CanFocus() bool
- func (r *RadioGroup) Draw(c Canvas)
- func (r *RadioGroup) HandleKey(Key) bool
- func (r *RadioGroup) HandleMouse(m Mouse) bool
- func (r *RadioGroup) Keymap() *Keymap
- func (r *RadioGroup) Select(i int)
- func (r *RadioGroup) Selected() int
- func (r *RadioGroup) SetDisabled(disabled bool) *RadioGroup
- func (r *RadioGroup) SetHorizontal(h bool) *RadioGroup
- func (r *RadioGroup) SetSelected(i int)
- func (r *RadioGroup) Size(width, height int) (int, int)
- func (r *RadioGroup) Value() string
- type Resize
- type Select
- func (s *Select) CanFocus() bool
- func (s *Select) Draw(c Canvas)
- func (s *Select) HandleKey(Key) bool
- func (s *Select) HandleMouse(m Mouse) bool
- func (s *Select) Keymap() *Keymap
- func (s *Select) Open()
- func (s *Select) Selected() int
- func (s *Select) SetDisabled(disabled bool) *Select
- func (s *Select) SetSelected(i int)
- func (s *Select) Size(width, _ int) (int, int)
- func (s *Select) Value() string
- type Sizer
- type Spacer
- type Span
- type StatusBar
- type Tabs
- type TextArea
- func (t *TextArea) CanFocus() bool
- func (t *TextArea) Draw(c Canvas)
- func (t *TextArea) HandleKey(k Key) bool
- func (t *TextArea) HandleMouse(m Mouse) bool
- func (t *TextArea) HandlePaste(text string) bool
- func (t *TextArea) Keymap() *Keymap
- func (t *TextArea) Len() int
- func (t *TextArea) Limit() int
- func (t *TextArea) SetDisabled(disabled bool) *TextArea
- func (t *TextArea) SetLimit(n int) *TextArea
- func (t *TextArea) SetPlaceholder(s string) *TextArea
- func (t *TextArea) SetValue(s string)
- func (t *TextArea) TakesText() bool
- func (t *TextArea) Value() string
- type Theme
- type Toggle
- func (t *Toggle) CanFocus() bool
- func (t *Toggle) Draw(c Canvas)
- func (t *Toggle) Flip()
- func (t *Toggle) HandleKey(Key) bool
- func (t *Toggle) HandleMouse(m Mouse) bool
- func (t *Toggle) Keymap() *Keymap
- func (t *Toggle) SetDisabled(disabled bool) *Toggle
- func (t *Toggle) SetLabel(label string)
- func (t *Toggle) SetValue(on bool)
- func (t *Toggle) Size(width, _ int) (int, int)
- func (t *Toggle) Value() bool
- type Viewport
- func (v *Viewport) Append(lines ...Line)
- func (v *Viewport) CanFocus() bool
- func (v *Viewport) Draw(c Canvas)
- func (v *Viewport) HandleKey(k Key) bool
- func (v *Viewport) HandleMouse(m Mouse) bool
- func (v *Viewport) HandlePaste(text string) bool
- func (v *Viewport) Keymap() *Keymap
- func (v *Viewport) Position() string
- func (v *Viewport) ScrollBottom()
- func (v *Viewport) ScrollBy(n int)
- func (v *Viewport) ScrollToLine(n int)
- func (v *Viewport) ScrollTop()
- func (v *Viewport) SetDisabled(disabled bool) *Viewport
- func (v *Viewport) SetFollow(follow bool) *Viewport
- func (v *Viewport) SetLines(lines []Line)
- func (v *Viewport) SetText(text string, style theme.Style)
- func (v *Viewport) TakesText() bool
- type Widget
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( BorderRounded = Border{"╭", "─", "╮", "│", "│", "╰", "─", "╯"} BorderSingle = Border{"┌", "─", "┐", "│", "│", "└", "─", "┘"} BorderDouble = Border{"╔", "═", "╗", "║", "║", "╚", "═", "╝"} BorderThick = Border{"┏", "━", "┓", "┃", "┃", "┗", "━", "┛"} BorderASCII = Border{"+", "-", "+", "|", "|", "+", "-", "+"} )
The borders a box can have.
var ErrInputClosed = errors.New("tui: input closed")
ErrInputClosed is what App.Run returns when the terminal went away before the application quit.
var ErrNotATerminal = errors.New("tui: not a terminal")
ErrNotATerminal is what App.Run returns when its input or output is not a terminal.
Functions ¶
Types ¶
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 (*App) ActiveBindings ¶
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 ¶
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 ¶
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) Confirm ¶
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 ¶
EditText edits text of several lines in a dialog: Ctrl-S saves, Esc cancels. onSave is called with the text.
func (*App) FocusNext ¶
FocusNext moves the focus to the next focusable widget of the topmost layer, by delta steps: 1 forward, -1 back.
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 ¶
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 ¶
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) Menu ¶
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) 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 ¶
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) Run ¶
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 ¶
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) Status ¶
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.
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.
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.
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 (*Button) HandleMouse ¶
HandleMouse presses the button on a click.
func (*Button) SetDisabled ¶
SetDisabled keeps the button from taking the focus.
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) Box ¶
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) ShowCursor ¶
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) Text ¶
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) VScrollbar ¶
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.
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 ¶
NewCheckList returns a check list with nothing checked.
func (*CheckList) HandleMouse ¶
HandleMouse checks the option clicked.
func (*CheckList) SetChecked ¶
SetChecked checks or unchecks the option of index i without calling OnChange.
func (*CheckList) SetDisabled ¶
SetDisabled keeps the list from taking the focus.
func (*CheckList) SetHorizontal ¶
SetHorizontal lays the options out in a row.
type Clicker ¶
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 ¶
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.
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 (*Form) AddButtons ¶
AddButtons adds buttons in a row at the bottom.
func (*Form) AddHint ¶
AddHint adds a field with its label and a muted line under it that says what it takes.
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 ¶
NewHeadless returns a headless run of app on a screen of width×height cells, drawn once.
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 ¶
Feed hands raw bytes to the application as the terminal would send them, escape sequences included.
func (*Headless) Press ¶
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) Screen ¶
Screen returns the screen as text, rows joined by "\n", trailing blank rows cut.
func (*Headless) Settle ¶
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.
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 (*Input) HandleMouse ¶
HandleMouse puts the cursor where the field was clicked.
func (*Input) HandlePaste ¶
HandlePaste inserts pasted text, its line breaks as spaces.
func (*Input) SetDisabled ¶
SetDisabled keeps the field from taking the focus.
func (*Input) SetPlaceholder ¶
SetPlaceholder sets the text shown, muted, while the field is empty.
func (*Input) SetSuggest ¶
SetSuggest sets where suggestions for the text come from; nil for none.
func (*Input) SetValue ¶
SetValue replaces the text and puts the cursor at its end. OnChange is not called.
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 ¶
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.
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 ¶
ParseKey reads a key name as Key.String writes it: "ctrl+s", "alt+x", "shift+tab", "f5", "space", "enter", "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.
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.
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 (*Keymap) Bind ¶
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")
type Label ¶
type Label struct {
// contains filtered or unexported fields
}
Label shows lines of text. It takes no focus.
func NewDynamic ¶
NewDynamic returns a label whose lines fn makes for every frame, such as a header with a count.
func NewLabel ¶
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.
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.
type Line ¶
type Line []Span
Line is a line of text made of spans.
func TruncateLine ¶
TruncateLine cuts a line to width cells, ending it in an ellipsis in the style of the span that was cut.
func WrapLine ¶
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 ¶
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.
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 (*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]) HandleMouse ¶
HandleMouse moves the cursor to the row clicked, and scrolls with the wheel.
func (*List[T]) HandlePaste ¶
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]) 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]) Position ¶
Position is where the cursor is, as "3/20", or "3/20 of 52541" with a total set.
func (*List[T]) Selected ¶
Selected returns the item under the cursor, and false when there is none.
func (*List[T]) SetColumns ¶
SetColumns shows the list as a table with these columns, one per cell.
func (*List[T]) SetDisabled ¶
SetDisabled keeps the list from taking the focus.
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 ¶
SetLoading shows that rows are being loaded.
func (*List[T]) SetMatch ¶
SetMatch sets the text the filter is matched against, the cells otherwise. A nil fn leaves filtering to OnFilter.
func (*List[T]) SetRowStyle ¶
SetRowStyle sets a style for whole rows, such as a muted one for closed tickets.
func (*List[T]) SetTotal ¶
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".
type MenuItem ¶
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 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 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 ¶
WithTerminal makes the application run on in and out rather than on os.Stdin and os.Stdout. Both must be the same terminal.
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.
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.
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 (*Panel) SetFooter ¶
SetFooter sets what the bottom edge shows on its right, such as a position.
func (*Panel) SetPadding ¶
SetPadding sets the blank columns inside the border on either side.
func (*Panel) SetTitleLine ¶
SetTitleLine sets a title of several styles, such as a title and a count.
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 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) 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 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 (*Select) HandleMouse ¶
HandleMouse opens the list on a click.
func (*Select) SetDisabled ¶
SetDisabled keeps the select from taking the focus.
func (*Select) SetSelected ¶
SetSelected shows the option of index i without calling OnChange.
type Sizer ¶
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 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 ¶
NewStatusBar returns a status bar. left and right make the text on either side for every frame; either may be nil.
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.
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 (*TextArea) HandleMouse ¶
HandleMouse puts the cursor where the field was clicked, and scrolls with the wheel.
func (*TextArea) HandlePaste ¶
HandlePaste inserts pasted text, its lines included.
func (*TextArea) Len ¶
Len is how many characters the text holds, line breaks counted: what a counter such as "120/8000" shows.
func (*TextArea) SetDisabled ¶
SetDisabled keeps the field from taking the focus.
func (*TextArea) SetLimit ¶
SetLimit sets the most characters the field takes, line breaks counted, 0 for no limit.
func (*TextArea) SetPlaceholder ¶
SetPlaceholder sets the text shown, muted, while the field is empty.
func (*TextArea) SetValue ¶
SetValue replaces the text and puts the cursor at its end. OnChange is not called.
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 ¶
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 ¶
NewCheckbox returns a toggle drawn as a checkbox.
func (*Toggle) HandleMouse ¶
HandleMouse flips the toggle on a click.
func (*Toggle) SetDisabled ¶
SetDisabled keeps the toggle from taking the focus.
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 (*Viewport) HandleMouse ¶
HandleMouse scrolls with the wheel.
func (*Viewport) HandlePaste ¶
HandlePaste takes pasted text into the search line while it is open.
func (*Viewport) Position ¶
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) ScrollToLine ¶
ScrollToLine scrolls so that line n, counted in the lines given rather than as wrapped, is at the top.
func (*Viewport) SetDisabled ¶
SetDisabled keeps the viewport from taking the focus, for text that is only shown.
func (*Viewport) SetLines ¶
SetLines replaces the lines. The view keeps its position, or stays at the bottom with follow on.
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.