tui: truncate title to width

This commit is contained in:
Matt Low 2024-03-29 15:48:50 +00:00
parent 3e24a54d0a
commit 5af857edae
1 changed files with 21 additions and 15 deletions

View File

@ -123,6 +123,8 @@ var (
PaddingLeft(2). PaddingLeft(2).
PaddingRight(2) PaddingRight(2)
headerStyle = lipgloss.NewStyle(). headerStyle = lipgloss.NewStyle().
PaddingLeft(1).
PaddingRight(1).
Background(lipgloss.Color("0")) Background(lipgloss.Color("0"))
footerStyle = lipgloss.NewStyle(). footerStyle = lipgloss.NewStyle().
BorderTop(true). BorderTop(true).
@ -327,6 +329,22 @@ func height(str string) int {
return strings.Count(str, "\n") + 1 return strings.Count(str, "\n") + 1
} }
func truncateToCellWidth(str string, width int, tail string) string {
cellWidth := ansi.PrintableRuneWidth(str)
if cellWidth <= width {
return str
}
tailWidth := ansi.PrintableRuneWidth(tail)
for {
str = str[:len(str)-((cellWidth+tailWidth)-width)]
cellWidth = ansi.PrintableRuneWidth(str)
if cellWidth+tailWidth <= max(width, 0) {
break
}
}
return str + tail
}
func (m model) View() string { func (m model) View() string {
if m.width == 0 { if m.width == 0 {
// this is the case upon initial startup, but it's also a safe bet that // this is the case upon initial startup, but it's also a safe bet that
@ -351,18 +369,15 @@ func (m model) View() string {
} }
func (m *model) headerView() string { func (m *model) headerView() string {
titleStyle := lipgloss.NewStyle(). titleStyle := lipgloss.NewStyle().Bold(true)
PaddingLeft(1).
PaddingRight(1).
Bold(true)
var title string var title string
if m.conversation != nil && m.conversation.Title != "" { if m.conversation != nil && m.conversation.Title != "" {
title = m.conversation.Title title = m.conversation.Title
} else { } else {
title = "Untitled" title = "Untitled"
} }
title = truncateToCellWidth(title, m.width-headerStyle.GetHorizontalPadding(), "...")
part := titleStyle.Render(title) part := titleStyle.Render(title)
return headerStyle.Width(m.width).Render(part) return headerStyle.Width(m.width).Render(part)
} }
@ -424,16 +439,7 @@ func (m *model) footerView() string {
footer := left + padding + right footer := left + padding + right
if remaining < 0 { if remaining < 0 {
ellipses := "... " footer = truncateToCellWidth(footer, m.width, "...")
for {
truncWidth := ansi.PrintableRuneWidth(footer) + len(ellipses)
if truncWidth <= m.width {
break
}
// truncate the minimum amount, not accounting for printed width
footer = footer[:len(footer)-(truncWidth-m.width)]
}
footer += ellipses
} }
return footerStyle.Width(m.width).Render(footer) return footerStyle.Width(m.width).Render(footer)
} }