Created
November 18, 2024 07:35
-
-
Save xqm32/9cb21d653f28c45849335659c758be6f 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 style | |
import ( | |
"os" | |
"github.com/charmbracelet/lipgloss" | |
"github.com/charmbracelet/lipgloss/table" | |
"github.com/samber/lo" | |
"golang.org/x/term" | |
) | |
func Table(headers []string, rows [][]string) *table.Table { | |
colWidths := ColWidths(append([][]string{headers}, rows...)) | |
return table.New(). | |
Border(lipgloss.HiddenBorder()). | |
BorderHeader(false). | |
BorderLeft(false).BorderRight(false). | |
BorderTop(false).BorderBottom(false). | |
Headers(headers...). | |
Rows(rows...). | |
StyleFunc(func(row, col int) lipgloss.Style { | |
style := lipgloss.NewStyle() | |
if row == table.HeaderRow { | |
style = style.Bold(true) | |
} | |
return style.Width(colWidths[col]) | |
}) | |
} | |
func Fields(fields []string) *table.Table { | |
rows := lo.Chunk(fields, 2) | |
colWidths := ColWidths(rows) | |
return table.New(). | |
Border(lipgloss.HiddenBorder()). | |
BorderLeft(false).BorderRight(false). | |
BorderTop(false).BorderBottom(false). | |
Rows(rows...). | |
StyleFunc(func(row, col int) lipgloss.Style { | |
style := lipgloss.NewStyle() | |
if col == 0 { | |
style = style.Bold(true) | |
} | |
return style.Width(colWidths[col]) | |
}) | |
} | |
func ColWidths(rows [][]string) []int { | |
maxCols := 0 | |
for _, row := range rows { | |
if len(row) > maxCols { | |
maxCols = len(row) | |
} | |
} | |
colWidths := make([]int, maxCols) | |
termWidth, _, err := term.GetSize(int(os.Stdout.Fd())) | |
if err != nil { | |
return colWidths | |
} | |
for _, row := range rows { | |
for i, cell := range row { | |
if lipgloss.Width(cell) > colWidths[i] { | |
colWidths[i] = lipgloss.Width(cell) | |
} | |
} | |
} | |
maxCol := 0 | |
for i, width := range colWidths { | |
if width > colWidths[maxCol] { | |
maxCol = i | |
} | |
} | |
totalWidth := lo.Sum(colWidths) + maxCols - 1 | |
if totalWidth > termWidth { | |
colWidths[maxCol] -= totalWidth - termWidth | |
} | |
return colWidths | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment