Skip to content

Commit

Permalink
word wrap text first before clamping
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Sep 25, 2020
1 parent b2ab0b1 commit 7d256a0
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 10 deletions.
1 change: 1 addition & 0 deletions go.mod
Expand Up @@ -7,6 +7,7 @@ require (
github.com/creack/pty v1.1.11
github.com/gookit/color v1.3.1
github.com/mitchellh/go-testing-interface v1.14.1
github.com/mitchellh/go-wordwrap v1.0.1
github.com/morikuni/aec v1.0.0
github.com/stretchr/testify v1.6.1
github.com/tj/go-spin v1.1.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Expand Up @@ -19,6 +19,8 @@ github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+tw
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
23 changes: 13 additions & 10 deletions measure.go
Expand Up @@ -7,6 +7,7 @@ import (
"unicode/utf8"

"github.com/mitchellh/go-glint/flex"
"github.com/mitchellh/go-wordwrap"
)

// TextNodeContext is the *flex.Node.Context set for all *TextComponent flex nodes.
Expand Down Expand Up @@ -53,6 +54,18 @@ func MeasureTextNode(
// Otherwise, we have to render this.
ctx.Text = ctx.C.Render(uint(height), uint(width))

// Word wrap and truncate if we're beyond the width limit.
if !math.IsNaN(float64(width)) && width > 0 {
ctx.Text = clampTextWidth(
wordwrap.WrapString(ctx.Text, uint(width)),
int(width))
}

// Truncate height if we have a limit. This is a no-op if it fits.
if !math.IsNaN(float64(height)) && height > 0 {
ctx.Text = truncateTextHeight(ctx.Text, int(height))
}

// Calculate the size
ctx.Size = flex.Size{
Width: float32(longestLine(ctx.Text)),
Expand All @@ -66,16 +79,6 @@ func MeasureTextNode(
ctx.Size.Height = 1
}

// Truncate height if we have a limit. This is a no-op if it fits.
if !math.IsNaN(float64(height)) && height > 0 {
ctx.Text = truncateTextHeight(ctx.Text, int(height))
}

// Truncate width if we have a limit. This is a no-op if it fits.
if !math.IsNaN(float64(width)) && width > 0 {
ctx.Text = clampTextWidth(ctx.Text, int(width))
}

return ctx.Size
}

Expand Down

0 comments on commit 7d256a0

Please sign in to comment.