-
-
Save maxatome/21d7fd2f08244b25994464b2ef776cf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/charmbracelet/bubbles/table" | |
tea "github.com/charmbracelet/bubbletea" | |
"github.com/charmbracelet/lipgloss" | |
) | |
var ( | |
styleHeader = lipgloss.NewStyle(). | |
Padding(0, 1, 0, 0). | |
Bold(true) | |
styleCell = lipgloss.NewStyle().Padding(0, 1, 0, 0) | |
) | |
func main() { | |
columns := []table.Column{ | |
{Title: "Name", Width: 4}, | |
{Title: "Status", Width: 6}, | |
{Title: "Info", Width: 4}, | |
} | |
t := table.New( | |
table.WithColumns(columns), | |
table.WithFocused(true), | |
table.WithWidth(70), | |
table.WithHeight(10), | |
) | |
s := table.DefaultStyles() | |
s.Header = styleHeader | |
s.Cell = styleCell | |
t.SetStyles(s) | |
m := model{ | |
table: t, | |
columns: columns, | |
} | |
tea.NewProgram(&m, tea.WithAltScreen()).Run() | |
} | |
type model struct { | |
table table.Model | |
columns []table.Column | |
height, width int | |
} | |
func (m *model) Init() tea.Cmd { | |
return nil | |
} | |
func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { | |
switch msg := msg.(type) { | |
case tea.KeyMsg: | |
switch msg.String() { | |
case "q", "ctrl+c": | |
return m, tea.Quit | |
} | |
case tea.WindowSizeMsg: | |
m.width, m.height = msg.Width, msg.Height | |
m.updateTable() | |
return m, nil | |
} | |
return m, nil | |
} | |
func (m *model) View() string { | |
return m.table.View() | |
} | |
func (m *model) updateTable() { | |
rows := []table.Row{ | |
{"name1", "status1", "infqsfqsdfqfdsfqdfqsfqsdfqsdfqsdfqsfsqdfqsdfqsfsqfqsdfqsfqsqsdfhfgatuo1"}, | |
{"name2", "", "info2"}, | |
{"name3", "", "info3"}, | |
{"name4", "status4", "info4"}, | |
} | |
for col := range m.columns { | |
m.columns[col].Width = len(m.columns[col].Title) | |
} | |
for _, row := range rows { | |
for col := range row { | |
m.columns[col].Width = max(m.columns[col].Width, len(row[col])) | |
} | |
} | |
m.table.SetColumns(m.columns) | |
m.table.SetRows(rows) | |
if m.table.Width() != m.width { | |
m.table.SetWidth(m.width) | |
} | |
h := m.height - 2 | |
if m.table.Height() != h { | |
m.table.SetHeight(h) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment