ui

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 28 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ui holds every terminal UI component: lipgloss styles, the reusable stack tree renderer and the bubbletea checkout picker. It is the only package allowed to import Charm libraries.

Index

Constants

This section is empty.

Variables

View Source
var ErrCancelled = fmt.Errorf("cancelled")

ErrCancelled is returned when the user dismisses a prompt. Dismissing it with Ctrl-C also matches context.Canceled, so the command ends as interrupted (exit 130), like any other Ctrl-C.

Functions

func Busy

func Busy(w io.Writer, enabled bool) func()

Busy marks the terminal as busy with an indeterminate progress indicator (a pulsing tab or taskbar entry, depending on the terminal) and returns a function that clears it. With enabled false (not a terminal) it does nothing. Terminals without OSC 9;4 support ignore the sequence.

func FitLine added in v0.4.0

func FitLine(head, text string, width int) string

FitLine is head followed by text, with text cut short ("…") so the line fits in width columns. head may hold styles and links; text must be plain. width 0 never cuts.

func FuzzyMatch

func FuzzyMatch(s, q string) (bool, []int)

FuzzyMatch reports whether q is a case-insensitive subsequence of s and returns the matched rune indices.

func Hyperlink(enabled bool, url, text string) string

Hyperlink wraps text in an OSC 8 hyperlink to url when enabled, so terminals such as Ghostty, iTerm2 and WezTerm make it clickable. With enabled false (not a terminal) or an empty url it returns text unchanged.

Every link is underlined, and that is the only thing that marks it out (docs/style.md); the text keeps whatever colour it had. The underline is part of the link, so it only appears when the link does, and it is switched back off (SGR 24, not a full reset) at the end so it never runs into the text after it or disturbs a style the link sits inside.

The link carries an id derived from the url. Lines drawn by bubbletea's renderer (the picker, lines printed above a spinner) can be written in several pieces as the screen updates; the id is what makes the terminal treat those pieces as one link, so hovering underlines all of it.

func Linkify added in v0.2.0

func Linkify(line string, prURL func(int) string) string

