Files

66 lines
1.7 KiB
Go
Raw Permalink Normal View History

package tui
import (
"strings"
"charm.land/lipgloss/v2"
)
// Truncate cuts text to width with a trailing "..." (width > 3).
// It counts runes, not terminal cells: wide (CJK, emoji) characters can
// still overflow -- the behavior the programs had; a cell-aware version
// would be a deliberate, tested change.
func Truncate(text string, width int) string {
if width <= 0 {
return ""
}
runes := []rune(text)
if len(runes) <= width {
return text
}
if width <= 3 {
return string(runes[:width])
}
return string(runes[:width-3]) + "..."
}
// TruncateBlock truncates every line of text to width.
func TruncateBlock(text string, width int) string {
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = Truncate(line, width)
}
return strings.Join(lines, "\n")
}
// WrapStyled wraps text to width and renders each line with style.
func WrapStyled(text string, width int, style lipgloss.Style) []string {
if strings.TrimSpace(text) == "" {
return []string{style.Render("")}
}
wrapped := lipgloss.NewStyle().Width(width).Render(text)
lines := strings.Split(wrapped, "\n")
for i, line := range lines {
lines[i] = style.Render(line)
}
return lines
}
// KeyValue returns a renderer for "key: value" lines of at most width
// cells, the value truncated.
func KeyValue(width int, styles Styles) func(k, v string) string {
return func(k, v string) string {
label := k + ": "
return styles.Key.Render(label) + styles.Value.Render(Truncate(v, width-lipgloss.Width(label)))
}
}
// FirstNonEmpty returns the first non-empty value, or "".
func FirstNonEmpty(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}