table

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 9 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.

README

Table Component (tui/table)

An importable, high-performance table component built on Bubble Tea v2. It supports massive datasets, two render modes, per‑cell styling, stable selection, and swappable data providers.

Design & Features

  • Modes: Auto (lipgloss.table decides widths) and Fit (constrain columns to fit width; no manual ASCII slicing).
  • Scale: Virtualized rendering — only visible rows are rendered; suitable for tens of thousands of rows.
  • Model-driven: The table consumes a List of Row items with stable IDs; no SetCell API.
  • Styling: Every cell renders through a lipgloss.Style; column headers and inner vertical separators are customizable. No outside frame or header underline.
  • Selection: Multi-select via stable row IDs; selection overlay style independent from focus.
  • Stability: When the focused row disappears, the selector moves to the first row after it that remains, else to the new last row; selection prunes vanished IDs. Only moves of the cursor (keys, Select, SetList) decide its row; a redraw does not. Cursor and Viewport report the position, so a host reads it from the table instead of keeping its own index.
  • Providers: Slice-backed (SliceList) and doubly linked (LinkedList), both storing Row. SimpleRow is a reusable Row implementation.

Interfaces

  • Row: Columns() (id string, cells []string, styles []*lipgloss.Style, exists bool)
  • List: Lines(top, num int) []Row, Above(rowID, num int) []Row, Below(rowID, num int) []Row, Len() int, Find(rowID string) (int, Row, bool)

Integrating

  • Import: table "github.com/stokaro/kc/tui/table"
  • Construct a provider and the table:
    cols := []table.Column{{Title: "ID", Width: 12}, {Title: "Status", Width: 8}}
    rows := []table.Row{table.SimpleRow{ID: "id-1"}, table.SimpleRow{ID: "id-2"}}
    list := table.NewSliceList(rows) // or table.NewLinkedList(rows)
    bt := table.NewBigTable(cols, list, width, height)
    
  • In your Bubble Tea model: forward tea.Msg to bt.Update(msg), call bt.SetSize on window changes, and render with bt.View().

Styling

  • Configure styles via Styles and SetStyles:
    st := table.DefaultStyles()
    st.Header = st.Header.Bold(true).Foreground(lipgloss.Color("#8F8"))
    st.Selector = lipgloss.NewStyle().Background(lipgloss.Color("12")).Foreground(lipgloss.Color("0"))
    st.Cell = lipgloss.NewStyle()
    bt.SetStyles(st)
    
  • Per-cell styles: return []*lipgloss.Style from your Row.Columns(); each cell’s style inherits from Styles.Cell and the selection overlay.
  • Selector highlight: applied to the focused row; multi-select overlay also uses Styles.Selector.

Testing

  • Package tests: go test ./tui/table -v
  • Covers: selection overlay, provider ops, selector stability, and render height for Auto/Fit.

Notes

  • Always import v2 packages: charm.land/bubbletea/v2, charm.land/bubbles/v2/..., charm.land/lipgloss/v2.
  • Rows are ASCII only; ANSI is produced by styles. No custom ASCII truncation is performed by the component.

Documentation

Overview

Package table shows a long list as a table that reads only the rows on screen, for the panels of a two-panel program.

A program describes its data as a List of Rows. A Row has a stable ID, plain text cells and an optional style for each cell. A List hands out a window of rows by position or next to an ID, so a list of tens of thousands of rows costs only the rows the table shows. SliceList and LinkedList are ready to use; a program can implement List over its own data, such as a cache that changes in the background.

BigTable is the widget. NewBigTable takes the Columns, the List and the size of the content area; SetSize changes the size. The program sends the key messages of the focused table to UpdateWithContext: Up and Down (or k and j), PgUp, PgDn, Home and End move the cursor, Left and Right (or h and l) pan a line wider than the table, and Insert or C-t toggles the mark of the row under the cursor and moves down. View draws the header line and the rows, with no frame around them, so the program draws its own.

The cursor and the marks follow row IDs, not positions. After SetList with rows added or removed, the cursor stays on its row, or moves to the next row that remains when its row is gone. Marks stay on the rows that remain.

In ModeScroll, the default, a column is as wide as its title or its widest cell on screen, and the line pans when it is wider than the table. The Column fields MinWidth, Fill, Keep, CutMiddle, StopAtShare, Yield, Whole and Drop say which columns narrow or go first when the table is too narrow. ModeFit fits every column into the width instead.

