table

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2024 License: MIT Imports: 12 Imported by: 89

Documentation

Overview

Package table contains a Bubble Tea component for an interactive and customizable table.

The simplest useful table can be created with table.New(...).WithRows(...). Row data should map to the column keys, as shown below. Note that extra data will simply not be shown, while missing data will be safely blank in the row's cell.

const (
	// This is not necessary, but recommended to avoid typos
	columnKeyName  = "name"
	columnKeyCount = "count"
)

// Define the columns and how they appear
columns := []table.Column{
	table.NewColumn(columnKeyName, "Name", 10),
	table.NewColumn(columnKeyCount, "Count", 6),
}

// Define the data that will be in the table, mapping to the column keys
rows := []table.Row{
	table.NewRow(table.RowData{
		columnKeyName:  "Cheeseburger",
		columnKeyCount: 3,
	}),
	table.NewRow(table.RowData{
		columnKeyName:  "Fries",
		columnKeyCount: 2,
	}),
}

// Create the table
tbl := table.New(columns).WithRows(rows)

// Use it like any Bubble Tea component in your view
tbl.View()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Border added in v0.2.0

type Border struct {
	Top         string
	Left        string
	Right       string
	Bottom      string
	TopRight    string
	TopLeft     string
	BottomRight string
	BottomLeft  string

	TopJunction    string
	LeftJunction   string
	RightJunction  string
	BottomJunction string

	InnerJunction string

	InnerDivider string
	// contains filtered or unexported fields
}

Border defines the borders in and around the table.

type Column added in v0.3.0

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

Column is a column in the table.

func NewColumn added in v0.3.0

func NewColumn(key, title string, width int) Column

NewColumn creates a new fixed-width column with the given information.

func NewFlexColumn added in v0.8.0

func NewFlexColumn(key, title string, flexFactor int) Column

NewFlexColumn creates a new flexible width column that tries to fill in the total table width. If multiple flex columns exist, each will measure against each other depending on their flexFactor. For example, if both have a flexFactor of 1, they will have equal width. If one has a flexFactor of 1 and the other has a flexFactor of 3, the second will be 3 times larger than the first. You must use WithTargetWidth if you have any flex columns, so that the table knows how much width it should fill.

func (Column) Filterable added in v0.15.5

func (c Column) Filterable() bool

Filterable returns whether the column is filterable.

func (Column) FlexFactor added in v0.15.5

func (c Column) FlexFactor() int

FlexFactor returns the flex factor of the column.

func (Column) FmtString added in v0.15.5

func (c Column) FmtString() string

FmtString returns the format string of the column.

func (Column) IsFlex added in v0.15.5

func (c Column) IsFlex() bool

IsFlex returns whether the column is a flex column.

func (Column) Key added in v0.3.0

func (c Column) Key() string

Key returns the key of the column.

func (Column) Style added in v0.15.5

func (c Column) Style() lipgloss.Style

Style returns the style of the column.

func (Column) Title added in v0.3.0

func (c Column) Title() string

Title returns the title of the column.

func (Column) Width added in v0.3.0

func (c Column) Width() int

Width returns the width of the column.

func (Column) WithFiltered added in v0.7.0

func (c Column) WithFiltered(filterable bool) Column

WithFiltered sets whether the column should be considered for filtering (true) or not (false).

func (Column) WithFormatString added in v0.14.6

func (c Column) WithFormatString(fmtString string) Column

WithFormatString sets the format string used by fmt.Sprintf to display the data. If not set, the default is "%v" for all data types. Intended mainly for numeric formatting.

Since data is of the interface{} type, make sure that all data in the column is of the expected type or the format may fail. For example, hardcoding '3' instead of '3.0' and using '%.2f' will fail because '3' is an integer.

func (Column) WithStyle added in v0.5.0

func (c Column) WithStyle(style lipgloss.Style) Column

WithStyle applies a style to the column as a whole.

type KeyMap added in v0.4.0

