diff options
Diffstat (limited to 'internal/game/table.go')
| -rw-r--r-- | internal/game/table.go | 50 |
1 files changed, 47 insertions, 3 deletions
diff --git a/internal/game/table.go b/internal/game/table.go index e3dad97..56c0079 100644 --- a/internal/game/table.go +++ b/internal/game/table.go @@ -11,6 +11,7 @@ type tableGlyphs struct { sepLeft, sepCross, sepRight rune botLeft, botSep, botRight rune fillH, fillHSep rune + titleSep rune } func tableGlyphSet(unicode bool) tableGlyphs { @@ -19,16 +20,19 @@ func tableGlyphSet(unicode bool) tableGlyphs { topLeft: '╔', topSep: '╤', topRight: '╗', side: '║', colSep: '│', sepLeft: '╟', sepCross: '┼', sepRight: '╢', botLeft: '╚', botSep: '╧', botRight: '╝', fillH: '═', fillHSep: '─', + titleSep: '┬', } } return tableGlyphs{ topLeft: '+', topSep: '+', topRight: '+', side: '|', colSep: '|', sepLeft: '+', sepCross: '+', sepRight: '+', botLeft: '+', botSep: '+', botRight: '+', fillH: '-', fillHSep: '-', + titleSep: '+', } } type Table struct { + Title string Columns []string Rows [][]string } @@ -37,6 +41,9 @@ func (t *Table) Render(unicode bool) []string { g := tableGlyphSet(unicode) nCols := len(t.Columns) + if nCols == 0 && len(t.Rows) > 0 { + nCols = len(t.Rows[0]) + } if nCols == 0 { return nil } @@ -86,14 +93,51 @@ func (t *Table) Render(unicode bool) []string { return b.String() } + hasTitle := t.Title != "" + hasCols := len(t.Columns) > 0 + var out []string - out = append(out, makeSep(g.topLeft, g.topSep, g.topRight, g.fillH)) - out = append(out, makeRow(t.Columns)) - out = append(out, makeSep(g.sepLeft, g.sepCross, g.sepRight, g.fillHSep)) + if hasTitle { + innerWidth := 0 + for _, w := range colWidths { + innerWidth += w + 2 + } + innerWidth += nCols - 1 + + var tb strings.Builder + tb.WriteRune(g.topLeft) + tb.WriteString(strings.Repeat(string(g.fillH), innerWidth)) + tb.WriteRune(g.topRight) + out = append(out, tb.String()) + + var tr strings.Builder + tr.WriteRune(g.side) + tr.WriteString(" ") + tr.WriteString(t.Title) + padding := innerWidth - 2 - len(t.Title) + if padding < 0 { + padding = 0 + } + tr.WriteString(strings.Repeat(" ", padding)) + tr.WriteString(" ") + tr.WriteRune(g.side) + out = append(out, tr.String()) + + out = append(out, makeSep(g.sepLeft, g.titleSep, g.sepRight, g.fillHSep)) + } else { + out = append(out, makeSep(g.topLeft, g.topSep, g.topRight, g.fillH)) + } + + if hasCols { + out = append(out, makeRow(t.Columns)) + out = append(out, makeSep(g.sepLeft, g.sepCross, g.sepRight, g.fillHSep)) + } + for _, row := range t.Rows { out = append(out, makeRow(row)) } + out = append(out, makeSep(g.botLeft, g.botSep, g.botRight, g.fillH)) return out |
