1
0
mirror of https://github.com/gizak/termui.git synced 2025-04-26 13:48:54 +08:00

feat: text wrap on table

This commit is contained in:
Ahmad Karlam 2021-05-12 07:25:37 +07:00
parent f976fe697a
commit 76662a1ebd

View File

@ -6,6 +6,7 @@ package widgets
import ( import (
"image" "image"
"strings"
. "github.com/gizak/termui/v3" . "github.com/gizak/termui/v3"
) )
@ -24,6 +25,7 @@ type Table struct {
Rows [][]string Rows [][]string
ColumnWidths []int ColumnWidths []int
TextStyle Style TextStyle Style
TextWrap bool
RowSeparator bool RowSeparator bool
TextAlignment Alignment TextAlignment Alignment
RowStyles map[int]Style RowStyles map[int]Style
@ -62,6 +64,7 @@ func (self *Table) Draw(buf *Buffer) {
// draw rows // draw rows
for i := 0; i < len(self.Rows) && yCoordinate < self.Inner.Max.Y; i++ { for i := 0; i < len(self.Rows) && yCoordinate < self.Inner.Max.Y; i++ {
row := self.Rows[i] row := self.Rows[i]
textWrap := false
colXCoordinate := self.Inner.Min.X colXCoordinate := self.Inner.Min.X
rowStyle := self.TextStyle rowStyle := self.TextStyle
@ -77,6 +80,10 @@ func (self *Table) Draw(buf *Buffer) {
// draw row cells // draw row cells
for j := 0; j < len(row); j++ { for j := 0; j < len(row); j++ {
if len(row[j]) > columnWidths[j] && self.TextWrap {
row = self.transformForTextWrap(row, i, j, columnWidths[j])
textWrap = true
}
col := ParseStyles(row[j], rowStyle) col := ParseStyles(row[j], rowStyle)
// draw row cell // draw row cell
if len(col) > columnWidths[j] || self.TextAlignment == AlignLeft { if len(col) > columnWidths[j] || self.TextAlignment == AlignLeft {
@ -127,6 +134,9 @@ func (self *Table) Draw(buf *Buffer) {
yCoordinate++ yCoordinate++
// draw horizontal separator // draw horizontal separator
if textWrap {
continue
}
horizontalCell := NewCell(HORIZONTAL_LINE, separatorStyle) horizontalCell := NewCell(HORIZONTAL_LINE, separatorStyle)
if self.RowSeparator && yCoordinate < self.Inner.Max.Y && i != len(self.Rows)-1 { if self.RowSeparator && yCoordinate < self.Inner.Max.Y && i != len(self.Rows)-1 {
buf.Fill(horizontalCell, image.Rect(self.Inner.Min.X, yCoordinate, self.Inner.Max.X, yCoordinate+1)) buf.Fill(horizontalCell, image.Rect(self.Inner.Min.X, yCoordinate, self.Inner.Max.X, yCoordinate+1))
@ -134,3 +144,27 @@ func (self *Table) Draw(buf *Buffer) {
} }
} }
} }
func (self *Table) transformForTextWrap(row []string, i, j, columnWidth int) []string {
words := strings.Split(row[j], " ")
newWords := []string{}
nextWords := []string{}
totalChar := 0
for i := 0; i < len(words); i++ {
word := words[i]
if totalChar+len(word)+1 > columnWidth {
nextWords = words[i:]
break
}
newWords = append(newWords, word)
totalChar += len(word) + 1
}
row[j] = strings.Join(newWords, " ")
last := len(self.Rows) - 1
self.Rows = append(self.Rows, self.Rows[last])
copy(self.Rows[i+1:], self.Rows[i:last])
self.Rows[i+1] = make([]string, len(self.Rows[i]))
self.Rows[i+1][j] = strings.Join(nextWords, " ")
return row
}