Skip to content

Commit

Permalink
table: adjust title width to table width (#133)
Browse files Browse the repository at this point in the history
Authored-by: FoamCactus <cahill@mtu.edu>
  • Loading branch information
jedib0t authored Oct 1, 2020
1 parent db920ca commit 9875be5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
8 changes: 6 additions & 2 deletions table/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,14 +393,18 @@ func (t *Table) renderRowsHeader(out *strings.Builder) {

func (t *Table) renderTitle(out *strings.Builder) {
if t.title != "" {
rowLength := t.maxRowLength
if t.allowedRowLength != 0 && t.allowedRowLength < rowLength {
rowLength = t.allowedRowLength
}
if t.style.Options.DrawBorder {
lenBorder := t.maxRowLength - text.RuneCount(t.style.Box.TopLeft+t.style.Box.TopRight)
lenBorder := rowLength - text.RuneCount(t.style.Box.TopLeft+t.style.Box.TopRight)
out.WriteString(t.style.Box.TopLeft)
out.WriteString(text.RepeatAndTrim(t.style.Box.MiddleHorizontal, lenBorder))
out.WriteString(t.style.Box.TopRight)
}

lenText := t.maxRowLength - text.RuneCount(t.style.Box.PaddingLeft+t.style.Box.PaddingRight)
lenText := rowLength - text.RuneCount(t.style.Box.PaddingLeft+t.style.Box.PaddingRight)
if t.style.Options.DrawBorder {
lenText -= text.RuneCount(t.style.Box.Left + t.style.Box.Right)
}
Expand Down
49 changes: 49 additions & 0 deletions table/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1242,3 +1242,52 @@ func TestTable_Render_TableWithTransformers(t *testing.T) {
}
}
}

func TestTable_Render_SetWidth_Title(t *testing.T) {
tw := NewWriter()
tw.AppendHeader(testHeader)
tw.AppendRows(testRows)
tw.AppendFooter(testFooter)
tw.SetTitle("Game Of Thrones")

t.Run("length 20", func(t *testing.T) {
tw.SetAllowedRowLength(20)

expectedOut := []string{
"+------------------+",
"| Game Of Thrones |",
"+-----+----------- ~",
"| # | FIRST NAME ~",
"+-----+----------- ~",
"| 1 | Arya ~",
"| 20 | Jon ~",
"| 300 | Tyrion ~",
"+-----+----------- ~",
"| | ~",
"+-----+----------- ~",
}

assert.Equal(t, strings.Join(expectedOut, "\n"), tw.Render())
})

t.Run("length 30", func(t *testing.T) {
tw.SetAllowedRowLength(30)

expectedOut := []string{
"+----------------------------+",
"| Game Of Thrones |",
"+-----+------------+-------- ~",
"| # | FIRST NAME | LAST NA ~",
"+-----+------------+-------- ~",
"| 1 | Arya | Stark ~",
"| 20 | Jon | Snow ~",
"| 300 | Tyrion | Lannist ~",
"+-----+------------+-------- ~",
"| | | TOTAL ~",
"+-----+------------+-------- ~",
}

assert.Equal(t, strings.Join(expectedOut, "\n"), tw.Render())
})

}

0 comments on commit 9875be5

Please sign in to comment.