Documentation
¶
Overview ¶
Package deck is the bubbletea runtime for viewkit.
Invariant: tea lives ONLY in this package — viewkit core (glyph/theme/layout/panels/…) must not import bubbletea. Apps and plugins implement View and register via RegisterView; Model owns stack navigation + chrome.
Rendering context is a ui.Scope (theme, keys, glyphs) passed via WithScope and swapped with Model.SetScope; there is no process-global theme or scheme. Contribution registries (theme.Register / keys.Register / RegisterView) and the glyph default mode (glyph.SetMode, write-once) remain process level.
See INTERFACE.md for the Model + scope contract.
Index ¶
- Constants
- Variables
- func ComponentKeys() []string
- func Confirm(spec ConfirmSpec) (bool, error)
- func ErrorReported(err error) bool
- func Prompt(spec PromptSpec) (map[string]any, error)
- func RegisterComponent(id string, ctor func() Component) bool
- func RegisterView(id string, ctor func() View) bool
- func Run(root View, opts ...Option) error
- func ViewKeys() []string
- type AnimatedResults
- type Chrome
- type Component
- type ConfirmSpec
- type Content
- type ContentFunc
- type Editor
- func (e *Editor) Body(frame layout.Frame) string
- func (e *Editor) Confirming() bool
- func (e *Editor) Context(scope *ui.Scope) []keys.Hint
- func (e *Editor) Form() *forms.Form
- func (e *Editor) Hints(scope *ui.Scope) []keys.Hint
- func (e *Editor) Init() tea.Cmd
- func (e *Editor) Notice() []string
- func (e *Editor) OnResults() bool
- func (e *Editor) Remembered() map[string]any
- func (e *Editor) Running() bool
- func (e *Editor) Selected() (list.Item, bool)
- func (e *Editor) SelectedOf(key string) int
- func (e *Editor) Status() string
- func (e *Editor) Title() string
- func (e *Editor) Update(a *Model, msg tea.Msg) tea.Cmd
- func (e *Editor) Value(key string) string
- type EditorDoc
- type EditorKeys
- type EditorOutput
- type ErrorCounter
- type FormKeys
- type FormSpec
- type FormView
- func (v *FormView) Body(f layout.Frame) string
- func (v *FormView) Context(scope *ui.Scope) []keys.Hint
- func (v *FormView) Hints(scope *ui.Scope) []keys.Hint
- func (v *FormView) Init() tea.Cmd
- func (v *FormView) Status(msg string)
- func (v *FormView) Title() string
- func (v *FormView) Update(a *Model, msg tea.Msg) tea.Cmd
- func (v *FormView) Values() map[string]any
- type HomeShell
- func (h *HomeShell) Body(f layout.Frame) string
- func (h *HomeShell) Context(scope *ui.Scope) []keys.Hint
- func (h *HomeShell) FocusSide() bool
- func (h *HomeShell) Hints(scope *ui.Scope) []keys.Hint
- func (h *HomeShell) Init() tea.Cmd
- func (h *HomeShell) Reload() tea.Cmd
- func (h *HomeShell) Title() string
- func (h *HomeShell) Update(host *Model, msg tea.Msg) tea.Cmd
- type HomeShellSpec
- type Inline
- type InlinePanel
- type InlineSpec
- type InlineState
- type ItemList
- func (r *ItemList) Body(f layout.Frame) string
- func (r *ItemList) Context(scope *ui.Scope) []keys.Hint
- func (r *ItemList) Hints(scope *ui.Scope) []keys.Hint
- func (r *ItemList) Init() tea.Cmd
- func (r *ItemList) Reload() tea.Cmd
- func (r *ItemList) Selected() (list.Item, bool)
- func (r *ItemList) Title() string
- func (r *ItemList) Update(h *Model, msg tea.Msg) tea.Cmd
- type ItemListSpec
- type Job
- type KeyHook
- type Menu
- type MenuItem
- type Message
- type Model
- func (h *Model) Height() int
- func (h *Model) Init() tea.Cmd
- func (h *Model) Pop() tea.Cmd
- func (h *Model) Push(v View) tea.Cmd
- func (h *Model) RefreshStatus() tea.Cmd
- func (h *Model) SetScope(scope *ui.Scope) tea.Cmd
- func (h *Model) SetStatus(info StatusInfo)
- func (h *Model) Top() View
- func (h *Model) UI() *ui.Scope
- func (h *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)
- func (h *Model) View() string
- func (h *Model) Width() int
- type MsgHook
- type Option
- func WithChrome(c Chrome) Option
- func WithInitCmd(cmd tea.Cmd) Option
- func WithKeyHook(fn KeyHook) Option
- func WithKeyMapQuit() Option
- func WithMsgHook(fn MsgHook) Option
- func WithQuitCheck(fn func(string) bool) Option
- func WithQuitHint(glyph string) Option
- func WithScope(scope *ui.Scope) Option
- func WithStatus(fn StatusFunc) Option
- func WithoutClock() Option
- type PromptSpec
- type ReloadMsg
- type Results
- type Resumer
- type Scroll
- func (c *Scroll) Body(f layout.Frame) string
- func (c *Scroll) Context(scope *ui.Scope) []keys.Hint
- func (c *Scroll) Hints(scope *ui.Scope) []keys.Hint
- func (c *Scroll) Init() tea.Cmd
- func (c *Scroll) Reload() tea.Cmd
- func (c *Scroll) Title() string
- func (c *Scroll) Update(h *Model, msg tea.Msg) tea.Cmd
- type ScrollBody
- type ScrollSpec
- type ServiceStatus
- type StatusFunc
- type StatusInfo
- type Text
- type Toaster
- func (t *Toaster) Active() bool
- func (t *Toaster) Body(f layout.Frame, body string) string
- func (t *Toaster) Current() (notify.Notification, bool)
- func (t *Toaster) Len() int
- func (t *Toaster) Prune()
- func (t *Toaster) Push(n notify.Notification) tea.Cmd
- func (t *Toaster) PushFor(n notify.Notification, ttl time.Duration) tea.Cmd
- func (t *Toaster) SetOverlayPos(pos layout.OverlayPos)
- func (t *Toaster) Snapshot() []notify.Notification
- func (t *Toaster) Tick() tea.Cmd
- func (t *Toaster) Update(msg tea.Msg) (cmd tea.Cmd, handled bool)
- type View
- type Work
Examples ¶
Constants ¶
const InlineClear keys.Action = "inline.clear"
InlineClear is the action that clears an Inline text response. The default binding is ctrl+u when not already used by the scoped editor map; override it through InlineSpec.Keys.
Variables ¶
var ErrCancelled = errors.New("prompt cancelled")
ErrCancelled reports that the user dismissed a prompt without submitting.
Functions ¶
func ComponentKeys ¶ added in v0.2.0
func ComponentKeys() []string
ComponentKeys returns registered component ids sorted.
func Confirm ¶
func Confirm(spec ConfirmSpec) (bool, error)
Confirm runs a yes/no tea prompt and returns whether the user confirmed. Besides the scope's scheme, y/Y and n/N always answer directly.
func ErrorReported ¶ added in v0.4.0
ErrorReported reports whether err (possibly wrapped) has already been displayed by Inline.Report. CLIs can suppress a duplicate stderr message while retaining their nonzero exit status and errors.Is/errors.As identity.
func Prompt ¶ added in v0.1.9
func Prompt(spec PromptSpec) (map[string]any, error)
Prompt runs spec as a standalone tea program and returns the entered values. A user cancel returns ErrCancelled; a nil Fields is an error.
func RegisterComponent ¶
RegisterComponent registers ctor under id. First registration wins; duplicate, empty, or nil registrations change nothing and return false.
func RegisterView ¶
RegisterView registers ctor under id. First registration wins; duplicate, empty, or nil registrations change nothing and return false.
Types ¶
type AnimatedResults ¶ added in v0.2.3
AnimatedResults is an optional Results extension for result rows whose presentation changes over time. Advance moves to the next frame and reports whether the Editor should keep scheduling animation ticks.
type Chrome ¶
Chrome configures brand/header appearance. Apps inject product branding; viewkit/deck never hard-codes app names.
type Component ¶
Component is a reusable UI fragment registered by id. Components are not full Views — they paint a region when asked.
func NamedComponent ¶ added in v0.2.0
NamedComponent returns a fresh Component for id.
type ConfirmSpec ¶ added in v0.2.1
type ConfirmSpec struct {
Title string
Message string
YesLabel string
NoLabel string
// UI is the rendering scope; nil snapshots the process defaults.
UI *ui.Scope
}
ConfirmSpec configures a one-shot yes/no prompt.
type Content ¶
type Content interface {
// Render returns the painted body for the given frame (may ignore it).
Render(f layout.Frame) string
}
Content is domain-agnostic job/panel body text. Apps adapt their types (e.g. domain section trees) into Content before crossing into deck.
type ContentFunc ¶
ContentFunc adapts a function to Content.
type Editor ¶ added in v0.1.6
type Editor struct {
// contains filtered or unexported fields
}
Editor is a two-pane View: an editable form above a scrollable result list. When the terminal is too short it collapses the results, then the form, to a one-line summary rather than overflowing.
func NewEditor ¶ added in v0.1.6
func NewEditor(doc EditorDoc, km EditorKeys, seed map[string]any) *Editor
NewEditor builds an Editor over doc. seed pre-fills the form and is carried across rebuilds when doc.Sync reports true.
func (*Editor) Body ¶ added in v0.1.6
Body implements View. When both panes exceed the height budget it collapses the unfocused pane — then both — to one-line summaries, and it overlays the delete-confirm dialog when that is open.
func (*Editor) Confirming ¶ added in v0.1.6
Confirming reports whether the delete dialog is open.
func (*Editor) Form ¶ added in v0.1.6
Form exposes the live form. Its Values() covers only currently rendered fields; use Remembered when Sync() rebuilds may have dropped some.
func (*Editor) Hints ¶ added in v0.1.6
Hints implements View. The legend follows the current mode: delete confirmation, results pane, suggestion completion, or plain form editing.
func (*Editor) OnResults ¶ added in v0.1.6
OnResults reports whether focus is on the results pane rather than the form.
func (*Editor) Remembered ¶ added in v0.1.13
Remembered returns every value the Editor is carrying, including those of fields a later rebuild stopped rendering. Live form values win over remembered ones. A document whose field set shrinks reads this rather than Form().Values() when it must not silently discard what is still held.
func (*Editor) SelectedOf ¶ added in v0.1.6
SelectedOf returns the chosen option index of the select field under key, or -1 when no such field exists.
func (*Editor) Status ¶ added in v0.1.6
Status is the error line shown beneath the form, or "" when clear.
type EditorDoc ¶ added in v0.1.6
type EditorDoc interface {
// Kind names the document type for messages, e.g. "query".
Kind() string
// Title heads the form panel.
Title() string
// Context supplies the chrome context pairs.
Context() []keys.Hint
// SavedName is the persisted name, or "" when never saved. Delete and
// the delete hint are suppressed while it is empty.
SavedName() string
// Fields builds the form, seeded from previously entered values.
Fields(prev map[string]any) []forms.Field
// Sync reports whether editing a field should rebuild the whole form,
// for documents whose field set depends on earlier answers.
Sync() bool
// Summary is the one-line description shown when the form is collapsed.
Summary() string
// PreviewLines renders the document for the yaml-style preview panel.
PreviewLines(f layout.Frame) []string
// ValidateLines checks the document and returns display lines for the
// validation panel. A non-nil error means the document could not be
// built at all, and is surfaced as the status line instead.
ValidateLines(f layout.Frame) ([]string, error)
// Run executes the document. The returned loader runs off the UI
// goroutine, so it must not touch the doc.
Run() (label string, load func() Results, err error)
// Persist saves the document and returns a confirmation summary.
Persist() (summary string, err error)
// Remove deletes the saved document. A non-nil error lands in the
// status line, like Persist.
Remove() (summary string, err error)
}
EditorDoc is the document an Editor edits. Implementations own all domain concerns — parsing, validation, persistence — and hand the Editor only strings, form fields and Results.
type EditorKeys ¶ added in v0.1.6
type EditorKeys struct {
// Map resolves keys while the form or results pane has focus.
Map *keys.Map
// Confirm resolves keys while the delete dialog is open.
Confirm *keys.Map
Run keys.Action
Save keys.Action
Validate keys.Action
Preview keys.Action
Delete keys.Action
Focus keys.Action
// Copy and Write drive EditorOutput. Leave them empty for documents that
// produce no text.
Copy keys.Action
Write keys.Action
}
EditorKeys binds an Editor's commands to a host application's key scheme. Actions are supplied by the caller because command vocabularies are app-specific; only Cancel and the navigation actions come from viewkit.
type EditorOutput ¶ added in v0.1.11
type EditorOutput interface {
// CopyOutput puts the last run's text on the clipboard.
CopyOutput() (summary string, err error)
// WriteOutput persists the last run's text and names where it landed.
WriteOutput() (summary string, err error)
}
EditorOutput is an optional EditorDoc extension for documents whose run produces text worth taking away — a rendered report, a generated file. An Editor offers Copy and Write only when its doc implements this and the host bound the matching keys, so documents without an output are unaffected.
type ErrorCounter ¶ added in v0.2.1
type ErrorCounter interface {
Errored() int
}
ErrorCounter is an optional Results extension: error records are excluded from the collapsed item count.
type FormKeys ¶ added in v0.1.6
type FormKeys struct {
// Map resolves keys while the form has focus. A nil Map falls back to the
// scope's editor bindings (navigation, confirm, cancel, erase, paging),
// resolved fresh on every key so a scheme swap still applies.
Map *keys.Map
// Save is the action that triggers OnSubmit. Leave it empty for a form
// with no save command (submit then only happens through OnKey).
Save keys.Action
}
FormKeys binds a FormView's commands to a host application's key scheme. Only cancel comes from viewkit's vocabulary (keys.Cancel, resolved through Map); the save action is supplied by the caller because command vocabularies are app-specific — an app may name it "app.save" and bind it to ctrl+s, or name it something else entirely. This mirrors EditorKeys.
type FormSpec ¶ added in v0.1.6
type FormSpec struct {
// Fields build the form, in display order.
Fields []forms.Field
// Keys binds cancel and save.
Keys FormKeys
// Title heads the breadcrumb trail. TitleFunc wins when both are set,
// for views whose title depends on state ("new role" vs "edit role").
Title string
// TitleFunc computes the title on every read.
TitleFunc func() string
// PanelTitle heads the rendered form panel. Defaults to the view title,
// which is what most forms want; set it when the panel wants a longer
// caption than the breadcrumb.
PanelTitle string
// Context supplies chrome context cues. ContextFunc wins when both are
// set; use it when the cues can change while the form is open.
Context []keys.Hint
// ContextFunc computes context cues on every read.
ContextFunc func() []keys.Hint
// Hints overrides the footer legend. When nil, the legend is derived from
// Keys: field movement, value change, and the save binding.
Hints []keys.Hint
// OnSubmit runs on the save action with the form's current values. It
// receives the Model so it can Pop back and Push a result view. A nil
// OnSubmit makes save a no-op.
OnSubmit func(a *Model, vals map[string]any) tea.Cmd
// OnKey sees every key before the form does. Return handled=true to
// suppress all default handling — including cancel, save and text entry —
// which is how a view adds its own commands (delete, preview) on top of
// the shared form behaviour.
OnKey func(a *Model, key tea.KeyMsg) (cmd tea.Cmd, handled bool)
// OnMsg sees every message before anything else, keys included. Views
// whose save runs as a tea.Cmd use it to catch the completion message and
// either Pop or Status the error.
OnMsg func(a *Model, msg tea.Msg) (cmd tea.Cmd, handled bool)
}
FormSpec configures a FormView. Every field beyond Fields is optional, and most views set only two or three of them; a struct keeps those call sites readable and lets the type grow a knob without breaking anyone, which a ten-argument constructor could not.
type FormView ¶ added in v0.1.6
type FormView struct {
// contains filtered or unexported fields
}
FormView is a single-panel form View: the boilerplate sibling of Menu, Message and Scroll. It owns the form, key routing (cancel pops, save calls back, everything else is navigation or text entry) and an error line under the panel. Domain concerns stay in the spec's callbacks.
func NewFormView ¶ added in v0.1.6
NewFormView builds a form View from spec.
func (*FormView) Body ¶ added in v0.1.6
Body renders the form panel, with the status line appended when set.
func (*FormView) Hints ¶ added in v0.1.6
Hints reports the footer legend: the spec's override, else one derived from the bound keys so the legend cannot advertise a binding the view ignores.
func (*FormView) Status ¶ added in v0.1.6
Status sets the error line shown beneath the form; "" clears it.
type HomeShell ¶
type HomeShell struct {
// contains filtered or unexported fields
}
HomeShell is a dual-pane View: navigable menu + optional side Item list. SideFetch/SideBind keep domain types out of deck (caller maps → list.Item).
func NewHomeShell ¶
func NewHomeShell(spec HomeShellSpec) *HomeShell
NewHomeShell builds a HomeShell from spec.
func (*HomeShell) Body ¶
Body implements View: the menu box, then the side list sized to the remaining height when a side pane is configured.
func (*HomeShell) FocusSide ¶
FocusSide reports whether the side pane has keyboard focus (for tests/adapters).
func (*HomeShell) Init ¶
Init implements View, starting the side fetch when a side pane is configured.
type HomeShellSpec ¶ added in v0.2.0
type HomeShellSpec struct {
// Title heads the breadcrumb trail.
Title string
// Ctx supplies chrome context cues.
Ctx []keys.Hint
// Items are the menu rows.
Items []MenuItem
// BoxTitle is the menu TitledBox title. Empty (default) omits the title.
BoxTitle string
// SideLabel is shown above the side list when SideFetch is set.
SideLabel string
// SideLabelFn, when set, supplies the side label on every read instead of
// SideLabel — the shape a long-lived shell needs when the side pane's
// subject can change beneath it. Returning "" hides the side pane.
SideLabelFn func() string
// SideHint is the tab-target label when menu-focused (default "side").
SideHint string
// SideFetch loads opaque side content once (nil disables the side pane).
SideFetch func() any
// SideBind maps fetched data → rows using current width.
SideBind func(width int, fetched any) []list.Item
// SideLoading shown while SideFetch has not completed (default "░▒▓ loading…").
SideLoading string
// ReloadHint is the footer label for the reload key (default "reload").
ReloadHint string
// IsAction maps a key string to a keys.Action. It is consulted first; keys
// it does not claim fall back to the active scheme map (keys.Cur), so
// paging and pane switching keep working without re-mapping them.
IsAction func(string) (keys.Action, bool)
// OnOpen overrides browser.Open when a side item Key is opened.
OnOpen func(url string) error
// OnSelect handles Confirm on the highlighted side row. The full item is
// passed so its Payload (and Key) are available without a side table.
OnSelect func(h *Model, it list.Item) tea.Cmd
}
HomeShellSpec configures a HomeShell, following the FormSpec pattern: every field beyond Title and Items is optional. SideLabel empty + SideFetch nil → menu-only shell.
type Inline ¶ added in v0.4.0
type Inline struct {
// contains filtered or unexported fields
}
Inline renders one workflow panel at a time, in normal terminal scrollback (never the alternate screen). Panel, Ask, and Report replace the preceding view only when both streams are terminals and output supports ANSI. Plain, dumb-terminal, and redirected streams are append-only transcripts.
An Inline owns its terminal region. Use it sequentially from one goroutine, do not nest it inside a deck session, and call Release before any other code writes to its output. It does not install global theme or key state.
Example ¶
var transcript bytes.Buffer
flow := NewInline(InlineSpec{
Input: strings.NewReader("workspace\n"), Output: &transcript, Plain: true,
})
if err := flow.Panel("Workspace", "Choose a local directory."); err != nil {
return
}
path, err := flow.Ask(context.Background(), "Workspace", "Directory", ".")
if err != nil {
_ = flow.Report(err)
return
}
flow.Release() // hand output back to the caller without erasing it later
fmt.Println(path)
Output: workspace
func NewInline ¶ added in v0.4.0
func NewInline(spec InlineSpec) *Inline
NewInline constructs a workflow without reading input or writing output.
func (*Inline) Ask ¶ added in v0.4.0
Ask collects one text response in the current panel, retaining instructions when title matches the preceding Panel. The value is an editable default, not a secret: it is displayed in clear text. Cancellation returns ErrCancelled. Scripted input accepts an empty line as the default and a final nonempty line without a newline. EOF without an answer returns io.EOF.
Context cancellation interrupts the interactive program. Arbitrary fallback readers cannot be interrupted: ctx is checked before and after a line read.
func (*Inline) Panel ¶ added in v0.4.0
Panel replaces the current view, or appends it to a transcript. All strings are untrusted text: terminal control sequences are stripped. A matching Ask retains these instructions inside the same panel.
func (*Inline) Reader ¶ added in v0.4.0
Reader returns the input stream for an external command after Release. For transcripts it includes any bytes buffered by Ask. Do not bypass this reader when handing scripted input to a child process.
func (*Inline) Release ¶ added in v0.4.0
func (u *Inline) Release()
Release relinquishes the current terminal region without erasing it. Call before external command output or other writers; the next Panel must not erase that output. Instructions are forgotten as well.
func (*Inline) Report ¶ added in v0.4.0
Report displays err inside the current panel and returns a marked error preserving its identity. Nil and already-reported errors are unchanged. If rendering fails, both errors are returned, without marking either reported. Error strings are shown verbatim as text; callers must redact secrets first.
type InlinePanel ¶ added in v0.5.1
type InlinePanel struct {
Title string
Lines []string
Width int
State InlineState
}
InlinePanel is the neutral input to a custom workflow renderer. Title and Lines contain sanitized text; Lines are wrapped to the preferred body width. Width includes the four columns reserved for default panel chrome.
type InlineSpec ¶ added in v0.4.0
type InlineSpec struct {
// Input and Output default to os.Stdin and os.Stdout.
Input io.Reader
Output io.Writer
// UI defaults to a snapshot of the built-in rendering scope.
UI *ui.Scope
// Width is the preferred body width, excluding the four columns of panel
// chrome. Zero uses layout.DocumentFrame's width. Terminal width caps it.
Width int
// Plain disables panels, cursor movement, and interactive editing.
Plain bool
// AppendOnly keeps completed panels in scrollback even on terminals.
// The active text prompt still edits and redraws interactively.
AppendOnly bool
// Render replaces the default panel presentation. It must be a pure
// renderer, fit within InlinePanel.Width, and return no trailing newline.
// It is not called in Plain mode or on terminals narrower than 5 cells.
// ANSI styles are allowed; terminal control commands are not. The host
// strips ANSI unless output supports it or AllowANSI is true.
Render func(InlinePanel) string
// AllowANSI preserves renderer styles even for redirected/dumb output
// (for example, an application's forced-color option). It never enables
// interaction or cursor movement, and Plain still strips all ANSI.
AllowANSI bool
// Keys overrides the text editor map, including submit and cancel. Nil
// uses text-safe scoped confirm/cancel/quit/erase and ctrl+u to clear.
Keys *keys.Map
}
InlineSpec configures a sequential, inline CLI workflow. Domain checks, validation, persistence, and external commands belong to the caller.
type InlineState ¶ added in v0.5.1
type InlineState uint8
InlineState identifies the lifecycle of a rendered workflow panel.
const ( // InlineContent is a caller-supplied panel, with no implied status. InlineContent InlineState = iota // InlineEditing is a text prompt awaiting a response. InlineEditing // InlineSubmitted is the final view of a submitted prompt. InlineSubmitted // InlineCancelled is the final view of a cancelled prompt. InlineCancelled // InlineError is an error displayed by Report. InlineError )
type ItemList ¶
type ItemList struct {
// Fetch loads opaque content once. Exported so hosts can wrap or replace
// the loader after construction (e.g. tests counting fetches).
Fetch func() any
// OnOpen overrides browser.Open when an item Key is opened.
OnOpen func(url string) error
// OnSelect handles Confirm on the highlighted row.
OnSelect func(h *Model, it list.Item) tea.Cmd
// contains filtered or unexported fields
}
ItemList is a lazy-loaded selectable list View. Fetch runs once on Init; Bind maps fetched data → rows using the current width so callers can width-wrap without importing domain types into deck.
func NewItemList ¶
func NewItemList(spec ItemListSpec) *ItemList
NewItemList builds an ItemList from spec.
func (*ItemList) Init ¶
Init implements View, kicking off Fetch — or reporting an immediate empty load when there is nothing to fetch.
func (*ItemList) Reload ¶ added in v0.1.11
Reload drops fetched content and re-runs Fetch, showing the loading text until the new data lands. No-op when there is nothing to fetch.
type ItemListSpec ¶ added in v0.2.0
type ItemListSpec struct {
// Title heads the breadcrumb trail.
Title string
// Ctx supplies chrome context cues.
Ctx []keys.Hint
// Fetch loads opaque content once on Init (optional if Bind alone is enough).
Fetch func() any
// Bind turns fetched data into list rows. Called on each refresh after load.
Bind func(width int, fetched any) []list.Item
// IsCancel reports whether a key string should pop the view.
IsCancel func(string) bool
// IsAction maps a key string to a keys.Action. It is consulted first; keys
// it does not claim fall back to the active scheme map (keys.Cur), so
// paging and navigation keep working without re-mapping them.
IsAction func(string) (keys.Action, bool)
// OnOpen overrides browser.Open when an item Key is opened.
OnOpen func(url string) error
// OnSelect handles Confirm on the highlighted row. The full item is passed
// so its Payload (and Key) are available without a side table.
OnSelect func(h *Model, it list.Item) tea.Cmd
// LoadingText shown before load completes (default "░▒▓ loading…").
LoadingText string
// ReloadHint is the footer label for the reload key (default "reload").
ReloadHint string
}
ItemListSpec configures an ItemList, following the FormSpec pattern: every field beyond Title is optional, and a struct keeps the call sites readable while letting the type grow a knob without breaking anyone.
type Job ¶ added in v0.1.5
Job is one unit of work. Run must be safe for concurrent execution; return Content (never domain types).
type KeyHook ¶
KeyHook handles a key before the top view. Return handled=true to skip view Update (and optionally a Cmd such as Push).
type Menu ¶
type Menu struct {
// contains filtered or unexported fields
}
Menu is a simple navigable list View.
type MenuItem ¶
type MenuItem struct {
Label string
Desc string
Icon string
Hue int
// OnSelect runs when the row is confirmed.
OnSelect func(m *Model) tea.Cmd
}
MenuItem is one row in a Menu.
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
Message is a dismissible text View.
func NewError ¶ added in v0.2.0
NewError builds a Message that renders err in the theme's failure style — the standard error screen, so hosts stop hand-rolling Cant.Render(err). Styling is deferred to Body so the render-time scope applies.
func NewMessage ¶
NewMessage builds a Message view.
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model is the tea root: the stateful Bubble Tea program root for deck, owning the navigable view stack, injectable chrome, and the async status strip. It implements tea.Model (Init / Update / View).
Contract:
- One Model owns one tea.Program for a deck session.
- Views receive *Model in Update so they can Push/Pop and read size.
- Domain state lives in View implementations (or app kits), not in Model.
func (*Model) Init ¶ added in v0.2.0
Init implements tea.Model: it starts the clock tick, the root view's Init, the status fetch when installed, and any WithInitCmd commands.
func (*Model) Pop ¶ added in v0.2.0
Pop leaves the current view (quits on root). The view it uncovers gets Resume when it implements Resumer, so stale data can be refetched.
func (*Model) RefreshStatus ¶ added in v0.2.0
RefreshStatus reloads the status strip via the installed StatusFunc. Same path as the periodic refresh ticker; no-op when WithStatus was not set.
func (*Model) SetScope ¶ added in v0.2.2
SetScope swaps the rendering scope and returns the resize command that makes every view rebind; run it, or the top view keeps its old styles. Scopes are immutable — always swap, never mutate.
func (*Model) SetStatus ¶ added in v0.2.0
func (h *Model) SetStatus(info StatusInfo)
SetStatus applies chrome status immediately (tests / non-async hosts).
func (*Model) Update ¶ added in v0.2.0
Update implements tea.Model. Chrome concerns — resize, clock, status, quit keys and installed hooks — are handled here; everything else routes to the top view, except an ownedMsg, which goes to its recipient even when that view is no longer on top.
type MsgHook ¶ added in v0.1.4
MsgHook handles a non-key message before the top view. Return handled=true to skip view Update (e.g. debounced role-lifecycle settle).
type Option ¶
type Option func(*Model)
Option configures Model.
func WithInitCmd ¶ added in v0.1.11
WithInitCmd adds a command to run when the program starts, alongside the root view's own Init. Use it to start a watcher that outlives navigation: a tick armed here and re-armed from a MsgHook keeps running whatever is on the stack, whereas one armed by a view stops as soon as that view is pushed over.
Repeated calls accumulate.
func WithKeyHook ¶
WithKeyHook installs a global key interceptor (e.g. app hotkeys).
func WithKeyMapQuit ¶
func WithKeyMapQuit() Option
WithKeyMapQuit installs a quit matcher from the scope's Quit binding. This is also the default; the option remains for explicit call sites.
func WithMsgHook ¶ added in v0.1.4
WithMsgHook installs a global message interceptor (e.g. debounce settle).
func WithQuitCheck ¶
WithQuitCheck overrides quit key matcher. An opaque matcher cannot be rendered, so pair it with WithQuitHint to keep the footer legend truthful.
func WithQuitHint ¶ added in v0.1.5
WithQuitHint overrides the quit glyph in the footer legend. Defaults to the active scheme's Quit binding.
func WithScope ¶ added in v0.2.2
WithScope installs the rendering scope (theme, keys, glyphs). Defaults to ui.Default(); swap at runtime with SetScope.
func WithStatus ¶
func WithStatus(fn StatusFunc) Option
WithStatus installs an async status loader for the footer strip.
func WithoutClock ¶ added in v0.1.13
func WithoutClock() Option
WithoutClock hides the header clock and disables its per-second tick.
type PromptSpec ¶ added in v0.1.9
type PromptSpec struct {
// Title heads the rendered panel.
Title string
// Fields builds the form, seeded from previously entered values. It is
// called again after every Sync, exactly like EditorDoc.Fields.
Fields func(prev map[string]any) []forms.Field
// Sync reports whether the last edit changed a value the field set
// depends on, and so whether to rebuild. A nil Sync never rebuilds.
Sync func(vals map[string]any) bool
// Seed pre-fills the form.
Seed map[string]any
// Save is the action that submits. It defaults to keys.Confirm when left
// empty; hosts with a save binding of their own pass it here.
Save keys.Action
// Keys resolves keys. A nil Map falls back to the scope's editor
// bindings, like FormView.
Keys *keys.Map
// UI is the rendering scope; nil snapshots the process defaults.
UI *ui.Scope
}
PromptSpec configures a one-shot form prompt. It is the Editor's shape minus everything a command-line caller has no use for — no results pane, no preview, no persistence — so a CLI command can collect the same fields, with the same suggestions, without entering the deck.
type ReloadMsg ¶ added in v0.1.11
type ReloadMsg struct{}
ReloadMsg asks the active view to discard what it fetched and fetch again. Views that load lazily honour it; the rest ignore it, so it is safe to emit from a global key hook without knowing what is on top of the stack.
type Results ¶ added in v0.1.6
type Results interface {
// Items renders the result set as list rows sized to f.
Items(f layout.Frame) []list.Item
// Count reports how many underlying records the rows represent.
Count() int
}
Results is the lower pane of an Editor: whatever a run produced.
type Resumer ¶ added in v0.2.4
type Resumer interface {
// Resume returns the command to run when navigation returns to this view.
Resume(m *Model) tea.Cmd
}
Resumer is an optional View extension. Model calls Resume on the view a Pop uncovers, before the resize that rebinds it.
type Scroll ¶
type Scroll struct {
// contains filtered or unexported fields
}
Scroll is a lazy-loaded scrollable text view (bubbles viewport). Hosted only in the deck module so tea stays out of viewkit core.
func (*Scroll) Body ¶
Body implements View, resizing the viewport to the frame before rendering so the scroll offset stays within the content.
type ScrollBody ¶ added in v0.2.0
type ScrollBody struct {
layout.ScrollState
// contains filtered or unexported fields
}
ScrollBody owns the scroll offset and row math that hand-rolled scrolling Views repeat: embed it, route navigation keys through Handle, and render through View with the height that View.Body receives (the deck passes the usable body height, so no chrome constants are needed).
func (v *myView) Body(f layout.Frame) string {
return v.scroll.View(f, render(f), f.Height)
}
func (*ScrollBody) Handle ¶ added in v0.2.0
func (s *ScrollBody) Handle(act keys.Action) bool
Handle applies a navigation action to the scroll offset — Up/Down move one line, PageUp/PageDown move one window — and reports whether act was a scroll action. Row math comes from the last View call.
func (*ScrollBody) Total ¶ added in v0.2.0
func (s *ScrollBody) Total() int
Total returns the line count of the last body given to View.
type ScrollSpec ¶ added in v0.2.0
type ScrollSpec struct {
// Title heads the breadcrumb trail.
Title string
// Ctx supplies chrome context cues.
Ctx []keys.Hint
// Hints are appended to the footer legend after the built-in ones.
Hints []keys.Hint
// Load produces the scrollable text; invoked once on Init.
Load func() string
// IsCancel reports whether a key string should pop the view.
IsCancel func(string) bool
// ReloadHint is the footer label for the reload key (default "reload").
ReloadHint string
}
ScrollSpec configures a Scroll, following the FormSpec pattern: every field beyond Title and Load is optional.
type ServiceStatus ¶
type ServiceStatus struct {
ID string
Name string
Detail string
Severity glyph.Severity
Glyph string
Color lipgloss.TerminalColor
}
ServiceStatus is one right-strip status chip. Severity drives the default glyph and color; Glyph and Color, when set, override that resolution. ID is an optional stable identifier apps can use to filter or configure chips.
type StatusFunc ¶
type StatusFunc func(context.Context) StatusInfo
StatusFunc loads status asynchronously for the chrome strip.
type StatusInfo ¶
type StatusInfo struct {
Identity string
Services []ServiceStatus
}
StatusInfo is optional chrome identity + service chips.
type Toaster ¶ added in v0.1.6
type Toaster struct {
// contains filtered or unexported fields
}
Toaster owns a view's notification lifecycle: a TTL queue, the once-a-second prune tick, and the overlay that floats the current notification over a rendered body. Embed one in a View and forward Update / Body to it.
Expiry does not depend on the tick arriving. Body prunes against the clock before it reads the queue, so a tick lost while another view was on top (see toastPruneMsg) delays nothing the user can see; the tick exists to repaint on time, not to be the only thing that expires a toast.
func NewToaster ¶ added in v0.1.6
NewToaster builds a Toaster holding at most capacity notifications (0 for unbounded), each shown for ttl.
func (*Toaster) Active ¶ added in v0.2.1
Active prunes expired toasts and reports whether any remain.
func (*Toaster) Body ¶ added in v0.1.6
Body overlays the current notification on an already-rendered body. f is the frame the view's Body received (full terminal width, carrying the scope). It returns body unchanged when nothing is showing.
func (*Toaster) Current ¶ added in v0.2.1
func (t *Toaster) Current() (notify.Notification, bool)
Current prunes expired toasts and returns the one showing now, if any.
func (*Toaster) Prune ¶ added in v0.1.6
func (t *Toaster) Prune()
Prune expires everything past its TTL. Body and the read accessors below already do this.
func (*Toaster) Push ¶ added in v0.1.6
func (t *Toaster) Push(n notify.Notification) tea.Cmd
Push shows n for the Toaster's default TTL and returns the command that keeps the prune loop running. Return it from the view's Update.
func (*Toaster) PushFor ¶ added in v0.1.6
PushFor shows n for ttl, overriding the Toaster's default.
func (*Toaster) SetOverlayPos ¶ added in v0.1.6
func (t *Toaster) SetOverlayPos(pos layout.OverlayPos)
SetOverlayPos moves the toast card. It defaults to top centre.
func (*Toaster) Snapshot ¶ added in v0.2.1
func (t *Toaster) Snapshot() []notify.Notification
Snapshot prunes expired toasts and returns the rest, oldest first.
func (*Toaster) Tick ¶ added in v0.1.6
Tick arms the prune loop and returns the command to run, or nil when a tick is already in flight or there is nothing left to expire. Views that push notifications through Push / PushFor never need to call it; a view that restores a Toaster it filled earlier (after a Pop back onto it) can.
type View ¶
type View interface {
// Title names the view in the breadcrumb trail.
Title() string
// Init returns the command to run when the view is first shown.
Init() tea.Cmd
// Update handles one message. m is the hosting Model, for Push/Pop
// and size; the returned command is run by the tea loop.
Update(m *Model, msg tea.Msg) tea.Cmd
// Body renders the view's content into f (the area left between header
// and footer chrome).
Body(f layout.Frame) string
// Hints lists key legend entries for the footer.
Hints(scope *ui.Scope) []keys.Hint
// Context lists key/label cues for the header context strip.
Context(scope *ui.Scope) []keys.Hint
}
View is a navigable screen hosted by Model. Apps implement domain views; the tea runtime lives only in this module (tea must not enter viewkit core).
func WithExtraHints ¶ added in v0.1.6
WithExtraHints wraps inner so the footer legend carries extra after the view's own hints. Every other method passes through untouched. inner is returned unchanged when extra is empty, so the wrapper never costs a level of indirection it does not earn.
func WithLiveContext ¶ added in v0.1.6
WithLiveContext wraps inner so its chrome context cues are recomputed on every render rather than captured when the view was built — the shape a long-lived view needs when the cue (active role, selection, count) can change beneath it. Every other method passes through untouched. inner is returned unchanged when fn is nil.
type Work ¶ added in v0.1.5
type Work []Job
Work is a set of jobs run together: Collect is the headless driver, RunInteractive the tea progressive UI driver.
func (Work) Collect ¶ added in v0.2.0
Collect runs the jobs concurrently via errgroup and returns bodies in order, with no UI — the headless driver.
func (Work) RunInteractive ¶ added in v0.2.0
RunInteractive is RunInteractiveIn on the process-default scope.
func (Work) RunInteractiveIn ¶ added in v0.2.2
RunInteractiveIn shows a progressive tea UI while the jobs run under errgroup, rendering with scope (nil snapshots the process defaults). Finished results print to scrollback in job order; quit keys follow the scope's scheme.