Methods that read rows take a context.Context and pass it to the List. A BigTable is not safe for concurrent use; the program owns it on its Bubble Tea update loop.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BigTable

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

BigTable is a reusable Bubble Tea component that renders large, dynamic tables backed by a List provider using a single lipgloss.table. Only inner vertical separators are supported; no outside borders or underline.

Example

This example builds a table over a slice of rows, moves the cursor and marks a row as the keys of the focused panel would, and prints the view without its colors. The bars show the edges of the 30 columns.

The quick start in the module's README.md is this example; a test keeps the two the same.

package main

import (
	"context"
	"fmt"
	"strings"

	tea "charm.land/bubbletea/v2"
	"github.com/charmbracelet/x/ansi"

	"github.com/stokaro/kc/tui/table"
)

func main() {
	ctx := context.Background()
	rows := []table.Row{
		table.SimpleRow{ID: "bin", Cells: []string{"bin", "<DIR>", "Nov 28"}},
		table.SimpleRow{ID: "docs", Cells: []string{"docs", "<DIR>", "Nov 29"}},
		table.SimpleRow{ID: "go.mod", Cells: []string{"go.mod", "1.2K", "Nov 27"}},
		table.SimpleRow{ID: "main.go", Cells: []string{"main.go", "8.4K", "Nov 29"}},
		table.SimpleRow{ID: "README.md", Cells: []string{"README.md", "3.1K", "Nov 20"}},
	}
	cols := []table.Column{{Title: "Name"}, {Title: "Size"}, {Title: "Modified"}}

	t := table.NewBigTable(cols, table.NewSliceList(rows), 30, 6)
	t.BorderVertical(ctx, true)
	t.Focus(ctx)

	t.UpdateWithContext(ctx, tea.KeyPressMsg{Code: tea.KeyDown})
	t.UpdateWithContext(ctx, tea.KeyPressMsg{Code: tea.KeyInsert})

	for line := range strings.SplitSeq(ansi.Strip(t.View().Content), "\n") {
		fmt.Printf("|%s|\n", line)
	}
	id, _ := t.CurrentID(ctx)
	fmt.Println("cursor:", id)
	fmt.Println("marked:", t.SelectedIDs())
}
Output:
|Name           │Size │Modified|
|bin            │<DIR>│Nov 28  |
|docs           │<DIR>│Nov 29  |
|go.mod         │1.2K │Nov 27  |
|main.go        │8.4K │Nov 29  |
|README.md      │3.1K │Nov 20  |
cursor: go.mod
marked: [docs]

func NewBigTable

func NewBigTable(cols []Column, list List, w, h int) BigTable

NewBigTable constructs a table with the given columns, data provider and initial size (content width and height). Titles are plain text; runes count as one cell each (sort marks such as "↓").

func (*BigTable) Blur

func (m *BigTable) Blur(ctx context.Context)

Blur sets the table as unfocused (selector hidden).

func (*BigTable) BorderVertical

func (m *BigTable) BorderVertical(ctx context.Context, v bool) *BigTable

BorderVertical toggles vertical separators between columns (inner verticals).

func (*BigTable) ClearMarks

func (m *BigTable) ClearMarks()

ClearMarks removes all multi-select marks.

func (*BigTable) CurrentID

func (m *BigTable) CurrentID(ctx context.Context) (string, bool)

CurrentID returns the focused row ID, if any.

func (*BigTable) Cursor

func (m *BigTable) Cursor() int

Cursor returns the index of the row under the cursor.

func (*BigTable) Focus

func (m *BigTable) Focus(ctx context.Context)

Focus sets the table as focused (selector visible on the focused row).

func (*BigTable) Focused

func (m *BigTable) Focused() bool

Focused reports whether the table is focused.

func (*BigTable) GetList

func (m *BigTable) GetList() List

GetList returns the current data provider.

func (*BigTable) Mark

func (m *BigTable) Mark(ctx context.Context, id string, selected bool) bool

Mark toggles selection state for a row ID without moving the cursor.

func (*BigTable) Refresh

func (m *BigTable) Refresh(ctx context.Context)

Refresh forces a re-render of the current window without changing state.