Linkify makes the pull request references (#123) and web URLs in a line OSC 8 hyperlinks. prURL maps a PR number to its URL ("" leaves it as text). Escape sequences in the line are kept, and text that is already inside a link is not linked again, so a styled or pre-linked line is safe to pass through. Callers decide whether the stream is a terminal.

func Printable added in v0.2.0

func Printable(s string) string

Printable makes text we didn't write (git's stderr, gh stack's output, messages that carry file or branch names) safe to print as one line: every control character but tab, and every invalid byte, is shown as an escape (\n, \x1b) instead of being sent to the terminal.

func QuoteName added in v0.2.0

func QuoteName(s string) string

QuoteName shows a file name or path as it is when it's plain, and C quoted ("a\nb.txt", "say \"hi\"") when it holds anything that could break the line or reach the terminal as a control: control characters, quotes, backslashes, unprintable or invalid UTF-8. Spaces and printable non-ASCII stay as they are. Display only; structured output (MCP) keeps the raw name.

func RelativeTime

func RelativeTime(t, now time.Time) string

RelativeTime renders t relative to now ("3h ago").

func RenderDoctor added in v0.5.0

func RenderDoctor(results []doctor.Result, st Styles, tty bool) string

RenderDoctor draws git stack doctor's checks as a tree, each check on its own line with what it found, the checks under it indented beneath:

✔ git: git 2.47.1
✔ GitHub CLI (gh): gh version 2.62.0
  ✔ gh is logged in: Logged in to github.com account dom
  ✖ gh-stack is new enough: gh-stack v0.2.1 is older than v0.3.0
    ↳ git stack doctor --fix runs: gh extension upgrade stack

On a terminal (tty) the marks are coloured; otherwise they are ok:, warn:, fail:, skip: and fixed: and the arrows "- ", so it stays ASCII. Text from outside (gh's stderr) is escaped.

func RenderLog

func RenderLog(v *app.View, o LogOptions) string

RenderLog renders every stack as a tree: trunk at the bottom, each stack a column rising from it, newest branch at the top. Under each branch name come its pull request and title, then its state, age and checkout, then its own commits, newest first (at most app.MaxCommits, then a count).

● feat-b
│  #13 Retry failed payments
│  draft · 2d ago
│
│  • 7ac32ef - Back off between retries
│  • 4f21abc - Retry failed payments
│
○ feat-a
│  #12 Add the payments queue
│  open · needs restack · 3h ago
│
│  • 9b1d2e0 - Add the payments queue
│
│ ○ hotfix
│ │  no PR
│ │  1w ago · in ~/src/app-hotfix
│ │
│ │  • 3c4d5e6 - Fix the typo in the banner
│ │
├─┘
■ main

Short leaves just the branch names, one line each, marking those that need a restack:

● feat-b
○ feat-a (needs restack)
│ ○ hotfix
├─┘
■ main

A trunk with no stacks is still drawn, so an empty repository shows where a stack would start. Untracked branches are not shown. It returns "" when there is no trunk at all.

func RenderRow

func RenderRow(tr TreeRow, o RenderOptions) string

RenderRow renders one tree row: prefix, name, PR, restack marker, age and worktree.

func RenderTree

func RenderTree(rows []TreeRow, o RenderOptions) string

RenderTree renders every row, one per line, without selection.

func ShortPath added in v0.1.1

func ShortPath(p string) string

ShortPath shows a path under $HOME as ~/...; other paths are unchanged.

func WithSpinner

func WithSpinner(ctx context.Context, in io.Reader, out io.Writer, message string, fn func(ctx context.Context) error) error

WithSpinner runs fn while showing a spinner and message on the terminal. It returns fn's error; ctrl+c cancels with context.Canceled.

Types

type LogOptions

type LogOptions struct {
	Styles Styles
	Now    time.Time
	// Links makes PR references OSC 8 hyperlinks.
	Links bool
	// PRURL finds the URL of a PR the row only has a number for (the forge
	// couldn't be reached and the stack metadata has no URL); usually
	// Reporter.PRURL.
	PRURL func(number int) string
	// Width is the terminal's width; a PR title or commit subject that
	// would run past it is cut short with "…". 0 never cuts (not a
	// terminal).
	Width int
	// Short shows only the branch names, with "(needs restack)" after those
	// that need one, and no PR, state or commits.
	Short bool
}

LogOptions controls RenderLog.

type Picker

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

Picker is the bubbletea model. It is exported for tests.

func NewPicker

func NewPicker(ctx context.Context, o PickerOptions) *Picker

NewPicker builds the model.

func (*Picker) Init

func (p *Picker) Init() tea.Cmd

Init starts the background refresh, if any.

func (*Picker) Result

func (p *Picker) Result() PickerResult

Result returns the choice once the program has finished.

func (*Picker) Update

func (p *Picker) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles keys, window size and refresh results.

func (*Picker) View

func (p *Picker) View() tea.View

View renders the picker inline.

type PickerOptions

type PickerOptions struct {
	Rows []app.Row
	// Title heads the picker; "Select a branch" when empty.
	Title string
	// Refresh, when set, is run in the background; its result updates the
	// PR decorations while the picker is open.
	Refresh func(ctx context.Context) ([]forge.PullRequest, error)
	// Styles defaults to DefaultStyles when nil.
	Styles *Styles
	Now    time.Time
	// Height limits the number of visible rows (0: derive from the terminal).
	Height int
	// Links makes PR references OSC 8 hyperlinks; set it when the picker's
	// output stream is a terminal.
	Links bool
	// PRURL finds the URL of a PR a row only has a number for; usually
	// Reporter.PRURL.
	PRURL func(number int) string
}

PickerOptions configures the checkout picker.

type PickerResult

type PickerResult struct {
	Branch    string
	Cancelled bool
	// Interrupted is set too when it was Ctrl-C rather than Escape or q:
	// the user wants the whole command stopped, not just the picker shut.
	Interrupted bool
}

PickerResult is the user's choice.

func RunPicker

func RunPicker(ctx context.Context, in io.Reader, out io.Writer, o PickerOptions) (PickerResult, error)

RunPicker runs the picker on the given terminal streams. Ctrl-C (or the context being cancelled, e.g. SIGTERM) is an interrupt and comes back as context.Canceled, like every other interrupted command; Escape is just a cancel and returns no error.

type Prompter

type Prompter struct {
	In  io.Reader
	Out io.Writer
	Ctx context.Context
	// Wait, when set, is told a question is waiting on the user; the
	// function it returns is called once it has been answered. The CLI
	// passes Reporter.Waiting so the terminal can show it.
	Wait func(question string) func()
}

Prompter asks yes/no and pick-one questions on the terminal. It satisfies app.Prompter.

func (Prompter) Confirm

func (p Prompter) Confirm(question string, defaultYes bool) (bool, error)

Confirm asks a yes/no question.

func (Prompter) Select

func (p Prompter) Select(question string, options []string) (int, error)

Select asks the user to pick one option and returns its index.

type RenderOptions

type RenderOptions struct {
	Styles Styles
	Now    time.Time
	// Selected highlights the row (picker cursor).
	Selected bool
	// Links makes PR references OSC 8 hyperlinks.
	Links bool
	// PRURL finds the URL of a PR the row only has a number for; usually
	// Reporter.PRURL.
	PRURL func(number int) string
}

RenderOptions controls RenderRow.

type Reorder added in v0.3.0

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

Reorder is the bubbletea model: the stack shown top first, a cursor, and keys that move the branch under it. Exported for tests.

func NewReorder added in v0.3.0

func NewReorder(o ReorderOptions) *Reorder

NewReorder builds the model with the cursor on the current branch.

func (*Reorder) Init added in v0.3.0

func (r *Reorder) Init() tea.Cmd

Init has nothing to start.

func (*Reorder) Result added in v0.3.0

func (r *Reorder) Result() ReorderResult

Result returns the choice once the program has finished.

func (*Reorder) Update added in v0.3.0

func (r *Reorder) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles keys.

func (*Reorder) View added in v0.3.0

func (r *Reorder) View() tea.View

View renders the list inline.

type ReorderOptions added in v0.3.0

type ReorderOptions struct {
	Trunk string
	// Branches run bottom to top, as the stack is stored.
	Branches []string
	Current  string
	// PRs maps a branch to its pull request number, when known.
	PRs    map[string]int
	Styles *Styles
}

ReorderOptions configures the reorder list.

type ReorderResult added in v0.3.0

type ReorderResult struct {
	// Order is the new order, bottom to top.
	Order       []string
	Cancelled   bool
	Interrupted bool
}

ReorderResult is the user's choice.

func RunReorder added in v0.3.0

func RunReorder(ctx context.Context, in io.Reader, out io.Writer, o ReorderOptions) (ReorderResult, error)

RunReorder runs the list on the given terminal streams. Ctrl-C (or a cancelled context) is an interrupt and comes back as context.Canceled; Escape is a cancel and returns no error.

type Reporter

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

Reporter prints every human facing line the CLI produces, so all commands share one look (see docs/style.md). On a terminal it uses marks, colour, emoji headlines and spinners; piped it falls back to plain ASCII prefixes (ok:, note:, error:) with the same words.

func NewReporter

func NewReporter(in io.Reader, out, err io.Writer, o ReporterOptions) *Reporter

NewReporter builds a Reporter over the given streams. Terminal writers are wrapped so colour is downsampled to what the terminal supports and dropped under NO_COLOR; hyperlinks and the busy state pass through.

func (*Reporter) Branch

func (r *Reporter) Branch(name string) string

Branch styles a branch name for use inside a message.

func (*Reporter) Error

func (r *Reporter) Error(err error)

Error prints an error on stderr: the message, any detail (faint) and the next steps. It renders stack.Error specially and anything else as one line.

func (*Reporter) Finish added in v0.2.0

func (r *Reporter) Finish(err error)

Finish puts back what steps and prompts changed about the terminal: it leaves the program status as done, error (err) or idle (interrupted) and restores the window title. Call it once the command is over, on every exit path; it is safe to call more than once and does nothing if no step or prompt ran.

func (*Reporter) Info

func (r *Reporter) Info(format string, args ...any)

Info prints a detail line on stdout, indented under the result line.

func (r *Reporter) Link(url string) string

Link returns url for use in a line. Every URL printed through the Reporter becomes a link when its stream is a terminal; this only marks the intent at the call site.

func (r *Reporter) Links() bool

Links reports whether stdout gets OSC 8 hyperlinks. It is for blocks rendered elsewhere (the log tree, the picker) that go to stdout; lines printed through the Reporter are linked per stream on their own.

func (*Reporter) NextStep added in v0.2.0

func (r *Reporter) NextStep(format string, args ...any)

NextStep prints something the user can do about the line above it, on stdout under a ⚠ result: " ↳ git -C ~/src/app stash, then git stack sync again" (" - " when piped). Errors carry their own next steps.

func (*Reporter) PRURL added in v0.2.0

func (r *Reporter) PRURL(number int) string

PRURL is the URL of pull request number, or "" if nothing local knows it: the URLs passed to Ref, then the resolver. It's the one lookup every link uses, the log, the tree and the picker included (their options take it), so a PR is linked the same way wherever it's shown.

func (*Reporter) Partial added in v0.2.0

func (r *Reporter) Partial(format string, args ...any)

Partial prints a result line on stdout for a command that finished but left something undone that the user has to deal with: "⚠ Synced, but main was not updated" (note: when piped). Use it instead of Success whenever claiming success would be untrue; a real failure is an error instead.

func (*Reporter) Print

func (r *Reporter) Print(block string)

Print writes an already rendered block (a tree) to stdout as is.

func (*Reporter) Quiet

func (r *Reporter) Quiet() bool

Quiet reports whether non-error output is suppressed.

func (*Reporter) Ref

func (r *Reporter) Ref(number int, url string, state forge.State) string

Ref styles a pull request reference (#123) for a stdout line in the colour of its state (the line's own colour when state is unknown) and remembers url, so the reference is a link, underlined, wherever it is printed to a terminal.

func (*Reporter) SHA

func (r *Reporter) SHA(sha string) string

SHA styles a commit id for use inside a message: abbreviated to seven characters and faint.

func (*Reporter) SetPRResolver added in v0.2.0

func (r *Reporter) SetPRResolver(fn func(number int) string)

SetPRResolver sets how a pull request number found in a line (#123) is turned into a URL; it should only use local state, as it runs on the output path. Numbers it doesn't know ("") are left as text.

func (*Reporter) Step

func (r *Reporter) Step(ctx context.Context, phase app.Phase, message string, fn func(ctx context.Context) error) error

Step runs fn under a headline for the phase: an emoji, the message and a spinner on a terminal (the line is replaced by whatever is printed next when fn returns), or the message printed once when piped. The terminal's busy state is set for the duration, and the window title shows the message until the next step or Finish, as does the program status. Output written to Stream while the step runs is shown above the spinner.

func (*Reporter) Stream

func (r *Reporter) Stream() io.Writer

Stream returns a writer for a subprocess's live output. Each line is shown in the "│" gutter on stderr (plain indent when piped), above the spinner while a Step is running.

func (*Reporter) Styles

func (r *Reporter) Styles() Styles

Styles returns the palette for stdout: the default styles on a terminal, the zero value (no escape codes) when piped.

func (*Reporter) Success

func (r *Reporter) Success(format string, args ...any)

Success prints a result line on stdout: "✔ Created feat-a on main".

func (*Reporter) Waiting added in v0.2.0

func (r *Reporter) Waiting(question string) func()

Waiting tells the terminal the command is blocked on the user answering question (a prompt or picker) and returns a function to call once they have.

func (*Reporter) Warn

func (r *Reporter) Warn(format string, args ...any)

Warn prints a notice on stderr: "⚠ gh stack submits the whole stack". Notices carry names and git's words, so control characters in them are shown escaped rather than sent to the terminal.

func (*Reporter) Width added in v0.2.0

func (r *Reporter) Width() int

Width is how many columns stdout has when it is a terminal, for blocks rendered elsewhere (the log tree) that fit their lines to it; 0 when it isn't one or its size can't be read, meaning lines are never cut.

type ReporterOptions

type ReporterOptions struct {
	// OutTTY / ErrTTY: stdout / stderr are terminals (marks and colour).
	OutTTY, ErrTTY bool
	// Spinners enables animated headlines; needs a terminal on stdin and
	// stderr. Without it Step prints the headline once as a plain line.
	Spinners bool
	// Quiet drops everything but errors.
	Quiet bool
	// TerminalStatus lets steps and prompts set the window title and the
	// OSC 7501 program status (put back or finished at Finish). It only
	// takes effect on a terminal stderr without Quiet.
	TerminalStatus bool
	// Tmux says stderr is a tmux pane, so program status reports go
	// through tmux's passthrough.
	Tmux bool
}

ReporterOptions describe the streams the Reporter writes to.

type Styles

type Styles struct {
	Trunk     lipgloss.Style
	Branch    lipgloss.Style
	Current   lipgloss.Style
	Untracked lipgloss.Style
	Prefix    lipgloss.Style
	Selected  lipgloss.Style
	Match     lipgloss.Style
	PROpen    lipgloss.Style
	PRDraft   lipgloss.Style
	PRMerged  lipgloss.Style
	PRClosed  lipgloss.Style
	Restack   lipgloss.Style
	Muted     lipgloss.Style
	Help      lipgloss.Style
	Title     lipgloss.Style
	// Reporter marks.
	Success lipgloss.Style
	Warning lipgloss.Style
	Error   lipgloss.Style
}

Styles groups the lipgloss styles used by the tree and picker.

func DefaultStyles

func DefaultStyles() Styles

DefaultStyles returns the standard palette (ANSI colours so NO_COLOR and 16-colour terminals degrade gracefully).

type TreeRow

type TreeRow struct {
	Row app.Row
	// Prefix holds the tree glyphs ("├─ ", "│  └─ ").
	Prefix string
	// Matched positions in Row.Name when a filter is active.
	Matched []int
	// IsMatch is true when the row itself matched the filter (as opposed to
	// being kept as an ancestor of a match).
	IsMatch bool
}

TreeRow is a display row: the app row plus its tree prefix and, after filtering, the matched rune positions.

func BuildTree

func BuildTree(rows []app.Row) []TreeRow

BuildTree computes tree prefixes for rows in display order. Stacks are linear, so only the branches directly above a trunk can have siblings.

func FilterTree

func FilterTree(rows []TreeRow, query string) []TreeRow

FilterTree keeps rows matching query plus their ancestors, so the tree context survives filtering. An empty query returns every row.

Jump to

Keyboard shortcuts

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