bar

package
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package bar provides bar animation styles and presets for clog. Widget functions (Percent, ETA, Bytes, Rate, etc.) live in the github.com/gechr/clog/fx/bar/widget subpackage.

Index

Constants

View Source
const (
	// TickRate is the repaint interval when a bar animation is active (~20fps).
	TickRate = 50 * time.Millisecond

	DefaultWidthMin = 10 // default minimum auto-sized inner width
	DefaultWidthMax = 40 // default maximum auto-sized inner width
	WidthDivisor    = 4  // terminal width fraction used for auto-sizing
)
View Source
const DefaultSmoothingTau = 120 * time.Millisecond

DefaultSmoothingTau is the default exponential decay time constant for SmoothEase. The bar reaches ~95% of its target in 3τ (≈ 360 ms at 120 ms τ).

View Source
const PercentDisplayMax = 100.0

PercentDisplayMax is the maximum display percentage (always 100).

Variables

View Source
var (
	// Basic uses only ASCII characters for maximum terminal compatibility.
	//
	//	[=====>    ] 50%
	Basic = Style{
		CapLeft:   "[",
		CapRight:  "]",
		CapStyle:  defaultCapStyle,
		CharEmpty: ' ',
		CharFill:  '=',
		CharHead:  '>',
		Separator: " ",
		WidthMax:  DefaultWidthMax,
		WidthMin:  DefaultWidthMin,
	}

	// Block uses solid block characters without sub-cell resolution.
	//
	//	│█████░░░░░│ 50%
	Block = Style{
		CapLeft:   "│",
		CapRight:  "│",
		CapStyle:  defaultCapStyle,
		CharEmpty: '░',
		CharFill:  '█',
		Separator: " ",
		WidthMax:  DefaultWidthMax,
		WidthMin:  DefaultWidthMin,
	}

	// Dash uses a simple dash for filled cells and spaces for empty.
	//
	//	[-----     ] 50%
	Dash = Style{
		CapLeft:   "[",
		CapRight:  "]",
		CapStyle:  defaultCapStyle,
		CharEmpty: ' ',
		CharFill:  '-',
		Separator: " ",
		WidthMax:  DefaultWidthMax,
		WidthMin:  DefaultWidthMin,
	}

	// Gradient uses block-element characters with 8x sub-cell resolution
	// for the smoothest possible progression.
	//
	//	│██████▍   │ 64%
	Gradient = Style{
		CapLeft:      "│",
		CapRight:     "│",
		CapStyle:     defaultCapStyle,
		CharEmpty:    ' ',
		CharFill:     '█',
		GradientFill: []rune{'▏', '▎', '▍', '▌', '▋', '▊', '▉'},
		Separator:    " ",
		WidthMax:     DefaultWidthMax,
		WidthMin:     DefaultWidthMin,
	}

	// Thin uses box-drawing characters with half-cell resolution for smooth
	// progress, inspired by Python's Rich library. Filled and empty cells
	// use the same character differentiated by color. The fill shifts through
	// a red → yellow → green gradient as progress advances.
	// This is the default style.
	//
	//	━━━━━━━━━╸╺━━━━━━━━━━━━━ 45%
	Thin = Style{
		CharEmpty:        '━',
		CharFill:         '━',
		ProgressGradient: style.DefaultPercentGradient(),
		Separator:        " ",
		StyleEmpty:       thinEmptyStyle,
		WidthMax:         DefaultWidthMax,
		WidthMin:         DefaultWidthMin,
	}

	// Braille uses braille dot-fill characters with 8x sub-cell resolution,
	// inspired by Docker Compose's progress display.
	//
	//	[⣿⣿⣿⣿⣿⣦⠀⠀⠀⠀] 50%
	Braille = Style{
		CapLeft:      "[",
		CapRight:     "]",
		CapStyle:     defaultCapStyle,
		CharEmpty:    '⠀',
		CharFill:     '⣿',
		GradientFill: []rune{'⡀', '⣀', '⣄', '⣤', '⣦', '⣶', '⣷'},
		Separator:    " ",
		WidthMax:     DefaultWidthMax,
		WidthMin:     DefaultWidthMin,
	}

	// Smooth uses solid block characters with no caps. Empty cells use
	// dim grey blocks for a continuous appearance.
	//
	//	██████████████████████ 45%
	Smooth = Style{
		CharEmpty:  '█',
		CharFill:   '█',
		StyleEmpty: thinEmptyStyle,
		Separator:  " ",
		WidthMax:   DefaultWidthMax,
		WidthMin:   DefaultWidthMin,
	}
)

Predefined bar styles for common visual appearances. Pass any of these to WithStyle to change the bar's look.

Functions

func DefaultGradient

func DefaultGradient() []gradient.ColorStop