type KeyMap struct {
	RowDown key.Binding
	RowUp   key.Binding

	RowSelectToggle key.Binding

	PageDown  key.Binding
	PageUp    key.Binding
	PageFirst key.Binding
	PageLast  key.Binding

	// Filter allows the user to start typing and filter the rows.
	Filter key.Binding

	// FilterBlur is the key that stops the user's input from typing into the filter.
	FilterBlur key.Binding

	// FilterClear will clear the filter while it's blurred.
	FilterClear key.Binding

	// ScrollRight will move one column to the right when overflow occurs.
	ScrollRight key.Binding

	// ScrollLeft will move one column to the left when overflow occurs.
	ScrollLeft key.Binding
}

KeyMap defines the keybindings for the table when it's focused.

func DefaultKeyMap added in v0.4.0

func DefaultKeyMap() KeyMap

DefaultKeyMap returns a set of sensible defaults for controlling a focused table with help text.

type Model

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

Model is the main table model. Create using New().

func New

func New(columns []Column) Model

New creates a new table ready for further modifications.

func (Model) Border added in v0.2.0

func (m Model) Border(border Border) Model

Border uses the given border components to render the table.

func (Model) BorderDefault added in v0.2.0

func (m Model) BorderDefault() Model

BorderDefault uses the basic square border, useful to reset the border if it was changed somehow.

func (Model) BorderRounded added in v0.13.5

func (m Model) BorderRounded() Model

BorderRounded uses a thin, rounded border.

func (*Model) CurrentPage added in v0.5.0

func (m *Model) CurrentPage() int

CurrentPage returns the current page that the table is on, starting from an index of 1.

func (Model) Filtered added in v0.7.0

func (m Model) Filtered(filtered bool) Model

Filtered allows the table to show rows that match the filter.

func (Model) Focused

func (m Model) Focused(focused bool) Model

Focused allows the table to show highlighted rows and take in controls of up/down/space/etc to let the user navigate the table and interact with it.

func (Model) FullHelp added in v0.17.1

func (m Model) FullHelp() [][]key.Binding

FullHelp returns a multi row view of all the helpkeys that are defined. Needed to fullfil the 'help.Model' interface. Also appends all user defined extra keys to the help.

func (*Model) GetCanFilter added in v0.11.1

func (m *Model) GetCanFilter() bool

GetCanFilter returns true if the table enables filtering at all. This does not say whether a filter is currently active, only that the feature is enabled.

func (*Model) GetColumnSorting added in v0.11.1

func (m *Model) GetColumnSorting() []SortColumn

GetColumnSorting returns the current sorting rules for the table as a list of SortColumns, which are applied from first to last. This means that data will be grouped by the later elements in the list. The returned list is a copy and modifications will have no effect.

func (*Model) GetCurrentFilter added in v0.11.1

func (m *Model) GetCurrentFilter() string

GetCurrentFilter returns the current filter text being applied, or an empty string if none is applied.

func (*Model) GetFocused added in v0.13.4

func (m *Model) GetFocused() bool

GetFocused returns whether or not the table is focused and is receiving inputs.

func (*Model) GetFooterVisibility added in v0.15.3

func (m *Model) GetFooterVisibility() bool

GetFooterVisibility returns true if the footer has been set to visible (default) or false if the footer has been set to hidden. Note that even if the footer is visible it will only be rendered if it has contents.

func (*Model) GetHeaderVisibility added in v0.13.5

func (m *Model) GetHeaderVisibility() bool

GetHeaderVisibility returns true if the header has been set to visible (default) or false if the header has been set to hidden.

func (*Model) GetHighlightedRowIndex added in v0.13.4

func (m *Model) GetHighlightedRowIndex() int

GetHighlightedRowIndex returns the index of the Row that's currently highlighted by the user.

func (*Model) GetHorizontalScrollColumnOffset added in v0.13.4

func (m *Model) GetHorizontalScrollColumnOffset() int

