prism

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2026 License: MIT Imports: 11 Imported by: 0

README

Prism

Build beautiful command-line tools in Go, without the boilerplate. A component library for consistent output styling, tables, spinners, progress bars, and interactive prompts. Import it into any Go project and ship a polished CLI in an afternoon.

go get github.com/velocitykode/prism
import "github.com/velocitykode/prism"

Prism has zero framework dependency. Use it in any Go program, Velocity or not. It is built on the Charm stack (lipgloss, bubbletea, bubbles).

Why Prism

  • Consistent by default. Leveled output, boxes, and prompts share one theme, so your whole tool looks intentional.
  • Batteries included. Output, tables, spinners, progress bars, and seven prompt types in one import.
  • One-liners. Each helper is a single call that returns a typed result; no models, no event loops to wire up.
  • Drop-in anywhere. No framework lock-in, no global state.

Output

prism.Header("migrate")               // MIGRATE (styled header)
prism.Info("Running migrations...")   // informational line
prism.Success("Done")                 // checkmark, success color
prism.Warning("No migrations found")  // warning glyph and color
prism.Error("Connection failed")      // error glyph and color
prism.Muted("skipping...")            // dimmed text
prism.Bold("important")               // bold text

prism.Note("Server running on port 4000")  // boxed message (primary border)
prism.Alert("Database connection failed")  // boxed message (error border)

Tables

prism.Table(
    []string{"Method", "Path", "Name"},
    [][]string{
        {"GET", "/users", "users.index"},
        {"POST", "/users", "users.store"},
    },
)

Spinners & Progress

A spinner wraps a slow step; a progress bar tracks a known count:

prism.Spinner("Building...", func() error {
    return exec.Command("go", "build", ".").Run()
})

prism.Progress(len(items), func(inc func()) {
    for _, item := range items {
        process(item)
        inc()
    }
})

Interactive Prompts

Each prompt blocks for input and returns the typed result:

name := prism.Text("Model name:", prism.WithRequired(), prism.WithPlaceholder("User"))
pass := prism.Password("Database password:")
yes  := prism.Confirm("Generate migration?", prism.WithDefaultYes())
db   := prism.Select("Database driver:", []string{"mysql", "postgres", "sqlite"})
features := prism.Multiselect("Enable:", []string{"soft-deletes", "uuid", "timestamps"})

user := prism.Search("Find user:", func(q string) []string {
    return filterUsers(q)
})

Theming

Output colors and prompt styling are driven by a shared theme, so a whole tool stays visually consistent. Override it to match your brand.

Built On

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alert

func Alert(message string)

Alert prints a message in a rounded box with error-colored border.

func Bold

func Bold(message string)

Bold prints bold text.

func Configure

func Configure(cfg Config)

Configure merges cfg into the active config and rebuilds all styles. Empty string fields are ignored (they keep the current value), so callers can override just the fields they care about.

func Confirm

func Confirm(label string, opts ...ConfirmOption) bool

Confirm displays a yes/no prompt and returns the user's choice.

func Error

func Error(message string)

Error prints an error message.

func ExitOnCancel

func ExitOnCancel(m any)
func Header(message string)

Header prints a styled command header.

func Highlight

func Highlight(text string) string

Highlight returns styled text without printing.

func Info

func Info(message string)

Info prints an informational message with an arrow symbol.

func KeyValue

func KeyValue(key, value string)

KeyValue prints a key-value pair.

func LoadConfig

func LoadConfig(r io.Reader) error

LoadConfig reads TOML config from r and applies it. Missing fields keep defaults. The caller owns the file - open with os.Open, pass the *os.File, close it yourself.

func Multiselect

func Multiselect(label string, options []string) []string

Multiselect displays a list of options with toggles and returns all selected options.

func Muted

func Muted(message string)

Muted prints dimmed text.

func Newline

func Newline()

Newline prints an empty line.

func NextSteps

func NextSteps(steps []string)

NextSteps prints formatted next steps.

func Note

func Note(message string)

Note prints a message in a rounded box with primary-colored border.

func Password

func Password(label string) string

Password displays a masked text input and returns the entered value.

func Progress

func Progress(total int, fn func(increment func()))

Progress displays an animated progress bar for batch operations. The fn receives an increment function to call after each completed item.

func ResetConfig

func ResetConfig()

ResetConfig reverts all styles to the built-in defaults.

func Search(label string, fn func(query string) []string) string