DefaultGradient returns the default red → yellow → green gradient used for Style.ProgressGradient.

func FormatLine

func FormatLine(msgParts, barPart, sep string, placement Placement, tw int) string

FormatLine positions barPart relative to msgParts according to the placement mode and terminal width. sep is the fallback separator used when the terminal is too narrow for padding.

func FormatPercent

func FormatPercent(current, total, digits int, pad bool) string

FormatPercent formats the percentage string for display alongside the bar. digits controls decimal places (0 → "50%", 1 → "50%" or "42.5%"). Trailing decimal zeros are always stripped ("50.0%" → "50%"). When pad is true, the result is right-aligned to the width of "100%" at the given digit count for stable display.

func PercentValue

func PercentValue(current, total int) float64

PercentValue computes the clamped percentage as a float64.

func Render

func Render(current, total int, s Style, termWidth int) string

Render renders the visual bar string for the given progress values. termWidth is the terminal column count (0 = fall back to auto-sizing from style).

func ShowPending added in v0.7.0

func ShowPending(s Style, current int) bool

ShowPending reports whether the bar block should be shown at the current progress.

Types

type Option

type Option func(*Style)

Option applies a configuration change to a Style.

func WithCapLeft

func WithCapLeft(s string) Option

WithCapLeft sets the left cap string (e.g. "[", "│").

func WithCapRight

func WithCapRight(s string) Option

WithCapRight sets the right cap string (e.g. "]", "│").

func WithCapStyle

func WithCapStyle(ls *lipgloss.Style) Option

WithCapStyle sets the lipgloss style applied to the left and right caps.

func WithCharEmpty

func WithCharEmpty(r rune) Option

WithCharEmpty sets the rune used for fully empty cells.

func WithCharFill

func WithCharFill(r rune) Option

WithCharFill sets the rune used for fully filled cells.

func WithCharHead

func WithCharHead(r rune) Option

WithCharHead sets the decorative rune at the leading edge of the filled section (1x resolution only). Set to 0 to disable. Ignored when Style.HalfFilled or Style.GradientFill is set.

func WithGradientFill

func WithGradientFill(runes []rune) Option

WithGradientFill sets the sub-cell fill runes ordered from least to most filled. Enables Nx sub-cell resolution where N = len(runes)+1. Overrides Style.HalfFilled and Style.CharHead.

func WithHalfEmpty

func WithHalfEmpty(r rune) Option

WithHalfEmpty sets the rune shown at the start of the empty section when Style.HalfFilled is not displayed (2x resolution). Set to 0 to disable.

func WithHalfFilled

func WithHalfFilled(r rune) Option

WithHalfFilled sets the rune shown at the leading edge of the filled section, enabling 2x sub-cell resolution. Set to 0 to disable.

func WithMaxWidth added in v0.7.6

func WithMaxWidth(w int) Option

WithMaxWidth sets the maximum auto-sized inner width.

func WithMinWidth added in v0.7.6

func WithMinWidth(w int) Option

WithMinWidth sets the minimum auto-sized inner width.

func WithPendingMode added in v0.7.0

func WithPendingMode(m PendingMode) Option

WithPendingMode sets how the bar behaves before any progress is reported.

func WithPlacement

func WithPlacement(p Placement) Option

WithPlacement sets the horizontal bar placement mode.

func WithProgressGradient

func WithProgressGradient(stops ...gradient.ColorStop) Option

WithProgressGradient sets the filled-cell color gradient.

func WithSeparator

func WithSeparator(sep string) Option

WithSeparator sets the string placed between the message, bar, and widget text.

func WithSmoothingMode added in v0.7.4

func WithSmoothingMode(m SmoothingMode) Option

WithSmoothingMode sets the bar fill smoothing mode.

func WithSmoothingTau added in v0.7.4

func WithSmoothingTau(d time.Duration) Option

WithSmoothingTau sets the exponential decay time constant for SmoothEase. Smaller values converge faster (snappier); larger values are smoother. Non-positive values reset to DefaultSmoothingTau.

func WithStyle

func WithStyle(s Style) Option

WithStyle replaces the entire bar style.

func WithStyleEmpty

func WithStyleEmpty(ls *lipgloss.Style) Option

WithStyleEmpty sets the lipgloss style for empty cells.

func WithStyleFill

func WithStyleFill(ls *lipgloss.Style) Option

WithStyleFill sets the lipgloss style for filled cells.

func WithUpdateInterval added in v0.7.0

func WithUpdateInterval(d time.Duration) Option

WithUpdateInterval samples the timing basis used by ETA, rate, and elapsed widgets/dynamic fields at most once per duration. Progress-driven text and the bar fill itself still render from live current/total updates. Non-positive values disable coalescing.

func WithWidgetLeft