GetHorizontalScrollColumnOffset returns how many columns to the right the table has been scrolled. 0 means the table is all the way to the left, which is the starting default.

func (*Model) GetIsFilterActive added in v0.11.1

func (m *Model) GetIsFilterActive() bool

GetIsFilterActive returns true if the table is currently being filtered. This does not say whether the table CAN be filtered, only whether or not a filter is actually currently being applied.

func (*Model) GetIsFilterInputFocused added in v0.14.5

func (m *Model) GetIsFilterInputFocused() bool

GetIsFilterInputFocused returns true if the table's built-in filter input is currently focused.

func (*Model) GetLastUpdateUserEvents added in v0.14.0

func (m *Model) GetLastUpdateUserEvents() []UserEvent

GetLastUpdateUserEvents returns a list of events that happened due to user input in the last Update call. This is useful to look for triggers such as whether the user moved to a new highlighted row.

func (*Model) GetPaginationWrapping added in v0.14.2

func (m *Model) GetPaginationWrapping() bool

GetPaginationWrapping returns true if pagination wrapping is enabled, or false if disabled. If disabled, navigating through pages will stop at the first and last pages.

func (*Model) GetVisibleRows added in v0.7.0

func (m *Model) GetVisibleRows() []Row

GetVisibleRows returns sorted and filtered rows.

func (Model) HeaderStyle

func (m Model) HeaderStyle(style lipgloss.Style) Model

HeaderStyle sets the style to apply to the header text, such as color or bold.

func (Model) HighlightStyle

func (m Model) HighlightStyle(style lipgloss.Style) Model

HighlightStyle sets a custom style to use when the row is being highlighted by the cursor. This should not be used with WithRowStyleFunc. Instead, use the IsHighlighted field in the style function.

func (Model) HighlightedRow

func (m Model) HighlightedRow() Row

HighlightedRow returns the full Row that's currently highlighted by the user.

func (Model) Init

func (m Model) Init() tea.Cmd

Init initializes the table per the Bubble Tea architecture.

func (Model) KeyMap added in v0.4.0

func (m Model) KeyMap() KeyMap

KeyMap returns a copy of the current key map in use.

func (*Model) MaxPages added in v0.5.0

func (m *Model) MaxPages() int

MaxPages returns the maximum number of pages that are visible.

func (Model) PageDown added in v0.9.0

func (m Model) PageDown() Model

PageDown goes to the next page of a paginated table, wrapping to the first page if the table is already on the last page.

func (Model) PageFirst added in v0.9.0

func (m Model) PageFirst() Model

PageFirst goes to the first page of a paginated table.

func (Model) PageLast added in v0.9.0

func (m Model) PageLast() Model

PageLast goes to the last page of a paginated table.

func (*Model) PageSize added in v0.5.0

func (m *Model) PageSize() int

PageSize returns the current page size for the table, or 0 if there is no pagination enabled.

func (Model) PageUp added in v0.9.0

func (m Model) PageUp() Model

PageUp goes to the previous page of a paginated table, wrapping to the last page if the table is already on the first page.

func (Model) ScrollLeft added in v0.13.0

func (m Model) ScrollLeft() Model

ScrollLeft moves one column to the left. Use with WithMaxTotalWidth.

func (Model) ScrollRight added in v0.13.0

func (m Model) ScrollRight() Model

ScrollRight moves one column to the right. Use with WithMaxTotalWidth.

func (Model) SelectableRows

func (m Model) SelectableRows(selectable bool) Model

SelectableRows sets whether or not rows are selectable. If set, adds a column in the front that acts as a checkbox and responds to controls if Focused.

func (Model) SelectedRows

func (m Model) SelectedRows() []Row

SelectedRows returns all rows that have been set as selected by the user.

func (Model) ShortHelp added in v0.17.1

func (m Model) ShortHelp() []key.Binding

ShortHelp just returns a single row of help views. Needed to fullfil the 'help.Model' interface. Also appends all user defined extra keys to the help.

