Documentation
¶
Index ¶
- Constants
- func AreaDisabled() func(*TextAreaEl)
- func CheckboxDisabled() func(*CheckboxEl)
- func Disabled() func(*ButtonEl)
- func IsTUI() bool
- func IsWeb() bool
- func PlatformText(tui, web string) string
- func PlatformValue[T any](tui, web T) T
- func RenderTUI(el Element) string
- func RenderTUISized(el Element, width, height int) string
- func SelectDisabled() func(*SelectEl)
- func SidebarGap(n int) func(*SidebarOpts)
- func SidebarMinMain(n int) func(*SidebarOpts)
- func SidebarRight() func(*SidebarOpts)
- func SidebarSnug() func(*SidebarOpts)
- func SidebarWidth(n int) func(*SidebarOpts)
- func SpinnerFrames() int
- func Walk(el Element, fn func(Element) bool)
- func WithAreaOnChange(f func(string) Msg) func(*TextAreaEl)
- func WithAreaPlaceholder(p string) func(*TextAreaEl)
- func WithAreaRows(n int) func(*TextAreaEl)
- func WithAreaStyle(s Style) func(*TextAreaEl)
- func WithAreaValue(v string) func(*TextAreaEl)
- func WithButtonStyle(s Style) func(*ButtonEl)
- func WithCardStyle(s Style) func(*CardEl)
- func WithCheckboxStyle(s Style) func(*CheckboxEl)
- func WithDividerStyle(s Style) func(*DividerEl)
- func WithID(id string) func(*ButtonEl)
- func WithOnChange(f func(string) Msg) func(*TextInputEl)
- func WithOnSubmit(f func(string) Msg) func(*TextInputEl)
- func WithPassword() func(*TextInputEl)
- func WithPlaceholder(p string) func(*TextInputEl)
- func WithProgressLabel() func(*ProgressEl)
- func WithProgressRunes(filled, empty string) func(*ProgressEl)
- func WithProgressStyle(s Style) func(*ProgressEl)
- func WithProgressWidth(n int) func(*ProgressEl)
- func WithSelectStyle(s Style) func(*SelectEl)
- func WithSpinnerLabel(label string) func(*SpinnerEl)
- func WithSpinnerStyle(s Style) func(*SpinnerEl)
- func WithTextStyle(s Style) func(*TextEl)
- func WithValue(v string) func(*TextInputEl)
- type AddrFlag
- type Align
- type BatchMsg
- type Binding
- type BindingOption
- type BoxEl
- type Breakpoint
- type ButtonEl
- type CardEl
- type CheckboxEl
- type ClickMsg
- type Cmd
- type Color
- type Direction
- type DividerEl
- type Element
- func AlignedX(align Align, children ...Element) Element
- func AppShell(header, body, footer Element) Element
- func Box(dir Direction, children ...Element) Element
- func BoxStyled(dir Direction, gap int, style Style, children ...Element) Element
- func Button(label string, onClick func() Msg, opts ...func(*ButtonEl)) Element
- func Card(title string, child Element, opts ...func(*CardEl)) Element
- func Center(width int, children ...Element) Element
- func Centered(child Element) Element
- func CenteredX(children ...Element) Element
- func Checkbox(id, label string, checked bool, onToggle func(bool) Msg, ...) Element
- func Children(el Element) []Element
- func Constrain(maxWidth int, children ...Element) Element
- func ConstrainBox(maxWidth int, dir Direction, place Align, children ...Element) Element
- func Divider(label string, opts ...func(*DividerEl)) Element
- func Empty() Element
- func Find(el Element, pred func(Element) bool) (Element, bool)
- func Flex() Element
- func Form(onSubmit func(map[string]string) Msg, children ...Element) Element
- func Fullscreen(children ...Element) Element
- func Group(children ...Element) Element
- func Grow(n int, child Element) Element
- func HStack(children ...Element) Element
- func If(cond bool, el Element) Element
- func IfElse(cond bool, yes, no Element) Element
- func Input(id string, opts ...func(*TextInputEl)) Element
- func Link(label, href string) Element
- func List(ordered bool, items ...Element) Element
- func Map[T any](items []T, build func(i int, item T) Element) []Element
- func OnPlatform(tui, web Element) Element
- func Progress(value float64, opts ...func(*ProgressEl)) Element
- func Responsive(variants ...Breakpoint) Element
- func ResponsiveText(style Style, variants ...TextVariant) Element
- func Scroll(child Element, maxHeight int) Element
- func Select(id string, options []SelectOption, value string, onChange func(string) Msg, ...) Element
- func Sidebar(side, main Element, opts ...func(*SidebarOpts)) Element
- func Spacer(n int) Element
- func Spinner(frame int, opts ...func(*SpinnerEl)) Element
- func Split(panes ...Element) Element
- func TUIOnly(children ...Element) Element
- func Table(columns []string, rows [][]string) Element
- func Text(s string, opts ...func(*TextEl)) Element
- func TextArea(id string, opts ...func(*TextAreaEl)) Element
- func VStack(children ...Element) Element
- func WebOnly(children ...Element) Element
- func When(cond bool, build func() Element) Element
- type EmptyEl
- type FormEl
- type Handler
- type HelpEntry
- type InputMsg
- type KeyMap
- func (k KeyMap) Add(bindings ...Binding) KeyMap
- func (k KeyMap) Bindings() []Binding
- func (k KeyMap) Get(name string) (Binding, bool)
- func (k KeyMap) HelpEntries() []HelpEntry
- func (k KeyMap) HelpView(dir Direction) Element
- func (k KeyMap) Match(msg KeyMsg) (string, bool)
- func (k KeyMap) SetEnabled(name string, enabled bool) KeyMap
- func (k KeyMap) ShortHelp() string
- type KeyMsg
- type LinkEl
- type ListEl
- type Model
- type Msg
- type NavigateMsg
- type NoneMsg
- type Option
- type Pather
- type Platform
- type Program
- type ProgressEl
- type QuitMsg
- type ResizeMsg
- type ResponsiveEl
- type ScrollAreaEl
- type SelectEl
- type SelectOption
- type SidebarOpts
- type SpacerEl
- type SpinnerEl
- type Status
- func (s Status) Empty() bool
- func (s Status) Hide() Status
- func (s Status) Item(it StatusItem) Status
- func (s Status) Left(texts ...string) Status
- func (s Status) Right(texts ...string) Status
- func (s Status) Styled(text string, style Style) Status
- func (s Status) WithSeparator(sep string) Status
- func (s Status) WithStyle(style Style) Status
- type StatusFunc
- type StatusItem
- type Style
- func (s Style) Aligned(a Align) Style
- func (s Style) Bg(c Color) Style
- func (s Style) Bordered(c Color) Style
- func (s Style) Fg(c Color) Style
- func (s Style) Grown(n int) Style
- func (s Style) H(n int) Style
- func (s Style) Mar(v ...int) Style
- func (s Style) MaxH(n int) Style
- func (s Style) MaxW(n int) Style
- func (s Style) Merge(other Style) Style
- func (s Style) MinW(n int) Style
- func (s Style) Pad(v ...int) Style
- func (s Style) PlacedX(a Align) Style
- func (s Style) SetBold(v bool) Style
- func (s Style) SetFaint(v bool) Style
- func (s Style) SetItalic(v bool) Style
- func (s Style) SetStrike(v bool) Style
- func (s Style) SetUnderline(v bool) Style
- func (s Style) W(n int) Style
- type SubmitMsg
- type TableEl
- type TextAreaEl
- type TextEl
- type TextInputEl
- type TextVariant
- type ToggleMsg
Constants ¶
const Fill = -1
Fill, given as Style.Width or Style.Height, sizes an element to the full available space: the terminal in the TUI (minus the status bar row), the viewport in the browser. Intended for top-level layout containers — see Fullscreen, AppShell, Centered.
Variables ¶
This section is empty.
Functions ¶
func AreaDisabled ¶
func AreaDisabled() func(*TextAreaEl)
AreaDisabled marks a TextAreaEl as disabled.
func CheckboxDisabled ¶
func CheckboxDisabled() func(*CheckboxEl)
CheckboxDisabled marks a CheckboxEl as disabled.
func PlatformText ¶
PlatformText returns tui in terminal builds and web in browser builds — the string form of the common case, where only the wording differs between platforms:
wui.Text(wui.PlatformText("press q to quit", "close this tab to quit"))
func PlatformValue ¶
func PlatformValue[T any](tui, web T) T
PlatformValue returns tui in terminal builds and web in browser builds. It is the generic form of PlatformText, for any value type.
func RenderTUI ¶
RenderTUI renders an element tree to the string the TUI renderer would draw, without running a Program: no focus, fresh input state, mouse-zone markers stripped. Intended for snapshot tests of Views. It assumes an 80x24 terminal; use RenderTUISized to pick the size.
func RenderTUISized ¶
RenderTUISized is RenderTUI at an explicit terminal size. Use it to test how a view responds to width — Responsive variants, Sidebar collapse, Fill sizing — without running a Program.
func SelectDisabled ¶
func SelectDisabled() func(*SelectEl)
SelectDisabled marks a SelectEl as disabled.
func SidebarGap ¶
func SidebarGap(n int) func(*SidebarOpts)
SidebarGap sets the gap between the panes.
func SidebarMinMain ¶
func SidebarMinMain(n int) func(*SidebarOpts)
SidebarMinMain sets the main pane width below which the layout collapses to a vertical stack.
func SidebarRight ¶
func SidebarRight() func(*SidebarOpts)
SidebarRight places the sidebar on the right of the main pane.
func SidebarSnug ¶
func SidebarSnug() func(*SidebarOpts)
SidebarSnug keeps the panes side by side at their natural widths rather than stretching the main pane across the whole terminal.
func SidebarWidth ¶
func SidebarWidth(n int) func(*SidebarOpts)
SidebarWidth sets the sidebar's fixed width in cells.
func SpinnerFrames ¶
func SpinnerFrames() int
SpinnerFrames returns the number of distinct spinner glyphs, for apps that want to keep their frame counter bounded.
func Walk ¶
Walk calls fn for el and every descendant, depth-first in tree order. Returning false from fn skips that element's children.
func WithAreaOnChange ¶
func WithAreaOnChange(f func(string) Msg) func(*TextAreaEl)
WithAreaOnChange sets the change handler on a TextAreaEl.
func WithAreaPlaceholder ¶
func WithAreaPlaceholder(p string) func(*TextAreaEl)
WithAreaPlaceholder sets placeholder text on a TextAreaEl.
func WithAreaRows ¶
func WithAreaRows(n int) func(*TextAreaEl)
WithAreaRows sets the visible line count of a TextAreaEl.
func WithAreaStyle ¶
func WithAreaStyle(s Style) func(*TextAreaEl)
WithAreaStyle sets style on a TextAreaEl.
func WithAreaValue ¶
func WithAreaValue(v string) func(*TextAreaEl)
WithAreaValue sets the current value of a TextAreaEl.
func WithButtonStyle ¶
WithButtonStyle sets style on a ButtonEl.
func WithCardStyle ¶
WithCardStyle sets style on a CardEl. Border is implied; Padding, Margin, Width and BorderColor apply.
func WithCheckboxStyle ¶
func WithCheckboxStyle(s Style) func(*CheckboxEl)
WithCheckboxStyle sets style on a CheckboxEl.
func WithDividerStyle ¶
WithDividerStyle sets style on a DividerEl. Width bounds the rule; without it the rule fills the available width.
func WithID ¶
WithID gives a button an explicit stable identity. Without it the focus key derives from the label, so two buttons sharing a label in one view would share focus; an ID also lets the browser restore focus to the button across re-renders.
func WithOnChange ¶
func WithOnChange(f func(string) Msg) func(*TextInputEl)
WithOnChange sets the change handler on a TextInputEl.
func WithOnSubmit ¶
func WithOnSubmit(f func(string) Msg) func(*TextInputEl)
WithOnSubmit sets the submit handler on a TextInputEl (Enter key).
func WithPassword ¶
func WithPassword() func(*TextInputEl)
WithPassword marks a TextInputEl as a password field.
func WithPlaceholder ¶
func WithPlaceholder(p string) func(*TextInputEl)
WithPlaceholder sets placeholder text on a TextInputEl.
func WithProgressLabel ¶
func WithProgressLabel() func(*ProgressEl)
WithProgressLabel appends a percentage readout after the bar.
func WithProgressRunes ¶
func WithProgressRunes(filled, empty string) func(*ProgressEl)
WithProgressRunes overrides the TUI fill and track glyphs. It has no effect in HTML, which draws a real bar.
func WithProgressStyle ¶
func WithProgressStyle(s Style) func(*ProgressEl)
WithProgressStyle sets style on a ProgressEl; FG colors the filled portion.
func WithProgressWidth ¶
func WithProgressWidth(n int) func(*ProgressEl)
WithProgressWidth sets the bar width in cells (pixels-equivalent ch units in HTML).
func WithSelectStyle ¶
WithSelectStyle sets style on a SelectEl.
func WithSpinnerLabel ¶
WithSpinnerLabel sets text shown next to the spinner glyph.
func WithSpinnerStyle ¶
WithSpinnerStyle sets style on a SpinnerEl.
func WithTextStyle ¶
WithTextStyle sets style on a TextEl built via Text.
func WithValue ¶
func WithValue(v string) func(*TextInputEl)
WithValue sets the current value of a TextInputEl.
Types ¶
type AddrFlag ¶
AddrFlag is a flag.Value for optional-address flags such as -serve. It accepts three forms:
(absent) Enabled=false — no web server -serve Enabled=true, Addr="" — pick a free port automatically -serve=:8765 Enabled=true, Addr=":8765"
Because the bare form is allowed, an explicit address must use the "=" syntax ("-serve=:8765", not "-serve :8765").
func ServeFlag ¶
ServeFlag registers an AddrFlag named name on flag.CommandLine and returns it. Call before flag.Parse; afterwards, pass the result to WithWebServer when Enabled:
serve := wui.ServeFlag("serve", "also serve the web build (optionally -serve=:8765)")
flag.Parse()
var opts []wui.Option
if serve.Enabled {
opts = append(opts, wui.WithWebServer(serve.Addr, "path/to/web"))
}
func (*AddrFlag) IsBoolFlag ¶
IsBoolFlag lets the flag package accept the bare form (-serve) with no value.
type BatchMsg ¶
type BatchMsg struct {
Msgs []Msg
}
BatchMsg carries several Msgs produced by Batch. The runtime unpacks it and feeds each Msg through Update in order.
type Binding ¶
type Binding struct {
// Name identifies the binding. It is the ID reported by KeyMap
// lookups and is handy as a Msg payload.
Name string
// contains filtered or unexported fields
}
Binding is a named keyboard shortcut: one or more key names, a short label for help output, and an optional enabled predicate.
Bindings are declarative — they describe intent ("q quits") rather than hard-coding a switch in Update, which lets wui derive help text automatically and lets both platforms share one definition.
var quit = wui.NewBinding("quit", wui.Keys("q", "ctrl+c"), wui.Help("q", "quit"))
func (m model) Update(msg wui.Msg) (wui.Model, wui.Cmd) {
switch v := msg.(type) {
case wui.KeyMsg:
if quit.Matches(v) {
return m, wui.Quit()
}
}
return m, nil
}
func NewBinding ¶
func NewBinding(name string, opts ...BindingOption) Binding
NewBinding creates a named Binding.
func (Binding) HelpKey ¶
HelpKey returns the key text for help output: the explicit Help key when set, else the binding's first key name.
func (Binding) Matches ¶
Matches reports whether msg is one of the binding's keys. A disabled binding matches nothing, so a single `if b.Matches(k)` in Update respects context-sensitive availability without extra conditionals.
func (Binding) MatchesKey ¶
MatchesKey reports whether the binding contains the given key name.
func (Binding) SetEnabled ¶
SetEnabled returns a copy of the binding with its enabled state set. Bindings are values, so context-sensitive availability is expressed by storing the result — typically rebuilt in View or Update:
km.Undo = km.Undo.SetEnabled(len(m.history) > 0)
type BindingOption ¶
type BindingOption func(*Binding)
BindingOption configures a Binding at construction time.
func BindingDisabled ¶
func BindingDisabled() BindingOption
BindingDisabled constructs the Binding in a disabled state: it matches nothing and is hidden from help until SetEnabled(true).
func Help ¶
func Help(key, desc string) BindingOption
Help sets the key text and description shown in help output. key may be a display form covering several bindings ("↑/k"); pass "" to show the binding's first key instead.
func Keys ¶
func Keys(keys ...string) BindingOption
Keys sets the key names a Binding matches. Names use the same normalized vocabulary as KeyMsg.Key ("enter", "ctrl+c", "up", "q").
type BoxEl ¶
type BoxEl struct {
Direction Direction
Gap int
Align Align // cross-axis placement of children (align-items)
Children []Element
Style Style
// Justify distributes children along the Box's main axis
// (justify-content). It needs a resolved main-axis size to work
// against — Style.Width for a Row, Style.Height for a Column —
// and AlignStretch behaves as AlignStart.
Justify Align
// Wrap lets a Row collapse: in HTML it is flex-wrap, in the TUI
// the Row re-lays itself out as a Column when its children do not
// fit the available width. See Sidebar for the ready-made use.
Wrap bool
}
type Breakpoint ¶
type Breakpoint struct {
// MinWidth is the smallest available width, in cells, at which
// Content applies. The variant with the largest satisfied
// MinWidth wins, so breakpoints read like CSS min-width media
// queries: 0 is the fallback for the narrowest case.
MinWidth int
Content Element
}
Breakpoint is one variant of a Responsive element: the content to use when at least MinWidth cells are available.
func At ¶
func At(minWidth int, content Element) Breakpoint
At pairs a minimum available width with the content to show at or above it, for use with Responsive.
type CheckboxEl ¶
type ClickMsg ¶
type ClickMsg struct {
TargetID string
}
ClickMsg is sent when a Link is activated. Buttons instead invoke their own OnClick callback directly.
type Cmd ¶
type Cmd func() Msg
Cmd is a function that produces a Msg asynchronously.
func Batch ¶
Batch runs cmds concurrently and delivers every resulting Msg. nil cmds are skipped; Batch returns nil when nothing is left to run.
func Do ¶
Do runs f in the background and delivers the Msg it returns. It is the plain-function form of a Cmd, for readability at call sites.
func Every ¶
Every delivers the Msg from build once, after the wall clock reaches the next multiple of d. Unlike Tick, successive ticks stay aligned to the clock rather than drifting by the time Update takes — use it for anything displaying a real time.
func Send ¶
Send wraps a value as a Cmd that delivers it immediately. It is the bridge from "I have a Msg" to "Update wants a Cmd":
return m, wui.Send(savedMsg{})
type Color ¶
type Color string
Color is a color value. In TUI it may be a hex string ("#ff0000"), a named ANSI color, or an ANSI index ("9"). In WASM it is passed through as CSS, with ANSI indices 0-15 translated to hex.
type Element ¶
type Element interface {
// contains filtered or unexported methods
}
Element is the renderable unit. Every concrete element type satisfies it; renderers type-switch on the concrete type.
func AlignedX ¶
AlignedX places children horizontally within the full width available — AlignStart (the default) left, AlignCenter middle, AlignEnd right — without taking vertical space. CenteredX is the AlignCenter case.
func AppShell ¶
AppShell is the classic application frame: a header pinned to the top, a footer pinned to the bottom, and a body that takes every line in between. Pass nil (or Empty()) for a part you don't need.
func Card ¶
Card wraps a child in a titled, bordered panel. The TUI draws the title embedded in the top border; HTML renders <fieldset><legend>.
func Centered ¶
Centered centers child both horizontally and vertically in the full terminal or viewport — the login-box / splash-screen layout.
func CenteredX ¶
CenteredX centers children horizontally across the full width available, without claiming any vertical space. Unlike Centered it is safe inside an AppShell body: Centered fills the terminal height and would push the header and footer off screen.
Use it to center a banner, a title, or a hint line within whatever pane it sits in.
func Checkbox ¶
func Checkbox(id, label string, checked bool, onToggle func(bool) Msg, opts ...func(*CheckboxEl)) Element
Checkbox creates a toggleable checkbox with a text label. id must be stable and unique — it identifies the checkbox in the focus ring and the DOM. onToggle receives the new checked state; pass nil to get a generic ToggleMsg instead.
func Children ¶
Children returns el's child elements, or nil for leaves. It is the single place that knows the shape of the tree, so walkers (focus collection, form value gathering, lookups) do not each have to enumerate every container type.
func Constrain ¶
Constrain caps content at an intended width and centers it in whatever space is left over. It is the fix for a layout that looks right at 100 columns and absurd at 400: panes stay together instead of drifting to opposite edges of the screen.
wui.AppShell(header, wui.Constrain(120, body), footer)
Children inside see the capped width, so Sidebar, Split and Responsive all lay out against the intended size rather than the terminal. Below the cap it is a no-op, so narrow terminals are unaffected.
func ConstrainBox ¶
ConstrainBox is Constrain with the placement and layout axis spelled out, for the cases where the content should hug an edge or run as a Row rather than being a centered Column.
func Empty ¶
func Empty() Element
Empty renders nothing. Use it as the "else" branch of a conditional view instead of returning nil.
func Flex ¶
func Flex() Element
Flex inserts stretchy empty space that pushes the siblings on either side apart — the idiom for pinning one child to the far end of a Row. In the TUI it expands to fill the Box's remaining width; in HTML it is flex:1.
func Fullscreen ¶
Fullscreen lays children out top-to-bottom in a Column that fills the whole terminal (minus the status bar) or browser viewport. Use it as the outermost element of an app that should own the screen.
func Group ¶
Group combines children into one Element without adding layout of its own beyond stacking them vertically. Use it where a single Element is required but several must be returned.
func Grow ¶
Grow wraps child in a Box that takes n shares of the leftover space along the parent Box's axis. It is the building block AppShell and Split use; reach for it directly when composing custom layouts.
func If ¶
If renders el when cond holds, and nothing otherwise — so a view can stay a single expression:
wui.Box(wui.Column,
wui.If(m.err != "", wui.Text(m.err)),
wui.Text("ready"),
)
func Input ¶
func Input(id string, opts ...func(*TextInputEl)) Element
Input creates a text input field identified by id.
func Map ¶
Map builds one Element per item — the loop that every View writes by hand, as an expression:
wui.List(false, wui.Map(m.items, func(i int, s string) wui.Element {
return wui.Text(s)
})...)
func OnPlatform ¶
OnPlatform renders tui in terminal builds and web in browser builds. Either may be nil to render nothing on that platform:
wui.OnPlatform(
wui.Text("Tab/Shift+Tab to move, Enter to activate"),
wui.Text("Click anything, or Tab through the page"),
)
func Progress ¶
func Progress(value float64, opts ...func(*ProgressEl)) Element
Progress creates a determinate progress bar. value is clamped to 0..1.
func Responsive ¶
func Responsive(variants ...Breakpoint) Element
Responsive picks the content that fits the width available to it.
Each variant applies from its MinWidth up to the next one; the widest satisfied variant wins. Include a MinWidth of 0 to give the narrowest case a definite answer — without one, a width below every breakpoint falls back to the smallest variant anyway, but stating it is clearer.
wui.Responsive(
wui.At(0, wui.Text("NR")), // very narrow
wui.At(24, wui.Text("NETRUNNER")), // roomier
wui.At(80, bigAsciiLogo), // full width
)
Variants are given in any order; ties on MinWidth keep the first.
func ResponsiveText ¶
func ResponsiveText(style Style, variants ...TextVariant) Element
ResponsiveText is the common case of Responsive over plain strings: the same message written for progressively wider space.
wui.ResponsiveText(style, wui.TextAt(0, "err"), wui.TextAt(40, "connection failed"))
func Select ¶
func Select(id string, options []SelectOption, value string, onChange func(string) Msg, opts ...func(*SelectEl)) Element
Select creates a single-choice picker. id must be stable and unique. In HTML it is a <select>; in the TUI it is a focusable field that cycles through options with left/right (or Space/Enter).
func Sidebar ¶
func Sidebar(side, main Element, opts ...func(*SidebarOpts)) Element
Sidebar places side at fixed width next to a main pane that grows to take the rest. When the viewport is too narrow for both — main would drop under its minimum width — the panes collapse into a vertical stack, sidebar first (browser: flex-wrap; TUI: the Row re-lays itself out as a Column).
func Spacer ¶
Spacer inserts n cells (in a Row) or n blank lines (in a Column) of empty space between siblings.
func Spinner ¶
Spinner creates an activity indicator showing the given animation frame. Advance frame from a Tick Cmd:
case tickMsg:
m.frame++
return m, wui.Tick(100*time.Millisecond, func() wui.Msg { return tickMsg{} })
func Split ¶
Split lays panes side by side, each taking an equal share of the full width. For unequal shares compose Grow directly:
wui.BoxEl{Direction: wui.Row, Style: wui.Style{Width: wui.Fill},
Children: []wui.Element{wui.Grow(2, left), wui.Grow(1, right)}}
func TextArea ¶
func TextArea(id string, opts ...func(*TextAreaEl)) Element
TextArea creates a multi-line text input identified by id.
type EmptyEl ¶
type EmptyEl struct{}
EmptyEl renders nothing. It is what conditional helpers return for a false branch, so callers never have to deal with a nil Element.
type Handler ¶
Handler pairs a Binding with the action it triggers, for apps that prefer table-driven dispatch over a switch on binding names.
type InputMsg ¶
InputMsg is sent when a TextInput's value changes and it has no OnChange callback of its own.
type KeyMap ¶
type KeyMap struct {
// contains filtered or unexported fields
}
KeyMap is an ordered set of Bindings. It gives an app one place to declare its shortcuts, one call to dispatch them, and automatic help rendering.
km := wui.NewKeyMap(
wui.NewBinding("inc", wui.Keys("+", "k"), wui.Help("+/k", "increment")),
wui.NewBinding("quit", wui.Keys("q"), wui.Help("q", "quit")),
)
func KeyMapFrom ¶
KeyMapFrom builds a KeyMap from handlers, preserving order — so one handler table can drive both dispatch and help output.
func NewKeyMap ¶
NewKeyMap creates a KeyMap from bindings, preserving their order — help output lists them as given.
func (KeyMap) HelpEntries ¶
HelpEntries returns a help row for every enabled binding that has a description. Bindings without Help text are skipped — they are implementation details, not user-facing shortcuts.
func (KeyMap) HelpView ¶
HelpView renders the key map as an Element: one dim "key desc" pair per binding, laid out along dir. Row gives a status-bar strip, Column a help panel.
func (KeyMap) Match ¶
Match returns the name of the first enabled binding matching msg. Bindings are tested in declaration order, so earlier entries win when two bindings share a key.
func (KeyMap) SetEnabled ¶
SetEnabled returns a copy of the KeyMap with the named binding's enabled state set. Unknown names are ignored.
type KeyMsg ¶
KeyMsg represents a key press. Key is a normalized name such as "enter", "ctrl+c", "tab", "backspace", or a single printable rune.
type Msg ¶
type Msg interface{}
Msg is the message type for the Elm Update loop. Any value can be a Msg, including application-defined types — analogous to tea.Msg.
type NavigateMsg ¶
type NavigateMsg struct {
}
NavigateMsg is sent in WASM builds when the browser URL hash names a path — on initial load with a "#/path" fragment and on every hashchange (back/forward navigation). TUI programs never receive it. See Pather.
type Option ¶
type Option func(*config)
Option configures a Program at construction time.
func WithKeyMap ¶
WithKeyMap registers the app's key map with the runtime. wui does not dispatch it for you — Update stays the single place where state changes — but registering it means the status bar shows the shortcuts automatically, and Program.KeyMap can be consulted when building a help view.
func WithStatus ¶
func WithStatus(f StatusFunc) Option
WithStatus supplies the status line content, replacing wui's default (the web URL plus the key map's short help). It is called on every frame with the current model:
wui.WithStatus(func(m wui.Model) wui.Status {
return wui.NewStatus().
Left(m.(model).file).
Right(fmt.Sprintf("%d items", len(m.(model).items)))
})
Returning a Status with no items falls back to the default bar; return NewStatus().Hide() to suppress the bar for a frame.
The bar renders in both TUI and WASM builds. In the browser it is a fixed strip at the bottom of the viewport.
func WithTitle ¶
WithTitle sets the application title. In WASM builds it becomes document.title; in the TUI it sets the terminal window title.
func WithWebServer ¶
WithWebServer serves dir — a WASM build of the same app (index.html, main.wasm, wasm_exec.js) — over HTTP for as long as the TUI runs, and displays a status bar at the bottom of the TUI linking to the equivalent web page.
addr is the listen address, e.g. ":8765" (all interfaces) or "127.0.0.1:8765". Pass "" to bind the loopback interface only, on the first free port in 8765–8864 (falling back to an OS-assigned port if the whole range is busy).
It has no effect in WASM builds, so it is safe to pass unconditionally from shared code.
func WithoutAltScreen ¶
func WithoutAltScreen() Option
WithoutAltScreen runs the TUI inline in the terminal's normal buffer instead of the alternate screen, so the final frame stays in the scrollback after exit. It has no effect in WASM builds.
func WithoutBaseCSS ¶
func WithoutBaseCSS() Option
WithoutBaseCSS disables injection of wui's default terminal-like stylesheet in WASM builds. Use it when the host page provides its own styling. It has no effect in TUI builds.
func WithoutMouse ¶
func WithoutMouse() Option
WithoutMouse disables TUI mouse tracking, leaving click and scroll events to the terminal (so text selection works normally). It has no effect in WASM builds.
func WithoutStatusBar ¶
func WithoutStatusBar() Option
WithoutStatusBar suppresses the status line on both platforms, even when WithWebServer or WithKeyMap would otherwise populate it.
type Pather ¶
type Pather interface {
Path() string
}
Pather is an optional interface a Model can implement to expose its current logical location as a path such as "/" or "/settings".
When the TUI runs with WithWebServer, the status bar link points at the equivalent web location ("http://host/#/settings"). In the browser, the path is mirrored into location.hash after every update, and a NavigateMsg is dispatched on initial load and whenever the hash changes (e.g. back/forward navigation), so both platforms stay addressable at the same locations.
type Platform ¶
type Platform int
Platform identifies which renderer is running.
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
Program is the wui runtime. Construct with NewProgram and call Run.
func NewProgram ¶
NewProgram creates a Program for the given model.
type ProgressEl ¶
type ProgressEl struct {
Value float64
Width int // bar width in cells; 0 = default (20)
ShowLabel bool // append " 42%"
Style Style
FilledRune string // TUI fill glyph; defaults to "█"
EmptyRune string // TUI track glyph; defaults to "░"
}
ProgressEl is a determinate progress bar. Value is clamped to 0..1.
type QuitMsg ¶
type QuitMsg struct{}
QuitMsg asks the runtime to shut the program down. Return it from a Cmd (or use Quit) rather than calling os.Exit, so the terminal is restored properly. In WASM builds it stops the event loop; the page itself stays open.
type ResponsiveEl ¶
type ResponsiveEl struct {
// Variants is sorted by ascending MinWidth by Responsive, which
// both renderers rely on.
Variants []Breakpoint
}
ResponsiveEl renders the variant matching the available width. It is built by Responsive; the renderers select from Variants.
type ScrollAreaEl ¶
type SelectEl ¶
type SelectEl struct {
ID string
Options []SelectOption
Value string
OnChange func(value string) Msg
Style Style
Disabled bool
}
SelectEl is a single-choice dropdown (HTML <select>) / cycling picker (TUI: left/right or space cycles the selection).
type SelectOption ¶
SelectOption is one choice in a SelectEl.
func Opt ¶
func Opt(value, label string) SelectOption
Opt builds a SelectOption. Pass an empty label to display the value.
func Options ¶
func Options(values ...string) []SelectOption
Options builds a SelectOption slice from values, using each value as its own label.
type SidebarOpts ¶
type SidebarOpts struct {
Width int // sidebar width in cells; default 24
MinMain int // main pane width below which the layout collapses; default 40
Gap int // cells between sidebar and main; default 2
Right bool // place the sidebar after the main pane
// Snug keeps the main pane at its natural width instead of letting
// it absorb the leftover space. Without it a wide terminal pushes
// the two panes to opposite edges with a gulf between them; with
// it they stay together and the slack falls outside the pair.
Snug bool
}
SidebarOpts configures a Sidebar layout; set it through the With/Sidebar* option functions.
type SpacerEl ¶
type SpacerEl struct {
Size int
}
SpacerEl is flexible empty space inside a Box: Size cells/lines of blank space, or — when Size is 0 — a stretch that pushes the surrounding children apart.
type SpinnerEl ¶
SpinnerEl is an indeterminate activity indicator. Frame selects which glyph of the animation to draw — the app owns the animation clock, so the renderers stay pure. Drive it from a Tick Cmd.
type Status ¶
type Status struct {
Items []StatusItem
// Separator is drawn between adjacent segments on the same side.
// Empty means the default (" │ ").
Separator string
// Style overrides the bar's default appearance (reverse video in
// the TUI, a bordered strip in HTML).
Style Style
// Hidden suppresses the bar entirely for this frame.
Hidden bool
}
Status is the content of the bottom status line: a list of segments plus the separator drawn between them.
wui fills in defaults an app rarely wants to write itself — the web URL when WithWebServer is active, and the key map's short help when WithKeyMap is set — so a status line is usually one option, not a layout problem:
wui.NewProgram(m,
wui.WithKeyMap(keys),
wui.WithStatus(func(m wui.Model) wui.Status {
return wui.NewStatus().Left(m.(model).filename).Right("ln 4")
}),
)
func NewStatus ¶
func NewStatus() Status
NewStatus returns an empty Status, as the head of a builder chain.
func (Status) Item ¶
func (s Status) Item(it StatusItem) Status
Item appends a fully specified segment.
func (Status) WithSeparator ¶
WithSeparator sets the text drawn between adjacent segments.
type StatusFunc ¶
StatusFunc builds the status line for the current model state. It is called on every frame, after Update.
type StatusItem ¶
type StatusItem struct {
// Text is the segment's content.
Text string
// Style overrides the bar's default styling for this segment.
Style Style
// Right pins the segment to the right-hand end of the bar. Items
// keep their declared order within each side.
Right bool
}
StatusItem is one segment of the status line.
type Style ¶
type Style struct {
FG Color
BG Color
Bold bool
Italic bool
Underline bool
Faint bool
Strike bool
Padding [4]int // top, right, bottom, left
Margin [4]int // top, right, bottom, left
Width int // 0 = auto, Fill = all available width
Height int // 0 = auto, Fill = all available height
Border bool
BorderColor Color
Align Align // text alignment within Width; AlignStart = left
// Grow is the element's flex-grow share when it is a direct child
// of a Box: leftover space along the Box's axis is split between
// growing children in proportion to their Grow values. 0 = fixed.
Grow int
// MinWidth floors the element's width in cells. With Grow it sets
// the smallest acceptable size; in a wrapping Box it is the
// threshold below which the row collapses to a column.
MinWidth int
// MaxWidth caps the element's width in cells, so a Fill layout
// stops growing once it reaches its intended size instead of
// stretching across a very wide terminal. It also caps the width
// children see, so everything inside lays out against the cap
// rather than the screen. 0 = uncapped.
//
// Pair it with Align to place the capped block in the leftover
// space; Constrain is the ready-made centered version.
MaxWidth int
// MaxHeight caps the element's height in rows: the vertical
// counterpart of MaxWidth. 0 = uncapped.
MaxHeight int
// PlaceX positions a MaxWidth-capped element within the space it
// was given but did not use. It is distinct from Align, which
// positions content *inside* the element: a block can be centered
// on screen while its own text stays left-aligned. Ignored without
// MaxWidth. AlignStart (the default) keeps the block flush left.
PlaceX Align
}
Style holds presentation properties shared by both renderers. Width/Height are terminal cells in TUI and pixels in WASM.
The zero Style is "no styling". Build styles by composition rather than by filling the struct literal by hand:
wui.NewStyle().Bold().FG("6").Pad(1, 2)
func NewStyle ¶
func NewStyle() Style
NewStyle returns the zero Style, as the head of a builder chain.
func (Style) Aligned ¶
Aligned returns a copy with text alignment set. It positions content inside the style's Width, so it has no visible effect without one.
func (Style) Bordered ¶
Bordered returns a copy with a border in the given color. Pass "" to use the current foreground color.
func (Style) Grown ¶
Grown returns a copy with the flex-grow share set. It only has an effect on direct children of a Box.
func (Style) MaxW ¶
MaxW returns a copy with the maximum width set: the element stops growing at n cells however wide the terminal is.
func (Style) Merge ¶
Merge returns a copy of s with every non-zero field of other applied on top. Use it to layer a variant over a base style:
danger := base.Merge(wui.Style{FG: "9", Bold: true})
Boolean attributes are additive — Merge can set them but never clears one already set in s.
func (Style) Pad ¶
Pad returns a copy with padding set CSS-style: one value applies to all sides, two are vertical/horizontal, three are top/horizontal/ bottom, four are top/right/bottom/left. Other counts are ignored.
func (Style) PlacedX ¶
PlacedX returns a copy with the placement of a MaxWidth-capped element within its leftover space set.
func (Style) SetUnderline ¶
Underline returns a copy with underline set.
type SubmitMsg ¶
SubmitMsg is sent when a Form is submitted and it has no OnSubmit callback of its own.
type TextAreaEl ¶
type TextAreaEl struct {
ID string
Value string
Placeholder string
Rows int // visible lines; 0 = default (4)
OnChange func(string) Msg
Style Style
Disabled bool
}
TextAreaEl is a multi-line text input.
type TextInputEl ¶
type TextVariant ¶
TextVariant is one string of a ResponsiveText.
func TextAt ¶
func TextAt(minWidth int, content string) TextVariant
TextAt pairs a minimum available width with the string to show at or above it, for use with ResponsiveText.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
serve
command
Command serve is a static file server for wui WASM web builds.
|
Command serve is a static file server for wui WASM web builds. |
|
example
|
|
|
counter
command
Command counter is a minimal wui example: buttons that adjust a count, rendering identically as a TUI or in a WASM build.
|
Command counter is a minimal wui example: buttons that adjust a count, rendering identically as a TUI or in a WASM build. |
|
dashboard
command
Command dashboard exercises the framework features that make wui pleasant to build with: declarative key bindings with generated help, a custom status line, platform-conditional content, and the layout and feedback elements (Divider, Spacer, Progress, Spinner, Select, TextArea).
|
Command dashboard exercises the framework features that make wui pleasant to build with: declarative key bindings with generated help, a custom status line, platform-conditional content, and the layout and feedback elements (Divider, Spacer, Progress, Spinner, Select, TextArea). |
|
form
command
Command form demonstrates wui text inputs, form submission, and rendering a results table — works identically as TUI or WASM.
|
Command form demonstrates wui text inputs, form submission, and rendering a results table — works identically as TUI or WASM. |
|
layout
command
Command layout demonstrates the layout helpers: an AppShell frame with a collapsing Sidebar, a Split pair of panels, and a Centered login screen — switchable at runtime to compare them.
|
Command layout demonstrates the layout helpers: an AppShell frame with a collapsing Sidebar, a Split pair of panels, and a Centered login screen — switchable at runtime to compare them. |
|
timer
command
Command timer is a stopwatch demonstrating Cmd-driven async work (self-rescheduling ticks) — identical in TUI and WASM builds.
|
Command timer is a stopwatch demonstrating Cmd-driven async work (self-rescheduling ticks) — identical in TUI and WASM builds. |
|
todo
command
Command todo demonstrates lists, scroll areas, per-item buttons, and clearing an input programmatically after submit — identical in TUI and WASM builds.
|
Command todo demonstrates lists, scroll areas, per-item buttons, and clearing an input programmatically after submit — identical in TUI and WASM builds. |
|
Package webserver provides the listener and URL helpers wui uses to serve WASM web builds.
|
Package webserver provides the listener and URL helpers wui uses to serve WASM web builds. |