From cc9fb502c2e2a747b5f35a58ea051a5460b37176 Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:36:56 -1000 Subject: [PATCH] perf(ui): eliminate SwiftUI invalidation storms during typing and peer updates (#1892) - Isolate composer draft text and autocomplete debounce task in ComposerDraftModel and split @mention autocomplete out of ConversationUIModel into ComposerAutocompleteModel so keystrokes only re-evaluate ContentComposerView instead of ContentView and all 300 message rows. - Inject non-observing AppEnvironmentModels so ContentView and sheet containers can forward models into sheets (#1558) and closures without subscribing to publicChatModel, privateInboxModel, peerListModel, verificationModel, or conversationUIModel. - Split MessageListView into PublicMessageListView and PrivateMessageListView hosts so public and DM timelines never invalidate each other. - Guard redundant publishes in PrivateConversationModel, PeerIdentityStore, AppChromeModel, LocationChannelsModel, and ConversationUIModel. - Cache mesh palette rebuilds in ChatMessageFormatter via meshPeerMembershipRevision and reuse viewModel.geohashIdentity(for:). --- bitchat/App/AppChromeModel.swift | 58 +- bitchat/App/AppEnvironmentModels.swift | 51 ++ bitchat/App/AppRuntime.swift | 20 + bitchat/App/ComposerDraftModel.swift | 172 ++++ bitchat/App/ConversationUIModel.swift | 63 +- bitchat/App/LocationChannelsModel.swift | 18 + bitchat/App/PeerIdentityStore.swift | 29 +- bitchat/App/PrivateConversationModels.swift | 10 +- bitchat/BitchatApp.swift | 11 +- bitchat/ViewModels/ChatMessageFormatter.swift | 35 +- bitchat/ViewModels/ChatViewModel.swift | 14 +- bitchat/Views/ContentComposerView.swift | 46 +- bitchat/Views/ContentSheetViews.swift | 44 +- bitchat/Views/ContentView.swift | 219 ++--- bitchat/Views/MessageListView.swift | 832 +++++++++--------- bitchatTests/AppArchitectureTests.swift | 119 ++- bitchatTests/ViewSmokeTests.swift | 51 +- 17 files changed, 1095 insertions(+), 697 deletions(-) create mode 100644 bitchat/App/AppEnvironmentModels.swift create mode 100644 bitchat/App/ComposerDraftModel.swift diff --git a/bitchat/App/AppChromeModel.swift b/bitchat/App/AppChromeModel.swift index e37615b1..598a9af0 100644 --- a/bitchat/App/AppChromeModel.swift +++ b/bitchat/App/AppChromeModel.swift @@ -46,6 +46,12 @@ final class AppChromeModel: ObservableObject { self.chatViewModel = chatViewModel self.onPanicWipe = onPanicWipe self.nickname = chatViewModel.nickname + self.hasUnreadPrivateMessages = !privateInboxModel.unreadPeerIDs.isEmpty + self.showBluetoothAlert = chatViewModel.showBluetoothAlert + self.bluetoothAlertMessage = chatViewModel.bluetoothAlertMessage + self.bluetoothState = chatViewModel.bluetoothState + self.torBlocked = chatViewModel.torBlocked + self.panicWipeBlocked = chatViewModel.panicRecoveryBlocked bind(privateInboxModel: privateInboxModel) } @@ -151,13 +157,19 @@ final class AppChromeModel: ObservableObject { private func bind(privateInboxModel: PrivateInboxModel) { privateInboxModel.$unreadPeerIDs + .map { !$0.isEmpty } + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .sink { [weak self] unreadPeerIDs in - self?.hasUnreadPrivateMessages = !unreadPeerIDs.isEmpty + .sink { [weak self] hasUnread in + guard let self, self.hasUnreadPrivateMessages != hasUnread else { return } + self.hasUnreadPrivateMessages = hasUnread } .store(in: &cancellables) chatViewModel.$nickname + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .sink { [weak self] nickname in guard let self, self.nickname != nickname else { return } @@ -166,25 +178,53 @@ final class AppChromeModel: ObservableObject { .store(in: &cancellables) chatViewModel.$showBluetoothAlert + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$showBluetoothAlert) + .sink { [weak self] showAlert in + guard let self, self.showBluetoothAlert != showAlert else { return } + self.showBluetoothAlert = showAlert + } + .store(in: &cancellables) chatViewModel.$bluetoothAlertMessage + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$bluetoothAlertMessage) + .sink { [weak self] message in + guard let self, self.bluetoothAlertMessage != message else { return } + self.bluetoothAlertMessage = message + } + .store(in: &cancellables) chatViewModel.$bluetoothState + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$bluetoothState) + .sink { [weak self] state in + guard let self, self.bluetoothState != state else { return } + self.bluetoothState = state + } + .store(in: &cancellables) chatViewModel.$torBlocked + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$torBlocked) + .sink { [weak self] blocked in + guard let self, self.torBlocked != blocked else { return } + self.torBlocked = blocked + } + .store(in: &cancellables) chatViewModel.$panicRecoveryBlocked + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$panicWipeBlocked) - - hasUnreadPrivateMessages = !privateInboxModel.unreadPeerIDs.isEmpty + .sink { [weak self] blocked in + guard let self, self.panicWipeBlocked != blocked else { return } + self.panicWipeBlocked = blocked + } + .store(in: &cancellables) } } diff --git a/bitchat/App/AppEnvironmentModels.swift b/bitchat/App/AppEnvironmentModels.swift new file mode 100644 index 00000000..2e2f367c --- /dev/null +++ b/bitchat/App/AppEnvironmentModels.swift @@ -0,0 +1,51 @@ +import SwiftUI + +/// Non-observing bundle of feature models injected once at the app root. +/// +/// Views that only need to forward models into `.sheet` presentations (#1558) +/// or invoke methods inside action closures read `@Environment(\.appEnvironmentModels)` +/// instead of declaring unused `@EnvironmentObject` subscriptions that would +/// invalidate their `body` on unrelated model publishes. +struct AppEnvironmentModels { + let publicChatModel: PublicChatModel + let privateInboxModel: PrivateInboxModel + let privateConversationModel: PrivateConversationModel + let verificationModel: VerificationModel + let conversationUIModel: ConversationUIModel + let composerAutocompleteModel: ComposerAutocompleteModel + let composerDraftModel: ComposerDraftModel + let locationChannelsModel: LocationChannelsModel + let peerListModel: PeerListModel + let appChromeModel: AppChromeModel + let boardAlertsModel: BoardAlertsModel + let sharedContentImportModel: SharedContentImportModel +} + +private struct AppEnvironmentModelsKey: EnvironmentKey { + static let defaultValue: AppEnvironmentModels? = nil +} + +extension EnvironmentValues { + var appEnvironmentModels: AppEnvironmentModels? { + get { self[AppEnvironmentModelsKey.self] } + set { self[AppEnvironmentModelsKey.self] = newValue } + } +} + +extension View { + func installAppEnvironment(_ models: AppEnvironmentModels) -> some View { + self + .environment(\.appEnvironmentModels, models) + .environmentObject(models.publicChatModel) + .environmentObject(models.privateInboxModel) + .environmentObject(models.privateConversationModel) + .environmentObject(models.verificationModel) + .environmentObject(models.conversationUIModel) + .environmentObject(models.composerAutocompleteModel) + .environmentObject(models.locationChannelsModel) + .environmentObject(models.peerListModel) + .environmentObject(models.appChromeModel) + .environmentObject(models.boardAlertsModel) + .environmentObject(models.sharedContentImportModel) + } +} diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 9b568427..3b21c595 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -23,12 +23,31 @@ final class AppRuntime: ObservableObject { let privateConversationModel: PrivateConversationModel let verificationModel: VerificationModel let conversationUIModel: ConversationUIModel + let composerAutocompleteModel: ComposerAutocompleteModel + let composerDraftModel = ComposerDraftModel() let locationChannelsModel: LocationChannelsModel let peerListModel: PeerListModel let appChromeModel: AppChromeModel let boardAlertsModel: BoardAlertsModel let sharedContentImportModel: SharedContentImportModel + var environmentModels: AppEnvironmentModels { + AppEnvironmentModels( + publicChatModel: publicChatModel, + privateInboxModel: privateInboxModel, + privateConversationModel: privateConversationModel, + verificationModel: verificationModel, + conversationUIModel: conversationUIModel, + composerAutocompleteModel: composerAutocompleteModel, + composerDraftModel: composerDraftModel, + locationChannelsModel: locationChannelsModel, + peerListModel: peerListModel, + appChromeModel: appChromeModel, + boardAlertsModel: boardAlertsModel, + sharedContentImportModel: sharedContentImportModel + ) + } + private let idBridge: NostrIdentityBridge private var cancellables = Set() private var started = false @@ -79,6 +98,7 @@ final class AppRuntime: ObservableObject { privateConversationModel: self.privateConversationModel, conversations: conversations ) + self.composerAutocompleteModel = ComposerAutocompleteModel(chatViewModel: self.chatViewModel) self.peerListModel = PeerListModel( chatViewModel: self.chatViewModel, conversations: conversations, diff --git a/bitchat/App/ComposerDraftModel.swift b/bitchat/App/ComposerDraftModel.swift new file mode 100644 index 00000000..c0c18259 --- /dev/null +++ b/bitchat/App/ComposerDraftModel.swift @@ -0,0 +1,172 @@ +import Combine +import Foundation + +/// Owns the composer's live text draft and autocomplete debounce task outside +/// `ContentView`, `MessageListView`, and the people/DM sheet shells. +/// +/// Only `ContentComposerView` subscribes to this object via `@ObservedObject`; +/// parent shells and timelines access it through the non-observing +/// `appEnvironmentModels` environment container so typing never triggers +/// full-tree or message-list diffs. +@MainActor +final class ComposerDraftModel: ObservableObject { + @Published var messageText = "" + + private(set) var activeDraftKey: ComposerDraftStore.Key = .mesh + private var autocompleteDebounceTask: Task? + + init() {} + + func loadInitialDraft(for key: ComposerDraftStore.Key) { + activeDraftKey = key + let loaded = ComposerDraftStore.load(key) + if messageText != loaded { + messageText = loaded + } + } + + func switchDraft(to newKey: ComposerDraftStore.Key) { + guard newKey != activeDraftKey else { return } + ComposerDraftStore.save(messageText, for: activeDraftKey) + activeDraftKey = newKey + let loaded = ComposerDraftStore.load(newKey) + if messageText != loaded { + messageText = loaded + } + } + + func saveCurrentDraft() { + ComposerDraftStore.save(messageText, for: activeDraftKey) + } + + func replaceText(_ text: String) { + messageText = text + } + + /// Appends an @mention to the composer draft without overwriting existing text. + func insertMention(_ sender: String) { + let mention = "@\(sender) " + if messageText.isEmpty { + messageText = mention + } else if messageText.hasSuffix(" ") { + messageText += mention + } else { + messageText += " " + mention + } + } + + /// Returns the trimmed message if non-empty, clearing the draft and + /// persisted draft store before sending. + func takeMessageToSend() -> String? { + guard let trimmed = messageText.trimmedOrNilIfEmpty else { return nil } + messageText = "" + ComposerDraftStore.save("", for: activeDraftKey) + return trimmed + } + + func resetForPanic() { + cancelAutocompleteDebounce() + if !messageText.isEmpty { + messageText = "" + } + activeDraftKey = .mesh + } + + func scheduleAutocompleteUpdate( + for text: String, + in autocompleteModel: ComposerAutocompleteModel + ) { + autocompleteDebounceTask?.cancel() + let cursorPosition = text.count + autocompleteDebounceTask = Task { @MainActor in + do { + try await Task.sleep(nanoseconds: 150_000_000) + } catch { + return + } + guard !Task.isCancelled else { return } + autocompleteModel.updateAutocomplete(for: text, cursorPosition: cursorPosition) + } + } + + func cancelAutocompleteDebounce() { + autocompleteDebounceTask?.cancel() + autocompleteDebounceTask = nil + } +} + +/// Focused observable model for `@mention` autocomplete state. +/// +/// Split out of `ConversationUIModel` so typing and cycling mention suggestions +/// only re-evaluates `ContentComposerView` instead of every `TextMessageView` +/// and `MediaMessageView` row in the timeline. +@MainActor +final class ComposerAutocompleteModel: ObservableObject { + @Published private(set) var showAutocomplete = false + @Published private(set) var autocompleteSuggestions: [String] = [] + @Published private(set) var selectedAutocompleteIndex = 0 + + private let chatViewModel: ChatViewModel + + init(chatViewModel: ChatViewModel) { + self.chatViewModel = chatViewModel + self.showAutocomplete = chatViewModel.showAutocomplete + self.autocompleteSuggestions = chatViewModel.autocompleteSuggestions + self.selectedAutocompleteIndex = chatViewModel.selectedAutocompleteIndex + + bind() + } + + func updateAutocomplete(for text: String, cursorPosition: Int) { + chatViewModel.updateAutocomplete(for: text, cursorPosition: cursorPosition) + } + + func completeNickname(_ nickname: String, in text: inout String) -> Int { + chatViewModel.completeNickname(nickname, in: &text) + } + + /// Accept the currently highlighted mention suggestion, if any. + func completeSelectedSuggestion(in text: inout String) -> Bool { + guard showAutocomplete, + autocompleteSuggestions.indices.contains(selectedAutocompleteIndex) + else { return false } + _ = completeNickname(autocompleteSuggestions[selectedAutocompleteIndex], in: &text) + return true + } + + /// Dismiss the mention suggestion panel without inserting (Escape). + func dismissAutocomplete() { + guard showAutocomplete else { return } + chatViewModel.showAutocomplete = false + chatViewModel.autocompleteSuggestions = [] + chatViewModel.autocompleteRange = nil + chatViewModel.selectedAutocompleteIndex = 0 + } + + func moveAutocompleteSelection(by delta: Int) { + guard showAutocomplete, !autocompleteSuggestions.isEmpty else { return } + let count = min(4, autocompleteSuggestions.count) + let next = (selectedAutocompleteIndex + delta + count) % count + chatViewModel.selectedAutocompleteIndex = next + } + + private func bind() { + chatViewModel.$showAutocomplete + .removeDuplicates() + .dropFirst() + .receive(on: DispatchQueue.main) + .assign(to: &$showAutocomplete) + + chatViewModel.$autocompleteSuggestions + .removeDuplicates() + .dropFirst() + .receive(on: DispatchQueue.main) + .assign(to: &$autocompleteSuggestions) + + chatViewModel.$selectedAutocompleteIndex + .removeDuplicates() + .dropFirst() + .receive(on: DispatchQueue.main) + .assign(to: &$selectedAutocompleteIndex) + } +} diff --git a/bitchat/App/ConversationUIModel.swift b/bitchat/App/ConversationUIModel.swift index 7e307bed..9f7a1e53 100644 --- a/bitchat/App/ConversationUIModel.swift +++ b/bitchat/App/ConversationUIModel.swift @@ -7,9 +7,6 @@ import UIKit @MainActor final class ConversationUIModel: ObservableObject { - @Published private(set) var showAutocomplete = false - @Published private(set) var autocompleteSuggestions: [String] = [] - @Published private(set) var selectedAutocompleteIndex = 0 @Published private(set) var currentNickname: String @Published private(set) var canSendMediaInCurrentContext = true @Published private(set) var legacyPrivateMediaConsentRequest: LegacyPrivateMediaConsentRequest? @@ -42,10 +39,9 @@ final class ConversationUIModel: ObservableObject { self.conversations = conversations self.activeChannel = conversations.activeChannel self.currentNickname = chatViewModel.nickname - self.showAutocomplete = chatViewModel.showAutocomplete - self.autocompleteSuggestions = chatViewModel.autocompleteSuggestions - self.selectedAutocompleteIndex = chatViewModel.selectedAutocompleteIndex self.canSendMediaInCurrentContext = chatViewModel.canSendMediaInCurrentContext + self.activeLiveVoiceTalker = chatViewModel.activePublicVoiceTalker + self.legacyPrivateMediaConsentRequest = chatViewModel.legacyPrivateMediaConsentRequest bind() } @@ -110,39 +106,6 @@ final class ConversationUIModel: ObservableObject { chatViewModel.getFingerprint(for: peerID) } - func updateAutocomplete(for text: String, cursorPosition: Int) { - chatViewModel.updateAutocomplete(for: text, cursorPosition: cursorPosition) - } - - func completeNickname(_ nickname: String, in text: inout String) -> Int { - chatViewModel.completeNickname(nickname, in: &text) - } - - /// Accept the currently highlighted mention suggestion, if any. - func completeSelectedSuggestion(in text: inout String) -> Bool { - guard showAutocomplete, - autocompleteSuggestions.indices.contains(selectedAutocompleteIndex) - else { return false } - _ = completeNickname(autocompleteSuggestions[selectedAutocompleteIndex], in: &text) - return true - } - - /// Dismiss the mention suggestion panel without inserting (Escape). - func dismissAutocomplete() { - guard showAutocomplete else { return } - chatViewModel.showAutocomplete = false - chatViewModel.autocompleteSuggestions = [] - chatViewModel.autocompleteRange = nil - chatViewModel.selectedAutocompleteIndex = 0 - } - - func moveAutocompleteSelection(by delta: Int) { - guard showAutocomplete, !autocompleteSuggestions.isEmpty else { return } - let count = min(4, autocompleteSuggestions.count) - let next = (selectedAutocompleteIndex + delta + count) % count - chatViewModel.selectedAutocompleteIndex = next - } - func formatMessage(_ message: BitchatMessage, colorScheme: ColorScheme, theme: AppTheme? = nil) -> AttributedString { chatViewModel.formatMessageAsText(message, colorScheme: colorScheme, theme: theme) } @@ -267,35 +230,24 @@ final class ConversationUIModel: ObservableObject { // all of them: forward only real changes, never a re-sent equal value. chatViewModel.$nickname .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$currentNickname) - chatViewModel.$showAutocomplete - .removeDuplicates() - .receive(on: DispatchQueue.main) - .assign(to: &$showAutocomplete) - - chatViewModel.$autocompleteSuggestions - .removeDuplicates() - .receive(on: DispatchQueue.main) - .assign(to: &$autocompleteSuggestions) - - chatViewModel.$selectedAutocompleteIndex - .removeDuplicates() - .receive(on: DispatchQueue.main) - .assign(to: &$selectedAutocompleteIndex) - chatViewModel.$activePublicVoiceTalker .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$activeLiveVoiceTalker) chatViewModel.$legacyPrivateMediaConsentRequest .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$legacyPrivateMediaConsentRequest) conversations.$activeChannel + .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak self] channel in self?.activeChannel = channel @@ -307,6 +259,7 @@ final class ConversationUIModel: ObservableObject { .store(in: &cancellables) privateConversationModel.$selectedPeerID + .removeDuplicates() .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.refreshComputedState() @@ -316,6 +269,8 @@ final class ConversationUIModel: ObservableObject { // Verify/unverify while a DM is open must repaint existing rows — // showsVerifiedSeal is computed per render, so forward the store change. chatViewModel.peerIdentityStore.$verifiedFingerprints + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.objectWillChange.send() diff --git a/bitchat/App/LocationChannelsModel.swift b/bitchat/App/LocationChannelsModel.swift index 25cb2b9f..91a7371c 100644 --- a/bitchat/App/LocationChannelsModel.swift +++ b/bitchat/App/LocationChannelsModel.swift @@ -134,38 +134,56 @@ final class LocationChannelsModel: ObservableObject { private func bind() { manager.$permissionState + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$permissionState) manager.$availableChannels + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$availableChannels) manager.$selectedChannel + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$selectedChannel) manager.$teleported + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$teleported) manager.$bookmarks + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$bookmarks) manager.$bookmarkNames + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$bookmarkNames) manager.$locationNames + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$locationNames) network.$userTorEnabled + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$userTorEnabled) gateway.$isEnabled + .removeDuplicates() + .dropFirst() .receive(on: DispatchQueue.main) .assign(to: &$gatewayEnabled) } diff --git a/bitchat/App/PeerIdentityStore.swift b/bitchat/App/PeerIdentityStore.swift index e7e49f01..57654cd4 100644 --- a/bitchat/App/PeerIdentityStore.swift +++ b/bitchat/App/PeerIdentityStore.swift @@ -11,6 +11,7 @@ final class PeerIdentityStore: ObservableObject { private(set) var selectedPrivateChatFingerprint: String? private var stablePeerIDsByShortID: [PeerID: PeerID] = [:] + private(set) var stablePeerMappingRevision: UInt64 = 0 private var encryptionStatusCache: [PeerID: EncryptionStatus] = [:] func stablePeerID(forShortID peerID: PeerID) -> PeerID? { @@ -22,7 +23,9 @@ final class PeerIdentityStore: ObservableObject { } func setStablePeerID(_ stablePeerID: PeerID, forShortID peerID: PeerID) { + guard stablePeerIDsByShortID[peerID] != stablePeerID else { return } stablePeerIDsByShortID[peerID] = stablePeerID + stablePeerMappingRevision &+= 1 } func fingerprint(for peerID: PeerID) -> String? { @@ -82,22 +85,27 @@ final class PeerIdentityStore: ObservableObject { } func setEncryptionStatus(_ status: EncryptionStatus?, for peerID: PeerID) { - if let status { - encryptionStatuses[peerID] = status - } else { - encryptionStatuses.removeValue(forKey: peerID) + if encryptionStatuses[peerID] != status { + if let status { + encryptionStatuses[peerID] = status + } else { + encryptionStatuses.removeValue(forKey: peerID) + } } invalidateEncryptionCache(for: peerID) } func setVerifiedFingerprints(_ fingerprints: Set) { + guard verifiedFingerprints != fingerprints else { return } verifiedFingerprints = fingerprints } func setVerified(_ fingerprint: String, verified: Bool) { if verified { + guard !verifiedFingerprints.contains(fingerprint) else { return } verifiedFingerprints.insert(fingerprint) } else { + guard verifiedFingerprints.contains(fingerprint) else { return } verifiedFingerprints.remove(fingerprint) } } @@ -107,11 +115,18 @@ final class PeerIdentityStore: ObservableObject { } func clearAll() { - encryptionStatuses.removeAll() - verifiedFingerprints.removeAll() + if !encryptionStatuses.isEmpty { + encryptionStatuses.removeAll() + } + if !verifiedFingerprints.isEmpty { + verifiedFingerprints.removeAll() + } peerFingerprintsByPeerID.removeAll() selectedPrivateChatFingerprint = nil - stablePeerIDsByShortID.removeAll() + if !stablePeerIDsByShortID.isEmpty { + stablePeerIDsByShortID.removeAll() + stablePeerMappingRevision &+= 1 + } encryptionStatusCache.removeAll() } } diff --git a/bitchat/App/PrivateConversationModels.swift b/bitchat/App/PrivateConversationModels.swift index 80d5cf29..dcee6fc3 100644 --- a/bitchat/App/PrivateConversationModels.swift +++ b/bitchat/App/PrivateConversationModels.swift @@ -235,10 +235,16 @@ final class PrivateConversationModel: ObservableObject { } private func refreshSelectedConversation() { - selectedPeerID = conversations.selectedPrivatePeerID - selectedHeaderState = selectedPeerID.flatMap { peerID in + let nextPeerID = conversations.selectedPrivatePeerID + let nextHeaderState = nextPeerID.flatMap { peerID in makeHeaderState(for: peerID) } + if selectedPeerID != nextPeerID { + selectedPeerID = nextPeerID + } + if selectedHeaderState != nextHeaderState { + selectedHeaderState = nextHeaderState + } } private func makeHeaderState(for conversationPeerID: PeerID) -> PrivateConversationHeaderState { diff --git a/bitchat/BitchatApp.swift b/bitchat/BitchatApp.swift index cf2e1bd1..5c909448 100644 --- a/bitchat/BitchatApp.swift +++ b/bitchat/BitchatApp.swift @@ -32,16 +32,7 @@ struct BitchatApp: App { WindowGroup { ContentView() .environment(\.appTheme, AppTheme(rawValue: appThemeRawValue) ?? .matrix) - .environmentObject(runtime.publicChatModel) - .environmentObject(runtime.privateInboxModel) - .environmentObject(runtime.privateConversationModel) - .environmentObject(runtime.verificationModel) - .environmentObject(runtime.conversationUIModel) - .environmentObject(runtime.locationChannelsModel) - .environmentObject(runtime.peerListModel) - .environmentObject(runtime.appChromeModel) - .environmentObject(runtime.boardAlertsModel) - .environmentObject(runtime.sharedContentImportModel) + .installAppEnvironment(runtime.environmentModels) .onAppear { appDelegate.runtime = runtime runtime.start() diff --git a/bitchat/ViewModels/ChatMessageFormatter.swift b/bitchat/ViewModels/ChatMessageFormatter.swift index 8a5310c1..987e9ca6 100644 --- a/bitchat/ViewModels/ChatMessageFormatter.swift +++ b/bitchat/ViewModels/ChatMessageFormatter.swift @@ -14,6 +14,10 @@ final class ChatMessageFormatter { /// is rebuilt only when the roster's membership (or our own excluded /// key) changes rather than recomputing the roster on every lookup. private var nostrPaletteKey: NostrPaletteKey? + /// What the mesh palette was last built from. Guarded by membership and + /// stable-ID mapping revisions so looking up colors across N rows is O(N) + /// instead of rebuilding the seed dictionary O(N²) times. + private var meshPaletteKey: MeshPaletteKey? private struct NostrPaletteKey: Equatable { // periphery:ignore - read only via the synthesized Equatable @@ -24,6 +28,17 @@ final class ChatMessageFormatter { let excludedHex: String? } + private struct MeshPaletteKey: Equatable { + // periphery:ignore - read only via the synthesized Equatable + // conformance (the rebuild check), which the indexer cannot + // attribute. + let membershipRevision: UInt64 + // periphery:ignore - see `membershipRevision`. + let stablePeerRevision: UInt64 + // periphery:ignore - see `membershipRevision`. + let myPeerID: PeerID + } + init(viewModel: ChatViewModel) { self.viewModel = viewModel } @@ -231,7 +246,7 @@ final class ChatMessageFormatter { let (mentionBase, mentionSuffix) = matchText.splitSuffix() let mySuffix: String? = { if case .location(let channel) = viewModel.activeChannel, - let identity = try? viewModel.idBridge.deriveIdentity(forGeohash: channel.geohash) { + let identity = viewModel.geohashIdentity(for: channel.geohash) { return String(identity.publicKeyHex.suffix(4)) } return String(viewModel.meshService.myPeerID.id.prefix(4)) @@ -371,7 +386,7 @@ final class ChatMessageFormatter { let isSelf: Bool = { if let spid = message.senderPeerID { if case .location(let channel) = viewModel.activeChannel, spid.id.hasPrefix("nostr:"), - let myGeo = try? viewModel.idBridge.deriveIdentity(forGeohash: channel.geohash) { + let myGeo = viewModel.geohashIdentity(for: channel.geohash) { return spid == PeerID(nostr: myGeo.publicKeyHex) } return spid == viewModel.meshService.myPeerID @@ -517,20 +532,28 @@ private extension ChatMessageFormatter { return .orange } - meshPalette.ensurePalette(for: currentMeshPaletteSeeds()) + ensureMeshPalette() if let color = meshPalette.color(for: peerID.id, isDark: isDark) { return color } return Color(peerSeed: meshSeed(for: peerID), isDark: isDark) } - func currentMeshPaletteSeeds() -> [String: String] { + func ensureMeshPalette() { let myID = viewModel.meshService.myPeerID + let key = MeshPaletteKey( + membershipRevision: viewModel.meshPeerMembershipRevision, + stablePeerRevision: viewModel.peerIdentityStore.stablePeerMappingRevision, + myPeerID: myID + ) + guard key != meshPaletteKey else { return } + meshPaletteKey = key + var seeds: [String: String] = [:] for peer in viewModel.allPeers where peer.peerID != myID { seeds[peer.peerID.id] = meshSeed(for: peer.peerID) } - return seeds + meshPalette.ensurePalette(for: seeds) } func getNostrPaletteColor(for pubkeyHexLowercased: String, isDark: Bool) -> Color { @@ -568,7 +591,7 @@ private extension ChatMessageFormatter { func currentGeohashIdentityHex() -> String? { if case .location(let channel) = viewModel.activeChannel, - let identity = try? viewModel.idBridge.deriveIdentity(forGeohash: channel.geohash) { + let identity = viewModel.geohashIdentity(for: channel.geohash) { return identity.publicKeyHex.lowercased() } return nil diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 7ee5de4f..6b40edfe 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -223,7 +223,19 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Computed properties for compatibility @MainActor var connectedPeers: Set { unifiedPeerService.connectedPeerIDs } - @Published var allPeers: [BitchatPeer] = [] + /// Monotonic counter incremented only when `allPeers`'s peer-ID membership + /// changes, allowing `ChatMessageFormatter` to skip O(N) mesh palette + /// seed rebuilds on every row lookup. + private(set) var meshPeerMembershipRevision: UInt64 = 0 + @Published var allPeers: [BitchatPeer] = [] { + didSet { + guard oldValue.count != allPeers.count + || zip(oldValue, allPeers).contains(where: { $0.peerID != $1.peerID }) else { + return + } + meshPeerMembershipRevision &+= 1 + } + } /// Nickname of whoever is talking live in the public mesh channel right /// now (floor-courtesy indicator on the composer mic), nil when nobody. @Published var activePublicVoiceTalker: String? diff --git a/bitchat/Views/ContentComposerView.swift b/bitchat/Views/ContentComposerView.swift index b7deab21..b18fc31b 100644 --- a/bitchat/Views/ContentComposerView.swift +++ b/bitchat/Views/ContentComposerView.swift @@ -8,16 +8,16 @@ import AppKit struct ContentComposerView: View { @EnvironmentObject private var conversationUIModel: ConversationUIModel + @EnvironmentObject private var autocompleteModel: ComposerAutocompleteModel @EnvironmentObject private var privateConversationModel: PrivateConversationModel @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @ObservedObject private var bridgeService = BridgeService.shared @Environment(\.appTheme) private var theme @ThemedPalette private var palette - @Binding var messageText: String + @ObservedObject var draftModel: ComposerDraftModel var isTextFieldFocused: FocusState.Binding @ObservedObject var voiceRecordingVM: VoiceRecordingViewModel - @Binding var autocompleteDebounceTimer: Timer? let onSendMessage: () -> Void @@ -30,11 +30,11 @@ struct ContentComposerView: View { var body: some View { VStack(alignment: .leading, spacing: 6) { - if conversationUIModel.showAutocomplete && !conversationUIModel.autocompleteSuggestions.isEmpty { + if autocompleteModel.showAutocomplete && !autocompleteModel.autocompleteSuggestions.isEmpty { VStack(alignment: .leading, spacing: 0) { - ForEach(Array(conversationUIModel.autocompleteSuggestions.prefix(4).enumerated()), id: \.element) { index, suggestion in + ForEach(Array(autocompleteModel.autocompleteSuggestions.prefix(4).enumerated()), id: \.element) { index, suggestion in Button(action: { - _ = conversationUIModel.completeNickname(suggestion, in: &messageText) + _ = autocompleteModel.completeNickname(suggestion, in: &draftModel.messageText) }) { HStack { Text(suggestion) @@ -47,7 +47,7 @@ struct ContentComposerView: View { .padding(.vertical, 3) .frame(maxWidth: .infinity, alignment: .leading) .background( - index == conversationUIModel.selectedAutocompleteIndex + index == autocompleteModel.selectedAutocompleteIndex ? palette.secondary.opacity(0.15) : Color.clear ) @@ -59,7 +59,7 @@ struct ContentComposerView: View { .padding(.horizontal, 12) } - CommandSuggestionsView(messageText: $messageText) + CommandSuggestionsView(messageText: $draftModel.messageText) if voiceRecordingVM.state.isActive { recordingIndicator @@ -68,7 +68,7 @@ struct ContentComposerView: View { HStack(alignment: .center, spacing: 4) { TextField( "", - text: $messageText, + text: $draftModel.messageText, prompt: Text(placeholderText) .foregroundColor(palette.secondary.opacity(0.6)) ) @@ -82,25 +82,25 @@ struct ContentComposerView: View { #endif .submitLabel(.send) .modifier(AutocompleteKeyboardNavigationModifier( - isActive: { conversationUIModel.showAutocomplete - && !conversationUIModel.autocompleteSuggestions.isEmpty }, + isActive: { autocompleteModel.showAutocomplete + && !autocompleteModel.autocompleteSuggestions.isEmpty }, onMove: { delta in - conversationUIModel.moveAutocompleteSelection(by: delta) + autocompleteModel.moveAutocompleteSelection(by: delta) }, onAccept: { - conversationUIModel.completeSelectedSuggestion(in: &messageText) + autocompleteModel.completeSelectedSuggestion(in: &draftModel.messageText) }, onDismiss: { - conversationUIModel.dismissAutocomplete() + autocompleteModel.dismissAutocomplete() } )) // Return while the mention panel is open completes the // highlight instead of sending — matches command suggestions // (#1504) and keeps Tab/Return/Escape on one convention. .onSubmit { - if conversationUIModel.showAutocomplete, - !conversationUIModel.autocompleteSuggestions.isEmpty, - conversationUIModel.completeSelectedSuggestion(in: &messageText) { + if autocompleteModel.showAutocomplete, + !autocompleteModel.autocompleteSuggestions.isEmpty, + autocompleteModel.completeSelectedSuggestion(in: &draftModel.messageText) { return } onSendMessage() @@ -115,14 +115,8 @@ struct ContentComposerView: View { .themedInputBackground() .modifier(FocusEffectDisabledModifier()) .frame(maxWidth: .infinity, alignment: .leading) - .onChange(of: messageText) { newValue in - autocompleteDebounceTimer?.invalidate() - autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in - let cursorPosition = newValue.count - Task { @MainActor in - conversationUIModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition) - } - } + .onChange(of: draftModel.messageText) { newValue in + draftModel.scheduleAutocompleteUpdate(for: newValue, in: autocompleteModel) } HStack(alignment: .center, spacing: 4) { @@ -143,7 +137,7 @@ struct ContentComposerView: View { .padding(.bottom, 8) .themedChromePanel(edge: .bottom) .onDisappear { - autocompleteDebounceTimer?.invalidate() + draftModel.cancelAutocompleteDebounce() } } } @@ -300,7 +294,7 @@ private extension ContentComposerView { @ViewBuilder var sendOrMicButton: some View { - let hasText = !messageText.trimmed.isEmpty + let hasText = !draftModel.messageText.trimmed.isEmpty if conversationUIModel.canSendMediaInCurrentContext { ZStack { micButtonView diff --git a/bitchat/Views/ContentSheetViews.swift b/bitchat/Views/ContentSheetViews.swift index e76cc2de..7e26775a 100644 --- a/bitchat/Views/ContentSheetViews.swift +++ b/bitchat/Views/ContentSheetViews.swift @@ -25,21 +25,19 @@ struct ContentPeopleSheetModalPresentationState { struct ContentPeopleSheetView: View { @EnvironmentObject private var appChromeModel: AppChromeModel @EnvironmentObject private var privateConversationModel: PrivateConversationModel - @EnvironmentObject private var verificationModel: VerificationModel @EnvironmentObject private var conversationUIModel: ConversationUIModel + @Environment(\.appEnvironmentModels) private var appEnvironmentModels @Environment(\.scenePhase) private var scenePhase @Binding var showSidebar: Bool - @Binding var messageText: String + let draftModel: ComposerDraftModel @Binding var selectedMessageSender: String? @Binding var selectedMessageSenderID: PeerID? @Binding var imagePreviewURL: URL? - @Binding var windowCountPublic: Int @Binding var windowCountPrivate: [PeerID: Int] @Binding var isAtBottomPrivate: Bool var isTextFieldFocused: FocusState.Binding @ObservedObject var voiceRecordingVM: VoiceRecordingViewModel - @Binding var autocompleteDebounceTimer: Timer? @State private var showVerifySheet = false @ThemedPalette private var palette @@ -130,16 +128,14 @@ struct ContentPeopleSheetView: View { #if os(iOS) ContentPrivateChatSheetView( showSidebar: $showSidebar, - messageText: $messageText, + draftModel: draftModel, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, windowCountPrivate: $windowCountPrivate, isAtBottomPrivate: $isAtBottomPrivate, isTextFieldFocused: isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, headerHeight: headerHeight, onSendMessage: onSendMessage, showImagePicker: $showImagePicker, @@ -148,16 +144,14 @@ struct ContentPeopleSheetView: View { #else ContentPrivateChatSheetView( showSidebar: $showSidebar, - messageText: $messageText, + draftModel: draftModel, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, windowCountPrivate: $windowCountPrivate, isAtBottomPrivate: $isAtBottomPrivate, isTextFieldFocused: isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, headerHeight: headerHeight, onSendMessage: onSendMessage, showMacImagePicker: $showMacImagePicker @@ -178,7 +172,8 @@ struct ContentPeopleSheetView: View { } } )) { - if let peerID = appChromeModel.showingFingerprintFor { + if let peerID = appChromeModel.showingFingerprintFor, + let verificationModel = appEnvironmentModels?.verificationModel { FingerprintView(peerID: peerID) .environmentObject(verificationModel) } @@ -312,10 +307,9 @@ struct ContentPeopleSheetView: View { private struct ContentPeopleListView: View { @EnvironmentObject private var appChromeModel: AppChromeModel @EnvironmentObject private var privateConversationModel: PrivateConversationModel - @EnvironmentObject private var verificationModel: VerificationModel - @EnvironmentObject private var conversationUIModel: ConversationUIModel @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @EnvironmentObject private var peerListModel: PeerListModel + @Environment(\.appEnvironmentModels) private var appEnvironmentModels @Environment(\.dismiss) private var dismiss @ThemedPalette private var palette @@ -412,9 +406,9 @@ private struct ContentPeopleListView: View { }, onToggleBlock: { peer in if peer.isBlocked { - conversationUIModel.unblock(peerID: peer.peerID, displayName: peer.displayName) + appEnvironmentModels?.conversationUIModel.unblock(peerID: peer.peerID, displayName: peer.displayName) } else { - conversationUIModel.block(peerID: peer.peerID, displayName: peer.displayName) + appEnvironmentModels?.conversationUIModel.block(peerID: peer.peerID, displayName: peer.displayName) } } ) @@ -454,8 +448,10 @@ private struct ContentPeopleListView: View { } } .sheet(isPresented: $showVerifySheet) { - VerificationSheetView(isPresented: $showVerifySheet) - .environmentObject(verificationModel) + if let verificationModel = appEnvironmentModels?.verificationModel { + VerificationSheetView(isPresented: $showVerifySheet) + .environmentObject(verificationModel) + } } } } @@ -471,16 +467,14 @@ private struct ContentPrivateChatSheetView: View { @EnvironmentObject private var privateConversationModel: PrivateConversationModel @Binding var showSidebar: Bool - @Binding var messageText: String + let draftModel: ComposerDraftModel @Binding var selectedMessageSender: String? @Binding var selectedMessageSenderID: PeerID? @Binding var imagePreviewURL: URL? - @Binding var windowCountPublic: Int @Binding var windowCountPrivate: [PeerID: Int] @Binding var isAtBottomPrivate: Bool var isTextFieldFocused: FocusState.Binding @ObservedObject var voiceRecordingVM: VoiceRecordingViewModel - @Binding var autocompleteDebounceTimer: Timer? @Environment(\.appTheme) private var theme @ThemedPalette private var palette @@ -561,14 +555,12 @@ private struct ContentPrivateChatSheetView: View { .modifier(PrivateHeaderChrome()) } - MessageListView( + PrivateMessageListView( privatePeer: privateConversationModel.selectedPeerID, isAtBottom: $isAtBottomPrivate, - messageText: $messageText, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, windowCountPrivate: $windowCountPrivate, showSidebar: $showSidebar, isTextFieldFocused: isTextFieldFocused @@ -589,20 +581,18 @@ private struct ContentPrivateChatSheetView: View { #if os(iOS) ContentComposerView( - messageText: $messageText, + draftModel: draftModel, isTextFieldFocused: isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, onSendMessage: onSendMessage, showImagePicker: $showImagePicker, imagePickerSourceType: $imagePickerSourceType ) #else ContentComposerView( - messageText: $messageText, + draftModel: draftModel, isTextFieldFocused: isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, onSendMessage: onSendMessage, showMacImagePicker: $showMacImagePicker ) diff --git a/bitchat/Views/ContentView.swift b/bitchat/Views/ContentView.swift index 9b09c73d..534c6735 100644 --- a/bitchat/Views/ContentView.swift +++ b/bitchat/Views/ContentView.swift @@ -88,19 +88,11 @@ struct FocusEffectDisabledModifier: ViewModifier { struct ContentView: View { @EnvironmentObject private var appChromeModel: AppChromeModel @EnvironmentObject private var privateConversationModel: PrivateConversationModel - @EnvironmentObject private var verificationModel: VerificationModel - @EnvironmentObject private var conversationUIModel: ConversationUIModel @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @EnvironmentObject private var sharedContentImportModel: SharedContentImportModel - @EnvironmentObject private var peerListModel: PeerListModel - @EnvironmentObject private var publicChatModel: PublicChatModel - @EnvironmentObject private var privateInboxModel: PrivateInboxModel + @Environment(\.appEnvironmentModels) private var appEnvironmentModels @StateObject private var voiceRecordingVM = VoiceRecordingViewModel() - @State private var messageText = "" - /// Conversation the current `messageText` belongs to, so a channel switch - /// can save under the previous key before loading the next draft. - @State private var activeDraftKey: ComposerDraftStore.Key = .mesh @FocusState private var isTextFieldFocused: Bool @Environment(\.colorScheme) var colorScheme @Environment(\.appTheme) private var appTheme @@ -111,7 +103,6 @@ struct ContentView: View { @FocusState private var isNicknameFieldFocused: Bool @State private var isAtBottomPublic = true @State private var isAtBottomPrivate = true - @State private var autocompleteDebounceTimer: Timer? @State private var showVerifySheet = false @State private var imagePreviewURL: URL? #if os(iOS) @@ -228,19 +219,20 @@ struct ContentView: View { var body: some View { mainContent - .onAppear { [conversationUIModel, voiceRecordingVM] in - conversationUIModel.setCurrentColorScheme(colorScheme) - conversationUIModel.setCurrentTheme(appTheme) - voiceRecordingVM.sessionProvider = { [weak conversationUIModel] in - conversationUIModel?.makeVoiceCaptureSession() ?? VoiceNoteCaptureSession() + .onAppear { [appEnvironmentModels, voiceRecordingVM] in + let uiModel = appEnvironmentModels?.conversationUIModel + let draftModel = appEnvironmentModels?.composerDraftModel + uiModel?.setCurrentColorScheme(colorScheme) + uiModel?.setCurrentTheme(appTheme) + voiceRecordingVM.sessionProvider = { [weak uiModel] in + uiModel?.makeVoiceCaptureSession() ?? VoiceNoteCaptureSession() } - appChromeModel.setPanicPreparation { [weak voiceRecordingVM] in + appChromeModel.setPanicPreparation { [weak voiceRecordingVM, weak draftModel] in voiceRecordingVM?.panicWipe() // Drop in-memory composer text before ChatViewModel resets // persisted drafts — otherwise the next inactive/background // transition would write the pre-wipe draft back. - messageText = "" - activeDraftKey = .mesh + draftModel?.resetForPanic() } #if os(macOS) DispatchQueue.main.async { @@ -249,18 +241,18 @@ struct ContentView: View { } #endif sharedContentImportModel.updateDestination(sharedContentDestination) - activeDraftKey = ComposerDraftStore.Key.from( + let initialKey = ComposerDraftStore.Key.from( peerID: selectedPrivatePeerID, - fingerprint: selectedPrivatePeerID.flatMap { conversationUIModel.getFingerprint(for: $0) }, + fingerprint: selectedPrivatePeerID.flatMap { uiModel?.getFingerprint(for: $0) }, channel: locationChannelsModel.selectedChannel ) - messageText = ComposerDraftStore.load(activeDraftKey) + draftModel?.loadInitialDraft(for: initialKey) } .onChange(of: colorScheme) { newValue in - conversationUIModel.setCurrentColorScheme(newValue) + appEnvironmentModels?.conversationUIModel.setCurrentColorScheme(newValue) } .onChange(of: appTheme) { newValue in - conversationUIModel.setCurrentTheme(newValue) + appEnvironmentModels?.conversationUIModel.setCurrentTheme(newValue) } .background(ThemedRootBackground()) .foregroundColor(palette.primary) @@ -272,9 +264,10 @@ struct ContentView: View { showSidebar = true } sharedContentImportModel.updateDestination(sharedContentDestination) - switchComposerDraft(to: ComposerDraftStore.Key.from( + let uiModel = appEnvironmentModels?.conversationUIModel + appEnvironmentModels?.composerDraftModel.switchDraft(to: ComposerDraftStore.Key.from( peerID: newValue, - fingerprint: newValue.flatMap { conversationUIModel.getFingerprint(for: $0) }, + fingerprint: newValue.flatMap { uiModel?.getFingerprint(for: $0) }, channel: locationChannelsModel.selectedChannel )) } @@ -283,7 +276,7 @@ struct ContentView: View { // Private drafts are keyed by peer; only public channel switches // need a draft swap while no DM is open. if selectedPrivatePeerID == nil { - switchComposerDraft(to: ComposerDraftStore.Key.from( + appEnvironmentModels?.composerDraftModel.switchDraft(to: ComposerDraftStore.Key.from( peerID: nil, fingerprint: nil, channel: newChannel @@ -295,7 +288,7 @@ struct ContentView: View { // Always save, including empty — clearing the composer must // remove the in-memory draft so it does not resurrect on the // next switch back into this conversation. - ComposerDraftStore.save(messageText, for: activeDraftKey) + appEnvironmentModels?.composerDraftModel.saveCurrentDraft() } } .sheet( @@ -318,61 +311,45 @@ struct ContentView: View { } ) ) { - #if os(iOS) - ContentPeopleSheetView( - showSidebar: $showSidebar, - messageText: $messageText, - selectedMessageSender: $selectedMessageSender, - selectedMessageSenderID: $selectedMessageSenderID, - imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, - windowCountPrivate: $windowCountPrivate, - isAtBottomPrivate: $isAtBottomPrivate, - isTextFieldFocused: $isTextFieldFocused, - voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, - headerHeight: headerHeight, - onSendMessage: sendMessage, - showImagePicker: $showImagePicker, - imagePickerSourceType: $imagePickerSourceType - ) - // Sheets + NavigationStack can drop inherited EnvironmentObjects on - // some iOS versions (#1558). Re-inject every model the sheet tree - // reads so ContentPeopleListView / MessageListView never crash. - .environmentObject(appChromeModel) - .environmentObject(privateConversationModel) - .environmentObject(verificationModel) - .environmentObject(conversationUIModel) - .environmentObject(locationChannelsModel) - .environmentObject(peerListModel) - .environmentObject(publicChatModel) - .environmentObject(privateInboxModel) - #else - ContentPeopleSheetView( - showSidebar: $showSidebar, - messageText: $messageText, - selectedMessageSender: $selectedMessageSender, - selectedMessageSenderID: $selectedMessageSenderID, - imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, - windowCountPrivate: $windowCountPrivate, - isAtBottomPrivate: $isAtBottomPrivate, - isTextFieldFocused: $isTextFieldFocused, - voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, - headerHeight: headerHeight, - onSendMessage: sendMessage, - showMacImagePicker: $showMacImagePicker - ) - .environmentObject(appChromeModel) - .environmentObject(privateConversationModel) - .environmentObject(verificationModel) - .environmentObject(conversationUIModel) - .environmentObject(locationChannelsModel) - .environmentObject(peerListModel) - .environmentObject(publicChatModel) - .environmentObject(privateInboxModel) - #endif + if let models = appEnvironmentModels { + #if os(iOS) + ContentPeopleSheetView( + showSidebar: $showSidebar, + draftModel: models.composerDraftModel, + selectedMessageSender: $selectedMessageSender, + selectedMessageSenderID: $selectedMessageSenderID, + imagePreviewURL: $imagePreviewURL, + windowCountPrivate: $windowCountPrivate, + isAtBottomPrivate: $isAtBottomPrivate, + isTextFieldFocused: $isTextFieldFocused, + voiceRecordingVM: voiceRecordingVM, + headerHeight: headerHeight, + onSendMessage: sendMessage, + showImagePicker: $showImagePicker, + imagePickerSourceType: $imagePickerSourceType + ) + // Sheets + NavigationStack can drop inherited EnvironmentObjects on + // some iOS versions (#1558). Re-inject every model the sheet tree + // reads so ContentPeopleListView / PrivateMessageListView never crash. + .installAppEnvironment(models) + #else + ContentPeopleSheetView( + showSidebar: $showSidebar, + draftModel: models.composerDraftModel, + selectedMessageSender: $selectedMessageSender, + selectedMessageSenderID: $selectedMessageSenderID, + imagePreviewURL: $imagePreviewURL, + windowCountPrivate: $windowCountPrivate, + isAtBottomPrivate: $isAtBottomPrivate, + isTextFieldFocused: $isTextFieldFocused, + voiceRecordingVM: voiceRecordingVM, + headerHeight: headerHeight, + onSendMessage: sendMessage, + showMacImagePicker: $showMacImagePicker + ) + .installAppEnvironment(models) + #endif + } } .sheet(isPresented: $appChromeModel.isAppInfoPresented) { AppInfoView( @@ -385,7 +362,8 @@ struct ContentView: View { get: { appChromeModel.showingFingerprintFor != nil && !showSidebar && selectedPrivatePeerID == nil }, set: { _ in appChromeModel.clearFingerprint() } )) { - if let peerID = appChromeModel.showingFingerprintFor { + if let peerID = appChromeModel.showingFingerprintFor, + let verificationModel = appEnvironmentModels?.verificationModel { FingerprintView(peerID: peerID) .environmentObject(verificationModel) } @@ -401,7 +379,7 @@ struct ContentView: View { )) { ImagePickerView(sourceType: imagePickerSourceType) { image in showImagePicker = false - conversationUIModel.processSelectedImage(image) + appEnvironmentModels?.conversationUIModel.processSelectedImage(image) } .ignoresSafeArea() } @@ -417,7 +395,7 @@ struct ContentView: View { )) { MacImagePickerView { url in showMacImagePicker = false - conversationUIModel.processSelectedImage(from: url) + appEnvironmentModels?.conversationUIModel.processSelectedImage(from: url) } } #endif @@ -472,7 +450,7 @@ struct ContentView: View { // Replacing is deliberate and called out in the prompt. It // avoids combining a stale draft from another conversation // with newly shared content. - messageText = importedText + appEnvironmentModels?.composerDraftModel.replaceText(importedText) isTextFieldFocused = true } } message: { offer in @@ -483,7 +461,7 @@ struct ContentView: View { Text(String(format: format, offer.destination.displayName) + "\n\n" + offer.payload.preview) } .onDisappear { - autocompleteDebounceTimer?.invalidate() + appEnvironmentModels?.composerDraftModel.cancelAutocompleteDebounce() appChromeModel.setPanicPreparation(nil) } } @@ -572,58 +550,47 @@ struct ContentView: View { } private var publicMessageList: some View { - MessageListView( - privatePeer: nil, + PublicMessageListView( isAtBottom: $isAtBottomPublic, - messageText: $messageText, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, windowCountPublic: $windowCountPublic, - windowCountPrivate: $windowCountPrivate, showSidebar: $showSidebar, isTextFieldFocused: $isTextFieldFocused ) } + @ViewBuilder private var composerView: some View { - #if os(iOS) - ContentComposerView( - messageText: $messageText, - isTextFieldFocused: $isTextFieldFocused, - voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, - onSendMessage: sendMessage, - showImagePicker: $showImagePicker, - imagePickerSourceType: $imagePickerSourceType - ) - #else - ContentComposerView( - messageText: $messageText, - isTextFieldFocused: $isTextFieldFocused, - voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, - onSendMessage: sendMessage, - showMacImagePicker: $showMacImagePicker - ) - #endif - } - - private func sendMessage() { - guard let trimmed = messageText.trimmedOrNilIfEmpty else { return } - - messageText = "" - ComposerDraftStore.save("", for: activeDraftKey) - - DispatchQueue.main.async { - self.conversationUIModel.sendMessage(trimmed) + if let draftModel = appEnvironmentModels?.composerDraftModel { + #if os(iOS) + ContentComposerView( + draftModel: draftModel, + isTextFieldFocused: $isTextFieldFocused, + voiceRecordingVM: voiceRecordingVM, + onSendMessage: sendMessage, + showImagePicker: $showImagePicker, + imagePickerSourceType: $imagePickerSourceType + ) + #else + ContentComposerView( + draftModel: draftModel, + isTextFieldFocused: $isTextFieldFocused, + voiceRecordingVM: voiceRecordingVM, + onSendMessage: sendMessage, + showMacImagePicker: $showMacImagePicker + ) + #endif } } - private func switchComposerDraft(to newKey: ComposerDraftStore.Key) { - guard newKey != activeDraftKey else { return } - ComposerDraftStore.save(messageText, for: activeDraftKey) - activeDraftKey = newKey - messageText = ComposerDraftStore.load(newKey) + private func sendMessage() { + guard let trimmed = appEnvironmentModels?.composerDraftModel.takeMessageToSend() else { return } + let uiModel = appEnvironmentModels?.conversationUIModel + + DispatchQueue.main.async { + uiModel?.sendMessage(trimmed) + } } } diff --git a/bitchat/Views/MessageListView.swift b/bitchat/Views/MessageListView.swift index 58722957..97a5d3ba 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -42,394 +42,71 @@ private struct TimelineSignature: Equatable { } } -struct MessageListView: View { +/// Public timeline host: observes only public-channel state so private DM +/// traffic never invalidates the public message list. +struct PublicMessageListView: View { @EnvironmentObject private var publicChatModel: PublicChatModel - @EnvironmentObject private var privateInboxModel: PrivateInboxModel - @EnvironmentObject private var privateConversationModel: PrivateConversationModel - @EnvironmentObject private var conversationUIModel: ConversationUIModel @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @EnvironmentObject private var appChromeModel: AppChromeModel @ObservedObject private var nearbyNotes = NearbyNotesCounter.shared - @Environment(\.colorScheme) private var colorScheme - @Environment(\.appTheme) private var theme - - let privatePeer: PeerID? @Binding var isAtBottom: Bool - @Binding var messageText: String @Binding var selectedMessageSender: String? @Binding var selectedMessageSenderID: PeerID? @Binding var imagePreviewURL: URL? @Binding var windowCountPublic: Int - @Binding var windowCountPrivate: [PeerID: Int] @Binding var showSidebar: Bool - var isTextFieldFocused: FocusState.Binding - @State private var showMessageActions = false - @State private var showClearConfirmation = false - @State private var lastScrollTime: Date = .distantPast - @State private var scrollThrottleTimer: Timer? - @State private var unseenCount = 0 - /// The timeline as of the last change this list observed: its newest - /// message (the next change counts what landed after it) and the - /// window's first row (kept in place while the reader is scrolled up). - /// Marks are per context: channel switches swap the timeline wholesale, - /// so a difference only means "new messages" within one context. Its - /// context is the one the list has landed in; row callbacks from any - /// other timeline are ignored. - @State private var timelineMark: MessageListScrollPolicy.TimelineMark? - /// Row whose appearance last put the list at the bottom, cleared when it - /// leaves the screen. Its leaving means the reader scrolled up, even while - /// a newer row that landed below it has not appeared yet. - @State private var bottomRowID: String? - /// Set while an expansion's position-restoring scroll is still queued. - @State private var isRestoringExpansion = false - /// Context whose newest row has appeared since the list appeared or - /// landed in it, i.e. whose scroll to the bottom has landed. Window - /// expansion waits for it. - @State private var bottomSettledContextKey: String? /// Whether this instance holds the nearby-notes counter active (mesh /// public timeline only); balanced against activate/deactivate. @State private var holdsNotesCounter = false - @ThemedPalette private var palette var body: some View { - let currentWindowCount = windowCount(for: privatePeer) - - let messages = conversationMessages(for: privatePeer) - let contextKey = timelineContextKey(for: privatePeer) - // While the reader is scrolled up, messages landing below the - // window's first row widen the window in this same render instead of - // pushing that row out of the top, which would shift what they are - // reading (onTimelineChange then records the wider window). - let renderedWindowCount = isAtBottom - ? currentWindowCount - : MessageListScrollPolicy.windowCountKeepingFirstRow( - current: currentWindowCount, - mark: contextMark(for: contextKey), - appendedCount: 0, - in: messages - ) - 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) - } - // Top edge of the rendered window (whitespace-only messages get no - // row, so they could never report reaching it). - let firstRowID = messageItems.first?.id - VStack(spacing: 0) { - // Notes pinned to this place stay visible while chatting — a - // conversation starting must not hide what's left here. - if privatePeer == nil, - case .mesh = locationChannelsModel.selectedChannel, - nearbyNotes.noteCount > 0 { - notesHereStrip - } - GeometryReader { geometry in - ScrollViewReader { proxy in - ScrollView { - if messageItems.isEmpty && privatePeer == nil { - publicEmptyState(fillHeight: geometry.size.height) - } - LazyVStack(alignment: .leading, spacing: 0) { - ForEach(messageItems) { item in - let message = item.message - messageRow(for: message) - .onAppear { - // Callbacks lag a timeline switch: the new - // rows appear before the old ones disappear, - // each with its own render's view of which row - // was last. Only rows of the timeline the list - // has landed in may move its state, checked - // against live state rather than the render's. - guard isLandedRow(item.id) else { return } - if item.id == newestRowID(for: privatePeer) { - isAtBottom = true - unseenCount = 0 - if bottomRowID != item.id { - bottomRowID = item.id - } - if bottomSettledContextKey != contextKey { - bottomSettledContextKey = contextKey - } - returnWindowToInitialSize(for: privatePeer, contextKey: contextKey, messages: messages) - } - if item.id == firstRowID, - messages.count > windowedMessages.count { - expandWindow( - ifNeededFor: message, - allMessages: messages, - privatePeer: privatePeer, - proxy: proxy - ) - } - } - .onDisappear { - // A row of the landed timeline shares this - // closure's peer, so newestRowID is live here. - guard isLandedRow(item.id) else { return } - if item.id == newestRowID(for: privatePeer) || item.id == bottomRowID { - isAtBottom = false - bottomRowID = nil - // Leaving the bottom drops a follow-scroll - // still waiting on the throttle: it would - // yank the reader back down. - cancelFollowScroll() - } - } - .contentShape(Rectangle()) - .contextMenu { - let showsUserActions = message.sender != "system" && !conversationUIModel.isSentByCurrentUser(message) - if showsUserActions { - // Mention and DM are redundant inside a 1:1 conversation: - // mentioning the only other participant is noise, and "DM" - // would just reopen the conversation that is already open. - if privatePeer == nil { - Button("content.actions.mention") { - insertMention(message.sender) - } - if let peerID = message.senderPeerID { - Button("content.actions.direct_message") { - privateConversationModel.openConversation(for: peerID) - withAnimation(.easeInOut(duration: TransportConfig.uiAnimationMediumSeconds)) { - showSidebar = true - } - } - } - } - Button("content.actions.hug") { - conversationUIModel.sendHug(to: message.sender) - } - Button("content.actions.slap") { - conversationUIModel.sendSlap(to: message.sender) - } - } - Button("content.message.copy") { - #if os(iOS) - UIPasteboard.general.string = message.content - #else - let pb = NSPasteboard.general - pb.clearContents() - pb.setString(message.content, forType: .string) - #endif - } - if isResendableFailedMessage(message) { - Button("content.actions.resend") { - conversationUIModel.resendFailedPrivateMessage(message) - } - } - if showsUserActions { - Button("content.actions.block", role: .destructive) { - conversationUIModel.block(peerID: message.senderPeerID, displayName: message.sender) - } - } - } - .padding(.horizontal, 12) - .padding(.vertical, 1) - // Archived echoes read as one tinted block, not - // just faded rows. - .background(message.isArchivedEcho ? palette.secondary.opacity(0.08) : Color.clear) - } - } - .padding(.vertical, 2) + // Notes pinned to this place stay visible while chatting — a + // conversation starting must not hide what's left here. + if case .mesh = locationChannelsModel.selectedChannel, + nearbyNotes.noteCount > 0 { + notesHereStrip + } - // Only carried history on screen: the ambient layer (radar, - // sightings, live hints) stays visible below it instead of - // vanishing the moment echoes exist. - if privatePeer == nil, showsAmbientFooter(messageItems: messageItems) { - MeshEmptyStateView(compact: true, bluetoothAvailable: bluetoothCanScan) - .padding(.horizontal, 12) - .padding(.top, 20) - .padding(.bottom, 8) - } - } - .overlay(alignment: .bottomTrailing) { - if !isAtBottom && !messageItems.isEmpty { - jumpToLatestPill(proxy: proxy) - } - } - .onOpenURL(perform: handleOpenURL) - .onTapGesture(count: 3) { - showClearConfirmation = true - } - .confirmationDialog( - "content.clear.confirm_title", - isPresented: $showClearConfirmation, - titleVisibility: .visible - ) { - Button("content.clear.confirm_action", role: .destructive) { - conversationUIModel.clearCurrentConversation() - } - Button("common.cancel", role: .cancel) {} - } - .onAppear { - // Runs before the rows' onAppear: lands the list (and sets the - // mark the row callbacks are checked against) before any row - // reports in. Expansion waits until the scroll below has - // brought the newest row on screen. - bottomSettledContextKey = nil - scrollToBottom(on: proxy, privatePeer: privatePeer) - } - // The one change handler: a channel or DM switch changes the - // signature too, so landing in the new timeline happens here, - // ahead of that update's row callbacks. - .onChange(of: TimelineSignature(privatePeer: privatePeer, contextKey: contextKey, messages: messages)) { signature in - onTimelineChange(signature, proxy: proxy) - } - .confirmationDialog( - selectedMessageSender.map { "@\($0)" } ?? String(localized: "content.actions.title", comment: "Fallback title for the message action sheet"), - isPresented: $showMessageActions, - titleVisibility: .visible - ) { - Button("content.actions.mention") { - if let sender = selectedMessageSender { - insertMention(sender) - } - } - - Button("content.actions.direct_message") { - if let peerID = selectedMessageSenderID { - privateConversationModel.openConversation(for: peerID) - withAnimation(.easeInOut(duration: TransportConfig.uiAnimationMediumSeconds)) { - showSidebar = true - } - } - } - - Button("content.actions.hug") { - if let sender = selectedMessageSender { - conversationUIModel.sendHug(to: sender) - } - } - - Button("content.actions.slap") { - if let sender = selectedMessageSender { - conversationUIModel.sendSlap(to: sender) - } - } - - Button("content.actions.block", role: .destructive) { - conversationUIModel.block(peerID: selectedMessageSenderID, displayName: selectedMessageSender) - } - - Button("common.cancel", role: .cancel) {} - } - .onAppear { - // Also check when view appears - if let peerID = privatePeer { - // Try multiple times to ensure read receipts are sent - privateConversationModel.markMessagesAsRead(from: peerID) - - DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryShortSeconds) { - privateConversationModel.markMessagesAsRead(from: peerID) - } - - DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryLongSeconds) { - privateConversationModel.markMessagesAsRead(from: peerID) - } - } - } - .onDisappear { - cancelFollowScroll() - } - } - } + MessageListContentView( + privatePeer: nil, + messages: publicChatModel.messages, + contextKey: publicChatModel.activeChannel.contextKey, + selectedPublicChannel: locationChannelsModel.selectedChannel, + bluetoothCanScan: bluetoothCanScan, + liveMessages: { _ in publicChatModel.messages }, + liveContextKey: { _ in publicChatModel.activeChannel.contextKey }, + liveWindowCount: { _ in windowCountPublic }, + setWindowCount: { count, _ in windowCountPublic = count }, + isAtBottom: $isAtBottom, + selectedMessageSender: $selectedMessageSender, + selectedMessageSenderID: $selectedMessageSenderID, + imagePreviewURL: $imagePreviewURL, + showSidebar: $showSidebar, + isTextFieldFocused: isTextFieldFocused + ) } .onAppear { updateNotesCounterHold() } .onDisappear { releaseNotesCounterHold() } .onChange(of: locationChannelsModel.selectedChannel) { _ in updateNotesCounterHold() } - .onChange(of: privatePeer) { _ in updateNotesCounterHold() } - .environment(\.openURL, OpenURLAction { url in - // Intercept custom cashu: links created in attributed text - if let scheme = url.scheme?.lowercased(), scheme == "cashu" || scheme == "lightning" { - #if os(iOS) - UIApplication.shared.open(url) - return .handled - #else - // On non-iOS platforms, let the system handle or ignore - return .systemAction - #endif - } - return .systemAction - }) } -} -private extension MessageListView { /// Whether the radio could be scanning at all — the empty-state radar /// must not sweep over a switched-off or denied radio. - var bluetoothCanScan: Bool { + private var bluetoothCanScan: Bool { switch appChromeModel.bluetoothState { case .poweredOff, .unauthorized, .unsupported: return false default: return true } } - /// Context key of the timeline shown for `privatePeer` (the DM, or the - /// public channel); also the prefix of its row IDs. The public key comes - /// from the channel PublicChatModel publishes together with its messages: - /// the selected channel switches one render or more before the timeline - /// does, and keying the old messages with the new channel re-keys (and - /// re-appears) every row. - func timelineContextKey(for privatePeer: PeerID?) -> String { - if let peer = privatePeer { - return "dm:\(peer)" - } - return publicChatModel.activeChannel.contextKey - } - - func windowCount(for privatePeer: PeerID?) -> Int { - if let peer = privatePeer { - return windowCountPrivate[peer] ?? TransportConfig.uiWindowInitialCountPrivate - } - return windowCountPublic - } - - func setWindowCount(_ count: Int, for privatePeer: PeerID?) { - if let peer = privatePeer { - windowCountPrivate[peer] = count - } else { - windowCountPublic = count - } - } - - /// Returns the window to its initial size once the reader is back at the - /// bottom (the newest row has appeared): whatever it grew by while they - /// were scrolled up, or expanded into history, need not stay rendered, - /// and dropping rows above the bottom moves nothing on screen. Never in - /// the same update as a scroll: rows changing above the viewport make - /// SwiftUI hold its position, and a pending scrollTo never lands. - func returnWindowToInitialSize(for privatePeer: PeerID?, contextKey: String, messages: [BitchatMessage]) { - let initialCount = privatePeer == nil - ? TransportConfig.uiWindowInitialCountPublic - : TransportConfig.uiWindowInitialCountPrivate - guard windowCount(for: privatePeer) > initialCount else { return } - setWindowCount(initialCount, for: privatePeer) - timelineMark = contextMark(for: contextKey)?.withWindowCount(initialCount, in: messages) - } - - /// The timeline mark, if it was taken in `contextKey`. - func contextMark(for contextKey: String) -> MessageListScrollPolicy.TimelineMark? { - guard let timelineMark, timelineMark.contextKey == contextKey else { return nil } - return timelineMark - } - - /// Whether a row belongs to the timeline the list has landed in (the - /// mark's context: the change handler lands a switch before the rows of - /// that update report in). - func isLandedRow(_ rowID: String) -> Bool { - guard let landedContextKey = timelineMark?.contextKey else { return false } - return MessageListScrollPolicy.isRow(rowID, inContext: landedContextKey) - } - /// Tappable strip above the mesh timeline while notes are pinned at this /// place: opens the notices sheet on the geo tab. - var notesHereStrip: some View { + private var notesHereStrip: some View { let text: String = nearbyNotes.noteCount == 1 ? String(localized: "content.empty.notes_one", comment: "Hint when exactly one note was left at this place") : String( @@ -462,8 +139,8 @@ private extension MessageListView { /// showing — the strip needs a live count before it can decide to exist. /// Holding is not subscribing: nothing hits the relays until an explicit /// act reveals the counter (tap-to-reveal). - func updateNotesCounterHold() { - let shouldHold = privatePeer == nil && locationChannelsModel.selectedChannel.isMesh + private func updateNotesCounterHold() { + let shouldHold = locationChannelsModel.selectedChannel.isMesh guard shouldHold != holdsNotesCounter else { return } holdsNotesCounter = shouldHold if shouldHold { @@ -473,17 +150,403 @@ private extension MessageListView { } } - func releaseNotesCounterHold() { + private func releaseNotesCounterHold() { guard holdsNotesCounter else { return } holdsNotesCounter = false NearbyNotesCounter.shared.deactivate() } +} + +/// Private DM timeline host: observes only `PrivateInboxModel` so public +/// channel messages, location updates, and nearby-note counts never invalidate +/// an open direct-message timeline. +struct PrivateMessageListView: View { + @EnvironmentObject private var privateInboxModel: PrivateInboxModel + + let privatePeer: PeerID? + @Binding var isAtBottom: Bool + @Binding var selectedMessageSender: String? + @Binding var selectedMessageSenderID: PeerID? + @Binding var imagePreviewURL: URL? + @Binding var windowCountPrivate: [PeerID: Int] + @Binding var showSidebar: Bool + var isTextFieldFocused: FocusState.Binding + + var body: some View { + MessageListContentView( + privatePeer: privatePeer, + messages: privateInboxModel.messages(for: privatePeer), + contextKey: Self.contextKey(for: privatePeer), + selectedPublicChannel: nil, + bluetoothCanScan: false, + liveMessages: { peer in privateInboxModel.messages(for: peer) }, + liveContextKey: { peer in Self.contextKey(for: peer) }, + liveWindowCount: { peer in + if let peer { + return windowCountPrivate[peer] ?? TransportConfig.uiWindowInitialCountPrivate + } + return TransportConfig.uiWindowInitialCountPrivate + }, + setWindowCount: { count, peer in + if let peer { + windowCountPrivate[peer] = count + } + }, + isAtBottom: $isAtBottom, + selectedMessageSender: $selectedMessageSender, + selectedMessageSenderID: $selectedMessageSenderID, + imagePreviewURL: $imagePreviewURL, + showSidebar: $showSidebar, + isTextFieldFocused: isTextFieldFocused + ) + } + + private static func contextKey(for peer: PeerID?) -> String { + if let peer { + return "dm:\(peer)" + } + return "dm:none" + } +} + +private struct MessageListContentView: View { + private static let allowedGeohashChars = Set("0123456789bcdefghjkmnpqrstuvwxyz") + + @EnvironmentObject private var conversationUIModel: ConversationUIModel + @Environment(\.appEnvironmentModels) private var appEnvironmentModels + @Environment(\.colorScheme) private var colorScheme + @Environment(\.appTheme) private var theme + + let privatePeer: PeerID? + let messages: [BitchatMessage] + let contextKey: String + let selectedPublicChannel: ChannelID? + let bluetoothCanScan: Bool + let liveMessages: (PeerID?) -> [BitchatMessage] + let liveContextKey: (PeerID?) -> String + let liveWindowCount: (PeerID?) -> Int + let setWindowCount: (Int, PeerID?) -> Void + + @Binding var isAtBottom: Bool + @Binding var selectedMessageSender: String? + @Binding var selectedMessageSenderID: PeerID? + @Binding var imagePreviewURL: URL? + @Binding var showSidebar: Bool + + var isTextFieldFocused: FocusState.Binding + + @State private var showMessageActions = false + @State private var showClearConfirmation = false + @State private var lastScrollTime: Date = .distantPast + @State private var scrollThrottleTimer: Timer? + @State private var unseenCount = 0 + /// The timeline as of the last change this list observed: its newest + /// message (the next change counts what landed after it) and the + /// window's first row (kept in place while the reader is scrolled up). + /// Marks are per context: channel switches swap the timeline wholesale, + /// so a difference only means "new messages" within one context. Its + /// context is the one the list has landed in; row callbacks from any + /// other timeline are ignored. + @State private var timelineMark: MessageListScrollPolicy.TimelineMark? + /// Row whose appearance last put the list at the bottom, cleared when it + /// leaves the screen. Its leaving means the reader scrolled up, even while + /// a newer row that landed below it has not appeared yet. + @State private var bottomRowID: String? + /// Set while an expansion's position-restoring scroll is still queued. + @State private var isRestoringExpansion = false + /// Context whose newest row has appeared since the list appeared or + /// landed in it, i.e. whose scroll to the bottom has landed. Window + /// expansion waits for it. + @State private var bottomSettledContextKey: String? + + @ThemedPalette private var palette + + var body: some View { + let currentWindowCount = liveWindowCount(privatePeer) + + // While the reader is scrolled up, messages landing below the + // window's first row widen the window in this same render instead of + // pushing that row out of the top, which would shift what they are + // reading (onTimelineChange then records the wider window). + let renderedWindowCount = isAtBottom + ? currentWindowCount + : MessageListScrollPolicy.windowCountKeepingFirstRow( + current: currentWindowCount, + mark: contextMark(for: contextKey), + appendedCount: 0, + in: messages + ) + 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) + } + // Top edge of the rendered window (whitespace-only messages get no + // row, so they could never report reaching it). + let firstRowID = messageItems.first?.id + + GeometryReader { geometry in + ScrollViewReader { proxy in + ScrollView { + if messageItems.isEmpty && privatePeer == nil { + publicEmptyState(fillHeight: geometry.size.height) + } + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(messageItems) { item in + let message = item.message + messageRow(for: message) + .onAppear { + // Callbacks lag a timeline switch: the new + // rows appear before the old ones disappear, + // each with its own render's view of which row + // was last. Only rows of the timeline the list + // has landed in may move its state, checked + // against live state rather than the render's. + guard isLandedRow(item.id) else { return } + if item.id == newestRowID(for: privatePeer) { + isAtBottom = true + unseenCount = 0 + if bottomRowID != item.id { + bottomRowID = item.id + } + if bottomSettledContextKey != contextKey { + bottomSettledContextKey = contextKey + } + returnWindowToInitialSize(for: privatePeer, contextKey: contextKey, messages: messages) + } + if item.id == firstRowID, + messages.count > windowedMessages.count { + expandWindow( + ifNeededFor: message, + allMessages: messages, + privatePeer: privatePeer, + proxy: proxy + ) + } + } + .onDisappear { + // A row of the landed timeline shares this + // closure's peer, so newestRowID is live here. + guard isLandedRow(item.id) else { return } + if item.id == newestRowID(for: privatePeer) || item.id == bottomRowID { + isAtBottom = false + bottomRowID = nil + // Leaving the bottom drops a follow-scroll + // still waiting on the throttle: it would + // yank the reader back down. + cancelFollowScroll() + } + } + .contentShape(Rectangle()) + .contextMenu { + let showsUserActions = message.sender != "system" && !conversationUIModel.isSentByCurrentUser(message) + if showsUserActions { + // Mention and DM are redundant inside a 1:1 conversation: + // mentioning the only other participant is noise, and "DM" + // would just reopen the conversation that is already open. + if privatePeer == nil { + Button("content.actions.mention") { + insertMention(message.sender) + } + if let peerID = message.senderPeerID { + Button("content.actions.direct_message") { + appEnvironmentModels?.privateConversationModel.openConversation(for: peerID) + withAnimation(.easeInOut(duration: TransportConfig.uiAnimationMediumSeconds)) { + showSidebar = true + } + } + } + } + Button("content.actions.hug") { + conversationUIModel.sendHug(to: message.sender) + } + Button("content.actions.slap") { + conversationUIModel.sendSlap(to: message.sender) + } + } + Button("content.message.copy") { + #if os(iOS) + UIPasteboard.general.string = message.content + #else + let pb = NSPasteboard.general + pb.clearContents() + pb.setString(message.content, forType: .string) + #endif + } + if isResendableFailedMessage(message) { + Button("content.actions.resend") { + conversationUIModel.resendFailedPrivateMessage(message) + } + } + if showsUserActions { + Button("content.actions.block", role: .destructive) { + conversationUIModel.block(peerID: message.senderPeerID, displayName: message.sender) + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 1) + // Archived echoes read as one tinted block, not + // just faded rows. + .background(message.isArchivedEcho ? palette.secondary.opacity(0.08) : Color.clear) + } + } + .padding(.vertical, 2) + + // Only carried history on screen: the ambient layer (radar, + // sightings, live hints) stays visible below it instead of + // vanishing the moment echoes exist. + if privatePeer == nil, showsAmbientFooter(messageItems: messageItems) { + MeshEmptyStateView(compact: true, bluetoothAvailable: bluetoothCanScan) + .padding(.horizontal, 12) + .padding(.top, 20) + .padding(.bottom, 8) + } + } + .overlay(alignment: .bottomTrailing) { + if !isAtBottom && !messageItems.isEmpty { + jumpToLatestPill(proxy: proxy) + } + } + .onOpenURL(perform: handleOpenURL) + .onTapGesture(count: 3) { + showClearConfirmation = true + } + .confirmationDialog( + "content.clear.confirm_title", + isPresented: $showClearConfirmation, + titleVisibility: .visible + ) { + Button("content.clear.confirm_action", role: .destructive) { + conversationUIModel.clearCurrentConversation() + } + Button("common.cancel", role: .cancel) {} + } + .onAppear { + // Runs before the rows' onAppear: lands the list (and sets the + // mark the row callbacks are checked against) before any row + // reports in. Expansion waits until the scroll below has + // brought the newest row on screen. + bottomSettledContextKey = nil + scrollToBottom(on: proxy, privatePeer: privatePeer) + } + // The one change handler: a channel or DM switch changes the + // signature too, so landing in the new timeline happens here, + // ahead of that update's row callbacks. + .onChange(of: TimelineSignature(privatePeer: privatePeer, contextKey: contextKey, messages: messages)) { signature in + onTimelineChange(signature, proxy: proxy) + } + .confirmationDialog( + selectedMessageSender.map { "@\($0)" } ?? String(localized: "content.actions.title", comment: "Fallback title for the message action sheet"), + isPresented: $showMessageActions, + titleVisibility: .visible + ) { + Button("content.actions.mention") { + if let sender = selectedMessageSender { + insertMention(sender) + } + } + + Button("content.actions.direct_message") { + if let peerID = selectedMessageSenderID { + appEnvironmentModels?.privateConversationModel.openConversation(for: peerID) + withAnimation(.easeInOut(duration: TransportConfig.uiAnimationMediumSeconds)) { + showSidebar = true + } + } + } + + Button("content.actions.hug") { + if let sender = selectedMessageSender { + conversationUIModel.sendHug(to: sender) + } + } + + Button("content.actions.slap") { + if let sender = selectedMessageSender { + conversationUIModel.sendSlap(to: sender) + } + } + + Button("content.actions.block", role: .destructive) { + conversationUIModel.block(peerID: selectedMessageSenderID, displayName: selectedMessageSender) + } + + Button("common.cancel", role: .cancel) {} + } + .onAppear { + // Also check when view appears + if let peerID = privatePeer, + let privateConversationModel = appEnvironmentModels?.privateConversationModel { + // Try multiple times to ensure read receipts are sent + privateConversationModel.markMessagesAsRead(from: peerID) + + DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryShortSeconds) { + privateConversationModel.markMessagesAsRead(from: peerID) + } + + DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryLongSeconds) { + privateConversationModel.markMessagesAsRead(from: peerID) + } + } + } + .onDisappear { + cancelFollowScroll() + } + } + } + .environment(\.openURL, OpenURLAction { url in + // Intercept custom cashu: links created in attributed text + if let scheme = url.scheme?.lowercased(), scheme == "cashu" || scheme == "lightning" { + #if os(iOS) + UIApplication.shared.open(url) + return .handled + #else + // On non-iOS platforms, let the system handle or ignore + return .systemAction + #endif + } + return .systemAction + }) + } +} + +private extension MessageListContentView { + /// Returns the window to its initial size once the reader is back at the + /// bottom (the newest row has appeared): whatever it grew by while they + /// were scrolled up, or expanded into history, need not stay rendered, + /// and dropping rows above the bottom moves nothing on screen. Never in + /// the same update as a scroll: rows changing above the viewport make + /// SwiftUI hold its position, and a pending scrollTo never lands. + func returnWindowToInitialSize(for privatePeer: PeerID?, contextKey: String, messages: [BitchatMessage]) { + let initialCount = privatePeer == nil + ? TransportConfig.uiWindowInitialCountPublic + : TransportConfig.uiWindowInitialCountPrivate + guard liveWindowCount(privatePeer) > initialCount else { return } + setWindowCount(initialCount, privatePeer) + timelineMark = contextMark(for: contextKey)?.withWindowCount(initialCount, in: messages) + } + + /// The timeline mark, if it was taken in `contextKey`. + func contextMark(for contextKey: String) -> MessageListScrollPolicy.TimelineMark? { + guard let timelineMark, timelineMark.contextKey == contextKey else { return nil } + return timelineMark + } + + /// Whether a row belongs to the timeline the list has landed in (the + /// mark's context: the change handler lands a switch before the rows of + /// that update report in). + func isLandedRow(_ rowID: String) -> Bool { + guard let landedContextKey = timelineMark?.contextKey else { return false } + return MessageListScrollPolicy.isRow(rowID, inContext: landedContextKey) + } /// True when the mesh timeline holds nothing but archived echoes and /// system lines — no live conversation yet, so the ambient layer still /// applies. - private func showsAmbientFooter(messageItems: [MessageDisplayItem]) -> Bool { - guard case .mesh = locationChannelsModel.selectedChannel, + func showsAmbientFooter(messageItems: [MessageDisplayItem]) -> Bool { + guard case .mesh = selectedPublicChannel, !messageItems.isEmpty else { return false } return messageItems.allSatisfy { $0.message.isArchivedEcho || $0.message.sender == "system" } } @@ -495,8 +558,8 @@ private extension MessageListView { /// in the space below the text. func publicEmptyState(fillHeight: CGFloat) -> some View { VStack(alignment: .leading, spacing: 6) { - switch locationChannelsModel.selectedChannel { - case .mesh: + switch selectedPublicChannel { + case .mesh, .none: MeshEmptyStateView( fillHeight: max(0, fillHeight - 24), bluetoothAvailable: bluetoothCanScan @@ -541,14 +604,7 @@ private extension MessageListView { /// Appends an @mention to the composer draft (never overwrites what the /// user has already typed) and focuses the input field. func insertMention(_ sender: String) { - let mention = "@\(sender) " - if messageText.isEmpty { - messageText = mention - } else if messageText.hasSuffix(" ") { - messageText += mention - } else { - messageText += " " + mention - } + appEnvironmentModels?.composerDraftModel.insertMention(sender) isTextFieldFocused.wrappedValue = true } @@ -623,17 +679,17 @@ private extension MessageListView { allMessages: [BitchatMessage], privatePeer: PeerID?, proxy: ScrollViewProxy) { - let contextKey = timelineContextKey(for: privatePeer) + let contextKey = liveContextKey(privatePeer) guard MessageListScrollPolicy.canExpandWindow( isRestoringExpansion: isRestoringExpansion, bottomSettledContextKey: bottomSettledContextKey, contextKey: contextKey ) else { return } - let current = windowCount(for: privatePeer) + let current = liveWindowCount(privatePeer) let newCount = min(allMessages.count, current + TransportConfig.uiWindowStepCount) guard newCount != current else { return } - setWindowCount(newCount, for: privatePeer) + setWindowCount(newCount, privatePeer) // The window's first row moved up with it: re-take the mark's window // so a scrolled-up reader keeps holding the new first row. timelineMark = contextMark(for: contextKey)?.withWindowCount(newCount, in: allMessages) @@ -658,7 +714,7 @@ private extension MessageListView { selectedMessageSender = conversationUIModel.senderDisplayName( for: peerID, - fallbackMessages: conversationMessages(for: privatePeer) + fallbackMessages: liveMessages(privatePeer) ) if conversationUIModel.isSelfSender(peerID: peerID, displayName: selectedMessageSender) { @@ -670,9 +726,8 @@ private extension MessageListView { case "geohash": let gh = url.path.trimmingCharacters(in: CharacterSet(charactersIn: "/")).lowercased() - let allowed = Set("0123456789bcdefghjkmnpqrstuvwxyz") - guard (2...12).contains(gh.count), gh.allSatisfy({ allowed.contains($0) }) else { return } - locationChannelsModel.openLocationChannel(for: gh) + guard (2...12).contains(gh.count), gh.allSatisfy({ Self.allowedGeohashChars.contains($0) }) else { return } + appEnvironmentModels?.locationChannelsModel.openLocationChannel(for: gh) default: return @@ -686,9 +741,9 @@ private extension MessageListView { isAtBottom = true unseenCount = 0 timelineMark = MessageListScrollPolicy.TimelineMark( - contextKey: timelineContextKey(for: privatePeer), - messages: conversationMessages(for: privatePeer), - windowCount: windowCount(for: privatePeer) + contextKey: liveContextKey(privatePeer), + messages: liveMessages(privatePeer), + windowCount: liveWindowCount(privatePeer) ) if let target = newestRowID(for: privatePeer) { proxy.scrollTo(target, anchor: .bottom) @@ -716,10 +771,10 @@ private extension MessageListView { /// Row ID of the newest message that has a row (whitespace-only /// messages render none). func newestRowID(for privatePeer: PeerID?) -> String? { - guard let newest = conversationMessages(for: privatePeer).last(where: { !$0.content.trimmed.isEmpty }) else { + guard let newest = liveMessages(privatePeer).last(where: { !$0.content.trimmed.isEmpty }) else { return nil } - return "\(timelineContextKey(for: privatePeer))|\(newest.id)" + return "\(liveContextKey(privatePeer))|\(newest.id)" } /// Handles any change to the shown timeline: an append, a late message @@ -730,14 +785,14 @@ private extension MessageListView { // timeline comes from the new value rather than `self.privatePeer`. let privatePeer = signature.privatePeer let contextKey = signature.contextKey - let messages = conversationMessages(for: privatePeer) + let messages = liveMessages(privatePeer) // No mark in this context means the timeline was swapped wholesale: // nothing is booked as "new", the list lands instead. let mark = contextMark(for: contextKey) let appended = mark.map { MessageListScrollPolicy.appended(since: $0, in: messages) } ?? MessageListScrollPolicy.Appended() - let currentWindowCount = windowCount(for: privatePeer) + let currentWindowCount = liveWindowCount(privatePeer) let reaction = MessageListScrollPolicy.reaction( mark: mark, messages: messages, @@ -766,7 +821,7 @@ private extension MessageListView { in: messages ) if keptWindowCount != currentWindowCount { - setWindowCount(keptWindowCount, for: privatePeer) + setWindowCount(keptWindowCount, privatePeer) } timelineMark = MessageListScrollPolicy.TimelineMark(contextKey: contextKey, messages: messages, windowCount: keptWindowCount) @@ -800,14 +855,14 @@ private extension MessageListView { return } // Schedule a delayed scroll - let scheduledContextKey = timelineContextKey(for: privatePeer) + let scheduledContextKey = liveContextKey(privatePeer) scrollThrottleTimer?.invalidate() scrollThrottleTimer = Timer.scheduledTimer(withTimeInterval: TransportConfig.uiScrollThrottleSeconds, repeats: false) { _ in Task { @MainActor in guard MessageListScrollPolicy.shouldRunDeferredFollowScroll( isAtBottom: isAtBottom, scheduledContextKey: scheduledContextKey, - currentContextKey: timelineContextKey(for: privatePeer) + currentContextKey: liveContextKey(privatePeer) ) else { return } scrollToNewestRow(privatePeer: privatePeer, proxy: proxy, at: Date()) } @@ -827,13 +882,6 @@ private extension MessageListView { timer.invalidate() scrollThrottleTimer = nil } - - func conversationMessages(for privatePeer: PeerID?) -> [BitchatMessage] { - if let privatePeer { - return privateInboxModel.messages(for: privatePeer) - } - return publicChatModel.messages - } } private extension ChannelID { @@ -844,7 +892,3 @@ private extension ChannelID { } } } - -// #Preview { -// MessageListView() -// } diff --git a/bitchatTests/AppArchitectureTests.swift b/bitchatTests/AppArchitectureTests.swift index 3d96b156..8e9ee83f 100644 --- a/bitchatTests/AppArchitectureTests.swift +++ b/bitchatTests/AppArchitectureTests.swift @@ -691,7 +691,7 @@ struct AppArchitectureTests { #expect(conversationModel.selectedHeaderState == nil) } - @Test("ConversationUIModel mirrors composer state and forwards sends") + @Test("ConversationUIModel and ComposerAutocompleteModel mirror composer state and forward sends") @MainActor func conversationUIModelMirrorsComposerStateAndForwardsSends() async { let locationManager = makeArchitectureLocationManager() @@ -713,6 +713,7 @@ struct AppArchitectureTests { privateConversationModel: privateConversationModel, conversations: viewModel.conversations ) + let autocompleteModel = ComposerAutocompleteModel(chatViewModel: viewModel) let geohashChannel = ChannelID.location(GeohashChannel(level: .city, geohash: "9q8yy")) defer { locationManager.select(.mesh) @@ -725,15 +726,15 @@ struct AppArchitectureTests { await waitUntil { viewModel.activeChannel == geohashChannel && uiModel.currentNickname == "builder" && - uiModel.showAutocomplete && - uiModel.autocompleteSuggestions == ["alice"] && + autocompleteModel.showAutocomplete && + autocompleteModel.autocompleteSuggestions == ["alice"] && !uiModel.canSendMediaInCurrentContext } #expect(viewModel.activeChannel == geohashChannel) #expect(uiModel.currentNickname == "builder") - #expect(uiModel.showAutocomplete) - #expect(uiModel.autocompleteSuggestions == ["alice"]) + #expect(autocompleteModel.showAutocomplete) + #expect(autocompleteModel.autocompleteSuggestions == ["alice"]) #expect(!uiModel.canSendMediaInCurrentContext) locationChannelsModel.select(ChannelID.mesh) @@ -754,7 +755,7 @@ struct AppArchitectureTests { #expect(transport.sentMessages.last?.content == "hello mesh") } - @Test("ConversationUIModel republishes only changed composer state") + @Test("Autocomplete changes do not invalidate ConversationUIModel and ComposerAutocompleteModel skips duplicates") @MainActor func conversationUIModelSkipsUnchangedComposerState() async { let viewModel = makeArchitectureViewModel() @@ -769,29 +770,121 @@ struct AppArchitectureTests { privateConversationModel: privateConversationModel, conversations: viewModel.conversations ) + let autocompleteModel = ComposerAutocompleteModel(chatViewModel: viewModel) // Bindings deliver on the main queue in FIFO order: once this change // lands, every initial value delivered before it has landed too. viewModel.selectedAutocompleteIndex = 1 - await waitUntil { uiModel.selectedAutocompleteIndex == 1 } + await waitUntil { autocompleteModel.selectedAutocompleteIndex == 1 } - var publishCount = 0 - let cancellable = uiModel.objectWillChange.sink { publishCount += 1 } - defer { cancellable.cancel() } + var uiPublishCount = 0 + let uiCancellable = uiModel.objectWillChange.sink { uiPublishCount += 1 } + defer { uiCancellable.cancel() } + + var autocompletePublishCount = 0 + let autocompleteCancellable = autocompleteModel.objectWillChange.sink { autocompletePublishCount += 1 } + defer { autocompleteCancellable.cancel() } // Re-sent equal values (what every typing pause used to produce) ... viewModel.showAutocomplete = viewModel.showAutocomplete viewModel.autocompleteSuggestions = viewModel.autocompleteSuggestions viewModel.selectedAutocompleteIndex = 1 viewModel.activePublicVoiceTalker = viewModel.activePublicVoiceTalker - // ... are dropped: only the real change queued behind them publishes. + // ... are dropped, and real autocomplete updates only publish on + // ComposerAutocompleteModel — never on ConversationUIModel. + viewModel.autocompleteSuggestions = ["alice", "bob"] + viewModel.showAutocomplete = true viewModel.selectedAutocompleteIndex = 2 - await waitUntil { uiModel.selectedAutocompleteIndex == 2 } + await waitUntil { autocompleteModel.selectedAutocompleteIndex == 2 } - #expect(uiModel.selectedAutocompleteIndex == 2) + #expect(autocompleteModel.selectedAutocompleteIndex == 2) + #expect(autocompletePublishCount == 3) + #expect(uiPublishCount == 0) + } + + @Test("PrivateConversationModel skips redundant publishes when selection and header are unchanged") + @MainActor + func privateConversationModelSkipsUnchangedRefreshes() async { + let viewModel = makeArchitectureViewModel() + let locationChannelsModel = LocationChannelsModel(manager: makeArchitectureLocationManager()) + let privateConversationModel = PrivateConversationModel( + chatViewModel: viewModel, + conversations: viewModel.conversations, + locationChannelsModel: locationChannelsModel + ) + + // Drain initial main-queue Combine deliveries before counting. + try? await Task.sleep(nanoseconds: 50_000_000) + + var publishCount = 0 + let cancellable = privateConversationModel.objectWillChange.sink { publishCount += 1 } + defer { cancellable.cancel() } + + let peerID = PeerID(str: "0011223344556677") + viewModel.allPeers = [ + BitchatPeer( + peerID: peerID, + noisePublicKey: Data(repeating: 0x11, count: 32), + nickname: "alice", + isConnected: true, + isReachable: true + ) + ] + viewModel.peerIdentityStore.setEncryptionStatus(.noiseSecured, for: peerID) + NotificationCenter.default.post(name: Notification.Name("peerStatusUpdated"), object: nil) + try? await Task.sleep(nanoseconds: 50_000_000) + + // No DM is open, so unrelated peer/status refreshes must not publish. + #expect(publishCount == 0) + } + + @Test("PeerIdentityStore skips redundant publishes for unchanged encryption and verification state") + @MainActor + func peerIdentityStoreSkipsNoOpPublishes() { + let store = PeerIdentityStore() + let peerID = PeerID(str: "0011223344556677") + + store.setEncryptionStatus(.noiseSecured, for: peerID) + store.setVerified("fp-1", verified: true) + + var publishCount = 0 + let cancellable = store.objectWillChange.sink { publishCount += 1 } + defer { cancellable.cancel() } + + store.setEncryptionStatus(.noiseSecured, for: peerID) + store.setVerified("fp-1", verified: true) + store.setVerifiedFingerprints(["fp-1"]) + + #expect(publishCount == 0) + + store.setEncryptionStatus(.noiseVerified, for: peerID) #expect(publishCount == 1) } + @Test("ComposerDraftModel manages mentions, sends, and panic reset") + @MainActor + func composerDraftModelBehavior() { + let draftModel = ComposerDraftModel() + draftModel.insertMention("alice") + #expect(draftModel.messageText == "@alice ") + + draftModel.insertMention("bob") + #expect(draftModel.messageText == "@alice @bob ") + + draftModel.replaceText("hello") + draftModel.insertMention("carol") + #expect(draftModel.messageText == "hello @carol ") + + let sent = draftModel.takeMessageToSend() + #expect(sent == "hello @carol") + #expect(draftModel.messageText.isEmpty) + + draftModel.replaceText("secret") + draftModel.resetForPanic() + #expect(draftModel.messageText.isEmpty) + #expect(draftModel.activeDraftKey == .mesh) + } + @Test("VerificationModel bridges selected conversation and fingerprint actions") @MainActor func verificationModelBridgesSelectedConversationAndFingerprintActions() async { diff --git a/bitchatTests/ViewSmokeTests.swift b/bitchatTests/ViewSmokeTests.swift index f12832d0..d8c8ca43 100644 --- a/bitchatTests/ViewSmokeTests.swift +++ b/bitchatTests/ViewSmokeTests.swift @@ -39,9 +39,28 @@ private struct SmokeFeatureModels { let privateConversationModel: PrivateConversationModel let verificationModel: VerificationModel let conversationUIModel: ConversationUIModel + let composerAutocompleteModel: ComposerAutocompleteModel + let composerDraftModel: ComposerDraftModel let peerListModel: PeerListModel let boardAlertsModel: BoardAlertsModel let sharedContentImportModel: SharedContentImportModel + + var environmentModels: AppEnvironmentModels { + AppEnvironmentModels( + publicChatModel: publicChatModel, + privateInboxModel: privateInboxModel, + privateConversationModel: privateConversationModel, + verificationModel: verificationModel, + conversationUIModel: conversationUIModel, + composerAutocompleteModel: composerAutocompleteModel, + composerDraftModel: composerDraftModel, + locationChannelsModel: locationChannelsModel, + peerListModel: peerListModel, + appChromeModel: appChromeModel, + boardAlertsModel: boardAlertsModel, + sharedContentImportModel: sharedContentImportModel + ) + } } @MainActor @@ -77,6 +96,8 @@ private func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatur privateConversationModel: privateConversationModel, conversations: conversations ) + let composerAutocompleteModel = ComposerAutocompleteModel(chatViewModel: viewModel) + let composerDraftModel = ComposerDraftModel() let peerListModel = PeerListModel( chatViewModel: viewModel, conversations: conversations, @@ -99,6 +120,8 @@ private func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatur privateConversationModel: privateConversationModel, verificationModel: verificationModel, conversationUIModel: conversationUIModel, + composerAutocompleteModel: composerAutocompleteModel, + composerDraftModel: composerDraftModel, peerListModel: peerListModel, boardAlertsModel: boardAlertsModel, sharedContentImportModel: SharedContentImportModel(store: nil) @@ -110,30 +133,18 @@ private func installSmokeEnvironment( _ view: V, featureModels: SmokeFeatureModels ) -> some View { - view - .environmentObject(featureModels.publicChatModel) - .environmentObject(featureModels.appChromeModel) - .environmentObject(featureModels.locationChannelsModel) - .environmentObject(featureModels.privateInboxModel) - .environmentObject(featureModels.privateConversationModel) - .environmentObject(featureModels.verificationModel) - .environmentObject(featureModels.conversationUIModel) - .environmentObject(featureModels.peerListModel) - .environmentObject(featureModels.boardAlertsModel) - .environmentObject(featureModels.sharedContentImportModel) + view.installAppEnvironment(featureModels.environmentModels) } @MainActor private struct ContentPeopleSheetHarness: View { + let draftModel: ComposerDraftModel @State private var showSidebar = true - @State private var messageText = "" @State private var selectedMessageSender: String? @State private var selectedMessageSenderID: PeerID? @State private var imagePreviewURL: URL? - @State private var windowCountPublic = 300 @State private var windowCountPrivate: [PeerID: Int] = [:] @State private var isAtBottomPrivate = true - @State private var autocompleteDebounceTimer: Timer? @StateObject private var voiceRecordingVM = VoiceRecordingViewModel() @FocusState private var isTextFieldFocused: Bool #if os(iOS) @@ -147,16 +158,14 @@ private struct ContentPeopleSheetHarness: View { #if os(iOS) ContentPeopleSheetView( showSidebar: $showSidebar, - messageText: $messageText, + draftModel: draftModel, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, windowCountPrivate: $windowCountPrivate, isAtBottomPrivate: $isAtBottomPrivate, isTextFieldFocused: $isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, headerHeight: 44, onSendMessage: {}, showImagePicker: $showImagePicker, @@ -165,16 +174,14 @@ private struct ContentPeopleSheetHarness: View { #else ContentPeopleSheetView( showSidebar: $showSidebar, - messageText: $messageText, + draftModel: draftModel, selectedMessageSender: $selectedMessageSender, selectedMessageSenderID: $selectedMessageSenderID, imagePreviewURL: $imagePreviewURL, - windowCountPublic: $windowCountPublic, windowCountPrivate: $windowCountPrivate, isAtBottomPrivate: $isAtBottomPrivate, isTextFieldFocused: $isTextFieldFocused, voiceRecordingVM: voiceRecordingVM, - autocompleteDebounceTimer: $autocompleteDebounceTimer, headerHeight: 44, onSendMessage: {}, showMacImagePicker: $showMacImagePicker @@ -546,12 +553,12 @@ struct ViewSmokeTests { // set (peerList / publicChat / privateInbox included). Missing any of // those crashes the NavigationStack sheet on some iOS versions (#1558). _ = mount(installSmokeEnvironment(ContentView(), featureModels: featureModels)) - _ = mount(installSmokeEnvironment(ContentPeopleSheetHarness(), featureModels: featureModels)) + _ = mount(installSmokeEnvironment(ContentPeopleSheetHarness(draftModel: featureModels.composerDraftModel), featureModels: featureModels)) featureModels.privateConversationModel.startConversation(with: peerID) try? await Task.sleep(nanoseconds: 50_000_000) - _ = mount(installSmokeEnvironment(ContentPeopleSheetHarness(), featureModels: featureModels)) + _ = mount(installSmokeEnvironment(ContentPeopleSheetHarness(draftModel: featureModels.composerDraftModel), featureModels: featureModels)) #expect(featureModels.privateConversationModel.selectedPeerID == peerID) #expect(featureModels.privateConversationModel.selectedHeaderState?.headerPeerID == peerID)