func (Model) SortByAsc added in v0.6.0

func (m Model) SortByAsc(columnKey string) Model

SortByAsc sets the main sorting column to the given key, in ascending order. If a previous sort was used, it is replaced by the given column each time this function is called. Values are sorted as numbers if possible, or just as simple string comparisons if not numbers.

func (Model) SortByDesc added in v0.6.0

func (m Model) SortByDesc(columnKey string) Model

SortByDesc sets the main sorting column to the given key, in descending order. If a previous sort was used, it is replaced by the given column each time this function is called. Values are sorted as numbers if possible, or just as simple string comparisons if not numbers.

func (Model) StartFilterTyping added in v0.7.0

func (m Model) StartFilterTyping() Model

StartFilterTyping focuses the text input to allow user typing to filter.

func (Model) ThenSortByAsc added in v0.6.0

func (m Model) ThenSortByAsc(columnKey string) Model

ThenSortByAsc provides a secondary sort after the first, in ascending order. Can be chained multiple times, applying to smaller subgroups each time.

func (Model) ThenSortByDesc added in v0.6.0

func (m Model) ThenSortByDesc(columnKey string) Model

ThenSortByDesc provides a secondary sort after the first, in descending order. Can be chained multiple times, applying to smaller subgroups each time.

func (*Model) TotalRows added in v0.5.0

func (m *Model) TotalRows() int

TotalRows returns the current total row count of the table. If the table is paginated, this is the total number of rows across all pages.

func (Model) Update

func (m Model) Update(msg tea.Msg) (Model, tea.Cmd)

Update responds to input from the user or other messages from Bubble Tea.

func (Model) View

func (m Model) View() string

View renders the table. It does not end in a newline, so that it can be composed with other elements more consistently.

func (*Model) VisibleIndices added in v0.5.0

func (m *Model) VisibleIndices() (start, end int)

VisibleIndices returns the current visible rows by their 0 based index. Useful for custom pagination footers.

func (Model) WithAdditionalFullHelpKeys added in v0.17.1

func (m Model) WithAdditionalFullHelpKeys(keys []key.Binding) Model

WithAdditionalFullHelpKeys enables you to add more keybindings to the 'full help' view.

func (Model) WithAdditionalShortHelpKeys added in v0.17.1

func (m Model) WithAdditionalShortHelpKeys(keys []key.Binding) Model

WithAdditionalShortHelpKeys enables you to add more keybindings to the 'short help' view.

func (Model) WithAllRowsDeselected added in v0.15.0

func (m Model) WithAllRowsDeselected() Model

WithAllRowsDeselected deselects any rows that are currently selected.

func (Model) WithBaseStyle added in v0.6.3

func (m Model) WithBaseStyle(style lipgloss.Style) Model

WithBaseStyle applies a base style as the default for everything in the table. This is useful for border colors, default alignment, default color, etc.

func (Model) WithColumns added in v0.10.0

func (m Model) WithColumns(columns []Column) Model

WithColumns sets the visible columns for the table, so that columns can be added/removed/resized or headers rewritten.

func (Model) WithCurrentPage added in v0.9.0

func (m Model) WithCurrentPage(currentPage int) Model

WithCurrentPage sets the current page (1 as the first page) of a paginated table, bounded to the total number of pages. The current selected row will be set to the top row of the page if the page changed.

func (Model) WithFilterInput added in v0.12.0

func (m Model) WithFilterInput(input textinput.Model) Model

WithFilterInput makes the table use the provided text input bubble for filtering rather than using the built-in default. This allows for external text input controls to be used.

func (Model) WithFilterInputValue added in v0.14.3

func (m Model) WithFilterInputValue(value string) Model

WithFilterInputValue sets the filter value to the given string, immediately applying it as if the user had typed it in. Useful for external filter inputs that are not necessarily a text input.

func (Model) WithFooterVisibility added in v0.12.0

func (m Model) WithFooterVisibility(visibility bool) Model

