diff --git a/README.md b/README.md index 190e4f6..eff69d7 100644 --- a/README.md +++ b/README.md @@ -261,9 +261,29 @@ lipgloss.HorizontalJoin(0.2, paragraphA, paragraphB, paragraphC) ``` +### Measuring Width and Height + +Sometimes you’ll want to know the width and height of text blocks when building +your layouts: + +```go +var block string = lipgloss.NewStyle(). + Width(40). + Padding(2). + Render(someLongString) + +// Get the actual, phsical dimensions of the text block. +width := lipgloss.Width(block) +height := lipgloss.Height(block) + +// Here's a shorthand function. +w, h := lipgloss.Size(block) +``` + + ### Placing Text in Whitespace -Sometimes you simply want to place a block of text in whitespace. +Sometimes you’ll simply want to place a block of text in whitespace. ```go // Center a paragraph horizontally in a space 80 cells wide. The height of diff --git a/size.go b/size.go index 23873a9..439a5cb 100644 --- a/size.go +++ b/size.go @@ -7,8 +7,8 @@ import ( ) // Width returns the cell width of characters in the string. ANSI sequences are -// ignored and characters wider than one cell (such as Chinese characters) are -// appropriately measured. +// ignored and characters wider than one cell (such as Chinese characters and +// emojis) are appropriately measured. // // You should use this instead of len(string) len([]rune(string) as neither // will give you accurate results. @@ -30,3 +30,12 @@ func Width(str string) (width int) { func Height(str string) int { return strings.Count(str, "\n") + 1 } + +// Size returns the width and height of the string in cells. ANSI sequences are +// ignored and characters wider than one cell (such as Chinese characters and +// emojis) are appropriately measured. +func Size(str string) (width, height int) { + width = Width(str) + height = Height(str) + return width, height +}