func (*BigTable) Select

func (m *BigTable) Select(ctx context.Context, id string) bool

Select moves the focus to the row with the given ID, if present, and adjusts the window so the focused row is visible. Returns true if found.

func (*BigTable) SelectedIDs

func (m *BigTable) SelectedIDs() []string

SelectedIDs returns the set of marked row IDs (multi-select state).

func (*BigTable) SetColumns

func (m *BigTable) SetColumns(ctx context.Context, cols []Column)

SetColumns replaces the columns and keeps the rows' state: the cursor stays on the same row at the same place in the window, and marked rows stay marked. The horizontal scroll goes back to the first column, since the old offset belongs to the old columns.

func (*BigTable) SetFocused

func (m *BigTable) SetFocused(ctx context.Context, v bool) *BigTable

SetFocused toggles focus explicitly and returns the receiver for chaining.

func (*BigTable) SetHorizontalStep

func (m *BigTable) SetHorizontalStep(step int) *BigTable

SetHorizontalStep sets the number of characters to pan left/right in ModeScroll. Values < 1 are clamped to 1. Returns the receiver for chaining.

func (*BigTable) SetList

func (m *BigTable) SetList(ctx context.Context, list List)

SetList swaps the data provider and repositions the cursor based on the previously focused row ID. If that row disappeared, the cursor moves to the first row after it that remains, else to the new last row, so rows that left with it are skipped.

Example

This example replaces the rows while the cursor is on a row that goes away: the cursor moves to the next row that remains.

package main

import (
	"context"
	"fmt"

	"github.com/stokaro/kc/tui/table"
)

func fileRow(name, size, modified string) table.Row {
	return table.SimpleRow{ID: name, Cells: []string{name, size, modified}}
}

func main() {
	ctx := context.Background()
	list := table.NewSliceList([]table.Row{
		fileRow("a.txt", "1K", "Nov 01"),
		fileRow("b.txt", "2K", "Nov 02"),
		fileRow("c.txt", "3K", "Nov 03"),
	})
	t := table.NewBigTable([]table.Column{{Title: "Name"}}, list, 20, 6)
	t.Select(ctx, "b.txt")

	t.SetList(ctx, table.NewSliceList([]table.Row{
		fileRow("a.txt", "1K", "Nov 01"),
		fileRow("c.txt", "3K", "Nov 03"),
	}))

	id, _ := t.CurrentID(ctx)
	fmt.Println("cursor:", id)
}
Output:
cursor: c.txt

func (*BigTable) SetMode

func (m *BigTable) SetMode(ctx context.Context, md GridMode)

SetMode switches between ModeScroll and ModeFit and refreshes the view.

func (*BigTable) SetSize

func (m *BigTable) SetSize(ctx context.Context, w, h int)

SetSize updates the component size (content area). Width/height are clamped to sensible minimums and trigger a relayout.

func (*BigTable) SetStyles

func (m *BigTable) SetStyles(s Styles)

SetStyles overrides the component styles.

func (*BigTable) ToggleMode

func (m *BigTable) ToggleMode(ctx context.Context)

ToggleMode flips the current GridMode.

func (*BigTable) Update

func (m *BigTable) Update(msg tea.Msg) (first, second tea.Cmd)

Update is UpdateWithContext under a context of its own with a short timeout, for a program that has no context at hand.

func (*BigTable) UpdateWithContext

func (m *BigTable) UpdateWithContext(ctx context.Context, msg tea.Msg) (first, second tea.Cmd)

UpdateWithContext handles key navigation and selection toggling. Both returned commands are nil today; the pair keeps the signature batchable for external composition.

func (*BigTable) View

func (m *BigTable) View() tea.View

View renders the component.

func (*BigTable) Viewport

func (m *BigTable) Viewport() (top, rows int)

Viewport returns the index of the first row shown and the number of rows the body has room for.

func (*BigTable) VisibleRowID

func (m *BigTable) VisibleRowID(i int) (string, bool)

VisibleRowID returns the row ID at the given zero-based visible row index within the current window (data rows only; header is not counted). It returns ok=false when the index is out of bounds.

type Column