WithFooterVisibility sets the visibility of the footer.

func (Model) WithHeaderVisibility added in v0.13.5

func (m Model) WithHeaderVisibility(visibility bool) Model

WithHeaderVisibility sets the visibility of the header.

func (Model) WithHighlightedRow added in v0.8.1

func (m Model) WithHighlightedRow(index int) Model

WithHighlightedRow sets the highlighted row to the given index.

func (Model) WithHorizontalFreezeColumnCount added in v0.13.0

func (m Model) WithHorizontalFreezeColumnCount(columnsToFreeze int) Model

WithHorizontalFreezeColumnCount freezes the given number of columns to the left side. This is useful for things like ID or Name columns that should always be visible even when scrolling.

func (Model) WithKeyMap added in v0.4.0

func (m Model) WithKeyMap(keyMap KeyMap) Model

WithKeyMap sets the key map to use for controls when focused.

func (Model) WithMaxTotalWidth added in v0.13.0

func (m Model) WithMaxTotalWidth(maxTotalWidth int) Model

WithMaxTotalWidth sets the maximum total width that the table should render. If this width is exceeded by either the target width or by the total width of all the columns (including borders!), anything extra will be treated as overflow and horizontal scrolling will be enabled to see the rest.

func (Model) WithMinimumHeight added in v0.15.4

func (m Model) WithMinimumHeight(minimumHeight int) Model

WithMinimumHeight sets the minimum total height of the table, including borders.

func (Model) WithMissingDataIndicator added in v0.13.5

func (m Model) WithMissingDataIndicator(str string) Model

WithMissingDataIndicator sets an indicator to use when data for a column is not found in a given row. Note that this is for completely missing data, an empty string or other zero value that is explicitly set is not considered to be missing.

func (Model) WithMissingDataIndicatorStyled added in v0.13.5

func (m Model) WithMissingDataIndicatorStyled(styled StyledCell) Model

WithMissingDataIndicatorStyled sets a styled indicator to use when data for a column is not found in a given row. Note that this is for completely missing data, an empty string or other zero value that is explicitly set is not considered to be missing.

func (Model) WithMultiline added in v0.15.6

func (m Model) WithMultiline(multiline bool) Model

WithMultiline sets whether or not to wrap text in cells to multiple lines.

func (Model) WithNoPagination added in v0.5.0

func (m Model) WithNoPagination() Model

WithNoPagination disables pagination in the table.

func (Model) WithPageSize added in v0.5.0

func (m Model) WithPageSize(pageSize int) Model

WithPageSize enables pagination using the given page size. This can be called again at any point to resize the height of the table.

func (Model) WithPaginationWrapping added in v0.14.2

func (m Model) WithPaginationWrapping(wrapping bool) Model

WithPaginationWrapping sets whether to wrap around from the beginning to the end when navigating through pages. Defaults to true.

func (Model) WithRowStyleFunc added in v0.16.0

func (m Model) WithRowStyleFunc(f func(RowStyleFuncInput) lipgloss.Style) Model

WithRowStyleFunc sets a function that can be used to apply a style to each row based on the row data. This is useful for things like zebra striping or other data-based styles. It can be safely set to nil to remove it later. This style is applied after the base style and before individual row styles. This will override any HighlightStyle settings.

func (Model) WithRows

func (m Model) WithRows(rows []Row) Model

WithRows sets the rows to show as data in the table.

func (Model) WithSelectedText added in v0.6.0

func (m Model) WithSelectedText(unselected, selected string) Model

WithSelectedText describes what text to show when selectable rows are enabled. The selectable column header will use the selected text string.

func (Model) WithStaticFooter added in v0.4.0

func (m Model) WithStaticFooter(footer string) Model

WithStaticFooter adds a footer that only displays the given text.

func (Model) WithTargetWidth added in v0.8.0

func (m Model) WithTargetWidth(totalWidth int) Model

