diff --git a/bitchat/App/ConversationUIModel.swift b/bitchat/App/ConversationUIModel.swift index e4db4e9c..071d7059 100644 --- a/bitchat/App/ConversationUIModel.swift +++ b/bitchat/App/ConversationUIModel.swift @@ -150,6 +150,21 @@ final class ConversationUIModel: ObservableObject { chatViewModel.formatMessageHeader(message, colorScheme: colorScheme, theme: theme) } + func formatBubbleBody(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme? = nil) -> AttributedString { + chatViewModel.formatBubbleBody(message, colorScheme: colorScheme, theme: theme) + } + + func formatBubbleSender(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme? = nil) -> AttributedString { + chatViewModel.formatBubbleSender(message, colorScheme: colorScheme, theme: theme) + } + + /// Wash color of a message's bubble: orange for my own, the sender's + /// stable peer color (the one their name is drawn in) for everyone else. + func bubbleTint(for message: BitchatMessage, colorScheme: ColorScheme) -> Color { + if isSentByCurrentUser(message) { return .orange } + return chatViewModel.senderColor(for: message, isDark: colorScheme == .dark) + } + func mediaAttachment(for message: BitchatMessage) -> BitchatMessage.Media? { // The model loads from outgoing/ exactly when the row's sender equals // the name it is given. Ask with the row's own sender first: text rows, diff --git a/bitchat/BitchatApp.swift b/bitchat/BitchatApp.swift index cf2e1bd1..ba73fa30 100644 --- a/bitchat/BitchatApp.swift +++ b/bitchat/BitchatApp.swift @@ -16,6 +16,7 @@ struct BitchatApp: App { @StateObject private var runtime: AppRuntime @AppStorage(AppTheme.storageKey) private var appThemeRawValue = AppTheme.matrix.rawValue + @AppStorage(ChatStyle.storageKey) private var chatStyleRawValue = ChatStyle.bubbles.rawValue #if os(iOS) @Environment(\.scenePhase) var scenePhase @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @@ -32,6 +33,7 @@ struct BitchatApp: App { WindowGroup { ContentView() .environment(\.appTheme, AppTheme(rawValue: appThemeRawValue) ?? .matrix) + .environment(\.chatStyle, ChatStyle(rawValue: chatStyleRawValue) ?? .bubbles) .environmentObject(runtime.publicChatModel) .environmentObject(runtime.privateInboxModel) .environmentObject(runtime.privateConversationModel) diff --git a/bitchat/Localizable.xcstrings b/bitchat/Localizable.xcstrings index 601d5b6a..eb47e072 100644 --- a/bitchat/Localizable.xcstrings +++ b/bitchat/Localizable.xcstrings @@ -20121,6 +20121,564 @@ } } }, + "app_info.chat_style.bubbles" : { + "comment" : "Chip label in settings for the messenger-style chat layout: messages in rounded bubbles, own messages on the right", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "فقاعات" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "বাবল" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "blasen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "bubbles" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "burbujas" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "حباب‌ها" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "bubbles" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "bulles" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "בועות" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "बबल" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "gelembung" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "fumetti" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "吹き出し" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "말풍선" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "gelembung" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "बबल" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "bubbels" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "dymki" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "balões" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "balões" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "пузыри" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "bubblor" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "குமிழ்கள்" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "บับเบิล" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "balonlar" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "бульбашки" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "ببلز" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "bong bóng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "气泡" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "氣泡" + } + } + } + }, + "app_info.chat_style.irc" : { + "comment" : "Chip label in settings for the classic IRC-style chat layout: flat <@name> message lines", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "irc" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "IRC" + } + } + } + }, + "app_info.chat_style.title" : { + "comment" : "Label of the settings row choosing the chat layout (bubbles or irc)", + "extractionState" : "manual", + "localizations" : { + "ar" : { + "stringUnit" : { + "state" : "translated", + "value" : "نمط الدردشة" + } + }, + "bn" : { + "stringUnit" : { + "state" : "translated", + "value" : "চ্যাট স্টাইল" + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "chat-stil" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "chat style" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "estilo de chat" + } + }, + "fa" : { + "stringUnit" : { + "state" : "translated", + "value" : "سبک گفتگو" + } + }, + "fil" : { + "stringUnit" : { + "state" : "translated", + "value" : "istilo ng chat" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "style de discussion" + } + }, + "he" : { + "stringUnit" : { + "state" : "translated", + "value" : "סגנון צ'אט" + } + }, + "hi" : { + "stringUnit" : { + "state" : "translated", + "value" : "चैट शैली" + } + }, + "id" : { + "stringUnit" : { + "state" : "translated", + "value" : "gaya obrolan" + } + }, + "it" : { + "stringUnit" : { + "state" : "translated", + "value" : "stile chat" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "チャットスタイル" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "채팅 스타일" + } + }, + "ms" : { + "stringUnit" : { + "state" : "translated", + "value" : "gaya sembang" + } + }, + "ne" : { + "stringUnit" : { + "state" : "translated", + "value" : "च्याट शैली" + } + }, + "nl" : { + "stringUnit" : { + "state" : "translated", + "value" : "chatstijl" + } + }, + "pl" : { + "stringUnit" : { + "state" : "translated", + "value" : "styl czatu" + } + }, + "pt" : { + "stringUnit" : { + "state" : "translated", + "value" : "estilo do chat" + } + }, + "pt-BR" : { + "stringUnit" : { + "state" : "translated", + "value" : "estilo do chat" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "стиль чата" + } + }, + "sv" : { + "stringUnit" : { + "state" : "translated", + "value" : "chattstil" + } + }, + "ta" : { + "stringUnit" : { + "state" : "translated", + "value" : "அரட்டை நடை" + } + }, + "th" : { + "stringUnit" : { + "state" : "translated", + "value" : "รูปแบบแชท" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "sohbet stili" + } + }, + "uk" : { + "stringUnit" : { + "state" : "translated", + "value" : "стиль чату" + } + }, + "ur" : { + "stringUnit" : { + "state" : "translated", + "value" : "چیٹ اسٹائل" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "kiểu trò chuyện" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "聊天样式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "聊天樣式" + } + } + } + }, "app_info.done" : { "extractionState" : "manual", "localizations" : { diff --git a/bitchat/Utils/ChatStyle.swift b/bitchat/Utils/ChatStyle.swift new file mode 100644 index 00000000..372f9f60 --- /dev/null +++ b/bitchat/Utils/ChatStyle.swift @@ -0,0 +1,48 @@ +// +// ChatStyle.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import SwiftUI + +/// How the chat transcript lays out messages. Independent of `AppTheme`: +/// the theme picks colors, fonts and chrome; the style only picks the row +/// layout. +/// +/// `bubbles` is the messenger layout (the Android app's default since +/// 2.0): messages hug their content inside rounded bubbles, own messages +/// on the right and everyone else on the left, each bubble washed with its +/// author's peer color. `irc` is the original flat `<@name> text [time]` +/// transcript. +enum ChatStyle: String, CaseIterable, Identifiable { + case bubbles + case irc + + var id: String { rawValue } + + /// UserDefaults key backing the style selection. + static let storageKey = "chatStyle" + + var displayNameKey: LocalizedStringKey { + switch self { + case .bubbles: return "app_info.chat_style.bubbles" + case .irc: return "app_info.chat_style.irc" + } + } + + var usesBubbles: Bool { self == .bubbles } +} + +private struct ChatStyleKey: EnvironmentKey { + static let defaultValue: ChatStyle = .bubbles +} + +extension EnvironmentValues { + var chatStyle: ChatStyle { + get { self[ChatStyleKey.self] } + set { self[ChatStyleKey.self] = newValue } + } +} diff --git a/bitchat/ViewModels/ChatMessageFormatter.swift b/bitchat/ViewModels/ChatMessageFormatter.swift index 8a5310c1..9ada4446 100644 --- a/bitchat/ViewModels/ChatMessageFormatter.swift +++ b/bitchat/ViewModels/ChatMessageFormatter.swift @@ -90,254 +90,17 @@ final class ChatMessageFormatter { } result.append(AttributedString("> ").mergingAttributes(senderStyle)) - let content = message.content - let nsContent = content as NSString - let nsLen = nsContent.length - - if content.isOversizedForRichFormatting() { - var plainStyle = AttributeContainer() - plainStyle.foregroundColor = baseColor - plainStyle.font = isSelf - ? .bitchatSystem(size: 14, weight: .bold, design: design) - : .bitchatSystem(size: 14, design: design) - result.append(AttributedString(content).mergingAttributes(plainStyle)) - } else { - let hashtagRegex = Patterns.hashtag - let mentionRegex = Patterns.mention - let cashuRegex = Patterns.cashu - let bolt11Regex = Patterns.bolt11 - let lnurlRegex = Patterns.lnurl - let lightningSchemeRegex = Patterns.lightningScheme - let detector = Patterns.linkDetector - let hasMentionsHint = content.contains("@") - let hasHashtagsHint = content.contains("#") - let hasURLHint = content.contains("://") || content.contains("www.") || content.contains("http") - let hasLightningHint = content.lowercased().contains("ln") || content.lowercased().contains("lightning:") - let hasCashuHint = content.lowercased().contains("cashu") - - let hashtagMatches = hasHashtagsHint - ? hashtagRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - let mentionMatches = hasMentionsHint - ? mentionRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - let urlMatches = hasURLHint - ? (detector?.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) ?? []) - : [] - let cashuMatches = hasCashuHint - ? cashuRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - let lightningMatches = hasLightningHint - ? lightningSchemeRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - let bolt11Matches = hasLightningHint - ? bolt11Regex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - let lnurlMatches = hasLightningHint - ? lnurlRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) - : [] - - let mentionRanges = mentionMatches.map { $0.range(at: 0) } - func overlapsMention(_ range: NSRange) -> Bool { - for mentionRange in mentionRanges where NSIntersectionRange(range, mentionRange).length > 0 { - return true - } - return false - } - - func attachedToMention(_ range: NSRange) -> Bool { - if let swiftRange = Range(range, in: content), swiftRange.lowerBound > content.startIndex { - var index = content.index(before: swiftRange.lowerBound) - while true { - let character = content[index] - if character.isWhitespace || character.isNewline { break } - if character == "@" { return true } - if index == content.startIndex { break } - index = content.index(before: index) - } - } - return false - } - - func isStandaloneHashtag(_ range: NSRange) -> Bool { - guard let swiftRange = Range(range, in: content) else { return false } - if swiftRange.lowerBound == content.startIndex { return true } - let previous = content.index(before: swiftRange.lowerBound) - return content[previous].isWhitespace || content[previous].isNewline - } - - var allMatches: [(range: NSRange, type: String)] = [] - for match in hashtagMatches - where !overlapsMention(match.range(at: 0)) - && !attachedToMention(match.range(at: 0)) - && isStandaloneHashtag(match.range(at: 0)) { - allMatches.append((match.range(at: 0), "hashtag")) - } - for match in mentionMatches { - allMatches.append((match.range(at: 0), "mention")) - } - for match in urlMatches where !overlapsMention(match.range) { - allMatches.append((match.range, "url")) - } - for match in cashuMatches where !overlapsMention(match.range(at: 0)) { - allMatches.append((match.range(at: 0), "cashu")) - } - for match in lightningMatches where !overlapsMention(match.range(at: 0)) { - allMatches.append((match.range(at: 0), "lightning")) - } - - let occupied = urlMatches.map(\.range) + lightningMatches.map { $0.range(at: 0) } - func overlapsOccupied(_ range: NSRange) -> Bool { - for occupiedRange in occupied where NSIntersectionRange(range, occupiedRange).length > 0 { - return true - } - return false - } - - for match in bolt11Matches - where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) { - allMatches.append((match.range(at: 0), "bolt11")) - } - for match in lnurlMatches - where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) { - allMatches.append((match.range(at: 0), "lnurl")) - } - allMatches.sort { $0.range.location < $1.range.location } - - var lastEnd = content.startIndex - let myNickname = viewModel.nickname.normalizedNickname - let isMentioned = message.mentions?.contains { $0.normalizedNickname == myNickname } ?? false - - for (range, type) in allMatches { - guard let swiftRange = Range(range, in: content) else { continue } - - if lastEnd < swiftRange.lowerBound { - let beforeText = String(content[lastEnd.. content.startIndex { - var index = content.index(before: swiftRange.lowerBound) - while true { - let character = content[index] - if character.isWhitespace || character.isNewline { break } - if character == "@" { return true } - if index == content.startIndex { break } - index = content.index(before: index) - } - } - return false - }() - let standalone: Bool = { - if swiftRange.lowerBound == content.startIndex { return true } - let previous = content.index(before: swiftRange.lowerBound) - return content[previous].isWhitespace || content[previous].isNewline - }() - - var tagStyle = AttributeContainer() - tagStyle.font = isSelf - ? .bitchatSystem(size: 14, weight: .bold, design: design) - : .bitchatSystem(size: 14, design: design) - tagStyle.foregroundColor = baseColor - if isGeohash && !attachedToMentionToken && standalone, - let url = URL(string: "bitchat://geohash/\(token)") { - tagStyle.link = url - tagStyle.underlineStyle = .single - } - result.append(AttributedString(matchText).mergingAttributes(tagStyle)) - } else if type == "cashu" || type == "lightning" || type == "bolt11" || type == "lnurl" { - var spacer = AttributeContainer() - spacer.foregroundColor = baseColor - spacer.font = isSelf - ? .bitchatSystem(size: 14, weight: .bold, design: design) - : .bitchatSystem(size: 14, design: design) - result.append(AttributedString(" ").mergingAttributes(spacer)) - } else { - var matchStyle = AttributeContainer() - matchStyle.font = .bitchatSystem( - size: 14, - weight: isSelf ? .bold : .semibold, - design: design - ) - if type == "url" { - matchStyle.foregroundColor = isSelf ? .orange : .blue - matchStyle.underlineStyle = .single - if let url = URL(string: matchText) { - matchStyle.link = url - } - } - result.append(AttributedString(matchText).mergingAttributes(matchStyle)) - } - - if lastEnd < swiftRange.upperBound { - lastEnd = swiftRange.upperBound - } - } - - if lastEnd < content.endIndex { - let remainingText = String(content[lastEnd...]) - var remainingStyle = AttributeContainer() - remainingStyle.foregroundColor = baseColor - remainingStyle.font = isSelf - ? .bitchatSystem(size: 14, weight: .bold, design: design) - : .bitchatSystem(size: 14, design: design) - if isMentioned { - remainingStyle.font = remainingStyle.font?.bold() - } - result.append(AttributedString(remainingText).mergingAttributes(remainingStyle)) - } - } + appendStyledContent( + of: message, + to: &result, + style: ContentStyle( + textColor: baseColor, + accentColor: baseColor, + linkColor: isSelf ? .orange : .blue, + emphasized: isSelf, + design: design + ) + ) let timestamp = AttributedString(" [\(message.formattedTimestamp)]") var timestampStyle = AttributeContainer() @@ -362,6 +125,276 @@ final class ChatMessageFormatter { return result } + /// Body styling: IRC rows tint the whole body with the author's color and + /// bold their own; bubbles keep the body neutral and let the bubble carry + /// the author's color. + private struct ContentStyle { + /// Plain runs, hashtags, and the spacers left for payment chips. + let textColor: Color + /// Mentions of anyone but me (mentions of me are always orange). + let accentColor: Color + let linkColor: Color + /// Bold body, used for my own IRC rows. + let emphasized: Bool + let design: Font.Design + } + + /// Appends the message's content, with mentions, hashtags, links and + /// payment tokens styled, to `result`. + private func appendStyledContent(of message: BitchatMessage, to result: inout AttributedString, style: ContentStyle) { + let content = message.content + let textColor = style.textColor + let emphasized = style.emphasized + let design = style.design + let nsContent = content as NSString + let nsLen = nsContent.length + + if content.isOversizedForRichFormatting() { + var plainStyle = AttributeContainer() + plainStyle.foregroundColor = textColor + plainStyle.font = emphasized + ? .bitchatSystem(size: 14, weight: .bold, design: design) + : .bitchatSystem(size: 14, design: design) + result.append(AttributedString(content).mergingAttributes(plainStyle)) + } else { + let hashtagRegex = Patterns.hashtag + let mentionRegex = Patterns.mention + let cashuRegex = Patterns.cashu + let bolt11Regex = Patterns.bolt11 + let lnurlRegex = Patterns.lnurl + let lightningSchemeRegex = Patterns.lightningScheme + let detector = Patterns.linkDetector + let hasMentionsHint = content.contains("@") + let hasHashtagsHint = content.contains("#") + let hasURLHint = content.contains("://") || content.contains("www.") || content.contains("http") + let hasLightningHint = content.lowercased().contains("ln") || content.lowercased().contains("lightning:") + let hasCashuHint = content.lowercased().contains("cashu") + + let hashtagMatches = hasHashtagsHint + ? hashtagRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + let mentionMatches = hasMentionsHint + ? mentionRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + let urlMatches = hasURLHint + ? (detector?.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) ?? []) + : [] + let cashuMatches = hasCashuHint + ? cashuRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + let lightningMatches = hasLightningHint + ? lightningSchemeRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + let bolt11Matches = hasLightningHint + ? bolt11Regex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + let lnurlMatches = hasLightningHint + ? lnurlRegex.matches(in: content, options: [], range: NSRange(location: 0, length: nsLen)) + : [] + + let mentionRanges = mentionMatches.map { $0.range(at: 0) } + func overlapsMention(_ range: NSRange) -> Bool { + for mentionRange in mentionRanges where NSIntersectionRange(range, mentionRange).length > 0 { + return true + } + return false + } + + func attachedToMention(_ range: NSRange) -> Bool { + if let swiftRange = Range(range, in: content), swiftRange.lowerBound > content.startIndex { + var index = content.index(before: swiftRange.lowerBound) + while true { + let character = content[index] + if character.isWhitespace || character.isNewline { break } + if character == "@" { return true } + if index == content.startIndex { break } + index = content.index(before: index) + } + } + return false + } + + func isStandaloneHashtag(_ range: NSRange) -> Bool { + guard let swiftRange = Range(range, in: content) else { return false } + if swiftRange.lowerBound == content.startIndex { return true } + let previous = content.index(before: swiftRange.lowerBound) + return content[previous].isWhitespace || content[previous].isNewline + } + + var allMatches: [(range: NSRange, type: String)] = [] + for match in hashtagMatches + where !overlapsMention(match.range(at: 0)) + && !attachedToMention(match.range(at: 0)) + && isStandaloneHashtag(match.range(at: 0)) { + allMatches.append((match.range(at: 0), "hashtag")) + } + for match in mentionMatches { + allMatches.append((match.range(at: 0), "mention")) + } + for match in urlMatches where !overlapsMention(match.range) { + allMatches.append((match.range, "url")) + } + for match in cashuMatches where !overlapsMention(match.range(at: 0)) { + allMatches.append((match.range(at: 0), "cashu")) + } + for match in lightningMatches where !overlapsMention(match.range(at: 0)) { + allMatches.append((match.range(at: 0), "lightning")) + } + + let occupied = urlMatches.map(\.range) + lightningMatches.map { $0.range(at: 0) } + func overlapsOccupied(_ range: NSRange) -> Bool { + for occupiedRange in occupied where NSIntersectionRange(range, occupiedRange).length > 0 { + return true + } + return false + } + + for match in bolt11Matches + where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) { + allMatches.append((match.range(at: 0), "bolt11")) + } + for match in lnurlMatches + where !overlapsMention(match.range(at: 0)) && !overlapsOccupied(match.range(at: 0)) { + allMatches.append((match.range(at: 0), "lnurl")) + } + allMatches.sort { $0.range.location < $1.range.location } + + var lastEnd = content.startIndex + let myNickname = viewModel.nickname.normalizedNickname + let isMentioned = message.mentions?.contains { $0.normalizedNickname == myNickname } ?? false + + for (range, type) in allMatches { + guard let swiftRange = Range(range, in: content) else { continue } + + if lastEnd < swiftRange.lowerBound { + let beforeText = String(content[lastEnd.. content.startIndex { + var index = content.index(before: swiftRange.lowerBound) + while true { + let character = content[index] + if character.isWhitespace || character.isNewline { break } + if character == "@" { return true } + if index == content.startIndex { break } + index = content.index(before: index) + } + } + return false + }() + let standalone: Bool = { + if swiftRange.lowerBound == content.startIndex { return true } + let previous = content.index(before: swiftRange.lowerBound) + return content[previous].isWhitespace || content[previous].isNewline + }() + + var tagStyle = AttributeContainer() + tagStyle.font = emphasized + ? .bitchatSystem(size: 14, weight: .bold, design: design) + : .bitchatSystem(size: 14, design: design) + tagStyle.foregroundColor = textColor + if isGeohash && !attachedToMentionToken && standalone, + let url = URL(string: "bitchat://geohash/\(token)") { + tagStyle.link = url + tagStyle.underlineStyle = .single + } + result.append(AttributedString(matchText).mergingAttributes(tagStyle)) + } else if type == "cashu" || type == "lightning" || type == "bolt11" || type == "lnurl" { + var spacer = AttributeContainer() + spacer.foregroundColor = textColor + spacer.font = emphasized + ? .bitchatSystem(size: 14, weight: .bold, design: design) + : .bitchatSystem(size: 14, design: design) + result.append(AttributedString(" ").mergingAttributes(spacer)) + } else { + var matchStyle = AttributeContainer() + matchStyle.font = .bitchatSystem( + size: 14, + weight: emphasized ? .bold : .semibold, + design: design + ) + if type == "url" { + matchStyle.foregroundColor = style.linkColor + matchStyle.underlineStyle = .single + if let url = URL(string: matchText) { + matchStyle.link = url + } + } + result.append(AttributedString(matchText).mergingAttributes(matchStyle)) + } + + if lastEnd < swiftRange.upperBound { + lastEnd = swiftRange.upperBound + } + } + + if lastEnd < content.endIndex { + let remainingText = String(content[lastEnd...]) + var remainingStyle = AttributeContainer() + remainingStyle.foregroundColor = textColor + remainingStyle.font = emphasized + ? .bitchatSystem(size: 14, weight: .bold, design: design) + : .bitchatSystem(size: 14, design: design) + if isMentioned { + remainingStyle.font = remainingStyle.font?.bold() + } + result.append(AttributedString(remainingText).mergingAttributes(remainingStyle)) + } + } + } + /// Prefix of the header's formatted-text cache variants. No full-text /// variant starts with it, so the two caches can't collide. static let headerCacheNamespace = "hdr:" @@ -426,6 +459,73 @@ final class ChatMessageFormatter { return result } + /// Prefix of the bubble layout's formatted-text cache variants, kept apart + /// from the IRC full-text and header caches for the same reason. + static let bubbleCacheNamespace = "bub:" + + /// Bubble body: the content alone, without the `<@name>` prefix or the + /// timestamp (the bubble draws both itself). The text stays neutral; the + /// bubble carries the author's color, and mentions keep it as an accent. + func formatBubbleBody(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme = .matrix) -> AttributedString { + let isSelf = isSelfMessage(message) + let isDark = colorScheme == .dark + let cacheVariant = Self.bubbleCacheNamespace + "body:" + theme.formatCacheVariant + if let cachedBody = message.getCachedFormattedText(isDark: isDark, isSelf: isSelf, variant: cacheVariant) { + return cachedBody + } + + var result = AttributedString() + appendStyledContent( + of: message, + to: &result, + style: ContentStyle( + textColor: .primary, + accentColor: isSelf ? .orange : peerColor(for: message, isDark: isDark), + linkColor: .blue, + emphasized: false, + design: theme.bodyFontDesign + ) + ) + message.setCachedFormattedText(result, isDark: isDark, isSelf: isSelf, variant: cacheVariant) + return result + } + + /// Bubble sender label: `@name` plus the dimmed `#abcd` suffix after a + /// thin space, linked to the sender's action sheet like the IRC header. + func formatBubbleSender(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme = .matrix) -> AttributedString { + let design = theme.bodyFontDesign + let isSelf = isSelfMessage(message) + let isDark = colorScheme == .dark + let isVerifiedSender = !isSelf && isVerifiedSender(of: message) + let cacheVariant = Self.bubbleCacheNamespace + "sender:" + theme.formatCacheVariant + (isVerifiedSender ? "-vf" : "") + if let cachedSender = message.getCachedFormattedText(isDark: isDark, isSelf: isSelf, variant: cacheVariant) { + return cachedSender + } + + let baseColor: Color = isSelf ? .orange : peerColor(for: message, isDark: isDark) + var result = AttributedString() + let (baseName, suffix) = message.sender.splitSuffix() + var senderStyle = AttributeContainer() + senderStyle.foregroundColor = baseColor + senderStyle.font = .bitchatSystem(size: 13, weight: .semibold, design: design) + if let spid = message.senderPeerID, let url = peerURL(for: spid) { + senderStyle.link = url + } + result.append(AttributedString("@\(baseName)").mergingAttributes(senderStyle)) + if !suffix.isEmpty { + var suffixStyle = senderStyle + suffixStyle.foregroundColor = baseColor.opacity(0.6) + suffixStyle.font = .bitchatSystem(size: 13, design: design) + result.append(AttributedString("\u{2009}\(suffix)").mergingAttributes(suffixStyle)) + } + // Private bubbles show the SF Symbol seal beside the name instead. + if isVerifiedSender, !message.isPrivate { + appendVerifiedSeal(to: &result, baseColor: baseColor, design: design) + } + message.setCachedFormattedText(result, isDark: isDark, isSelf: isSelf, variant: cacheVariant) + return result + } + func isSelfMessage(_ message: BitchatMessage) -> Bool { if let spid = message.senderPeerID { if case .location(let channel) = viewModel.activeChannel, spid.isGeoChat { diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 36742d29..aacbde0c 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -1840,6 +1840,16 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage messageFormatter.formatMessageHeader(message, colorScheme: colorScheme, theme: theme ?? currentTheme) } + @MainActor + func formatBubbleBody(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme? = nil) -> AttributedString { + messageFormatter.formatBubbleBody(message, colorScheme: colorScheme, theme: theme ?? currentTheme) + } + + @MainActor + func formatBubbleSender(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme? = nil) -> AttributedString { + messageFormatter.formatBubbleSender(message, colorScheme: colorScheme, theme: theme ?? currentTheme) + } + // MARK: - Noise Protocol Support @MainActor diff --git a/bitchat/Views/AppInfoView.swift b/bitchat/Views/AppInfoView.swift index cb99fbac..26db556e 100644 --- a/bitchat/Views/AppInfoView.swift +++ b/bitchat/Views/AppInfoView.swift @@ -8,6 +8,7 @@ struct AppInfoView: View { @Environment(\.dismiss) var dismiss @ThemedPalette private var palette @AppStorage(AppTheme.storageKey) private var appThemeRawValue = AppTheme.matrix.rawValue + @AppStorage(ChatStyle.storageKey) private var chatStyleRawValue = ChatStyle.bubbles.rawValue @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @ObservedObject private var bridgeService = BridgeService.shared @@ -44,6 +45,10 @@ struct AppInfoView: View { AppTheme(rawValue: appThemeRawValue) ?? .matrix } + private var selectedChatStyle: ChatStyle { + ChatStyle(rawValue: chatStyleRawValue) ?? .bubbles + } + private var textColor: Color { palette.primary } private var secondaryTextColor: Color { palette.secondary } @@ -53,6 +58,7 @@ struct AppInfoView: View { static let appName: LocalizedStringKey = "app_info.app_name" static let tagline: LocalizedStringKey = "app_info.tagline" static let appearanceTitle: LocalizedStringKey = "app_info.appearance.title" + static let chatStyleTitle: LocalizedStringKey = "app_info.chat_style.title" /// New keys carry their English copy inline (defaultValue) until the /// i18n pass lands them in the catalog; moved keys keep their homes. @@ -318,6 +324,23 @@ struct AppInfoView: View { .padding(.top, 12) } + private func appearanceChip(_ title: LocalizedStringKey, isSelected: Bool, action: @escaping () -> Void) -> some View { + Button(action: action) { + Text(title) + .bitchatFont(size: 13, weight: isSelected ? .semibold : .regular) + .foregroundColor(isSelected ? palette.accent : secondaryTextColor) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(isSelected ? palette.accent.opacity(0.15) : Color.clear) + ) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(isSelected ? .isSelected : []) + } + @ViewBuilder private var paneContent: some View { switch selectedPane { @@ -333,27 +356,28 @@ struct AppInfoView: View { @ViewBuilder private var settingsContent: some View { VStack(alignment: .leading, spacing: 24) { - // Appearance — single row: label left, theme chips right - HStack(spacing: 12) { - SectionHeader(Strings.appearanceTitle) - Spacer() - ForEach(AppTheme.allCases) { theme in - Button { - appThemeRawValue = theme.rawValue - } label: { - Text(theme.displayNameKey) - .bitchatFont(size: 13, weight: selectedTheme == theme ? .semibold : .regular) - .foregroundColor(selectedTheme == theme ? palette.accent : secondaryTextColor) - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background( - RoundedRectangle(cornerRadius: 8, style: .continuous) - .fill(selectedTheme == theme ? palette.accent.opacity(0.15) : Color.clear) - ) - .contentShape(Rectangle()) + // Appearance — label left, chips right: the theme, then the + // chat layout (independent of the theme). + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 12) { + SectionHeader(Strings.appearanceTitle) + Spacer() + ForEach(AppTheme.allCases) { theme in + appearanceChip(theme.displayNameKey, isSelected: selectedTheme == theme) { + appThemeRawValue = theme.rawValue + } + } + } + HStack(spacing: 12) { + Text(Strings.chatStyleTitle) + .bitchatFont(size: 13) + .foregroundColor(secondaryTextColor) + Spacer() + ForEach(ChatStyle.allCases) { style in + appearanceChip(style.displayNameKey, isSelected: selectedChatStyle == style) { + chatStyleRawValue = style.rawValue + } } - .buttonStyle(.plain) - .accessibilityAddTraits(selectedTheme == theme ? .isSelected : []) } } diff --git a/bitchat/Views/Components/MessageBubble.swift b/bitchat/Views/Components/MessageBubble.swift new file mode 100644 index 00000000..54f13665 --- /dev/null +++ b/bitchat/Views/Components/MessageBubble.swift @@ -0,0 +1,247 @@ +// +// MessageBubble.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import SwiftUI +import BitFoundation + +/// Geometry and tint of the bubble layout (`ChatStyle.bubbles`), matching the +/// Android client's `ChatVisualTokens`. +enum MessageBubbleMetrics { + /// Corner radius of the three "free" corners. + static let cornerRadius: CGFloat = 16 + /// Tightened corner on the speaker's side, giving the bubble a subtle tail. + static let tailRadius: CGFloat = 4 + static let horizontalPadding: CGFloat = 12 + static let verticalPadding: CGFloat = 8 + /// A bubble never grows past this fraction of the row, so long lines + /// still wrap well clear of the opposite edge. + static let maxWidthFraction: CGFloat = 0.8 + /// Author-color wash inside the bubble; light enough to keep body text + /// legible on both the dark and light backgrounds. + static let fillOpacity: Double = 0.18 + /// Author-color hairline, stronger than the fill so the shape reads. + static let borderOpacity: Double = 0.38 + /// Space above a bubble that follows one from the same author, and above + /// one where the author changes. The outline is drawn inside the bubble, + /// so these are the gaps as seen. + static let runSpacing: CGFloat = 2 + static let newRunSpacing: CGFloat = 8 + static let metaFontSize: CGFloat = 10 + + /// Bubble timestamps drop the seconds the IRC rows show: they add noise + /// without helping anyone scan a conversation. + static func timestamp(for date: Date) -> String { + timestampFormatter.string(from: date) + } + + private static let timestampFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter + }() +} + +/// Rounded bubble outline whose bottom corner on the speaker's side is +/// tightened into a tail. Written out rather than `UnevenRoundedRectangle`, +/// which needs iOS 17 / macOS 14. Insettable so its outline can be stroked +/// inside the bubble's bounds rather than straddling them. +struct MessageBubbleShape: InsettableShape { + let isOwn: Bool + var insetAmount: CGFloat = 0 + + func inset(by amount: CGFloat) -> MessageBubbleShape { + var shape = self + shape.insetAmount += amount + return shape + } + + func path(in bounds: CGRect) -> Path { + let rect = bounds.insetBy(dx: insetAmount, dy: insetAmount) + let corner = max(0, min(MessageBubbleMetrics.cornerRadius - insetAmount, rect.width / 2, rect.height / 2)) + let tail = max(0, min(MessageBubbleMetrics.tailRadius - insetAmount, corner)) + let bottomLeft = isOwn ? corner : tail + let bottomRight = isOwn ? tail : corner + + var path = Path() + path.move(to: CGPoint(x: rect.minX + corner, y: rect.minY)) + path.addLine(to: CGPoint(x: rect.maxX - corner, y: rect.minY)) + path.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.minY), tangent2End: CGPoint(x: rect.maxX, y: rect.minY + corner), radius: corner) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - bottomRight)) + path.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.maxY), tangent2End: CGPoint(x: rect.maxX - bottomRight, y: rect.maxY), radius: bottomRight) + path.addLine(to: CGPoint(x: rect.minX + bottomLeft, y: rect.maxY)) + path.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.maxY), tangent2End: CGPoint(x: rect.minX, y: rect.maxY - bottomLeft), radius: bottomLeft) + path.addLine(to: CGPoint(x: rect.minX, y: rect.minY + corner)) + path.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.minY), tangent2End: CGPoint(x: rect.minX + corner, y: rect.minY), radius: corner) + path.closeSubpath() + return path + } +} + +/// Places one bubble row: offers the bubble at most `maxWidthFraction` of +/// the row and pins it to the trailing edge (own) or leading edge (everyone +/// else). A layout rather than a GeometryReader, so rows keep their natural +/// height and cost nothing extra to measure. +struct MessageBubbleRowLayout: Layout { + let isOwn: Bool + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard let bubble = subviews.first else { return .zero } + let size = bubble.sizeThatFits(bubbleProposal(for: proposal.width)) + return CGSize(width: proposal.width ?? size.width, height: size.height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard let bubble = subviews.first else { return } + let bubbleProposal = bubbleProposal(for: bounds.width) + let size = bubble.sizeThatFits(bubbleProposal) + let x = isOwn ? bounds.maxX - size.width : bounds.minX + bubble.place(at: CGPoint(x: x, y: bounds.minY), proposal: ProposedViewSize(width: size.width, height: size.height)) + } + + private func bubbleProposal(for width: CGFloat?) -> ProposedViewSize { + ProposedViewSize(width: width.map { $0 * MessageBubbleMetrics.maxWidthFraction }, height: nil) + } +} + +extension View { + /// Fills and outlines the receiver as a message bubble washed with `tint`. + func messageBubbleChrome(tint: Color, isOwn: Bool) -> some View { + let shape = MessageBubbleShape(isOwn: isOwn) + return self + .padding(.horizontal, MessageBubbleMetrics.horizontalPadding) + .padding(.vertical, MessageBubbleMetrics.verticalPadding) + .background(shape.fill(tint.opacity(MessageBubbleMetrics.fillOpacity))) + .overlay(shape.strokeBorder(tint.opacity(MessageBubbleMetrics.borderOpacity), lineWidth: 1)) + } +} + +extension View { + /// A bubble row lifts into its context menu as a rounded card, not as a + /// sharp-cornered rectangle. (Context menu previews are iOS-only.) + @ViewBuilder + func bubbleContextMenuPreviewShape(isBubble: Bool) -> some View { + #if os(iOS) + contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: isBubble ? MessageBubbleMetrics.cornerRadius : 0, style: .continuous)) + #else + self + #endif + } +} + +/// The cluster in a bubble's bottom-trailing corner: an optional bridge +/// glyph, the time, and (own private messages) the tappable delivery status. +/// +/// Text bubbles ride it on the body's last line when that line has room and +/// drop it onto a line of its own when not. They reserve its exact width +/// with `placeholder`, appended to the body text, and overlay the cluster on +/// top: every slot has a fixed width, so the two always agree. +struct MessageBubbleMeta: View { + @Environment(\.appTheme) private var theme + + let time: String + let isBridged: Bool + /// Delivery status to show; nil for rows that show none. + let status: DeliveryStatus? + /// The body text ends in this cluster's `placeholder`, which already + /// reads the time to VoiceOver. Only then is the visible time hidden + /// from it; media bubbles and collapsed long messages have no + /// placeholder, and their time must stay readable here. + var timeIsSpokenByBody = false + let onStatusTap: () -> Void + + private static let spacing: CGFloat = 3 + private static let bridgeSlotWidth: CGFloat = 10 + + var body: some View { + HStack(spacing: Self.spacing) { + if isBridged { + Image(systemName: "network") + .font(.bitchatSystem(size: 8)) + .foregroundColor(Color.cyan.opacity(0.75)) + .frame(width: Self.bridgeSlotWidth) + .accessibilityLabel( + String(localized: "content.accessibility.bridged_message", defaultValue: "Arrived across a mesh bridge", comment: "Accessibility label for the glyph marking a message that arrived across a mesh bridge") + ) + } + Text(verbatim: time) + .font(.bitchatSystem(size: MessageBubbleMetrics.metaFontSize, design: theme.bodyFontDesign)) + // Neutral grey like the IRC timestamps: the bubble's tint + // already says whose it is. + .foregroundColor(Color.gray.opacity(0.8)) + .lineLimit(1) + .accessibilityHidden(timeIsSpokenByBody) + if let status { + Button(action: onStatusTap) { + DeliveryStatusView(status: status) + .frame(width: Self.statusSlotWidth(for: status), alignment: .trailing) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityHint( + String(localized: "content.accessibility.delivery_detail_hint", comment: "Accessibility hint for the delivery status glyph explaining a tap reveals details") + ) + } + } + .fixedSize() + } + + /// Clear run appended to a body text that reserves the cluster's width + /// at the end of its last line: a gap, the time itself (VoiceOver reads + /// it there), and kerned spaces standing in for the glyph slots. Only the + /// leading space can break, so the run wraps as one piece. + static func placeholder(time: String, isBridged: Bool, status: DeliveryStatus?, design: Font.Design) -> Text { + var slots: CGFloat = 0 + if isBridged { slots += bridgeSlotWidth + spacing } + if let status { slots += spacing + statusSlotWidth(for: status) } + let timeRun = Text(verbatim: " \u{00A0}" + time) + .font(.bitchatSystem(size: MessageBubbleMetrics.metaFontSize, design: design)) + .foregroundColor(.clear) + guard slots > 0 else { return timeRun } + return timeRun + Text(verbatim: "\u{00A0}") + .font(.bitchatSystem(size: MessageBubbleMetrics.metaFontSize, design: design)) + .kerning(slots) + .foregroundColor(.clear) + } + + /// Fixed width of the status glyph, wide enough for the widest glyph of + /// that status (`DeliveryStatusView`). + private static func statusSlotWidth(for status: DeliveryStatus) -> CGFloat { + switch status { + case .delivered: return 18 + case .read: return 22 + case .partiallyDelivered(let reached, let total): + return 14 + CGFloat("\(reached)/\(total)".count) * 7 + case .notSentYet, .sending, .sent, .carried, .failed: + return 12 + } + } +} + +/// Caption under an own private bubble: the failure reason (always shown) or +/// the tapped-open status detail. +struct MessageBubbleDeliveryCaption: View { + @ThemedPalette private var palette + let status: DeliveryStatus + let showsDetail: Bool + + var body: some View { + if case .failed = status { + caption.foregroundColor(Color.red.opacity(0.9)) + } else if showsDetail { + caption.foregroundColor(palette.secondary) + } + } + + private var caption: some View { + Text(verbatim: status.bitchatDescription) + .bitchatFont(size: 11) + .fixedSize(horizontal: false, vertical: true) + .multilineTextAlignment(.trailing) + .padding(.horizontal, 4) + } +} diff --git a/bitchat/Views/Components/TextMessageView.swift b/bitchat/Views/Components/TextMessageView.swift index c7f3ee36..67398cb3 100644 --- a/bitchat/Views/Components/TextMessageView.swift +++ b/bitchat/Views/Components/TextMessageView.swift @@ -13,9 +13,13 @@ struct TextMessageView: View { @Environment(\.colorScheme) private var colorScheme: ColorScheme @Environment(\.appTheme) private var theme @ThemedPalette private var palette + @Environment(\.chatStyle) private var chatStyle @EnvironmentObject private var conversationUIModel: ConversationUIModel let message: BitchatMessage + /// Whether this row starts its author's run of messages; the bubble + /// layout names the sender only on the first bubble of a run. + let startsRun: Bool /// Value snapshot of the message's mutable delivery status, captured at /// construction. `BitchatMessage` is a reference type mutated in place by /// `ConversationStore`, and SwiftUI compares reference-typed view fields @@ -27,12 +31,34 @@ struct TextMessageView: View { @State private var expandedMessageIDs: Set = [] @State private var showDeliveryDetail = false - init(message: BitchatMessage) { + init(message: BitchatMessage, startsRun: Bool = true) { self.message = message + self.startsRun = startsRun self.deliveryStatus = message.deliveryStatus } var body: some View { + Group { + if chatStyle.usesBubbles { + bubbleBody + } else { + ircBody + } + } + // Collapse the revealed caption when the status advances (e.g. + // sending → sent → delivered) so a detail opened for one state + // doesn't linger and silently morph into another. Guarded write: + // under a message storm many rows change status within one frame, + // and an unconditional state write per change trips SwiftUI's + // "tried to update multiple times per frame" re-entrancy warning. + .onChange(of: deliveryStatus) { _ in + if showDeliveryDetail { + showDeliveryDetail = false + } + } + } + + private var ircBody: some View { VStack(alignment: .leading, spacing: 0) { // Heavy token scans run once per message, not once per render let scan = message.contentScan @@ -111,40 +137,112 @@ struct TextMessageView: View { // Expand/Collapse for very long messages if scan.isLongForDisplay { - let isExpanded = expandedMessageIDs.contains(message.id) - let labelKey = isExpanded ? LocalizedStringKey("content.message.show_less") : LocalizedStringKey("content.message.show_more") - Button(labelKey) { - if isExpanded { expandedMessageIDs.remove(message.id) } - else { expandedMessageIDs.insert(message.id) } - } - .bitchatFont(size: 11, weight: .medium) - .foregroundColor(palette.accentBlue) - .padding(.top, 4) + expandToggle + .padding(.top, 4) } // Render payment chips (Lightning / Cashu) with rounded background if !scan.lightningLinks.isEmpty || !scan.cashuLinks.isEmpty { - HStack(spacing: 8) { - ForEach(scan.lightningLinks, id: \.self) { link in - PaymentChipView(paymentType: .lightning(link)) - } - ForEach(scan.cashuLinks, id: \.self) { link in - PaymentChipView(paymentType: .cashu(link)) - } - } - .padding(.top, 6) - .padding(.leading, 2) + paymentChips(for: scan) + .padding(.top, 6) + .padding(.leading, 2) } } - // Collapse the revealed caption when the status advances (e.g. - // sending → sent → delivered) so a detail opened for one state - // doesn't linger and silently morph into another. Guarded write: - // under a message storm many rows change status within one frame, - // and an unconditional state write per change trips SwiftUI's - // "tried to update multiple times per frame" re-entrancy warning. - .onChange(of: deliveryStatus) { _ in - if showDeliveryDetail { - showDeliveryDetail = false + } + + /// Messenger layout: the content in a bubble washed with the author's + /// color, the sender named on the first bubble of their run (never on my + /// own), and the time plus delivery status in the bottom-trailing corner. + private var bubbleBody: some View { + let scan = message.contentScan + let isOwn = conversationUIModel.isSentByCurrentUser(message) + let isCollapsed = scan.isLongForDisplay && !expandedMessageIDs.contains(message.id) + let status: DeliveryStatus? = message.isPrivate && isOwn && deliveryStatus != .notSentYet ? deliveryStatus : nil + let time = MessageBubbleMetrics.timestamp(for: message.timestamp) + // Only the inline cluster sits beside a placeholder that reads the + // time; the one under a collapsed message must read it itself. + func meta(timeIsSpokenByBody: Bool) -> MessageBubbleMeta { + MessageBubbleMeta(time: time, isBridged: message.isBridged, status: status, timeIsSpokenByBody: timeIsSpokenByBody) { + showDeliveryDetail.toggle() + } + } + + return VStack(alignment: isOwn ? .trailing : .leading, spacing: 3) { + VStack(alignment: .leading, spacing: 2) { + if startsRun && !isOwn { + bubbleSenderLine + } + + let bodyText = Text(conversationUIModel.formatBubbleBody(message, colorScheme: colorScheme, theme: theme)) + // A collapsed long message hangs its meta off the toggle row + // instead: the truncated last line has no room to reserve. + (isCollapsed + ? bodyText + : bodyText + MessageBubbleMeta.placeholder(time: time, isBridged: message.isBridged, status: status, design: theme.bodyFontDesign)) + .fixedSize(horizontal: false, vertical: true) + .lineLimit(isCollapsed ? TransportConfig.uiLongMessageLineLimit : nil) + .overlay(alignment: Alignment(horizontal: .trailing, vertical: .lastTextBaseline)) { + if !isCollapsed { + meta(timeIsSpokenByBody: true) + } + } + + if scan.isLongForDisplay { + HStack(alignment: .firstTextBaseline, spacing: 12) { + expandToggle + if isCollapsed { + meta(timeIsSpokenByBody: false) + } + } + .padding(.top, 2) + } + + if !scan.lightningLinks.isEmpty || !scan.cashuLinks.isEmpty { + paymentChips(for: scan) + .padding(.top, 4) + } + } + .messageBubbleChrome(tint: conversationUIModel.bubbleTint(for: message, colorScheme: colorScheme), isOwn: isOwn) + + if let status { + MessageBubbleDeliveryCaption(status: status, showsDetail: showDeliveryDetail) + } + } + } + + private var bubbleSenderLine: some View { + HStack(alignment: .firstTextBaseline, spacing: 4) { + Text(conversationUIModel.formatBubbleSender(message, colorScheme: colorScheme, theme: theme)) + .lineLimit(1) + if conversationUIModel.showsVerifiedSeal(for: message) { + Image(systemName: "checkmark.seal.fill") + .font(.bitchatSystem(size: 9)) + .foregroundColor(Color.green.opacity(0.85)) + .accessibilityLabel( + String(localized: "content.accessibility.verified_sender", defaultValue: "Verified sender", comment: "Accessibility label for the seal next to a verified peer's name on a private message") + ) + } + } + } + + private var expandToggle: some View { + let isExpanded = expandedMessageIDs.contains(message.id) + let labelKey = isExpanded ? LocalizedStringKey("content.message.show_less") : LocalizedStringKey("content.message.show_more") + return Button(labelKey) { + if isExpanded { expandedMessageIDs.remove(message.id) } + else { expandedMessageIDs.insert(message.id) } + } + .bitchatFont(size: 11, weight: .medium) + .foregroundColor(palette.accentBlue) + } + + private func paymentChips(for scan: BitchatMessage.ContentScan) -> some View { + HStack(spacing: 8) { + ForEach(scan.lightningLinks, id: \.self) { link in + PaymentChipView(paymentType: .lightning(link)) + } + ForEach(scan.cashuLinks, id: \.self) { link in + PaymentChipView(paymentType: .cashu(link)) } } } diff --git a/bitchat/Views/Media/MediaMessageView.swift b/bitchat/Views/Media/MediaMessageView.swift index 29711f38..11ce7b5a 100644 --- a/bitchat/Views/Media/MediaMessageView.swift +++ b/bitchat/Views/Media/MediaMessageView.swift @@ -11,10 +11,13 @@ import BitFoundation struct MediaMessageView: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.appTheme) private var theme + @Environment(\.chatStyle) private var chatStyle @ThemedPalette private var palette @EnvironmentObject private var conversationUIModel: ConversationUIModel let message: BitchatMessage let media: BitchatMessage.Media + /// Whether this row starts its author's run (see `TextMessageView`). + let startsRun: Bool /// Value snapshot of the message's mutable delivery status, captured at /// construction (see `TextMessageView.deliveryStatus`): `BitchatMessage` /// is a reference type mutated in place, and SwiftUI compares reference @@ -25,22 +28,42 @@ struct MediaMessageView: View { @Binding var imagePreviewURL: URL? - init(message: BitchatMessage, media: BitchatMessage.Media, imagePreviewURL: Binding) { + init(message: BitchatMessage, media: BitchatMessage.Media, startsRun: Bool = true, imagePreviewURL: Binding) { self.message = message self.media = media + self.startsRun = startsRun self.deliveryStatus = message.deliveryStatus self._imagePreviewURL = imagePreviewURL } var body: some View { + Group { + if chatStyle.usesBubbles { + bubbleBody + } else { + ircBody + } + } + // Collapse the revealed caption when the status advances (e.g. + // sending → sent → delivered) so a detail opened for one state + // doesn't linger and silently morph into another. Guarded write: + // under a message storm many rows change status within one frame, + // and an unconditional state write per change trips SwiftUI's + // "tried to update multiple times per frame" re-entrancy warning. + .onChange(of: deliveryStatus) { _ in + if showDeliveryDetail { + showDeliveryDetail = false + } + } + } + + private var ircBody: some View { let isFromMe = conversationUIModel.isMediaMessageFromCurrentUser(message) - let state = mediaSendState(for: deliveryStatus, isFromMe: isFromMe) - let cancelAction: (() -> Void)? = state.canCancel ? { conversationUIModel.cancelMediaSend(messageID: message.id) } : nil // Baseline alignment (via the header text inside the VStack) keeps the // lock on the header line; a fixed top padding left its solid body // hanging below the line's visual center. - HStack(alignment: .firstTextBaseline, spacing: 0) { + return HStack(alignment: .firstTextBaseline, spacing: 0) { if message.isPrivate { Image(systemName: "lock.fill") .font(.bitchatSystem(size: 8)) @@ -98,46 +121,99 @@ struct MediaMessageView: View { } } - Group { - switch media { - case .voice(let url): - VoiceNoteView( - url: url, - isSending: state.isSending, - sendProgress: state.progress, - isLive: conversationUIModel.isLiveVoiceMessage(message), - onCancel: cancelAction - ) - case .image(let url): - BlockRevealImageView( - url: url, - revealProgress: state.progress, - isSending: state.isSending, - onCancel: cancelAction, - initiallyBlurred: !isFromMe, - onOpen: { - if !state.isSending { - imagePreviewURL = url - } - }, - onDelete: !isFromMe ? { conversationUIModel.deleteMediaMessage(messageID: message.id) } : nil - ) - .frame(maxWidth: 280) - } - } + mediaContent(isFromMe: isFromMe, showsVoiceCard: true) } } .padding(.vertical, 4) - // Collapse the revealed caption when the status advances (e.g. - // sending → sent → delivered) so a detail opened for one state - // doesn't linger and silently morph into another. Guarded write: - // under a message storm many rows change status within one frame, - // and an unconditional state write per change trips SwiftUI's - // "tried to update multiple times per frame" re-entrancy warning. - .onChange(of: deliveryStatus) { _ in - if showDeliveryDetail { - showDeliveryDetail = false + } + + /// Messenger layout, the same shell as a text bubble: sender on the + /// first bubble of a run, the media, then the time and delivery status + /// flush with the bubble's trailing edge. + private var bubbleBody: some View { + let isFromMe = conversationUIModel.isMediaMessageFromCurrentUser(message) + let isOwn = conversationUIModel.isSentByCurrentUser(message) + let status: DeliveryStatus? = message.isPrivate && isOwn && deliveryStatus != .notSentYet ? deliveryStatus : nil + + return VStack(alignment: isOwn ? .trailing : .leading, spacing: 3) { + // A one-column grid hugs its widest cell and still lets each + // cell pick its own edge; a VStack would need a flexible frame + // to push the meta right, stretching every bubble to full width. + Grid(alignment: .leading, verticalSpacing: 6) { + if startsRun && !isOwn { + GridRow { + bubbleSenderLine + } + } + GridRow { + mediaContent(isFromMe: isFromMe, showsVoiceCard: false) + } + GridRow { + MessageBubbleMeta( + time: MessageBubbleMetrics.timestamp(for: message.timestamp), + isBridged: message.isBridged, + status: status + ) { + showDeliveryDetail.toggle() + } + .gridCellAnchor(.trailing) + } } + .messageBubbleChrome(tint: conversationUIModel.bubbleTint(for: message, colorScheme: colorScheme), isOwn: isOwn) + + if let status { + MessageBubbleDeliveryCaption(status: status, showsDetail: showDeliveryDetail) + } + } + } + + private var bubbleSenderLine: some View { + HStack(alignment: .firstTextBaseline, spacing: 4) { + Text(conversationUIModel.formatBubbleSender(message, colorScheme: colorScheme, theme: theme)) + .lineLimit(1) + if conversationUIModel.showsVerifiedSeal(for: message) { + Image(systemName: "checkmark.seal.fill") + .font(.bitchatSystem(size: 9)) + .foregroundColor(Color.green.opacity(0.85)) + .accessibilityLabel( + String(localized: "content.accessibility.verified_sender", defaultValue: "Verified sender", comment: "Accessibility label for the seal next to a verified peer's name on a private message") + ) + } + } + } + + /// The voice note or image itself. Inside a bubble the voice note drops + /// its own card: the bubble already frames it. + @ViewBuilder + private func mediaContent(isFromMe: Bool, showsVoiceCard: Bool) -> some View { + let state = mediaSendState(for: deliveryStatus, isFromMe: isFromMe) + let cancelAction: (() -> Void)? = state.canCancel ? { conversationUIModel.cancelMediaSend(messageID: message.id) } : nil + switch media { + case .voice(let url): + VoiceNoteView( + url: url, + isSending: state.isSending, + sendProgress: state.progress, + isLive: conversationUIModel.isLiveVoiceMessage(message), + showsCard: showsVoiceCard, + onCancel: cancelAction + ) + .frame(maxWidth: showsVoiceCard ? nil : 260) + case .image(let url): + BlockRevealImageView( + url: url, + revealProgress: state.progress, + isSending: state.isSending, + onCancel: cancelAction, + initiallyBlurred: !isFromMe, + onOpen: { + if !state.isSending { + imagePreviewURL = url + } + }, + onDelete: !isFromMe ? { conversationUIModel.deleteMediaMessage(messageID: message.id) } : nil + ) + .frame(maxWidth: 280) } } diff --git a/bitchat/Views/Media/VoiceNoteView.swift b/bitchat/Views/Media/VoiceNoteView.swift index 661d2193..f19edd99 100644 --- a/bitchat/Views/Media/VoiceNoteView.swift +++ b/bitchat/Views/Media/VoiceNoteView.swift @@ -6,6 +6,9 @@ struct VoiceNoteView: View { private let isSending: Bool private let sendProgress: Double? private let isLive: Bool + /// Draws the rounded card behind the player. Off inside a message + /// bubble, which already frames it. + private let showsCard: Bool private let onCancel: (() -> Void)? @Environment(\.colorScheme) private var colorScheme @@ -13,11 +16,12 @@ struct VoiceNoteView: View { @StateObject private var playback: VoiceNotePlaybackController @State private var waveform: [Float] = [] - init(url: URL, isSending: Bool, sendProgress: Double?, isLive: Bool = false, onCancel: (() -> Void)?) { + init(url: URL, isSending: Bool, sendProgress: Double?, isLive: Bool = false, showsCard: Bool = true, onCancel: (() -> Void)?) { self.url = url self.isSending = isSending self.sendProgress = sendProgress self.isLive = isLive + self.showsCard = showsCard self.onCancel = onCancel _playback = StateObject(wrappedValue: VoiceNotePlaybackController(url: url)) } @@ -93,15 +97,15 @@ struct VoiceNoteView: View { ) } } - .padding(12) + .padding(showsCard ? 12 : 0) .background( RoundedRectangle(cornerRadius: 14) - .fill(backgroundColor) - .shadow(color: Color.black.opacity(colorScheme == .dark ? 0.3 : 0.1), radius: 6, x: 0, y: 2) + .fill(showsCard ? backgroundColor : .clear) + .shadow(color: Color.black.opacity(showsCard ? (colorScheme == .dark ? 0.3 : 0.1) : 0), radius: 6, x: 0, y: 2) ) .overlay( RoundedRectangle(cornerRadius: 14) - .stroke(borderColor, lineWidth: 1) + .stroke(showsCard ? borderColor : .clear, lineWidth: 1) ) .task { // Defer loading to let UI settle after view appears diff --git a/bitchat/Views/MessageBubbleGrouping.swift b/bitchat/Views/MessageBubbleGrouping.swift new file mode 100644 index 00000000..975562e7 --- /dev/null +++ b/bitchat/Views/MessageBubbleGrouping.swift @@ -0,0 +1,53 @@ +// +// MessageBubbleGrouping.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import Foundation + +/// Runs of consecutive messages from one author, for the bubble layout: only +/// the first bubble of a run names its sender, and bubbles inside a run sit +/// closer together than bubbles between runs, so the eye registers a name +/// only when the speaker actually changes. Mirrors the Android client's +/// `MessageGrouping`. +enum MessageBubbleGrouping { + /// Messages further apart than this start a new run even from the same + /// sender: a reply an hour later is a new thought, not a continuation. + static let window: TimeInterval = 5 * 60 + + /// Whether `current` continues the run of `previous`, its chronological + /// predecessor in the rendered timeline, and so goes without a name. + static func continuesRun(_ current: BitchatMessage, after previous: BitchatMessage?) -> Bool { + guard let previous, hasSameAuthor(current, as: previous) else { return false } + let elapsed = current.timestamp.timeIntervalSince(previous.timestamp) + return elapsed >= 0 && elapsed <= window + } + + /// Whether `current` comes from the same author as `previous`, however + /// long after. This sets the spacing: consecutive bubbles from one + /// author always sit at the tight run spacing, while a pause only brings + /// back the name. Spacing by the time window too gave my own bubbles, + /// which never show a name, gaps that changed for no visible reason. + static func hasSameAuthor(_ current: BitchatMessage, as previous: BitchatMessage?) -> Bool { + guard let previous else { return false } + // System lines are narration: folding a real message into one would + // attribute it to "system". + if previous.sender == "system" || current.sender == "system" { return false } + if previous.isPrivate != current.isPrivate { return false } + return isSameSender(previous, current) + } + + /// Sender IDs are authoritative when both rows carry one, since two peers + /// can share a nickname; the display name (with its `#abcd` suffix) is the + /// fallback for rows without one. + private static func isSameSender(_ lhs: BitchatMessage, _ rhs: BitchatMessage) -> Bool { + if let lhsID = lhs.senderPeerID, let rhsID = rhs.senderPeerID { + return lhsID == rhsID + } + return lhs.sender == rhs.sender + } +} diff --git a/bitchat/Views/MessageListView.swift b/bitchat/Views/MessageListView.swift index 58722957..b8945755 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -12,6 +12,19 @@ import SwiftUI private struct MessageDisplayItem: Identifiable { let id: String let message: BitchatMessage + /// First row of its author's run (`MessageBubbleGrouping`): names its + /// sender. + let startsRun: Bool + /// Follows a row from the same author, however long before: sits at + /// the tight run spacing. + let followsSameAuthor: Bool + /// Rendered as a bubble, and if so, which edge it hugs. + let bubble: BubblePlacement? + + enum BubblePlacement { + case own + case other + } } /// What the list's change detection keys on. The count alone stops moving @@ -53,6 +66,7 @@ struct MessageListView: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.appTheme) private var theme + @Environment(\.chatStyle) private var chatStyle let privatePeer: PeerID? @Binding var isAtBottom: Bool @@ -114,10 +128,7 @@ struct MessageListView: View { ) let windowedMessages = Array(messages.suffix(renderedWindowCount)) - let messageItems: [MessageDisplayItem] = windowedMessages.compactMap { message in - guard !message.content.trimmed.isEmpty else { return nil } - return MessageDisplayItem(id: "\(contextKey)|\(message.id)", message: message) - } + let messageItems = displayItems(for: windowedMessages, contextKey: contextKey) // Top edge of the rendered window (whitespace-only messages get no // row, so they could never report reaching it). let firstRowID = messageItems.first?.id @@ -139,7 +150,7 @@ struct MessageListView: View { LazyVStack(alignment: .leading, spacing: 0) { ForEach(messageItems) { item in let message = item.message - messageRow(for: message) + messageRow(for: item) .onAppear { // Callbacks lag a timeline switch: the new // rows appear before the old ones disappear, @@ -183,6 +194,7 @@ struct MessageListView: View { } } .contentShape(Rectangle()) + .bubbleContextMenuPreviewShape(isBubble: item.bubble != nil) .contextMenu { let showsUserActions = message.sender != "system" && !conversationUIModel.isSentByCurrentUser(message) if showsUserActions { @@ -229,8 +241,12 @@ struct MessageListView: View { } } } + // Placed after the context menu so the menu lifts + // only the bubble, not the empty side of the row. + .modifier(BubbleRowPlacement(placement: item.bubble)) .padding(.horizontal, 12) - .padding(.vertical, 1) + .padding(.top, rowTopPadding(for: item)) + .padding(.bottom, item.bubble == nil ? 1 : 0) // Archived echoes read as one tinted block, not // just faded rows. .background(message.isArchivedEcho ? palette.secondary.opacity(0.08) : Color.clear) @@ -596,15 +612,48 @@ private extension MessageListView { return "\(base), \(count)" } + /// Rows for the rendered window (whitespace-only messages get none), + /// each knowing whether it starts its author's run and, in the bubble + /// layout, which edge its bubble hugs. + private func displayItems(for messages: [BitchatMessage], contextKey: String) -> [MessageDisplayItem] { + let usesBubbles = chatStyle.usesBubbles + var items: [MessageDisplayItem] = [] + items.reserveCapacity(messages.count) + var previous: BitchatMessage? + for message in messages where !message.content.trimmed.isEmpty { + var bubble: MessageDisplayItem.BubblePlacement? + if usesBubbles, message.sender != "system" { + bubble = conversationUIModel.isSentByCurrentUser(message) ? .own : .other + } + items.append(MessageDisplayItem( + id: "\(contextKey)|\(message.id)", + message: message, + startsRun: !MessageBubbleGrouping.continuesRun(message, after: previous), + followsSameAuthor: MessageBubbleGrouping.hasSameAuthor(message, as: previous), + bubble: bubble + )) + previous = message + } + return items + } + + /// Consecutive bubbles from one author sit close together and a change + /// of author opens a wider gap; every IRC row keeps the original rhythm. + private func rowTopPadding(for item: MessageDisplayItem) -> CGFloat { + guard item.bubble != nil else { return 1 } + return item.followsSameAuthor ? MessageBubbleMetrics.runSpacing : MessageBubbleMetrics.newRunSpacing + } + @ViewBuilder - func messageRow(for message: BitchatMessage) -> some View { + func messageRow(for item: MessageDisplayItem) -> some View { + let message = item.message Group { if message.sender == "system" { systemMessageRow(message) } else if let media = conversationUIModel.mediaAttachment(for: message) { - MediaMessageView(message: message, media: media, imagePreviewURL: $imagePreviewURL) + MediaMessageView(message: message, media: media, startsRun: item.startsRun, imagePreviewURL: $imagePreviewURL) } else { - TextMessageView(message: message) + TextMessageView(message: message, startsRun: item.startsRun) } } // Archived echoes ("heard here earlier") render dimmed: real history, @@ -836,6 +885,22 @@ private extension MessageListView { } } +/// Pins a bubble row to its edge at no more than the bubble's maximum width; +/// IRC and system rows pass through untouched. +private struct BubbleRowPlacement: ViewModifier { + let placement: MessageDisplayItem.BubblePlacement? + + func body(content: Content) -> some View { + if let placement { + MessageBubbleRowLayout(isOwn: placement == .own) { + content + } + } else { + content + } + } +} + private extension ChannelID { var contextKey: String { switch self { diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 9306c606..d743337e 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -724,6 +724,69 @@ struct ChatViewModelFormattingTests { #expect(viewModel.formatMessageHeader(message, colorScheme: .dark, theme: .matrix) == header) #expect(viewModel.formatMessageAsText(message, colorScheme: .dark, theme: .matrix) == fullText) } + + @Test @MainActor + func formatBubbleBody_isTheContentAlone() async { + let (viewModel, _) = makeTestableViewModel() + let message = BitchatMessage( + id: "fmt-bubble-1", + sender: "Alice#a1b2", + content: "hello @bob #mesh", + timestamp: Date(), + isRelay: false, + senderPeerID: PeerID(str: "00000000000000b4") + ) + + // The bubble draws sender and time itself. + let body = viewModel.formatBubbleBody(message, colorScheme: .dark, theme: .matrix) + + #expect(String(body.characters) == "hello @bob #mesh") + } + + @Test @MainActor + func formatBubbleSender_setsTheSuffixOffWithAThinSpace() async { + let (viewModel, _) = makeTestableViewModel() + let message = BitchatMessage( + id: "fmt-bubble-2", + sender: "Alice#a1b2", + content: "hello", + timestamp: Date(), + isRelay: false, + senderPeerID: PeerID(str: "00000000000000b5") + ) + + let sender = viewModel.formatBubbleSender(message, colorScheme: .dark, theme: .matrix) + + #expect(String(sender.characters) == "@Alice\u{2009}#a1b2") + #expect(sender.runs.contains { $0.link?.absoluteString == "bitchat://user/00000000000000b5" }) + } + + @Test @MainActor + func bubbleFormats_areCachedApartFromTheIRCFormats() async { + let (viewModel, _) = makeTestableViewModel() + let message = BitchatMessage( + id: "fmt-bubble-3", + sender: "Alice#a1b2", + content: "hello", + timestamp: Date(), + isRelay: false, + senderPeerID: PeerID(str: "00000000000000b6") + ) + + // Switching styles must never serve one layout's cached text to the + // other: each lookup answers from its own entry. + let fullText = viewModel.formatMessageAsText(message, colorScheme: .dark, theme: .matrix) + let header = viewModel.formatMessageHeader(message, colorScheme: .dark, theme: .matrix) + let body = viewModel.formatBubbleBody(message, colorScheme: .dark, theme: .matrix) + let sender = viewModel.formatBubbleSender(message, colorScheme: .dark, theme: .matrix) + + #expect(String(body.characters) == "hello") + #expect(String(sender.characters) == "@Alice\u{2009}#a1b2") + #expect(viewModel.formatMessageAsText(message, colorScheme: .dark, theme: .matrix) == fullText) + #expect(viewModel.formatMessageHeader(message, colorScheme: .dark, theme: .matrix) == header) + #expect(viewModel.formatBubbleBody(message, colorScheme: .dark, theme: .matrix) == body) + #expect(viewModel.formatBubbleSender(message, colorScheme: .dark, theme: .matrix) == sender) + } } // MARK: - Verification Tests diff --git a/bitchatTests/MessageBubbleGroupingTests.swift b/bitchatTests/MessageBubbleGroupingTests.swift new file mode 100644 index 00000000..5aec057b --- /dev/null +++ b/bitchatTests/MessageBubbleGroupingTests.swift @@ -0,0 +1,102 @@ +// +// MessageBubbleGroupingTests.swift +// bitchatTests +// +// Which bubbles continue their author's run (and so drop the sender label): +// same sender by ID (falling back to the display name), same privacy, within +// the five-minute window, and never across a system line. +// + +import BitFoundation +import Foundation +import Testing +@testable import bitchat + +private let baseDate = Date(timeIntervalSince1970: 1_700_000_000) + +private func message( + _ id: String, + sender: String = "alice", + peerID: PeerID? = PeerID(str: "00000000000000a1"), + at seconds: TimeInterval = 0, + isPrivate: Bool = false +) -> BitchatMessage { + BitchatMessage( + id: id, + sender: sender, + content: "message \(id)", + timestamp: baseDate.addingTimeInterval(seconds), + isRelay: false, + isPrivate: isPrivate, + senderPeerID: peerID + ) +} + +struct MessageBubbleGroupingTests { + @Test func firstMessageStartsARun() { + #expect(!MessageBubbleGrouping.continuesRun(message("1"), after: nil)) + } + + @Test func sameSenderWithinTheWindowContinues() { + let previous = message("1") + #expect(MessageBubbleGrouping.continuesRun(message("2", at: 60), after: previous)) + #expect(MessageBubbleGrouping.continuesRun(message("3", at: MessageBubbleGrouping.window), after: previous)) + } + + @Test func aLongPauseStartsANewRun() { + let previous = message("1") + #expect(!MessageBubbleGrouping.continuesRun(message("2", at: MessageBubbleGrouping.window + 1), after: previous)) + } + + @Test func anOutOfOrderTimestampStartsANewRun() { + let previous = message("1", at: 60) + #expect(!MessageBubbleGrouping.continuesRun(message("2", at: 0), after: previous)) + } + + @Test func namesakesWithDifferentIDsAreDifferentSenders() { + let previous = message("1", sender: "anon", peerID: PeerID(str: "00000000000000a1")) + let current = message("2", sender: "anon", peerID: PeerID(str: "00000000000000b2"), at: 10) + #expect(!MessageBubbleGrouping.continuesRun(current, after: previous)) + } + + @Test func sameIDContinuesAcrossARename() { + let previous = message("1", sender: "alice") + let current = message("2", sender: "alice2", at: 10) + #expect(MessageBubbleGrouping.continuesRun(current, after: previous)) + } + + @Test func rowsWithoutIDsFallBackToTheDisplayName() { + let previous = message("1", sender: "alice#a1b2", peerID: nil) + #expect(MessageBubbleGrouping.continuesRun(message("2", sender: "alice#a1b2", peerID: nil, at: 10), after: previous)) + #expect(!MessageBubbleGrouping.continuesRun(message("3", sender: "alice#c3d4", peerID: nil, at: 10), after: previous)) + } + + @Test func systemLinesNeverJoinARun() { + let system = message("s", sender: "system", peerID: nil) + #expect(!MessageBubbleGrouping.continuesRun(message("1", at: 10), after: system)) + #expect(!MessageBubbleGrouping.continuesRun(message("s2", sender: "system", peerID: nil, at: 10), after: system)) + } + + @Test func thePrivateBoundaryStartsANewRun() { + let previous = message("1") + #expect(!MessageBubbleGrouping.continuesRun(message("2", at: 10, isPrivate: true), after: previous)) + } + + /// Spacing follows the author alone: a pause brings the name back but + /// must not widen the gap, or a run of my own (nameless) bubbles gets + /// gaps that change for no visible reason. + @Test func aLongPauseKeepsTheSameAuthor() { + let previous = message("1") + let later = message("2", at: MessageBubbleGrouping.window * 10) + #expect(MessageBubbleGrouping.hasSameAuthor(later, as: previous)) + #expect(!MessageBubbleGrouping.continuesRun(later, after: previous)) + } + + @Test func authorChangesWhereRunsAlwaysBreak() { + let previous = message("1") + #expect(!MessageBubbleGrouping.hasSameAuthor(message("2"), as: nil)) + #expect(!MessageBubbleGrouping.hasSameAuthor(message("3", peerID: PeerID(str: "00000000000000b2"), at: 10), as: previous)) + #expect(!MessageBubbleGrouping.hasSameAuthor(message("4", at: 10, isPrivate: true), as: previous)) + #expect(!MessageBubbleGrouping.hasSameAuthor(message("5", sender: "system", peerID: nil, at: 10), as: previous)) + } +}