From 5af857edaea996c9c3b6c6696b2a5672e44d2b88 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Fri, 29 Mar 2024 15:48:50 +0000 Subject: [PATCH] tui: truncate title to width --- pkg/tui/tui.go | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/pkg/tui/tui.go b/pkg/tui/tui.go index e7782ef..b0d957a 100644 --- a/pkg/tui/tui.go +++ b/pkg/tui/tui.go @@ -123,6 +123,8 @@ var ( PaddingLeft(2). PaddingRight(2) headerStyle = lipgloss.NewStyle(). + PaddingLeft(1). + PaddingRight(1). Background(lipgloss.Color("0")) footerStyle = lipgloss.NewStyle(). BorderTop(true). @@ -327,6 +329,22 @@ func height(str string) int { 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 { if m.width == 0 { // 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 { - titleStyle := lipgloss.NewStyle(). - PaddingLeft(1). - PaddingRight(1). - Bold(true) + titleStyle := lipgloss.NewStyle().Bold(true) var title string if m.conversation != nil && m.conversation.Title != "" { title = m.conversation.Title } else { title = "Untitled" } + title = truncateToCellWidth(title, m.width-headerStyle.GetHorizontalPadding(), "...") part := titleStyle.Render(title) - return headerStyle.Width(m.width).Render(part) } @@ -424,16 +439,7 @@ func (m *model) footerView() string { footer := left + padding + right if remaining < 0 { - ellipses := "... " - 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 + footer = truncateToCellWidth(footer, m.width, "...") } return footerStyle.Width(m.width).Render(footer) }