WithTargetWidth sets the total target width of the table, including borders. This only takes effect when using flex columns. When using flex columns, columns will stretch to fill out to the total width given here.

type Row

type Row struct {
	Style lipgloss.Style
	Data  RowData
	// contains filtered or unexported fields
}

Row represents a row in the table with some data keyed to the table columns> Can have a style applied to it such as color/bold. Create using NewRow().

func NewRow

func NewRow(data RowData) Row

NewRow creates a new row and copies the given row data.

func (Row) Selected added in v0.13.3

func (r Row) Selected(selected bool) Row

Selected returns a copy of the row that's set to be selected or deselected. The old row is not changed in-place.

func (Row) WithStyle

func (r Row) WithStyle(style lipgloss.Style) Row

WithStyle uses the given style for the text in the row.

type RowData

type RowData map[string]interface{}

RowData is a map of string column keys to interface{} data. Data with a key that matches a column key will be displayed. Data with a key that does not match a column key will not be displayed, but will remain attached to the Row. This can be useful for attaching hidden metadata for future reference when retrieving rows.

type RowStyleFuncInput added in v0.16.0

type RowStyleFuncInput struct {
	// Index is the index of the row, starting at 0.
	Index int

	// Row is the full row data.
	Row Row

	// IsHighlighted is true if the row is currently highlighted.
	IsHighlighted bool
}

RowStyleFuncInput is the input to the style function that can be applied to each row. This is useful for things like zebra striping or other data-based styles.

Note that we use a struct here to allow for future expansion while keeping backwards compatibility.

type SortColumn added in v0.11.1

type SortColumn struct {
	ColumnKey string
	Direction SortDirection
}

SortColumn describes which column should be sorted and how.

type SortDirection added in v0.11.1

type SortDirection int

SortDirection indicates whether a column should sort by ascending or descending.

const (
	// SortDirectionAsc indicates the column should be in ascending order.
	SortDirectionAsc SortDirection = iota

	// SortDirectionDesc indicates the column should be in descending order.
	SortDirectionDesc
)

type StyledCell added in v0.5.0

type StyledCell struct {
	Data  interface{}
	Style lipgloss.Style
}

StyledCell represents a cell in the table that has a particular style applied. The cell style takes highest precedence and will overwrite more general styles from the row, column, or table as a whole. This style should be generally limited to colors, font style, and alignments - spacing style such as margin will break the table format.

func NewStyledCell added in v0.5.0

func NewStyledCell(data interface{}, style lipgloss.Style) StyledCell

NewStyledCell creates an entry that can be set in the row data and show as styled with the given style.

type UserEvent added in v0.14.0

type UserEvent interface{}

UserEvent is some state change that has occurred due to user input. These will ONLY be generated when a user has interacted directly with the table. These will NOT be generated when code programmatically changes values in the table.

type UserEventFilterInputFocused added in v0.14.5

type UserEventFilterInputFocused struct{}

UserEventFilterInputFocused indicates that the user has focused the filter text input, so that any other typing will type into the filter field. Only activates for the built-in filter text box.

type UserEventFilterInputUnfocused added in v0.14.5

type UserEventFilterInputUnfocused struct{}

UserEventFilterInputUnfocused indicates that the user has unfocused the filter text input, which means the user is done typing into the filter field. Only activates for the built-in filter text box.

type UserEventHighlightedIndexChanged added in v0.14.0

type UserEventHighlightedIndexChanged struct {
	// PreviousRow is the row that was selected before the change.
	PreviousRowIndex int

	// SelectedRow is the row index that is now selected
	SelectedRowIndex int
}

UserEventHighlightedIndexChanged indicates that the user has scrolled to a new row.

type UserEventRowSelectToggled added in v0.14.1

type UserEventRowSelectToggled struct {
	RowIndex   int
	IsSelected bool
}

UserEventRowSelectToggled indicates that the user has either selected or deselected a row by toggling the selection. The event contains information about which row index was selected and whether it was selected or deselected.

Jump to

Keyboard shortcuts

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