table

package
v0.0.39 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultTerminalWidth is used when terminal width cannot be determined
	DefaultTerminalWidth = 80
)

Variables

This section is empty.

Functions

func CalculateColumnWidths

func CalculateColumnWidths(columns []Column, termWidth int, padding int) []int

CalculateColumnWidths computes actual column widths based on terminal width. Use CalculateColumnWidthsWithContent for content-aware sizing.

func CalculateColumnWidthsWithContent

func CalculateColumnWidthsWithContent(columns []Column, termWidth int, padding int, contentWidths []int) []int

CalculateColumnWidthsWithContent computes column widths with optional content-awareness. The algorithm: 1. Allocate fixed-width columns first 2. Distribute remaining space to flexible columns by weight 3. Clamp flexible columns to min/max constraints 4. Cap flexible columns at actual content width (if contentWidths provided) 5. Give any remaining space to flexible columns that can use it

func FormatCell

func FormatCell(value string, col Column, width int) string

FormatCell formats a cell value according to column settings

func GetTerminalWidth

func GetTerminalWidth() int

GetTerminalWidth returns the current terminal width. Falls back to DefaultTerminalWidth if width cannot be determined.

func MaxScrollOffset added in v0.0.27

func MaxScrollOffset(s string, maxWidth int) int

MaxScrollOffset returns the maximum scroll offset (in display cells) for ScrollWindow. Returns 0 if the string fits within maxWidth.

func PadCenter

func PadCenter(s string, width int) string

PadCenter centers a string within the specified display width. If the string is wider than width, it is truncated.

func PadLeft

func PadLeft(s string, width int) string

PadLeft pads a string to the specified display width with spaces on the left. If the string is wider than width, it is truncated.

func PadRight

func PadRight(s string, width int) string

PadRight pads a string to the specified display width with spaces on the right. If the string is wider than width, it is truncated.

func ParseSortKeyNumber

func ParseSortKeyNumber(key string) int

ParseSortKeyNumber converts a key string ("1", "f1", etc.) to a 1-based number. Returns 0 if the key is not a sort key.

func ScrollWindow added in v0.0.27

func ScrollWindow(s string, maxWidth int, offset int) string

ScrollWindow returns a sliding window view of a string for scroll animation. At offset 0, truncates from end (like TruncateWithEllipsis). At offset > 0, shows content starting from that display-cell offset with ellipsis indicators.

func ShortenPath

func ShortenPath(p string, maxWidth int) string

ShortenPath shortens a file path to fit within maxWidth display cells. It prioritizes keeping the filename visible and shortens directory components.

func SortableColumnIndex

func SortableColumnIndex(columns []Column, n int) int

SortableColumnIndex returns the actual column index for the n-th sortable column (1-based). Returns -1 if n is out of range.

func SortableColumnsHelp

func SortableColumnsHelp(columns []Column) []string

SortableColumnsHelp returns help text lines for sortable columns.

func StringWidth

func StringWidth(s string) int

StringWidth returns the display width of a string in terminal cells. Accounts for wide characters (CJK, emojis, etc.) AND ANSI escape codes.

func TruncateFromStart

func TruncateFromStart(s string, maxWidth int) string

TruncateFromStart truncates a string from the beginning, keeping the end. Adds "…" prefix if truncated. Useful for paths where the end is more relevant.

func TruncateWithEllipsis

func TruncateWithEllipsis(s string, maxWidth int) string

TruncateWithEllipsis truncates a string to fit within maxWidth display cells, adding "…" if truncated. Handles wide characters correctly.

Types

type Alignment

type Alignment int

Alignment specifies text alignment within a column

const (
	AlignLeft Alignment = iota
	AlignRight
	AlignCenter
)

type Column

type Column struct {
	Header       string       // Column header text
	Width        int          // Fixed width (0 = flexible)
	MinWidth     int          // Minimum width for flexible columns
	MaxWidth     int          // Maximum width (0 = unlimited)
	Weight       float64      // Weight for distributing remaining space (default 1.0)
	Align        Alignment    // Left, Right, Center (default Left)
	Truncate     bool         // Truncate with ellipsis if content too long
	TruncateMode TruncateMode // How to truncate: TruncateEnd (default) or TruncateStart
	SortKey      string       // When non-empty, column is sortable. Keys 1-9/F1-F9 map to sortable columns in order.
}

Column defines a table column configuration

func (*Column) EffectiveWeight

func (c *Column) EffectiveWeight() float64

EffectiveWeight returns the weight for flexible width distribution. Defaults to 1.0 if not set.

func (*Column) IsFixed

func (c *Column) IsFixed() bool

IsFixed returns true if the column has a fixed width

type Row

type Row struct {
	Cells []string       // Cell contents (one per column)
	Style lipgloss.Style // Optional row-level style override
}

Row represents a table row

type SortConfig