type Column struct {
	Title string
	Width int
	// MinWidth lets the column give up width in ModeScroll: when the
	// columns are wider than the viewport, it shrinks, down to MinWidth,
	// before the line needs horizontal panning, so the columns after it
	// stay visible. A cell cut this way ends in "…". Zero never shrinks.
	MinWidth int
	// Fill marks a free-text column, such as a message or a description.
	// In ModeScroll it takes the spare width of the line, and when the
	// line is too wide it gives up width before the other columns, down
	// to MinWidth or, without one, the width of its title. The columns
	// that name things then keep their natural width.
	Fill bool
	// Keep is the width a Fill column keeps in ModeScroll before the
	// columns with a Drop give way: while it would get fewer cells than
	// Keep (or than its text needs, when that is less), the next column
	// with a Drop is left out. Zero never drops a column for it.
	Keep int
	// CutMiddle makes a cell that is longer than its column keep its
	// start and its end, with "…" between them, as mc cuts a long file
	// name. Generated names, such as pod names, differ at the end. A cell
	// cut by horizontal panning still ends in "…".
	CutMiddle bool
	// StopAtShare stops a column with a MinWidth from giving up width
	// once it is two fifths of the viewport wide (or MinWidth, when that
	// is more). A name column then gives way in a narrow panel, where the
	// columns after it would be cut, but keeps its whole text in a wide
	// one, where the line pans instead.
	StopAtShare bool
	// Yield makes a column with a MinWidth give up width in ModeScroll
	// only for the last Whole column after it: while that column ends
	// past the viewport, the Yield column narrows, down to MinWidth, and
	// its cells end in "…". Otherwise it keeps its width, also when the
	// line pans. Without a Whole column after it, it never narrows.
	Yield bool
	// Whole marks a column that the Yield columns before it give up
	// width for, so that it is shown whole when they can make room.
	Whole bool
	// Drop lets the column be left out in ModeScroll so that a Fill
	// column keeps its Keep width. The lowest Drop goes first. A dropped
	// column is not drawn, its title neither. Zero never drops. ModeFit
	// shows every column.
	Drop int
}

Column describes a visible column with a title and desired width hint.

type GridMode

type GridMode int

GridMode controls how the table renders horizontally.

  • ModeScroll: automatic column widths (lipgloss.table decides).
  • ModeFit: constrain columns to fit the total width (no manual slicing).
const (
	// ModeScroll uses automatic column widths.
	ModeScroll GridMode = iota
	// ModeFit constrains columns to fit the viewport width.
	ModeFit
)

type LinkedList

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

LinkedList is a doubly-linked list List implementation. It offers efficient inserts/removals by pointer and linear-time indexing.

func NewLinkedList

func NewLinkedList(rows []Row) *LinkedList

NewLinkedList builds a LinkedList from rows in order.

func (*LinkedList) Above

func (l *LinkedList) Above(_ context.Context, rowID string, num int) []Row

Above returns up to num rows strictly above the row with rowID.

func (*LinkedList) Append

func (l *LinkedList) Append(rows ...Row)

Append adds rows to the end of the list.

func (*LinkedList) Below

func (l *LinkedList) Below(_ context.Context, rowID string, num int) []Row

Below returns up to num rows strictly below the row with rowID.

func (*LinkedList) Find

func (l *LinkedList) Find(_ context.Context, rowID string) (int, Row, bool)

Find returns the index and row with the given ID, if present.

func (*LinkedList) InsertAfterID

func (l *LinkedList) InsertAfterID(anchorID string, rows ...Row) bool

InsertAfterID inserts rows after the node with anchorID. Returns false if the anchor is not found.

func (*LinkedList) InsertBeforeID

func (l *LinkedList) InsertBeforeID(anchorID string, rows ...Row) bool

InsertBeforeID inserts rows before the node with anchorID. Returns false if the anchor is not found.

func (*LinkedList) Len

func (l *LinkedList) Len(context.Context) int

Len returns the number of rows in the list.

func (*LinkedList) Lines

func (l *LinkedList) Lines(_ context.Context, top, num int) []Row

Lines returns a slice of rows starting at top with length up to num.

func (*LinkedList) Prepend

func (l *LinkedList) Prepend(rows ...Row)

Prepend inserts rows at the beginning of the list.

func (*LinkedList) RemoveIDs

func (l *LinkedList) RemoveIDs(ids ...string) int

RemoveIDs removes all rows with the provided IDs. Returns count removed.

