Files
bubbles/table/table.go
T
2024-09-16 10:05:09 -07:00

458 lines
10 KiB
Go

package table
import (
"strings"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"
)
const (
header int = 0
firstRow int = 1
)
// Model defines a state for the table widget.
type Model struct {
KeyMap KeyMap
Help help.Model
YOffset int
height int
headers []string
rows [][]string
cursor int
focus bool
styles Styles
table *table.Table
start int
end int
// deprecated: don't use viewport, use table instead.
viewport viewport.Model
}
// Row represents one line in the table.
// Deprecated: use []string.
type Row []string
// Column defines the table structure.
// Deprecated: use []string.
type Column struct {
Title string
Width int
}
// KeyMap defines keybindings. It satisfies to the help.KeyMap interface, which
// is used to render the help menu.
type KeyMap struct {
LineUp key.Binding
LineDown key.Binding
PageUp key.Binding
PageDown key.Binding
HalfPageUp key.Binding
HalfPageDown key.Binding
GotoTop key.Binding
GotoBottom key.Binding
}
// ShortHelp implements the KeyMap interface.
func (km KeyMap) ShortHelp() []key.Binding {
return []key.Binding{km.LineUp, km.LineDown}
}
// FullHelp implements the KeyMap interface.
func (km KeyMap) FullHelp() [][]key.Binding {
return [][]key.Binding{
{km.LineUp, km.LineDown, km.GotoTop, km.GotoBottom},
{km.PageUp, km.PageDown, km.HalfPageUp, km.HalfPageDown},
}
}
// DefaultKeyMap returns a default set of keybindings.
func DefaultKeyMap() KeyMap {
const spacebar = " "
return KeyMap{
LineUp: key.NewBinding(
key.WithKeys("up", "k"),
key.WithHelp("↑/k", "up"),
),
LineDown: key.NewBinding(
key.WithKeys("down", "j"),
key.WithHelp("↓/j", "down"),
),
PageUp: key.NewBinding(
key.WithKeys("b", "pgup"),
key.WithHelp("b/pgup", "page up"),
),
PageDown: key.NewBinding(
key.WithKeys("f", "pgdown", spacebar),
key.WithHelp("f/pgdn", "page down"),
),
HalfPageUp: key.NewBinding(
key.WithKeys("u", "ctrl+u"),
key.WithHelp("u", "½ page up"),
),
HalfPageDown: key.NewBinding(
key.WithKeys("d", "ctrl+d"),
key.WithHelp("d", "½ page down"),
),
GotoTop: key.NewBinding(
key.WithKeys("home", "g"),
key.WithHelp("g/home", "go to start"),
),
GotoBottom: key.NewBinding(
key.WithKeys("end", "G"),
key.WithHelp("G/end", "go to end"),
),
}
}
// Styles contains style definitions for this list component. By default, these
// values are generated by DefaultStyles.
type Styles struct {
Border lipgloss.Border
BorderStyle lipgloss.Style
BorderHeader bool
Header lipgloss.Style
Cell lipgloss.Style
Selected lipgloss.Style
}
// DefaultStyles returns a set of default style definitions for this table.
func DefaultStyles() Styles {
return Styles{
Border: lipgloss.NormalBorder(),
BorderHeader: true,
Selected: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("212")),
Header: lipgloss.NewStyle().Bold(true).Padding(0, 1),
Cell: lipgloss.NewStyle().Margin(0, 1),
}
}
// SetStyles sets the table styles.
func (m *Model) SetStyles(s Styles) {
m.styles = s
m.table.Border(s.Border)
m.table.BorderStyle(s.BorderStyle)
m.table.BorderHeader(s.BorderHeader)
}
// Option is used to set options in New. For example:
//
// TODO change this to WithRows as the example instead
//
// table := New(WithColumns([]Column{{Title: "ID", Width: 10}}))
type Option func(*Model)
// New creates a new model for the table widget.
func New(opts ...Option) Model {
m := Model{
cursor: firstRow,
table: table.New(),
KeyMap: DefaultKeyMap(),
Help: help.New(),
styles: DefaultStyles(),
}
for _, opt := range opts {
opt(&m)
}
return m
}
// WithHeaders sets the table headers.
func WithHeaders(headers []string) Option {
return func(m *Model) {
m.SetHeaders(headers...)
}
}
// WithColumns sets the table columns (headers).
// Deprecated: use WithHeaders instead.
func WithColumns(cols []Column) Option {
return func(m *Model) {
m.SetHeaders(colToString(cols)...)
}
}
// colToString helper to unwrap the Column type to its underlying string type.
func colToString(cols []Column) []string {
var out []string
for _, col := range cols {
out = append(out, col.Title)
}
return out
}
// WithRows sets the table rows (data).
func WithRows(rows []Row) Option {
return func(m *Model) {
m.SetRows(rows)
}
}
// WithHeight sets the height of the table.
func WithHeight(h int) Option {
return func(m *Model) {
m.SetHeight(h)
}
}
// WithWidth sets the width of the table.
func WithWidth(w int) Option {
return func(m *Model) {
m.SetWidth(w)
}
}
// WithFocused sets the focus state of the table.
func WithFocused(f bool) Option {
return func(m *Model) {
m.focus = f
}
}
// WithStyles sets the table styles.
func WithStyles(s Styles) Option {
return func(m *Model) {
m.SetStyles(s)
}
}
// WithKeyMap sets the key map.
func WithKeyMap(km KeyMap) Option {
return func(m *Model) {
m.KeyMap = km
}
}
// Update for the Bubble Tea update loop.
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.focus {
return m, nil
}
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case key.Matches(msg, m.KeyMap.LineUp):
m.MoveUp(1)
case key.Matches(msg, m.KeyMap.LineDown):
m.MoveDown(1)
case key.Matches(msg, m.KeyMap.PageUp):
m.MoveUp(m.height)
case key.Matches(msg, m.KeyMap.PageDown):
m.MoveDown(m.height)
case key.Matches(msg, m.KeyMap.HalfPageUp):
m.MoveUp(m.height / 2)
case key.Matches(msg, m.KeyMap.HalfPageDown):
m.MoveDown(m.height / 2)
case key.Matches(msg, m.KeyMap.LineDown):
m.MoveDown(1)
case key.Matches(msg, m.KeyMap.GotoTop):
m.GotoTop()
case key.Matches(msg, m.KeyMap.GotoBottom):
m.GotoBottom()
}
}
return m, nil
}
// Focused returns the focus state of the table.
func (m Model) Focused() bool {
return m.focus
}
// Focus focuses the table, allowing the user to move around the rows and
// interact.
func (m *Model) Focus() {
m.focus = true
}
// Blur blurs the table, preventing selection or movement.
func (m *Model) Blur() {
m.focus = false
}
// View renders the component.
func (m Model) View() string {
m.table.StyleFunc(func(row, col int) lipgloss.Style {
if row == header {
return m.styles.Header
}
if row == m.cursor {
log.Printf("row and cursor match %d\n", m.cursor)
return m.styles.Selected
}
return m.styles.Cell
})
return m.table.String()
}
// HelpView is a helper method for rendering the help menu from the keymap.
// Note that this view is not rendered by default and you must call it
// manually in your application, where applicable.
func (m Model) HelpView() string {
return m.Help.View(m.KeyMap)
}
// SelectedRow returns the selected row.
// You can cast it to your own implementation.
func (m Model) SelectedRow() Row {
if m.cursor < 0 || m.cursor >= len(m.rows) {
return nil
}
return m.rows[m.cursor]
}
// Append appends rows to the table.
func (m *Model) Append(rows ...[]string) {
m.rows = append(m.rows, rows...)
m.table.Rows(m.rows...)
}
// SetRows overwrites existing rows with new ones.
func (m *Model) SetRows(r []Row) {
// lipgloss' table requires []string, so it's easier to convert these.
// TODO should we just deprecate the Row type altogether?
rows := rowToString(r)
m.rows = rows
// TODO test this
m.table.ClearRows()
m.table.Rows(rows...)
}
// rowToString helper to unwrap the Row type.
func rowToString(rows []Row) [][]string {
var out [][]string
for _, row := range rows {
var newRow []string
for _, val := range row {
newRow = append(newRow, val)
}
out = append(out, newRow)
}
return out
}
// SetHeaders sets the table headers.
// TODO should this be variadic to match lipgloss table?
func (m *Model) SetHeaders(headers ...string) {
m.headers = headers
m.table.Headers(headers...)
}
// SetWidth sets the width of the table.
func (m *Model) SetWidth(w int) {
m.table.Width(w)
}
// SetHeight sets the height of the table.
func (m *Model) SetHeight(h int) {
m.height = h
m.table.Height(h)
}
// Cursor returns the index of the selected row.
func (m Model) Cursor() int {
return m.cursor
}
// SetCursor sets the cursor position in the table.
func (m *Model) SetCursor(n int) {
m.cursor = clamp(n, 0, len(m.rows)-1)
// TODO should I update YOffset here?
}
// MoveUp moves the selection up by any number of rows.
// It can not go above the first row.
func (m *Model) MoveUp(n int) {
if m.cursor > firstRow {
m.SetCursor(m.cursor - n)
m.YOffset = m.YOffset - n
m.table.Offset(m.YOffset)
}
// check that the table has contents
// if len(m.rows) < 1 {
// return
// }
// firstRow := firstRow
// m.SetCursor(m.cursor - n)
// switch {
// case m.start == firstRow:
// m.YOffset = clamp(m.YOffset, firstRow, m.cursor)
// case m.start < m.height:
// m.YOffset = (clamp(clamp(m.YOffset+n, firstRow, m.cursor), firstRow, m.height))
// case m.YOffset >= firstRow+1:
// m.YOffset = clamp(m.YOffset+n, firstRow+1, m.height)
// }
}
// MoveDown moves the selection down by any number of rows.
// It can not go below the last row.
func (m *Model) MoveDown(n int) {
if m.cursor < len(m.rows) {
m.SetCursor(m.cursor + n)
m.YOffset = m.YOffset + n
m.table.Offset(m.YOffset)
}
// TODO stop setting offset when visible rows less than expected
// TODO we should track visible row indices
}
// GotoTop moves the selection to the first row.
func (m *Model) GotoTop() {
m.MoveUp(m.cursor)
}
// GotoBottom moves the selection to the last row.
func (m *Model) GotoBottom() {
m.MoveDown(len(m.rows))
}
// FromValues create the table rows from a simple string. It uses `\n` by
// default for getting all the rows and the given separator for the fields on
// each row.
func (m *Model) FromValues(value, separator string) {
rows := []Row{}
for _, line := range strings.Split(value, "\n") {
r := Row{}
for _, field := range strings.Split(line, separator) {
r = append(r, field)
}
rows = append(rows, r)
}
m.SetRows(rows)
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func clamp(v, low, high int) int {
return min(max(v, low), high)
}