type SortConfig struct {
	Column    int           // Column index to sort by (-1 = none)
	Direction SortDirection // Sort direction
}

SortConfig specifies current sort state

type SortDirection

type SortDirection int

SortDirection for column sorting

const (
	SortNone SortDirection = iota
	SortAsc
	SortDesc
)

type SortState

type SortState struct {
	Key       string        // SortKey of the sorted column ("" = none)
	Direction SortDirection // Sort direction
}

SortState tracks current sort settings using a key name. Unlike SortConfig (which uses column indices), SortState uses string keys so it can persist across table rebuilds and adapt to different column layouts.

func (*SortState) HandleSortKey

func (s *SortState) HandleSortKey(columns []Column, key string) bool

HandleSortKey processes a keyboard key press (e.g., "1", "f1") and toggles sort for the corresponding sortable column. Returns true if sort state changed.

func (*SortState) ToConfig

func (s *SortState) ToConfig(columns []Column) SortConfig

ToConfig converts key-based SortState to index-based SortConfig for table rendering.

func (*SortState) Toggle

func (s *SortState) Toggle(key string)

Toggle cycles sort for a key: none -> asc -> desc -> none

type Table

type Table struct {
	Columns        []Column
	Rows           []Row
	SelectedIndex  int // Currently selected row (-1 for none)
	ViewportOffset int // First visible row index
	ViewportHeight int // Number of visible rows (0 = show all)
	TerminalWidth  int // Terminal width for width calculations
	Sort           SortConfig
	Padding        int // Padding between columns (default 2)

	// Styles
	HeaderStyle   lipgloss.Style
	SelectedStyle lipgloss.Style
	SeparatorChar string // Default "─"
	// contains filtered or unexported fields
}

Table holds table state and configuration

func New

func New(columns ...Column) *Table

New creates a new Table with the given columns

func (*Table) AddRow

func (t *Table) AddRow(row Row)

AddRow adds a row to the table and invalidates cached widths

func (*Table) CalculateWidths

func (t *Table) CalculateWidths() []int

CalculateWidths computes actual column widths based on terminal width. For flexible columns, widths are capped at actual content width (no wasted space).

func (*Table) ClearRows

func (t *Table) ClearRows()

ClearRows removes all rows from the table and invalidates cached widths

func (*Table) EnsureCursorVisible

func (t *Table) EnsureCursorVisible()

EnsureCursorVisible adjusts viewport to keep selected row visible

func (*Table) GetColumnWidth

func (t *Table) GetColumnWidth(index int) int

GetColumnWidth returns the calculated width for a specific column index. Useful for pre-truncating content before adding rows.

func (*Table) InvalidateWidths

func (t *Table) InvalidateWidths()

InvalidateWidths forces recalculation of column widths on next render

func (*Table) MoveSelection

func (t *Table) MoveSelection(delta int)

MoveSelection moves the selection by delta rows (positive = down, negative = up)

func (*Table) NeedsScrollIndicator

func (t *Table) NeedsScrollIndicator() bool

NeedsScrollIndicator returns true if viewport scrolling is active

func (*Table) Render

func (t *Table) Render() string

Render returns the complete table as a string (header, separator, rows)

func (*Table) RenderHeader

func (t *Table) RenderHeader() string

RenderHeader returns the formatted header row

func (*Table) RenderRows

func (t *Table) RenderRows() string

RenderRows returns visible rows as formatted string

func (*Table) RenderScrollIndicator

func (t *Table) RenderScrollIndicator(style lipgloss.Style) string

RenderScrollIndicator returns scroll percentage indicator

func (*Table) RenderSeparator

func (t *Table) RenderSeparator() string

RenderSeparator returns the separator line between header and rows

func (*Table) RenderWithScroll

func (t *Table) RenderWithScroll(scrollStyle *lipgloss.Style) string

RenderWithScroll returns the complete table with optional scroll indicator. Pass a style for the scroll indicator, or nil to omit it.

func (*Table) RowCount

func (t *Table) RowCount() int

RowCount returns the total number of rows

func (*Table) ScrollPercentage

func (t *Table) ScrollPercentage() int

ScrollPercentage returns current scroll position as percentage (0-100)

func (*Table) SelectedRow

func (t *Table) SelectedRow() *Row

SelectedRow returns the currently selected row, or nil if none selected

func (*Table) SetTerminalWidth

func (t *Table) SetTerminalWidth(width int)

SetTerminalWidth sets the terminal width and invalidates cached widths

func (*Table) VisibleRows

func (t *Table) VisibleRows() []Row

VisibleRows returns the slice of rows currently visible in the viewport

type TruncateMode

type TruncateMode int

TruncateMode specifies how to truncate content that's too long

const (
	TruncateEnd   TruncateMode = iota // Truncate from end: "hello..." (default)
	TruncateStart                     // Truncate from start: "...world" (good for paths)
)

Jump to

Keyboard shortcuts

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