type List

type List interface {
	Lines(ctx context.Context, top, num int) []Row
	Above(ctx context.Context, rowID string, num int) []Row
	Below(ctx context.Context, rowID string, num int) []Row
	Len(ctx context.Context) int
	// Find returns the absolute index and row for a given ID if present.
	Find(ctx context.Context, rowID string) (int, Row, bool)
}

List provides windowed access to rows. Implementations should be efficient for large datasets (10s of thousands), serving only the requested slices.

type Row

type Row interface {
	Columns() (id string, cells []string, styles []*lipgloss.Style, exists bool)
}

Row represents a single logical row in the table. It must return a stable ID, ASCII cell strings, and a style for each cell.

func LinesToRows

func LinesToRows(in []Row) []Row

LinesToRows is a helper to copy a slice of Row values.

type SimpleRow

type SimpleRow struct {
	ID     string
	Cells  []string
	Styles []*lipgloss.Style
}

SimpleRow is a reusable row type with a stable ID and per-cell styles. It implements Row and can be used by any List implementation.

func (SimpleRow) Columns

func (r SimpleRow) Columns() (string, []string, []*lipgloss.Style, bool)

Columns returns the ID, the cells and the styles of r; a SimpleRow always exists.

func (*SimpleRow) SetColumn

func (r *SimpleRow) SetColumn(col int, text string, style *lipgloss.Style)

SetColumn sets the text and optional style at the given column index. If style is nil, the previous style is kept; if it doesn't exist, a neutral style is used.

type SliceList

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

SliceList is a default slice-backed data source with copy-on-insert/remove.

func NewSliceList

func NewSliceList(rows []Row) *SliceList

NewSliceList returns a list of a copy of rows, in order. Row IDs must be unique.

func (*SliceList) Above

func (l *SliceList) Above(_ context.Context, rowID string, num int) []Row

Above returns up to num rows strictly above the row with rowID, in order.

func (*SliceList) Append

func (l *SliceList) Append(newRows ...Row)

Append adds rows to the end of the list.

func (*SliceList) Below

func (l *SliceList) Below(_ context.Context, rowID string, num int) []Row

Below returns up to num rows strictly below the row with rowID, in order.

func (*SliceList) Find

func (l *SliceList) Find(_ context.Context, rowID string) (int, Row, bool)

Find returns the index and row with the given ID, if present.

func (*SliceList) InsertAfter

func (l *SliceList) InsertAfter(anchorID string, newRows ...Row) int

InsertAfter inserts rows after the row with anchorID. Returns the first insert index or -1.

func (*SliceList) InsertBefore

func (l *SliceList) InsertBefore(anchorID string, newRows ...Row) int

InsertBefore inserts rows before the row with anchorID. Returns the insert index or -1 if anchor not found.

func (*SliceList) Len

func (l *SliceList) Len(context.Context) int

Len returns the number of rows in the list.

func (*SliceList) Lines

func (l *SliceList) Lines(_ context.Context, top, num int) []Row

Lines returns up to num rows starting at index top.

func (*SliceList) Prepend

func (l *SliceList) Prepend(newRows ...Row)

Prepend inserts rows at the beginning of the list.

func (*SliceList) RemoveAt

func (l *SliceList) RemoveAt(i, count int) int

RemoveAt removes a contiguous range [i, i+count). Returns count actually removed.

func (*SliceList) RemoveIDs

func (l *SliceList) RemoveIDs(ids ...string) int

RemoveIDs removes all rows with the provided IDs. Returns count removed.

type Styles

type Styles struct {
	Header   lipgloss.Style
	Selector lipgloss.Style
	Cell     lipgloss.Style
	Border   lipgloss.Style
	// Marked applies to rows toggled via C-t/Insert (multi-select).
	// It should not generally change the background; prefer fg/bold changes.
	Marked lipgloss.Style
}

Styles groups all externally configurable styles.

func DefaultStyles

func DefaultStyles() Styles

DefaultStyles returns a set of defaults for the table.

Directories

Path Synopsis
Command demo shows two tables over the same 1,000 rows of made-up data, side by side, with a status column that changes every second.
Command demo shows two tables over the same 1,000 rows of made-up data, side by side, with a status column that changes every second.

Jump to

Keyboard shortcuts

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