Skip to content

Commit

Permalink
Use muesli/reflow to compute str width & truncate (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
greglanthier committed May 2, 2022
1 parent 7f13fb1 commit af9e08b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ require (
github.com/charmbracelet/bubbles v0.10.3
github.com/charmbracelet/bubbletea v0.19.3
github.com/charmbracelet/lipgloss v0.4.0
github.com/mattn/go-runewidth v0.0.13
github.com/muesli/reflow v0.3.0
github.com/stretchr/testify v1.7.0
)

Expand All @@ -15,9 +17,7 @@ require (
github.com/davecgh/go-spew v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.13 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.9.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
Expand Down
7 changes: 4 additions & 3 deletions table/strlimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package table
import (
"strings"

"github.com/mattn/go-runewidth"
"github.com/muesli/reflow/ansi"
"github.com/muesli/reflow/truncate"
)

func limitStr(str string, maxLen int) string {
Expand All @@ -16,8 +17,8 @@ func limitStr(str string, maxLen int) string {
str = str[:newLineIndex] + "…"
}

if runewidth.StringWidth(str) > maxLen {
return runewidth.Truncate(str, maxLen-1, "") + "…"
if ansi.PrintableRuneWidth(str) > maxLen {
return truncate.StringWithTail(str, uint(maxLen), "…")
}

return str
Expand Down
16 changes: 14 additions & 2 deletions table/strlimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package table

import (
"testing"
"unicode/utf8"

"github.com/muesli/reflow/ansi"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -82,14 +82,26 @@ func TestLimitStr(t *testing.T) {
max: 5,
expected: "hell…",
},
{
name: "Embedded ANSI control sequences with exact max width",
input: "\x1b[31;41mtest\x1b[0m",
max: 4,
expected: "\x1b[31;41mtest\x1b[0m",
},
{
name: "Embedded ANSI control sequences with truncation",
input: "\x1b[31;41mte\x1b[0m\x1b[0m\x1b[0mst",
max: 3,
expected: "\x1b[31;41mte\x1b[0m\x1b[0m\x1b[0m…",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
output := limitStr(test.input, test.max)

assert.Equal(t, test.expected, output)
assert.LessOrEqual(t, utf8.RuneCountInString(output), test.max)
assert.LessOrEqual(t, ansi.PrintableRuneWidth(output), test.max)
})
}
}

0 comments on commit af9e08b

Please sign in to comment.