func WithWidgetLeft(w Widget) Option

WithWidgetLeft sets the widget displayed to the left of the bar.

func WithWidgetRight

func WithWidgetRight(w Widget) Option

WithWidgetRight sets the widget displayed to the right of the bar.

func WithWidth

func WithWidth(w int) Option

WithWidth sets a fixed inner width for the bar. When w is 0, the bar auto-sizes from the terminal width.

type PendingMode added in v0.7.0

type PendingMode int

PendingMode controls how a bar is rendered before any progress is reported.

const (
	// PendingShow renders the bar and its widgets immediately, even at 0 progress.
	PendingShow PendingMode = iota
	// PendingHide suppresses the entire bar block until progress becomes positive.
	PendingHide
)

type Placement

type Placement int

Placement controls the horizontal placement of the progress bar within the terminal line.

const (
	// PlaceRightPad pushes the bar to the right edge of the terminal (default).
	PlaceRightPad Placement = iota
	// PlaceLeftPad places the bar before the message, padding the message to the right edge.
	PlaceLeftPad
	// PlaceInline places the bar immediately after the message with no gap.
	PlaceInline
	// PlaceLeft places the bar before the message with no padding.
	PlaceLeft
	// PlaceRight places the bar after the message with no padding.
	PlaceRight
	// PlaceAligned pads the message so that all bars in a group start at the
	// same column, determined by the longest message. Falls back to PlaceRight
	// for standalone (non-group) bars.
	PlaceAligned
)

type SmoothingMode added in v0.7.4

type SmoothingMode int

SmoothingMode controls how the bar fill interpolates toward the target progress.

const (
	// SmoothEase applies exponential smoothing so the bar eases toward the
	// target value instead of jumping instantly. This is the default.
	SmoothEase SmoothingMode = iota
	// SmoothNone disables smoothing; the bar jumps to the exact progress each frame.
	SmoothNone
)

type State

type State struct {
	Current int
	Elapsed time.Duration
	Rate    float64 // items per second (0 when elapsed or current is 0)
	Total   int
}

State holds progress information passed to Widget functions.

type Style

type Style struct {
	CapLeft          string               // left bracket; default "["
	CapRight         string               // right bracket; default "]"
	CapStyle         *lipgloss.Style      // lipgloss style for left/right caps; nil = plain text
	CharEmpty        rune                 // full empty cell; default '─'
	CharFill         rune                 // full filled cell; default '━'
	CharHead         rune                 // decorative head at leading edge (1x resolution); 0 = disabled; ignored when HalfFilled is set
	GradientFill     []rune               // sub-cell fill chars, least→most filled; enables Nx resolution (N = len+1); overrides HalfFilled/CharHead
	HalfEmpty        rune                 // half-cell at start of empty when HalfFilled is not shown; 0 = disabled
	HalfFilled       rune                 // half-cell at leading edge of filled (enables 2x resolution); 0 = disabled
	Placement        Placement            // horizontal bar placement; default PlaceRightPad
	PendingMode      PendingMode          // whether to show the bar before progress starts; default PendingShow
	ProgressGradient []gradient.ColorStop // when set, colors filled cells based on progress; overrides StyleFill foreground
	Separator        string               // separator between message, bar, and widget text; default " "
	Smoothing        SmoothingMode        // bar fill smoothing mode; default SmoothEase
	SmoothingTau     time.Duration        // exponential decay time constant; 0 = DefaultSmoothingTau (150ms)
	StyleEmpty       *lipgloss.Style      // lipgloss style for empty cells; nil = plain text
	StyleFill        *lipgloss.Style      // lipgloss style for filled cells; nil = plain text
	UpdateInterval   time.Duration        // samples the timing basis for ETA/rate/elapsed while leaving progress live
	Width            int                  // fixed inner width; 0 = auto-size
	WidgetLeft       Widget               // widget to the left of the bar; nil = nothing
	WidgetRight      Widget               // widget to the right of the bar; nil = default padded percent
	WidthMax         int                  // maximum auto-sized width; default 40
	WidthMin         int                  // minimum auto-sized width; default 10
}

Style configures the visual appearance of a determinate progress bar.

func ApplyOptions

func ApplyOptions(opts []Option) Style

ApplyOptions returns a copy of DefaultStyle with all opts applied in order. Use WithStyle as the first option to start from a different base style.

func DefaultStyle

func DefaultStyle() Style

DefaultStyle returns the default bar Style. It uses box-drawing characters with half-cell resolution for smooth progress.

type Widget

type Widget func(State) string

Widget renders a text label from the current bar state. Return "" to display nothing for this tick.

Directories

Path Synopsis
Package widget provides composable text widgets for progress bars.
Package widget provides composable text widgets for progress bars.

Jump to

Keyboard shortcuts

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