size.go

 1package lipgloss
 2
 3import (
 4	"strings"
 5
 6	"github.com/charmbracelet/x/ansi"
 7)
 8
 9// Width returns the cell width of characters in the string. ANSI sequences are
10// ignored and characters wider than one cell (such as Chinese characters and
11// emojis) are appropriately measured.
12//
13// You should use this instead of len(string) or len([]rune(string) as neither
14// will give you accurate results.
15func Width(str string) (width int) {
16	for _, l := range strings.Split(str, "\n") {
17		w := ansi.StringWidth(l)
18		if w > width {
19			width = w
20		}
21	}
22
23	return width
24}
25
26// Height returns height of a string in cells. This is done simply by
27// counting \n characters. If your output has \r\n, that sequence will be
28// replaced with a \n in [Style.Render].
29func Height(str string) int {
30	return strings.Count(str, "\n") + 1
31}
32
33// Size returns the width and height of the string in cells. ANSI sequences are
34// ignored and characters wider than one cell (such as Chinese characters and
35// emojis) are appropriately measured.
36func Size(str string) (width, height int) {
37	width = Width(str)
38	height = Height(str)
39	return width, height
40}