Search displays a text input that filters results dynamically. The fn is called with the current query and should return matching options.

func Select

func Select(label string, options []string, opts ...SelectOption) string

Select displays a list of options and returns the selected one.

func SetCancelHandler

func SetCancelHandler(fn func())

SetCancelHandler registers a callback invoked right before the process exits on cancel. Pass nil to restore the default (exit only). The callback should be cheap and non-blocking; it runs inside the prompt's return path.

func SetWriter

func SetWriter(w io.Writer)

SetWriter sets the output writer for all non-interactive components. Pass nil to fall back to os.Stdout (resolved dynamically at each call).

func Spinner

func Spinner(message string, fn func() error) error

Spinner displays an animated spinner while fn executes. Returns the error from fn, if any.

Without an interactive terminal (CI, headless, piped output) the bubbletea program cannot open /dev/tty and p.Run would fail, masking fn's result entirely. In that case Spinner degrades to a plain one-line message and runs fn directly, so the wrapped work still executes and its real error is returned unchanged.

func Step

func Step(message string)

Step prints an indented step message.

func StyleError

func StyleError(text string) string

StyleError renders text in the error color.

func StyleMuted

func StyleMuted(text string) string

StyleMuted renders text in the muted color.

func StylePrimary

func StylePrimary(text string) string

StylePrimary renders text in the primary brand color (same as Highlight).

func StyleSuccess

func StyleSuccess(text string) string

StyleSuccess renders text in the success color.

func StyleWarning

func StyleWarning(text string) string

StyleWarning renders text in the warning color.

func Success

func Success(message string)

Success prints a success message with a checkmark.

func Table

func Table(headers []string, rows [][]string)

Table prints a formatted table with styled headers and dynamic column widths.

func Text

func Text(label string, opts ...TextOption) string

Text displays a single-line text input and returns the entered value.

func Tip

func Tip(message string)

Tip prints a highlighted hint with an info glyph. Styled with primaryStyle (bold) so it stands out from Info's muted line - intended for callouts like "install bun for faster installs" that users might otherwise skim past.

func Warning

func Warning(message string)

Warning prints a warning message.

Types

type Canceller

type Canceller interface {
	Cancelled() bool
}

Canceller is implemented by interactive prompt models that can be cancelled via Ctrl+C or Esc. Implementations return true once the user has signalled a cancel.

type Colors

type Colors struct {
	Primary string `toml:"primary"`
	Success string `toml:"success"`
	Warning string `toml:"warning"`
	Error   string `toml:"error"`
	Muted   string `toml:"muted"`
}

Colors are hex strings like "#0e87cd" or named ANSI colors accepted by lipgloss.

type Config

type Config struct {
	Colors  Colors  `toml:"colors"`
	Symbols Symbols `toml:"symbols"`
}

Config controls colors and symbols used by all output and prompt components. Empty string fields are ignored by Configure - they keep the current value.

func ActiveConfig

func ActiveConfig() Config

ActiveConfig returns the currently applied config.

type ConfirmOption

type ConfirmOption func(*confirmConfig)

ConfirmOption configures a Confirm prompt.

func WithDefaultNo

func WithDefaultNo() ConfirmOption

WithDefaultNo sets the default to no.

func WithDefaultYes

func WithDefaultYes() ConfirmOption

WithDefaultYes sets the default to yes.

type SelectOption

type SelectOption func(*selectConfig)

SelectOption configures a Select prompt.

func WithSelectDefault

func WithSelectDefault(val string) SelectOption

WithSelectDefault sets the initially highlighted option.

type Symbols

type Symbols struct {
	Arrow string `toml:"arrow"`
	Check string `toml:"check"`
	Warn  string `toml:"warn"`
	Cross string `toml:"cross"`
	Tip   string `toml:"tip"`
}

Symbols are the glyphs used by Info (arrow), Success (check), Warning (warn), Error (cross), and Tip (info glyph).

type TextOption

type TextOption func(*textConfig)

TextOption configures a Text prompt.

func WithDefault

func WithDefault(s string) TextOption

WithDefault sets a default value pre-filled in the input.

func WithPlaceholder

func WithPlaceholder(s string) TextOption

WithPlaceholder sets placeholder text shown when input is empty.

func WithRequired

func WithRequired() TextOption

WithRequired marks the input as required.

func WithValidation

func WithValidation(fn func(string) error) TextOption

WithValidation sets a validation function.

Jump to

Keyboard shortcuts

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