Documentation
¶
Overview ¶
Package tui implements the QYVORA interactive terminal application.
Index ¶
- Constants
- Variables
- func Bullets(items []string, width int) []string
- func Capture(dst io.Writer, fn func() error) error
- func GetHelpLines(query string, cmds []Command, toolName string, width int, theme *Theme) []string
- func InTUISession() bool
- func IsInteractive(out *os.File) bool
- func IsNotInteractive(err error) bool
- func KeyValue(pairs [][2]string, width int) []string
- func Numbered(items []string, width int) []string
- func Panel(lines []string, width int, style lipgloss.Style) []string
- func RenderCLIArt(art []string, width int, name, tagline string) []string
- func RenderHelpDetail(cmd Command, toolName string, width int, theme *Theme) []string
- func RenderHelpIndex(cmds []Command, toolName string, width int, theme *Theme) []string
- func RenderHelpNotFound(query string, cmds []Command, theme *Theme) []string
- func Run(cfg Config) (int, error)
- func Section(heading string, count int) string
- func Table(cols []Col, rows [][]string, width int) []string
- func TerminalWidth() int
- func ThinBanner(name, tagline string) string
- func Truncate(s string, width int) string
- func TruncateMiddle(s string, width int) string
- func Wrap(s string, opts WrapOpts) []string
- type Activity
- type Aliaser
- type Artifact
- type Banner
- type Capabilities
- type Capability
- type CobraAdapter
- type Col
- type Color16
- type Color256
- type ColorDepth
- type Command
- type CommandNode
- type Config
- type Deprecator
- type Entry
- type Event
- type Example
- type ExampleInfo
- type Exampler
- type ExecRunner
- type ExecuteArgsFunc
- type Finding
- type Flag
- type FlagInfo
- type Flagger
- type Form
- func (f *Form) Args() []string
- func (f *Form) Backspace()
- func (f *Form) ClearField()
- func (f *Form) Err() string
- func (f *Form) Focus() *formField
- func (f *Form) FocusNext() bool
- func (f *Form) FocusPrev() bool
- func (f *Form) Insert(r rune)
- func (f *Form) Len() int
- func (f *Form) MoveCursor(delta int) bool
- func (f *Form) MoveToEnd()
- func (f *Form) MoveToStart()
- func (f *Form) Validate() error
- type Grouper
- type History
- type InProcessRunner
- type Longer
- type Palette
- type Parameter
- type RGB
- type Region
- type RenderedBanner
- type Row
- type Runner
- type Status
- type Theme
- type Usager
- type Variant
- type WrapOpts
Constants ¶
const ( StatusRunning = domain.StatusRunning StatusDone = domain.StatusDone StatusFailed = domain.StatusFailed StatusCancelled = domain.StatusCancelled )
Execution lifecycle states, re-exported from the domain package.
const ( EventExecutionStarted = domain.EventExecutionStarted EventExecutionCompleted = domain.EventExecutionCompleted EventExecutionFailed = domain.EventExecutionFailed EventExecutionCancelled = domain.EventExecutionCancelled EventFindingDiscovered = domain.EventFindingDiscovered EventProgressUpdated = domain.EventProgressUpdated EventArtifactCreated = domain.EventArtifactCreated EventTargetDiscovered = domain.EventTargetDiscovered )
Known lifecycle and payload event types, re-exported from the domain package.
const ExitCancelled = 130
ExitCancelled is the conventional shell status for a process interrupted by SIGINT. The TUI reports it for any execution whose context was cancelled, so a script and the interactive transcript agree on what an interrupt meant.
const TUISessionEnv = "QYVORA_TUI"
TUISessionEnv is the environment variable the TUI's runners set while they are executing a command on the interactive console's behalf.
It exists to break exactly one ambiguity. A framework prints its own identity banner when a command runs -- tool name, tagline, target, timestamp -- and the TUI draws a header band carrying the same identity. Under the console both would appear, stacked, and the transcript would repeat what the header already says. A framework checks this signal before printing and stays quiet when it is set.
The signal is deliberately an environment variable set by the runner, not an inference from the environment. "Is stdout a TTY" cannot tell a run inside the console from a standalone run that has been piped into a log, and both of those deserve different treatment; a standalone run must keep its banner whether it is piped or not. With the variable absent -- every standalone run, and any tool that forgets to consult it -- the default is to print, so the failure mode is the current, correct standalone behaviour rather than a silently missing banner.
Variables ¶
var ( CapabilitiesFrom = capabilities.CapabilitiesFrom NormalizeCapabilities = capabilities.NormalizeCapabilities IsLifecycle = capabilities.IsLifecycle IsStage = capabilities.IsStage )
Helpers
var BaseTheme = Palette{
Inset: "#020302",
Base: "#0F1D16",
Surface: "#182D22",
Raised: "#1F3B2D",
Rule: "#274938",
Border: "#2D5541",
Text: "#E9F7EF",
Muted: "#93AC9F",
Faint: "#6F8378",
Accent: "#22E58B",
AccentHi: "#6BFFB0",
AccentLo: "#12B76A",
AccentBg: "#0E3B26",
Info: "#4DA6FF",
InfoBg: "#10263F",
Cyan: "#35D4DE",
Violet: "#B794F6",
Warning: "#FFC93C",
High: "#FF9340",
Danger: "#FF6E85",
CriticalBg: "#D7263D",
Cancelled: "#949FAA",
PillText: "#FFFFFF",
}
BaseTheme is the QYVORA palette every tool inherits unless it supplies its own.
The ground is a green-black ladder rather than a neutral grey: the accent is the QYVORA green, and a neutral ground under a saturated accent reads as two different products. Four steps, darkest to lightest, each far enough above the last that the layering still separates on a panel only a few rows tall.
Colour is rationed the same way it always was. A terminal agent spends most of its life showing text, and colouring all of it is how a session becomes unreadable. What has changed is what the ration is spent on: the accent now carries the prompt, the mode bar and identity, and severity has a real scale rather than three words in three shades of the same hue.
var CobraCommands = commands.CobraCommands
CobraCommands collects completion metadata from a cobra command tree.
var CollectCommands = commands.CollectCommands
CollectCommands walks a command tree into the metadata the TUI completes against.
var NewCobraAdapter = commands.NewCobraAdapter
NewCobraAdapter adapts a cobra command tree.
var NewHistory = commands.NewHistory
NewHistory starts an empty input history.
var StaticCommands = commands.StaticCommands
StaticCommands adapts a fixed list into the metadata type.
Functions ¶
func GetHelpLines ¶
GetHelpLines is the main entry point for rendering help. If query is empty, renders index. Otherwise renders detail for that command.
func InTUISession ¶
func InTUISession() bool
InTUISession reports whether the current process is executing a command on behalf of the interactive console.
A framework calls it before printing its own banner:
if !tui.InTUISession() {
printBanner()
}
It reads the environment on every call rather than caching the answer. The in-process runner sets the signal for the duration of one command and clears it afterwards, and the same process may print a standalone banner outside a run, so a cached value would be wrong the moment the context changed.
func IsInteractive ¶
IsInteractive reports whether an interactive session should be started on the given output stream.
Tools call this before launching the TUI so that a piped or redirected invocation -- `tool scan target | tee out`, CI, a cron job -- falls through to the ordinary one-shot CLI instead of filling a pipe with escape codes.
func IsNotInteractive ¶
IsNotInteractive reports whether err means "there is no terminal here", so a caller can fall back to ordinary CLI behaviour instead of reporting an error.
func KeyValue ¶
KeyValue formats key-value pairs with aligned values. Keys in Muted, values in Text (styling applied by caller).
func Panel ¶
Panel wraps lines in an inset or raised filled rectangle with padding. Every row padded to full width so background is solid.
func RenderCLIArt ¶
RenderCLIArt is the width-aware rule every tool's CLI banner follows: when the art fits the terminal it is returned with its common leading column removed (so every tool's mark starts at the same place), and when it does not fit, a thin banner that cannot wrap is returned instead. An art block is never drawn cut or shifted mid-glyph.
A non-positive width is treated as unconstrained: a caller that could not measure the terminal (a pipe, a file, a log) gets the full art, which is the form that belongs in an archive.
func RenderHelpDetail ¶
RenderHelpDetail produces detailed help for a single command per PROMPT1.md §4. Sections: NAME, USAGE, DESCRIPTION, SUBCOMMANDS, FLAGS, EXAMPLES, SEE ALSO.
func RenderHelpIndex ¶
RenderHelpIndex produces the help index view per PROMPT1.md §4. Groups commands by Group field, presents as two-column table with hanging indent.
func RenderHelpNotFound ¶
RenderHelpNotFound produces help for an unknown command with suggestions.
func Run ¶
Run starts an interactive session and returns the process exit code.
It returns an error satisfying IsNotInteractive when the streams cannot support a TUI, which is the caller's cue to use the one-shot CLI instead.
func Section ¶
Section formats a section heading with count. Returns: "HEADING (count)" styled, plus spacing.
func Table ¶
Table formats rows into aligned columns with optional wrapping. Returns lines with color already applied.
Per PROMPT1.md §5:
- Computes widths from content, shrinks flex columns first
- Wraps the last column if configured
- Header row optional (first row in Faint if provided)
func TerminalWidth ¶
func TerminalWidth() int
TerminalWidth reports the column count of the terminal attached to stdout, or 0 when the width cannot be measured: stdout is not a terminal, or the size is unavailable. Zero means "unconstrained", so a caller renders the fullest banner form and lets the output medium decide.
func ThinBanner ¶
ThinBanner builds the single-line banner a tool prints in place of its wordmark when the wordmark would not fit the terminal. It carries the name between two rules and the tagline after, so the identity and the descriptor survive a narrow window that cannot draw the art.
func TruncateMiddle ¶
TruncateMiddle truncates in the middle, keeping head and tail. Useful for paths and URLs: /very/long/path/to/file.txt -> /very/.../file.txt
func Wrap ¶
Wrap performs word wrapping that preserves runs of spaces and indentation. Never splits a word unless it alone exceeds the width, then hard-splits with a visible continuation marker ↪ in Faint style.
Per PROMPT1.md §5: Wrap on plain text first, colour second, so colour codes never break wrapping. Display width measured with lipgloss.Width.
Types ¶
type Activity ¶
type Activity struct {
// Total is every event seen for the current run.
Total int
// ByLevel counts events by the envelope's level field. Levels the TUI does
// not know about are still counted, under their own name, so a tool using
// "notice" does not have its events vanish from the tally.
ByLevel map[string]int
// Recent holds the tail of event labels, newest last, for the region to
// show. It is a ring: a long run must not grow the interface's memory
// without bound.
Recent []string
// Stages holds the current stage and the most recently completed one, for
// tools that emit stage transitions.
CurrentStage string
LastStage string
// Findings counts finding events, which is the one universal topic that
// reliably means "the tool produced something worth reading".
Findings int
// Started is when the current run began.
Started time.Time
}
Activity is the live view of a run: what is happening, what has been discovered, and how much of it there is.
It is a consumer of events and nothing else. It does not know what a scan is, does not interpret a tool's vocabulary, and holds no reference to any scanner. A tool it has never seen produces a perfectly good Activity region, because the only thing it requires is the seven-field envelope every tool already emits.
The design consequence is deliberate: the measured topic distribution is bimodal -- seven topics shared by all twelve tools, then a long tail of tool-specific ones. So this tracks counts and the most recent lines, and treats every topic alike. Anything cleverer would have to guess which tool-specific topic is important, and a wrong guess invents a priority the tool never expressed.
func (*Activity) Note ¶
Note records a topic in the recent tail without incrementing counts. The region's own status and header lines go through here so the tail is a consistent record rather than a mix of two sources.
func (*Activity) Region ¶
Region renders the activity as a side region.
The region leads with the counts, because "how much has happened" is the first question about a running command, and then lists the recent tail. It never claims a percentage: a run that emits no progress data has no percentage, and inventing one is the failure mode §39 warns about.
type Banner ¶
type Banner struct {
// Tool is the product name, with or without a QYVORA prefix. It is the word
// the banner draws.
Tool string
// Tagline is an optional line set under the wordmark.
Tagline string
// Version is optional and is normally drawn by the header rather than the
// banner; it is kept here so a caller can pass everything it knows in one
// value.
Version string
// Glyphs names the box-drawing set used for framed variants. Empty means
// rounded.
Glyphs string
// Variant pins the rung instead of letting RenderBanner choose. Tests use
// this; the interface leaves it Auto.
Variant Variant
// Art overrides the generated wordmark wholesale. A tool that wants a
// hand-drawn mark supplies it here and still gets the same fit rules.
Art []string
}
Banner is the identity a tool hands the interface. It is a description, not artwork: the wordmark is generated from Tool in the standard block font, so a tool gets a wordmark without shipping one, and the same name always produces the same picture.
func ToolBanner ¶
ToolBanner builds a Banner with the house defaults for a QYVORA tool.
type Capabilities ¶
type Capabilities = capabilities.Capabilities
Capabilities describes what a tool can do.
type Capability ¶
type Capability = capabilities.Capability
Capability describes a single capability.
type CobraAdapter ¶
type CobraAdapter = commands.CobraAdapter
CobraAdapter adapts a cobra command tree to CommandNode.
type Col ¶
type Col struct {
// Min is the minimum width for this column.
Min int
// Max is the maximum width (0 = unlimited).
Max int
// Flex allows the column to grow to fill available space.
Flex bool
// Align is "left" or "right".
Align string
// Policy is "wrap" or "truncate" for overflow handling.
Policy string
}
Col describes one column in a table.
type ColorDepth ¶
type ColorDepth int
ColorDepth is how much colour the terminal can actually render.
It exists because lipgloss's own degradation of a hex value to the nearest available colour is not good enough for this interface. Measured against the QYVORA ground, its nearest-colour answer turns a quiet divider into a bright green line and turns the CRITICAL badge's red background into black. The interface draws layered surfaces and severity badges for a living; guessing which of the 256 colours is nearest is the one thing it must not do. So the depth is resolved once at startup and every slot is then replaced by an explicit index from a table someone checked.
const ( // DepthNone means no colour at all: NO_COLOR, TERM=dumb, or a pipe. DepthNone ColorDepth = iota // Depth16 is the sixteen-colour palette. Depth16 // Depth256 is the 256-colour palette. Depth256 // DepthTrueColor is 24-bit colour. DepthTrueColor )
func (ColorDepth) String ¶
func (d ColorDepth) String() string
type CommandNode ¶
type CommandNode = commands.CommandNode
CommandNode is the minimal shape of a command tree the TUI completes against.
type Config ¶
type Config struct {
// Runner executes commands. Required.
Runner Runner
// Title is the header label, conventionally "QYVORA / TOOL".
Title string
// Version is shown in the header when set.
Version string
// Banner is the tool's identity art, drawn at the richest rung of the
// banner ladder that fits the terminal. A zero value draws nothing and the
// header carries the name on its own, which is the correct default: most
// tools are libraries and commands with no wordmark to show.
//
// The banner is a TUI-only affordance. It never reaches the one-shot CLI
// output, because that output is parsed by scripts and compared in tests and
// a wordmark is not part of any tool's contract.
Banner Banner
// In, Out and Err are the streams the TUI owns. Out defaults to stdout.
In io.Reader
Out io.Writer
// Err receives the tool's human-readable output during execution. Nil keeps
// it in the transcript, which is the default and normally what is wanted:
// a capability table, a resolved configuration and the explanation of a
// failure are all things the operator asked to see. Set it only to divert
// that text somewhere else entirely.
Err io.Writer
// NoColor forces plain output regardless of terminal detection. It is
// decided once at startup and is not overridable by a Theme, so a tool
// cannot opt out of a user's NO_COLOR request.
NoColor bool
// Capabilities is the tool's capability registry, normalised.
//
// It is produced by NormalizeCapabilities from the tool's own
// `capabilities -o json` output, which is the same command an operator can
// run by hand. Nothing here is a second hand-maintained list, so a
// capability added to a tool appears in the interface without a second
// edit -- the same property CollectCommands gives commands.
//
// A nil value is normal and means the tool publishes no registry. The
// interface stays fully usable without it.
Capabilities *Capabilities
// Theme is the tool's optional palette. A nil Theme, or one that sets
// nothing, resolves to QYVORA_BASE, so branding is never required and never
// required to be complete: a tool sets the slots it means to change and
// inherits the rest.
//
// A tool with no meaningful brand palette should leave this nil. An
// invented colour is worse than the shared one, and most tools should
// inherit.
Theme *Palette
// OutputCap is how many lines of one command's printed output the session
// retains per execution. The tail is kept, so commands that print without
// bound grow no further than this, and the transcript says when it trips.
// Zero uses the shared default (outputCap).
OutputCap int
}
Config configures a TUI session.
type ExampleInfo ¶
type ExampleInfo = commands.ExampleInfo
ExampleInfo describes one example from a CommandNode's Exampler interface.
type ExecRunner ¶
type ExecRunner struct {
// Path is the executable to run. Empty means the current process.
Path string
// Args are prepended to every invocation, before the event routing flag.
Args []string
// Meta supplies completion metadata.
Meta []Command
// ToolName is the header name.
ToolName string
// Stderr receives the child's human-readable output. When nil it is
// discarded: the transcript shows events, and interleaving the child's
// progress bars with the TUI's own frames produces unreadable output.
Stderr io.Writer
}
ExecRunner runs commands as child processes of the tool's own binary.
This is the fallback for tools whose in-process entry point is not re-entrant. It consumes the same documented `--events stdout` contract as everything else, so it never parses human-readable output.
Cancellation sends SIGINT to the child rather than SIGKILL, so the child runs its own signal-cancellation path, persists partial artifacts and exits 130 -- the same path a real Ctrl+C at a terminal takes.
func (*ExecRunner) Commands ¶
func (r *ExecRunner) Commands() []Command
func (*ExecRunner) Name ¶
func (r *ExecRunner) Name() string
type ExecuteArgsFunc ¶
ExecuteArgsFunc is a tool's in-process entry point. It runs one command with an explicit argument vector and returns the process exit code, without calling os.Exit.
This is the seam the TUI prefers: no process spawn, and the execution runs inside the tool's own binary, so it exercises the same code path a shell invocation would.
type Form ¶
type Form struct {
// Capability is the capability this form fills in.
Capability Capability
// contains filtered or unexported fields
}
Form is a structured input for one capability, built from the parameter metadata the tool's own registry publishes.
The gate is the whole design. OpenForm returns nil for a capability that describes no parameters, and the interface then keeps its composer. A form for a tool that publishes no input schema would be the TUI inventing fields an operator has to guess at, which is worse than typing arguments.
Nothing here knows any tool's vocabulary. A field is a name, a type and a required flag, all read from the registry; the form's job is to check that what the operator typed satisfies what the tool said, not to decide what the tool accepts.
func OpenForm ¶
func OpenForm(c Capability) *Form
OpenForm builds a form for a capability, or nil when the capability describes no parameters.
The nil return is load-bearing: callers treat it as "keep the composer".
func (*Form) Args ¶
Args renders the filled-in form as command-line arguments.
A field with no value is omitted entirely rather than passed as an empty string, because `--duration ""` is a value the tool has to reject and an omitted flag is not. That rule is the one judgement call here, and it errs towards sending less: an argument the operator did not fill in is not something the interface should invent.
func (*Form) ClearField ¶
func (f *Form) ClearField()
ClearField empties the focused field, which is what a dedicated delete key should do to a field rather than to the character before the cursor.
func (*Form) Focus ¶
func (f *Form) Focus() *formField
Focus returns the field being edited, or nil.
func (*Form) FocusNext ¶
FocusNext and FocusPrev move between fields. They report whether the focus moved, so a caller can leave the form when it runs off the end rather than silently wrapping: a form that wraps is a form you cannot leave with the arrow keys.
func (*Form) Insert ¶
Insert adds a rune at the cursor.
The cursor is a byte offset into the value, because that is what slicing needs, but it always lands on a rune boundary: a value is typed a character at a time and moved a character at a time, so an offset that can fall inside a multi-byte character is an offset that will eventually produce mojibake.
func (*Form) MoveCursor ¶
MoveCursor shifts the cursor within the focused field, and reports whether it moved.
A field is edited in place, so the cursor has to be able to go both ways. A form that can only append cannot change a character in the middle of a value, which is most of editing.
func (*Form) MoveToStart ¶
func (f *Form) MoveToStart()
MoveToStart and MoveToEnd put the cursor at either end of the focused field.
type InProcessRunner ¶
type InProcessRunner struct {
// Execute is the tool's in-process entry point.
Execute ExecuteArgsFunc
// ToolName is the header name.
ToolName string
// Meta supplies completion metadata.
Meta []Command
// Prefix is prepended to every argument vector, for flags the tool
// requires on all invocations.
Prefix []string
// EventFlag and EventValue form the flag used to route JSONL to stdout.
// Tools whose flag is spelled differently can override these; the
// defaults match the shared --events contract.
EventFlag string
EventValue string
}
InProcessRunner invokes a tool's own ExecuteArgs, capturing its event stream in the same pipe a shell pipeline would have produced.
It works by pointing the --events flag at stdout and temporarily swapping os.Stdout for the write end of a pipe. That is the tool's own documented contract -- `--events stdout` emits JSONL on stdout and routes report text to stderr -- so no repository needs its event layer modified to support the TUI. Because stdout carries only JSONL, the transcript cannot be polluted by the tool's human-readable output, and the TUI still never parses prose.
The swap is safe because the TUI runs exactly one command at a time on its own goroutine while the render loop is the only other consumer of the process. Concurrent invocations are not supported, and the mutex makes that explicit rather than letting it corrupt the stream.
func (*InProcessRunner) Commands ¶
func (r *InProcessRunner) Commands() []Command
func (*InProcessRunner) Name ¶
func (r *InProcessRunner) Name() string
type Palette ¶
type Palette struct {
// The ground, darkest to lightest. These are painted, so a component
// distinguishes them only by their being different.
Inset string
Base string
Surface string
Raised string
// Rule and Border draw structure. They are foreground colours, not fields.
Rule string
Border string
// Accent is the interface's identity colour: prompt, rules, success.
Accent string
// AccentHi, AccentLo and AccentBg are the ends of the accent ramp and the
// field a pill sits on.
AccentHi string
AccentLo string
AccentBg string
// Warning, Danger, Cancelled and Info carry execution state.
Warning string
Danger string
Cancelled string
Info string
// Text, Muted and Faint are the three inks set on the ground.
Text string
Muted string
Faint string
// Cyan and Violet extend the non-severity scale: cyan for work in progress,
// violet for the evidence side of a session. Neither implies urgency.
Cyan string
Violet string
// High is the step above Warning on the severity ramp.
High string
// InfoBg and CriticalBg are the two filled fields the interface paints.
// Nothing else earns a saturated background.
InfoBg string
CriticalBg string
// PillText is fixed, not themeable. See BaseTheme.
PillText string
}
Palette is the semantic colour set a theme is written in.
A tool fills in only the slots it means to change; everything else falls back to the base. That is what makes a partial theme legitimate: a tool with one recognisable brand colour should be able to set Accent and inherit the rest, rather than restating thirty hex values to get one of them right.
A slot may be empty after resolution when the terminal cannot render it. An empty background slot means "paint no fill", which is the correct state at sixteen colours rather than a missing value.
type Parameter ¶
type Parameter = capabilities.Parameter
Parameter describes a capability input parameter.
type RGB ¶
type RGB struct{ R, G, B uint8 }
RGB is a red-green-blue triple. Terminal palette indices are resolved to one of these so a colour can be measured rather than assumed.
type Region ¶
type Region struct {
// Title is the region's heading.
Title string
// Rows are the region's content, already formatted. A region composes
// rows rather than owning state.
Rows []string
// Width is the column width the region is rendered at.
Width int
// Empty is shown in place of Rows when there is nothing to display, so the
// region explains itself instead of being a blank column.
Empty string
// Focused marks the region as holding keyboard focus, for tools that route
// keys to a region. A region that cannot be focused leaves it false.
Focused bool
// Height is the number of rows the region may occupy, or zero for as many as
// it has. It is set from the layout rather than inferred, because a panel
// taller than the terminal is not scrolled: the rows past the bottom are
// simply never seen, so a region that renders everything has silently thrown
// away whatever the operator most recently needed.
Height int
}
Region is a side panel: a titled column beside the transcript.
A region is a component in the sense the architecture needs: it knows its width, it takes its colours from the theme rather than holding any of its own, and it can be tested without a terminal or a model. It is not a widget framework, and it deliberately does not grow into one.
Rendering a region to an empty string is the normal case, not an error. A tool with no capabilities renders no navigation region, and a layout that reserved space for it would be worse than one that did not.
func (*Region) Add ¶
Add appends a row, ignoring any wider than the region. Clamping here rather than at render time keeps the row list meaningful for tests.
func (*Region) Boxed ¶
Boxed renders the region with a vertical rule on its inner edge, which is how a side region reads as a panel rather than as more transcript.
The rule is drawn as a separate column so the transcript's own width is not disturbed: a region that ate a character of every transcript line would make the session harder to read for no gain.
func (*Region) Len ¶
Len reports how many rows the region holds, which is what a layout uses to decide whether a region is worth drawing at all.
func (*Region) Render ¶
Render draws the region: a title, a rule, and its rows.
A region with a height budget draws at most Height lines in total, title and rule included. Rows that do not fit are dropped, not wrapped and not scrolled: the alternative is a panel whose contents move under the operator's fingers every time it repaints.
type RenderedBanner ¶
type RenderedBanner struct {
// ASCII is the art, one string per row, with no colour applied.
ASCII []string
// Width and Height are the measured extent of ASCII.
Width int
Height int
// Variant is the rung that produced this art.
Variant Variant
// Dropped is true when the name had no legible rendering at the available
// width. A caller must not draw a partial banner in that case; the header
// already carries the tool name.
Dropped bool
}
RenderedBanner is a wordmark that has already been chosen and measured.
func RenderBanner ¶
func RenderBanner(spec Banner, width, height int) RenderedBanner
RenderBanner picks the richest variant of spec.Tool that fits width and, when height is a positive constraint, fits that too.
A width of zero or less is treated as unconstrained, because a caller that has not measured yet should get the full wordmark and clamp it itself rather than be handed nothing.
func (RenderedBanner) IsDropped ¶
func (r RenderedBanner) IsDropped() bool
IsDropped reports whether the banner carries no art.
type Row ¶
type Row struct {
// Marker is an optional leading glyph, e.g. a status symbol or a tree
// branch. It is never truncated, because a status symbol is the one thing
// in the row that carries meaning.
Marker string
// Key is the leading label, e.g. a capability name or a command.
Key string
// Value is the trailing detail, dropped before the key when space runs
// out. Losing detail is preferable to losing the label that identifies the
// row.
Value string
}
Row is one line of a region, built from labelled parts so a component does not have to hand-align text.
A region is narrow, and hand-aligned text at a narrow width is how columns stop lining up. A Row measures its own parts and pads them to fit.
type Runner ¶
type Runner interface {
// Name is the tool's name, used in the header and in messages.
Name() string
// Commands returns the command metadata available for completion and help.
// Tools should source this from their command registry rather than
// maintaining a second list, so the two cannot drift.
Commands() []Command
// Run executes args, writing one JSONL event envelope per line to events.
// It must not close events; the TUI owns the writer.
Run(ctx context.Context, args []string, events io.Writer) (int, error)
}
Runner executes tool commands on behalf of the TUI and produces structured events for them.
Implementations must honour ctx: when it is cancelled, the underlying work stops and Run returns promptly. The TUI's Ctrl+C cancels the context it passed in, so a Runner that ignores ctx makes Ctrl+C a lie.
Run returns the process exit code. A cancelled execution returns 130, the conventional status for SIGINT, so the TUI and a shell agree on what interrupting a tool meant.
type Theme ¶
type Theme struct {
// Color reports whether styling is active. When false every style is the
// identity transform and NO_COLOR is honoured on the one rendering path.
Color bool
// Depth is the colour depth the styles were resolved for. Components need it
// for decisions colour cannot express, such as whether a framed panel is
// drawn at all.
Depth ColorDepth
// Palette is the resolved palette, kept for diagnostics and for components
// that need a raw colour rather than a style.
Palette Palette
// Identity.
Title lipglossStyle
Version lipglossStyle
Rule lipglossStyle
// Structure. These carry the shape of the interface rather than the state
// of the work: the gutter that groups a command with its output, and the
// heading, count and column styles that separate a section label from the
// data beneath it. They are deliberately the quietest slots in the theme,
// because structure is read constantly and must never compete for
// attention with something that actually happened.
Gutter lipglossStyle
Heading lipglossStyle
Count lipglossStyle
Column lipglossStyle
// Status. These are the only saturated colours in the resting interface.
Ready lipglossStyle
Running lipglossStyle
Failed lipglossStyle
Cancelled lipglossStyle
Warning lipglossStyle
// Session.
Command lipglossStyle
// Output is the tool's own printed text. It is deliberately unadorned: the
// interface did not interpret it, so it does not dress it up.
Output lipglossStyle
Arg lipglossStyle
Group lipglossStyle
Label lipglossStyle
Value lipglossStyle
Detail lipglossStyle
Success lipglossStyle
// Composer.
Prompt lipglossStyle
Hint lipglossStyle
Badge lipglossStyle
// ModeBar is the coloured strip that carries the composer's mode, so the
// session's state is legible without reading the status word in the header.
ModeBar lipglossStyle
ModeFg lipglossStyle
// Tip is the rotating one-line hint. It is the quietest text in the
// interface on purpose: it is the first thing to disappear.
Tip lipglossStyle
// Severity.
Critical lipglossStyle
High lipglossStyle
Medium lipglossStyle
Low lipglossStyle
Info lipglossStyle
// Cyan and Violet are the two non-urgency hues, for work in progress and for
// evidence respectively.
Cyan lipglossStyle
Violet lipglossStyle
// Progress.
BarFill lipglossStyle
BarEmpty lipglossStyle
BarLead lipglossStyle
// Ground and surfaces. These are the painted fills, in the order they stack.
Base lipglossStyle
Inset lipglossStyle
Surface lipglossStyle
Raised lipglossStyle
// Border draws a panel edge; FocusRing is the same edge on the panel that
// has keyboard focus. They are separate slots because the difference is the
// only cue that says where a keystroke will land.
Border lipglossStyle
FocusRing lipglossStyle
Selection lipglossStyle
// Activity severity, for the region that renders live events.
Activity lipglossStyle
// Pills. A pill is a filled label; the caps are drawn in the pill's own
// background so the field reaches the edge of the cell.
Pill lipglossStyle
PillCritical lipglossStyle
PillHigh lipglossStyle
PillMuted lipglossStyle
}
Theme carries the styles used across the interface.
Colour is decided once, at startup, from NO_COLOR and the detected terminal. Every style is a no-op when colour is off, so there is one rendering path rather than a plain-text variant that could drift from it.
A Theme is built from a Palette, and a Palette is built from BaseTheme plus whatever a tool supplied. No rendering component holds a colour: components ask the theme. That is what keeps branding out of the presentation code -- a component that hard-coded a hex would be a tool's identity leaking into the shared layer, and a second place to change when the palette does.
type Variant ¶
type Variant int
Variant is one rung of the banner ladder. A tool name is rendered at the richest variant that fits the width it was given, so the identity is as large as the terminal allows and is never truncated into nonsense.
const ( // VariantAuto lets RenderBanner choose. VariantAuto Variant = iota // VariantFull is the five-row pixel wordmark: one glyph per letter. VariantFull // VariantCompact is the three-row wordmark: half the rows, same width. VariantCompact // VariantStacked splits the name across rows for a narrow terminal. VariantStacked // VariantMarquee is a single bordered row carrying the name. VariantMarquee // VariantNone is no art at all. The name has no legible rendering at the // available width, so the header carries identity on its own instead. VariantNone )
type WrapOpts ¶
type WrapOpts struct {
// Width is the target line width in display columns.
Width int
// HangingIndent is the number of columns to indent continuation lines.
HangingIndent int
// FirstIndent is the number of columns to indent the first line (in addition to HangingIndent on subsequent lines).
FirstIndent int
// PreserveSpacing keeps runs of spaces intact (for pre-formatted tables).
PreserveSpacing bool
}
WrapOpts configures text wrapping behavior.
Source Files
¶
- activity.go
- ansi.go
- api.go
- api_capabilities.go
- api_commands.go
- banner.go
- banner_cli.go
- bannerfont.go
- block.go
- capture.go
- child_unix.go
- colordepth.go
- component_region.go
- composer.go
- doc.go
- events.go
- executions.go
- exitcode.go
- export.go
- fd_dup2.go
- fd_unix.go
- form.go
- frame.go
- glyphs.go
- ground.go
- header.go
- help.go
- highlight.go
- inprocess.go
- layoutglue.go
- model.go
- output.go
- progress.go
- regions.go
- runner.go
- session.go
- style.go
- summary.go
- terminalwidth_unix.go
- text.go
- textutil.go
- theme.go
- transcript.go
- tty.go
- view.go
- wrap.go