fix(messages): properly measure width when rendering attachment paths

Christian Rocha created

Change summary

internal/tui/components/chat/messages/messages.go | 27 +++++++++++-----
1 file changed, 18 insertions(+), 9 deletions(-)

Detailed changes

internal/tui/components/chat/messages/messages.go 🔗

@@ -207,18 +207,27 @@ func (m *messageCmp) renderUserMessage() string {
 
 	attachments := make([]string, len(m.message.BinaryContent()))
 	for i, attachment := range m.message.BinaryContent() {
-		file := filepath.Base(attachment.Path)
-		var filename string
-		runes := []rune(file)
-
-		const truncatePathAt = 7
-		if len(runes) > truncatePathAt {
-			filename = fmt.Sprintf(" %s %s... ", styles.DocumentIcon, string(runes[0:truncatePathAt]))
+		filename := filepath.Base(attachment.Path)
+		var displayFilename string
+		runes := []rune(filename)
+
+		const truncateAtChars = 7
+		const truncateSuffix = "..."
+
+		// If the filename is too long, truncate it to fit within the maximum
+		// width we’ve chosen.
+		if lipgloss.Width(filename) > truncateAtChars+lipgloss.Width(truncateSuffix) {
+			displayFilename = fmt.Sprintf(
+				" %s %s%s ",
+				styles.DocumentIcon,
+				string(runes[0:truncateAtChars]),
+				truncateSuffix,
+			)
 		} else {
-			filename = fmt.Sprintf(" %s %s ", styles.DocumentIcon, file)
+			displayFilename = fmt.Sprintf(" %s %s ", styles.DocumentIcon, filename)
 		}
 
-		attachments[i] = attachmentStyles.Render(filename)
+		attachments[i] = attachmentStyles.Render(displayFilename)
 	}
 
 	if len(attachments) > 0 {