From 25c331fb90ee2f2f35f9418f7e482c43ec9ad2a7 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:26:26 +0100 Subject: [PATCH 01/12] Make QMS parsing and chat screen crash-safe - Parse QMS chat, list and user responses with Decodable instead of force casts, malformed responses now throw ParsingError - Add ParsingClientTests with QMS parser tests - Don't force unwrap chat and user session in QMSFeature, don't mark chat as read when it failed to load - Reload chat right after sending instead of waiting for socket event - Fix attachment link range for file names with emoji Co-Authored-By: Claude Opus 5.5 --- .../ParsingClient/Parsers/QMS/JSONValue.swift | 86 ++++++++ .../ParsingClient/Parsers/QMSListParser.swift | 143 +++++++------ .../ParsingClient/Parsers/QMSParser.swift | 118 +++++++---- Modules/Sources/QMSFeature/QMSBuilder.swift | 7 +- Modules/Sources/QMSFeature/QMSFeature.swift | 11 +- .../ParsingClientTests/QMSParserTests.swift | 192 ++++++++++++++++++ Project.swift | 19 ++ 7 files changed, 473 insertions(+), 103 deletions(-) create mode 100644 Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift create mode 100644 Modules/Tests/ParsingClientTests/QMSParserTests.swift diff --git a/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift b/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift new file mode 100644 index 00000000..90d5775c --- /dev/null +++ b/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift @@ -0,0 +1,86 @@ +// +// JSONValue.swift +// ParsingClient +// + +import Foundation + +/// Any JSON value, used for parts of positional responses that are parsed by legacy `[Any]` based parsers. +enum JSONValue: Decodable, Equatable, Sendable { + case null + case bool(Bool) + case int(Int) + case double(Double) + case string(String) + case array([JSONValue]) + case object([String: JSONValue]) + + init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else if let value = try? container.decode(Int.self) { + self = .int(value) + } else if let value = try? container.decode(Double.self) { + self = .double(value) + } else if let value = try? container.decode(Bool.self) { + self = .bool(value) + } else if let value = try? container.decode(String.self) { + self = .string(value) + } else if let value = try? container.decode([JSONValue].self) { + self = .array(value) + } else { + self = .object(try container.decode([String: JSONValue].self)) + } + } + + /// Value in the same shape `JSONSerialization` produces. + var anyValue: Any { + switch self { + case .null: return NSNull() + case let .bool(value): return value + case let .int(value): return value + case let .double(value): return value + case let .string(value): return value + case let .array(value): return value.map(\.anyValue) + case let .object(value): return value.mapValues(\.anyValue) + } + } +} + +/// Element of a positional array that is not used. +struct SkippedValue: Decodable { + init(from decoder: any Decoder) throws { + _ = try decoder.singleValueContainer().decode(JSONValue.self) + } +} + +extension UnkeyedDecodingContainer { + mutating func skip(_ count: Int = 1) throws { + for _ in 0.. Date { + Date(timeIntervalSince1970: try decode(TimeInterval.self)) + } + + mutating func decodeURL() throws -> URL? { + (try decodeIfPresent(String.self)).flatMap { URL(string: $0) } + } +} + +extension JSONDecoder { + /// Decodes API response string, wrapping any failure into `ParsingError`. + static func decodeResponse(_ type: T.Type, from string: String) throws -> T { + guard let data = string.data(using: .utf8) else { + throw ParsingError.failedToCreateDataFromString + } + do { + return try JSONDecoder().decode(type, from: data) + } catch { + throw ParsingError.failedToSerializeData(error) + } + } +} diff --git a/Modules/Sources/ParsingClient/Parsers/QMSListParser.swift b/Modules/Sources/ParsingClient/Parsers/QMSListParser.swift index 96d34234..2e3b6ca4 100644 --- a/Modules/Sources/ParsingClient/Parsers/QMSListParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/QMSListParser.swift @@ -10,88 +10,107 @@ import Models public struct QMSUserParser { public static func parse(from string: String) throws -> QMSUser { - let users = try QMSListParser.parseUserRows(from: string) - guard let user = users.first else { + let response = try JSONDecoder.decodeResponse(QMSUsersResponse.self, from: string) + guard let user = response.users.first else { throw ParsingError.failedToCastFields } - return try QMSListParser.parseUser(user, decodeName: false) + return user.makeUser(decodeName: false) } } public struct QMSListParser { public static func parse(from string: String) throws -> QMSList { - let rows = try parseUserRows(from: string) - let users = try rows.map { try parseUser($0, decodeName: true) } - return QMSList(users: users) + let response = try JSONDecoder.decodeResponse(QMSUsersResponse.self, from: string) + return QMSList(users: response.users.map { $0.makeUser(decodeName: true) }) } +} - fileprivate static func parseUserRows(from string: String) throws -> [[Any]] { - guard let data = string.data(using: .utf8) else { - throw ParsingError.failedToCreateDataFromString - } - - let json: Any - do { - json = try JSONSerialization.jsonObject(with: data) - } catch { - throw ParsingError.failedToSerializeData(error) - } +/** + Dialogs list or single user info response + 0. response header + 1. response header + 2. users, see `QMSUserResponse` + */ +struct QMSUsersResponse: Decodable { + let users: [QMSUserResponse] - guard let array = json as? [Any] else { - throw ParsingError.failedToCastDataToAny - } - guard let users = array[safe: 2] as? [[Any]] else { - throw ParsingError.failedToCastFields - } - return users + init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + try container.skip(2) + users = try container.decode([QMSUserResponse].self) } +} - fileprivate static func parseUser(_ user: [Any], decodeName: Bool) throws -> QMSUser { - guard let userId = user[safe: 0] as? Int, - let name = user[safe: 1] as? String, - let flag = user[safe: 2] as? Int, - let avatar = user[safe: 3], - avatar is String || avatar is NSNull, - let lastSeenOnline = user[safe: 4] as? TimeInterval, - let lastMessageDate = user[safe: 5] as? TimeInterval, - let unreadCount = user[safe: 6] as? Int, - let chats = user[safe: 7] as? [[Any]] else { - throw ParsingError.failedToCastFields - } +/** + Dialog partner + 0. user id + 1. name + 2. flag + 3. avatar url, can be null + 4. last seen online date + 5. last message date + 6. unread messages count + 7. dialogs, see `QMSChatInfoResponse` + */ +struct QMSUserResponse: Decodable { + let userId: Int + let name: String + let flag: Int + let avatarUrl: URL? + let lastSeenOnline: Date + let lastMessageDate: Date + let unreadCount: Int + let chats: [QMSChatInfo] + + init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + userId = try container.decode(Int.self) + name = try container.decode(String.self) + flag = try container.decode(Int.self) + avatarUrl = try container.decodeURL() + lastSeenOnline = try container.decodeDate() + lastMessageDate = try container.decodeDate() + unreadCount = try container.decode(Int.self) + chats = try container.decode([QMSChatInfoResponse].self).map(\.chat) + } - return QMSUser( + func makeUser(decodeName: Bool) -> QMSUser { + QMSUser( userId: userId, name: decodeName ? name.convertCodes() : name, flag: flag, - avatarUrl: (avatar as? String).flatMap { URL(string: $0) }, - lastSeenOnline: Date(timeIntervalSince1970: lastSeenOnline), - lastMessageDate: Date(timeIntervalSince1970: lastMessageDate), + avatarUrl: avatarUrl, + lastSeenOnline: lastSeenOnline, + lastMessageDate: lastMessageDate, unreadCount: unreadCount, - chats: try parseChats(chats) + chats: chats ) } +} - public static func parseChats(_ array: [[Any]]) throws -> [QMSChatInfo] { - return try array.map { chat in - guard let id = chat[safe: 0] as? Int, - let creationDate = chat[safe: 1] as? TimeInterval, - let lastMessageDate = chat[safe: 2] as? TimeInterval, - let name = chat[safe: 3] as? String, - let totalCount = chat[safe: 4] as? Int, - let unreadCount = chat[safe: 5] as? Int, - let lastMessageId = chat[safe: 6] as? Int else { - throw ParsingError.failedToCastFields - } +/** + Dialog in list + 0. dialog id + 1. creation date + 2. last message date + 3. name + 4. total messages count + 5. unread messages count + 6. last message id + */ +struct QMSChatInfoResponse: Decodable { + let chat: QMSChatInfo - return QMSChatInfo( - id: id, - creationDate: Date(timeIntervalSince1970: creationDate), - lastMessageDate: Date(timeIntervalSince1970: lastMessageDate), - name: name, - totalCount: totalCount, - unreadCount: unreadCount, - lastMessageId: lastMessageId - ) - } + init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + chat = QMSChatInfo( + id: try container.decode(Int.self), + creationDate: try container.decodeDate(), + lastMessageDate: try container.decodeDate(), + name: try container.decode(String.self), + totalCount: try container.decode(Int.self), + unreadCount: try container.decode(Int.self), + lastMessageId: try container.decode(Int.self) + ) } } diff --git a/Modules/Sources/ParsingClient/Parsers/QMSParser.swift b/Modules/Sources/ParsingClient/Parsers/QMSParser.swift index fe0a4ad7..35ee793d 100644 --- a/Modules/Sources/ParsingClient/Parsers/QMSParser.swift +++ b/Modules/Sources/ParsingClient/Parsers/QMSParser.swift @@ -10,42 +10,90 @@ import Models public struct QMSChatParser { public static func parse(from string: String) throws -> QMSChat { - if let data = string.data(using: .utf8) { - do { - guard let array = try JSONSerialization.jsonObject(with: data, options: []) as? [Any] else { throw ParsingError.failedToCastDataToAny } - return QMSChat( - id: array[2] as! Int, - creationDate: Date(timeIntervalSince1970: array[3] as! TimeInterval), - lastMessageDate: Date(timeIntervalSince1970: array[4] as! TimeInterval), - name: array[5] as! String, - partnerId: array[6] as! Int, - partnerName: array[7] as! String, - flag: array[8] as! Int, - avatarUrl: URL(string: array[9] as! String), - unknownId1: array[10] as! Int, - totalCount: array[11] as! Int, - unknownId2: array[12] as! Int, - lastMessageId: array[13] as! Int, - unreadCount: array[14] as! Int, - messages: parseMessages(array[15] as! [[Any]]) - ) - } catch { - throw ParsingError.failedToSerializeData(error) - } - } else { - throw ParsingError.failedToCreateDataFromString - } + try JSONDecoder.decodeResponse(QMSChatResponse.self, from: string).chat + } +} + +/** + Dialog view response + 0. response header + 1. response header + 2. dialog id + 3. creation date + 4. last message date + 5. dialog name + 6. partner id + 7. partner name + 8. partner flag + 9. partner avatar url + 10. unknown + 11. total messages count + 12. unknown + 13. last message id + 14. unread messages count + 15. messages, see `QMSMessageResponse` + */ +struct QMSChatResponse: Decodable { + let chat: QMSChat + + init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + try container.skip(2) + chat = QMSChat( + id: try container.decode(Int.self), + creationDate: try container.decodeDate(), + lastMessageDate: try container.decodeDate(), + name: try container.decode(String.self), + partnerId: try container.decode(Int.self), + partnerName: try container.decode(String.self), + flag: try container.decode(Int.self), + avatarUrl: try container.decodeURL(), + unknownId1: try container.decode(Int.self), + totalCount: try container.decode(Int.self), + unknownId2: try container.decode(Int.self), + lastMessageId: try container.decode(Int.self), + unreadCount: try container.decode(Int.self), + messages: try container.decode([QMSMessageResponse].self).map(\.message) + ) } - - private static func parseMessages(_ array: [[Any]]) -> [QMSMessage] { - return array.map { message in - return QMSMessage( - id: message[0] as! Int, - senderId: message[1] as! Int, - date: Date(timeIntervalSince1970: message[2] as! TimeInterval), - text: message[3] as! String, - attachments: try! AttachmentParser.parseAttachment(message[4] as! [[Any]]) - ) +} + +/** + Dialog message + 0. message id + 1. sender id + 2. date + 3. text + 4. attachments, same format as forum post attachments + */ +struct QMSMessageResponse: Decodable { + let message: QMSMessage + + init(from decoder: any Decoder) throws { + var container = try decoder.unkeyedContainer() + let id = try container.decode(Int.self) + let senderId = try container.decode(Int.self) + let date = try container.decodeDate() + let text = try container.decode(String.self) + let attachmentsRaw = try container.decode([[JSONValue]].self) + + let attachments: [Attachment] + do { + attachments = try AttachmentParser.parseAttachment(attachmentsRaw.map { $0.map(\.anyValue) }) + } catch { + throw DecodingError.dataCorrupted(.init( + codingPath: container.codingPath, + debugDescription: "Message \(id) has invalid attachments", + underlyingError: error + )) } + + message = QMSMessage( + id: id, + senderId: senderId, + date: date, + text: text, + attachments: attachments + ) } } diff --git a/Modules/Sources/QMSFeature/QMSBuilder.swift b/Modules/Sources/QMSFeature/QMSBuilder.swift index 584dcf74..e08ce67c 100644 --- a/Modules/Sources/QMSFeature/QMSBuilder.swift +++ b/Modules/Sources/QMSFeature/QMSBuilder.swift @@ -40,8 +40,11 @@ public struct QMSBuilder { let linkText = NSMutableAttributedString(string: fileName) let downloadLink = "https://4pda.to/forum/dl/post/\(attachmentID)/\(fileName)" - let downloadUrl = URL(string: downloadLink.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)! - linkText.addAttribute(.link, value: downloadUrl, range: NSRange(location: 0, length: fileName.count)) + if let encodedLink = downloadLink.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), + let downloadUrl = URL(string: encodedLink) { + // NSString length (UTF-16), not Character count, otherwise emoji names go out of range + linkText.addAttribute(.link, value: downloadUrl, range: NSRange(location: 0, length: linkText.length)) + } result.replaceCharacters(in: match.range, with: linkText) } diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index c2671413..895006c4 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -138,6 +138,8 @@ public struct QMSFeature: Reducer, Sendable { return .run { [chatId = state.chatId, message = draftMessage.text] send in try await qmsClient.sendMessage(chatId: chatId, message: message) + // Don't rely on socket event, it may never come for the current chat + await send(.internal(.loadChat)) } catch: { error, send in await send(.internal(.messageSendError(error))) } @@ -210,7 +212,7 @@ public struct QMSFeature: Reducer, Sendable { state.messages = makeLocalMessages( from: mergeResult.messages, chat: mergedChat, - currentUserId: state.userSession!.userId + currentUserId: state.userSession?.userId ?? 0 ) state.chat = mergedChat @@ -228,9 +230,10 @@ public struct QMSFeature: Reducer, Sendable { } analyticsClient.reportFullyDisplayed() - return .run { [userId = state.chat!.partnerId] send in - let ids = (try? result.get().id).map { [$0] } ?? [] - await notificationsClient.removeNotifications(ids: ids) + // Chat is not marked as read if it failed to load + guard case let .success(chat) = result else { return .none } + return .run { [chatId = chat.id, userId = chat.partnerId] send in + await notificationsClient.removeNotifications(ids: [chatId]) await send(.delegate(.fullyRead(userId))) } diff --git a/Modules/Tests/ParsingClientTests/QMSParserTests.swift b/Modules/Tests/ParsingClientTests/QMSParserTests.swift new file mode 100644 index 00000000..f802b9ad --- /dev/null +++ b/Modules/Tests/ParsingClientTests/QMSParserTests.swift @@ -0,0 +1,192 @@ +// +// QMSParserTests.swift +// ParsingClientTests +// + +import CustomDump +import Foundation +import Models +import Testing + +@testable import ParsingClient + +@Suite("QMS parsers") +struct QMSParserTests { + + // MARK: - Chat + + @Test("Chat with messages and attachments") + func chat() throws { + let response = """ + [5, 0, 77, 1700000000, 1700000600, "Dialog", 42, "Partner", 0, "https://4pda.to/a.jpg", 9, 2, 8, 1002, 1, + [ + [1001, 42, 1700000100, "Hello", []], + [1002, 1, 1700000600, "With file", [[300, 1, "pic.jpg", 1024, "https://4pda.to/pic.jpg", 640, 480, 7]]] + ] + ] + """ + + let chat = try QMSChatParser.parse(from: response) + + expectNoDifference(chat, QMSChat( + id: 77, + creationDate: Date(timeIntervalSince1970: 1700000000), + lastMessageDate: Date(timeIntervalSince1970: 1700000600), + name: "Dialog", + partnerId: 42, + partnerName: "Partner", + flag: 0, + avatarUrl: URL(string: "https://4pda.to/a.jpg"), + unknownId1: 9, + totalCount: 2, + unknownId2: 8, + lastMessageId: 1002, + unreadCount: 1, + messages: [ + QMSMessage( + id: 1001, + senderId: 42, + date: Date(timeIntervalSince1970: 1700000100), + text: "Hello", + attachments: [] + ), + QMSMessage( + id: 1002, + senderId: 1, + date: Date(timeIntervalSince1970: 1700000600), + text: "With file", + attachments: [ + Attachment( + id: 300, + type: .image, + name: "pic.jpg", + size: 1024, + metadata: .init(width: 640, height: 480, url: URL(string: "https://4pda.to/pic.jpg")!), + downloadCount: 7 + ) + ] + ) + ] + )) + } + + @Test("Chat with empty or null avatar has no avatar url") + func chatWithoutAvatar() throws { + for avatar in ["\"\"", "null"] { + let response = """ + [5, 0, 77, 1, 2, "Dialog", 42, "Partner", 0, \(avatar), 0, 0, 0, 0, 0, []] + """ + #expect(try QMSChatParser.parse(from: response).avatarUrl == nil) + } + } + + @Test("Trailing unknown fields are ignored") + func chatWithExtraFields() throws { + let response = """ + [5, 0, 77, 1, 2, "Dialog", 42, "Partner", 0, "", 0, 0, 0, 0, 0, [[1, 2, 3, "text", [], "new field"]], {"new": 1}] + """ + let chat = try QMSChatParser.parse(from: response) + #expect(chat.messages.map(\.text) == ["text"]) + } + + @Test("Malformed chat responses throw instead of crashing", arguments: [ + "", + "not json", + "{}", + "[5, 0]", + // Dialog id is a string + #"[5, 0, "77", 1, 2, "Dialog", 42, "Partner", 0, "", 0, 0, 0, 0, 0, []]"#, + // Message without text + #"[5, 0, 77, 1, 2, "Dialog", 42, "Partner", 0, "", 0, 0, 0, 0, 0, [[1, 2, 3]]]"#, + // Unknown attachment type + #"[5, 0, 77, 1, 2, "Dialog", 42, "Partner", 0, "", 0, 0, 0, 0, 0, [[1, 2, 3, "t", [[1, 9, "a", 1]]]]]"#, + ]) + func malformedChat(response: String) { + #expect(throws: ParsingError.self) { + try QMSChatParser.parse(from: response) + } + } + + // MARK: - List + + @Test("List with users and dialogs") + func list() throws { + let response = """ + [3, 0, [ + [42, "Tom & Jerry", 0, null, 1700000000, 1700000600, 2, [ + [77, 1699990000, 1700000600, "Dialog", 10, 2, 1002] + ]], + [43, "Empty", 1, "https://4pda.to/b.jpg", 1, 0, 0, []] + ]] + """ + + let list = try QMSListParser.parse(from: response) + + expectNoDifference(list, QMSList(users: [ + QMSUser( + userId: 42, + name: "Tom & Jerry", + flag: 0, + avatarUrl: nil, + lastSeenOnline: Date(timeIntervalSince1970: 1700000000), + lastMessageDate: Date(timeIntervalSince1970: 1700000600), + unreadCount: 2, + chats: [ + QMSChatInfo( + id: 77, + creationDate: Date(timeIntervalSince1970: 1699990000), + lastMessageDate: Date(timeIntervalSince1970: 1700000600), + name: "Dialog", + totalCount: 10, + unreadCount: 2, + lastMessageId: 1002 + ) + ] + ), + QMSUser( + userId: 43, + name: "Empty", + flag: 1, + avatarUrl: URL(string: "https://4pda.to/b.jpg"), + lastSeenOnline: Date(timeIntervalSince1970: 1), + lastMessageDate: Date(timeIntervalSince1970: 0), + unreadCount: 0, + chats: [] + ) + ])) + } + + @Test("Empty list") + func emptyList() throws { + #expect(try QMSListParser.parse(from: "[3, 0, []]").users.isEmpty) + } + + @Test("Malformed list responses throw instead of crashing", arguments: [ + "[3, 0]", + "[3, 0, {}]", + #"[3, 0, [[42, "Name", 0, null, 1, 2, 3]]]"#, + #"[3, 0, [[42, "Name", 0, null, 1, 2, 3, [[77, 1, 2, "Dialog", 10, 2]]]]]"#, + ]) + func malformedList(response: String) { + #expect(throws: ParsingError.self) { + try QMSListParser.parse(from: response) + } + } + + // MARK: - User + + @Test("User info keeps name as is") + func user() throws { + let response = #"[3, 0, [[42, "Tom & Jerry", 0, null, 1, 2, 0, []]]]"# + let user = try QMSUserParser.parse(from: response) + #expect(user.id == 42) + #expect(user.name == "Tom & Jerry") + } + + @Test("User info without users throws") + func userMissing() { + #expect(throws: ParsingError.self) { + try QMSUserParser.parse(from: "[3, 0, []]") + } + } +} diff --git a/Project.swift b/Project.swift index 785371eb..948983ad 100644 --- a/Project.swift +++ b/Project.swift @@ -934,6 +934,25 @@ let project = Project( defaultSettings: .recommended ) ), + + .target( + name: "ParsingClientTests", + destinations: App.destinations, + product: .unitTests, + bundleId: App.bundleId + ".ParsingClient.Tests", + deploymentTargets: App.deploymentTargets, + infoPlist: .default, + sources: ["Modules/Tests/ParsingClientTests/**"], + dependencies: [ + .Internal.Models, + .Internal.ParsingClient, + .SPM.CustomDump, + ], + settings: .settings( + base: .targetSettings, + defaultSettings: .recommended + ) + ), // .target( // name: "ForPDATests", From ccf68f256d70e3978dd1a4f7870dc8347a363fd0 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:34:03 +0100 Subject: [PATCH 02/12] Add QMSStore as single source of truth for QMS dialogs - QMSStore actor keeps dialog snapshots in memory and on disk (Caches/QMS//.json, last 300 messages), so a dialog opens instantly from cache and refreshes in background - Pages are merged by message id; a full latest page after a gap drops stale messages instead of showing a hole - Concurrent syncs of a dialog (socket events, scene activation, send) are coalesced into at most one extra request; older pages are loaded once - QMSFeature observes the store instead of merging pages itself; long running effects are cancellable so repeated onAppear doesn't duplicate them - Failed background refresh of a shown chat no longer shows an alert - QMS cache is removed on logout and on cache clearing - Add QMSClientTests for merge, store and file cache Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/AppFeature/AppFeature.swift | 3 + .../Sources/QMSClient/QMSDialogCache.swift | 116 ++++++++ .../Sources/QMSClient/QMSDialogMerge.swift | 59 ++++ Modules/Sources/QMSClient/QMSStore.swift | 205 ++++++++++++++ Modules/Sources/QMSFeature/QMSFeature.swift | 168 +++++------ .../SettingsFeature/SettingsFeature.swift | 3 + .../Tests/QMSClientTests/QMSStoreTests.swift | 267 ++++++++++++++++++ Project.swift | 21 ++ 8 files changed, 740 insertions(+), 102 deletions(-) create mode 100644 Modules/Sources/QMSClient/QMSDialogCache.swift create mode 100644 Modules/Sources/QMSClient/QMSDialogMerge.swift create mode 100644 Modules/Sources/QMSClient/QMSStore.swift create mode 100644 Modules/Tests/QMSClientTests/QMSStoreTests.swift diff --git a/Modules/Sources/AppFeature/AppFeature.swift b/Modules/Sources/AppFeature/AppFeature.swift index f2325464..2d23e1b4 100644 --- a/Modules/Sources/AppFeature/AppFeature.swift +++ b/Modules/Sources/AppFeature/AppFeature.swift @@ -36,6 +36,7 @@ import ToastClient import Combine import SearchResultFeature import CacheClient +import QMSClient import DeviceSpecificationsFeature import DeviceTypeFeature import MoreFeature @@ -176,6 +177,7 @@ public struct AppFeature: Reducer, Sendable { @Dependency(\.logger[.app]) private var logger @Dependency(\.apiClient) private var apiClient @Dependency(\.cacheClient) private var cacheClient + @Dependency(\.qmsStore) private var qmsStore @Dependency(\.toastClient) private var toastClient @Dependency(\.hapticClient) private var hapticClient @Dependency(\.analyticsClient) private var analyticsClient @@ -403,6 +405,7 @@ public struct AppFeature: Reducer, Sendable { state.favoritesBadges = 0 state.profileBadges = 0 return .run { _ in + await qmsStore.removeAll() notificationsClient.setNotificationContext(context: nil) await notificationsClient.removeNotifications( categories: [.qmsMessage, .newTopic, .newPost, .forumMention, .siteMention] diff --git a/Modules/Sources/QMSClient/QMSDialogCache.swift b/Modules/Sources/QMSClient/QMSDialogCache.swift new file mode 100644 index 00000000..ac3ca2ad --- /dev/null +++ b/Modules/Sources/QMSClient/QMSDialogCache.swift @@ -0,0 +1,116 @@ +// +// QMSDialogCache.swift +// QMSClient +// + +import Dependencies +import Foundation +import Models +import PersistenceKeys +import ComposableArchitecture + +/// Disk storage of dialog snapshots, one file per dialog in a folder of the current user. +public struct QMSDialogCache: Sendable { + public var load: @Sendable (_ dialogId: Int) async -> QMSDialogSnapshot? + public var save: @Sendable (_ snapshot: QMSDialogSnapshot) async -> Void + public var removeAll: @Sendable () async -> Void + + public init( + load: @escaping @Sendable (_ dialogId: Int) async -> QMSDialogSnapshot?, + save: @escaping @Sendable (_ snapshot: QMSDialogSnapshot) async -> Void, + removeAll: @escaping @Sendable () async -> Void + ) { + self.load = load + self.save = save + self.removeAll = removeAll + } +} + +extension QMSDialogCache { + + /// How many newest messages of a dialog are kept on disk + static let maxStoredMessages = 300 + + public static var liveValue: QMSDialogCache { + let root = URL.cachesDirectory.appending(path: "QMS", directoryHint: .isDirectory) + return files(root: root) { + @Shared(.userSession) var userSession + return userSession?.userId + } + } + + /// - Parameter userId: current user, nothing is read or written without it + static func files(root: URL, userId: @escaping @Sendable () -> Int?) -> QMSDialogCache { + let storage = FileStorage(root: root) + return QMSDialogCache( + load: { dialogId in + guard let userId = userId() else { return nil } + return await storage.load(userId: userId, dialogId: dialogId) + }, + save: { snapshot in + guard let userId = userId() else { return } + var trimmed = snapshot + if trimmed.chat.messages.count > maxStoredMessages { + trimmed.chat.messages = Array(trimmed.chat.messages.suffix(maxStoredMessages)) + trimmed.hasMoreOlder = true + } + await storage.save(trimmed, userId: userId) + }, + removeAll: { + await storage.removeAll() + } + ) + } + + public static var inMemory: QMSDialogCache { + let storage = LockIsolated<[Int: QMSDialogSnapshot]>([:]) + return QMSDialogCache( + load: { id in storage.value[id] }, + save: { snapshot in storage.withValue { $0[snapshot.chat.id] = snapshot } }, + removeAll: { storage.setValue([:]) } + ) + } +} + +/// Serializes disk access so writes of the same dialog never interleave. +private actor FileStorage { + let root: URL + + init(root: URL) { + self.root = root + } + + func load(userId: Int, dialogId: Int) -> QMSDialogSnapshot? { + let url = fileURL(userId: userId, dialogId: dialogId) + guard let data = try? Data(contentsOf: url) else { return nil } + guard let snapshot = try? JSONDecoder().decode(QMSDialogSnapshot.self, from: data) else { + // Outdated format or broken file, it will be rewritten on next sync + try? FileManager.default.removeItem(at: url) + return nil + } + return snapshot + } + + func save(_ snapshot: QMSDialogSnapshot, userId: Int) { + let url = fileURL(userId: userId, dialogId: snapshot.chat.id) + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try JSONEncoder().encode(snapshot).write(to: url, options: .atomic) + } catch { + // Cache is optional, the dialog is loaded from network anyway + } + } + + func removeAll() { + try? FileManager.default.removeItem(at: root) + } + + private func fileURL(userId: Int, dialogId: Int) -> URL { + root + .appending(path: String(userId), directoryHint: .isDirectory) + .appending(path: "\(dialogId).json", directoryHint: .notDirectory) + } +} diff --git a/Modules/Sources/QMSClient/QMSDialogMerge.swift b/Modules/Sources/QMSClient/QMSDialogMerge.swift new file mode 100644 index 00000000..e8a34be4 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSDialogMerge.swift @@ -0,0 +1,59 @@ +// +// QMSDialogMerge.swift +// QMSClient +// + +import Foundation +import Models + +/// Pure merge logic of a dialog page into already known messages. +enum QMSDialogMerge { + + enum PageKind: Equatable, Sendable { + /// Newest messages of the dialog + case latest + /// Messages older than the oldest known message + case older + } + + struct Result: Equatable { + /// Messages sorted from oldest to newest, unique by id + let messages: [QMSMessage] + /// Count of messages from the page that were not known before + let newCount: Int + } + + /// - Parameters: + /// - pageSize: requested page size, used to detect a gap between known messages and the latest page + static func merge( + existing: [QMSMessage], + page: [QMSMessage], + kind: PageKind, + pageSize: Int + ) -> Result { + var base = existing + + // Latest page is full and doesn't touch known messages, so there may be + // unknown messages in between. Drop known ones to never show a hole. + if kind == .latest, + page.count >= pageSize, + let oldestInPage = page.map(\.id).min(), + let newestKnown = existing.map(\.id).max(), + oldestInPage > newestKnown { + base = [] + } + + var byId = Dictionary(base.map { ($0.id, $0) }, uniquingKeysWith: { _, new in new }) + var newCount = 0 + for message in page { + if byId.updateValue(message, forKey: message.id) == nil { + newCount += 1 + } + } + + let messages = byId.values.sorted { + $0.date == $1.date ? $0.id < $1.id : $0.date < $1.date + } + return Result(messages: messages, newCount: newCount) + } +} diff --git a/Modules/Sources/QMSClient/QMSStore.swift b/Modules/Sources/QMSClient/QMSStore.swift new file mode 100644 index 00000000..10151314 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSStore.swift @@ -0,0 +1,205 @@ +// +// QMSStore.swift +// QMSClient +// + +import Dependencies +import Foundation +import Models + +/// State of a single dialog as the store knows it. +public struct QMSDialogSnapshot: Equatable, Sendable, Codable { + /// Dialog info with merged messages sorted from oldest to newest + public var chat: QMSChat + /// There are messages older than the oldest loaded one + public var hasMoreOlder: Bool + + public init(chat: QMSChat, hasMoreOlder: Bool) { + self.chat = chat + self.hasMoreOlder = hasMoreOlder + } +} + +/// Single source of truth for QMS dialogs. +/// +/// - Shows cached dialog instantly and refreshes it in background +/// - Merges pages by message id instead of replacing everything +/// - Coalesces sync requests: any number of triggers during a running sync +/// (socket events, scene activation, pull to refresh) lead to at most one extra request +public actor QMSStore { + + public typealias LoadChat = @Sendable (_ id: Int, _ lastMessageId: Int, _ offset: Int) async throws -> QMSChat + + private let loadChat: LoadChat + private let cache: QMSDialogCache + private let pageSize: Int + + private var snapshots: [Int: QMSDialogSnapshot] = [:] + private var observers: [Int: [UUID: AsyncStream.Continuation]] = [:] + + private var syncTasks: [Int: Task] = [:] + private var pendingSync: Set = [] + private var olderTasks: [Int: Task] = [:] + + public init(loadChat: @escaping LoadChat, cache: QMSDialogCache, pageSize: Int = 30) { + self.loadChat = loadChat + self.cache = cache + self.pageSize = pageSize + } + + // MARK: - Observe + + /// Stream of dialog snapshots. Yields known (in memory or cached) snapshot right away. + /// Doesn't load anything by itself, call `sync(dialogId:)` for that. + public func observe(dialogId: Int) async -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream( + of: QMSDialogSnapshot.self, + bufferingPolicy: .bufferingNewest(1) + ) + let token = UUID() + observers[dialogId, default: [:]][token] = continuation + continuation.onTermination = { [weak self] _ in + Task { await self?.removeObserver(dialogId: dialogId, token: token) } + } + + if snapshots[dialogId] == nil, let cached = await cache.load(dialogId) { + // Could be filled by sync while cache was loading + if snapshots[dialogId] == nil { + snapshots[dialogId] = cached + } + } + if let snapshot = snapshots[dialogId] { + continuation.yield(snapshot) + } + return stream + } + + public func snapshot(dialogId: Int) -> QMSDialogSnapshot? { + snapshots[dialogId] + } + + // MARK: - Sync + + /// Loads the newest messages of the dialog and merges them in. + /// If a sync of this dialog is already running, waits for it and makes sure one more request happens after it. + public func sync(dialogId: Int) async throws { + if let running = syncTasks[dialogId] { + pendingSync.insert(dialogId) + try await running.value + return + } + let task = Task { try await self.runSync(dialogId: dialogId) } + syncTasks[dialogId] = task + try await task.value + } + + private func runSync(dialogId: Int) async throws { + // Runs synchronously on exit, so no caller can join a finished task + defer { + syncTasks[dialogId] = nil + pendingSync.remove(dialogId) + } + repeat { + pendingSync.remove(dialogId) + let chat = try await loadChat(dialogId, 0, -pageSize) + await apply(chat, kind: .latest) + } while pendingSync.contains(dialogId) + } + + // MARK: - Older + + /// Loads a page of messages older than the oldest known one. Repeated calls while loading are ignored. + public func loadOlder(dialogId: Int) async throws { + if let running = olderTasks[dialogId] { + try await running.value + return + } + guard let snapshot = snapshots[dialogId], snapshot.hasMoreOlder, + let oldestId = snapshot.chat.messages.first?.id else { return } + + let task = Task { + defer { self.olderTasks[dialogId] = nil } + let chat = try await self.loadChat(dialogId, oldestId, -self.pageSize) + await self.apply(chat, kind: .older) + } + olderTasks[dialogId] = task + try await task.value + } + + // MARK: - Remove + + /// Drops everything, e.g. on logout or cache clearing. + public func removeAll() async { + snapshots = [:] + await cache.removeAll() + } + + // MARK: - Private + + private func apply(_ chat: QMSChat, kind: QMSDialogMerge.PageKind) async { + let existing = snapshots[chat.id] + let merge = QMSDialogMerge.merge( + existing: existing?.chat.messages ?? [], + page: chat.messages, + kind: kind, + pageSize: pageSize + ) + + let hasMoreOlder: Bool + if merge.messages.count >= chat.totalCount { + hasMoreOlder = false + } else if kind == .older { + // Server returned nothing new, stop paginating to avoid endless requests + hasMoreOlder = merge.newCount > 0 + } else { + hasMoreOlder = true + } + + var mergedChat = chat + mergedChat.messages = merge.messages + let snapshot = QMSDialogSnapshot(chat: mergedChat, hasMoreOlder: hasMoreOlder) + guard snapshot != existing else { return } + + snapshots[chat.id] = snapshot + for continuation in observers[chat.id, default: [:]].values { + continuation.yield(snapshot) + } + await cache.save(snapshot) + } + + private func removeObserver(dialogId: Int, token: UUID) { + observers[dialogId]?[token] = nil + if observers[dialogId]?.isEmpty == true { + observers[dialogId] = nil + } + } +} + +// MARK: - Dependency + +extension QMSStore: DependencyKey { + public static var liveValue: QMSStore { + @Dependency(\.qmsClient) var qmsClient + return QMSStore( + loadChat: { try await qmsClient.loadChat($0, $1, $2) }, + cache: .liveValue + ) + } + + public static var testValue: QMSStore { + @Dependency(\.qmsClient) var qmsClient + return QMSStore( + loadChat: { try await qmsClient.loadChat($0, $1, $2) }, + cache: .inMemory + ) + } + + public static var previewValue: QMSStore { testValue } +} + +extension DependencyValues { + public var qmsStore: QMSStore { + get { self[QMSStore.self] } + set { self[QMSStore.self] = newValue } + } +} diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index 895006c4..0140ad05 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -21,13 +21,9 @@ public struct QMSFeature: Reducer, Sendable { public init() {} - let defaultOffset = -30 - - // MARK: - Enums - - public enum LoadKind { - case latest // initial/refresh - case older // pagination + private enum CancelID: Hashable { + case observe + case triggers } // MARK: - State @@ -83,8 +79,10 @@ public struct QMSFeature: Reducer, Sendable { case `internal`(Internal) public enum Internal { - case loadChat - case chatLoaded(Result, LoadKind) + case sync + case syncFinished(Result) + case olderLoaded(Result) + case snapshotUpdated(QMSDialogSnapshot) case messageSendError(any Error) } @@ -98,6 +96,7 @@ public struct QMSFeature: Reducer, Sendable { // MARK: - Dependencies @Dependency(\.qmsClient) private var qmsClient + @Dependency(\.qmsStore) private var qmsStore @Dependency(\.analyticsClient) private var analyticsClient @Dependency(\.notificationCenter) private var notificationCenter @Dependency(\.notificationsClient) private var notificationsClient @@ -113,20 +112,32 @@ public struct QMSFeature: Reducer, Sendable { return .none case .view(.onAppear): + // onAppear fires again when returning from pushed screens, so long-running effects are restarted, not duplicated return .merge([ - .send(.internal(.loadChat)), - .run { send in - for await _ in notificationCenter.notifications(named: .sceneBecomeActive) { - await send(.internal(.loadChat)) + .run { [id = state.chatId] send in + for await snapshot in await qmsStore.observe(dialogId: id) { + await send(.internal(.snapshotUpdated(snapshot))) } - }, - .run { [chatId = state.chatId] send in - for await notification in notificationsClient.eventPublisher().values { - if case let .qms(id) = notification, chatId == id { - await send(.internal(.loadChat)) + } + .cancellable(id: CancelID.observe, cancelInFlight: true), + + .send(.internal(.sync)), + + .merge( + .run { send in + for await _ in notificationCenter.notifications(named: .sceneBecomeActive) { + await send(.internal(.sync)) + } + }, + .run { [chatId = state.chatId] send in + for await notification in notificationsClient.eventPublisher().values { + if case let .qms(id) = notification, chatId == id { + await send(.internal(.sync)) + } } } - } + ) + .cancellable(id: CancelID.triggers, cancelInFlight: true) ]) case let .view(.sendMessageButtonTapped(draftMessage)): @@ -139,20 +150,17 @@ public struct QMSFeature: Reducer, Sendable { return .run { [chatId = state.chatId, message = draftMessage.text] send in try await qmsClient.sendMessage(chatId: chatId, message: message) // Don't rely on socket event, it may never come for the current chat - await send(.internal(.loadChat)) + await send(.internal(.sync)) } catch: { error, send in await send(.internal(.messageSendError(error))) } case .view(.loadMoreTriggered): - guard !state.isLoadingMore else { return .none } - guard state.hasMoreOlderMessages else { return .none } - guard (state.chat?.totalCount ?? defaultOffset) > abs(defaultOffset) else { return .none } + guard !state.isLoadingMore, state.hasMoreOlderMessages else { return .none } state.isLoadingMore = true - return .run { [id = state.chatId, chat = state.chat] send in - let lastMessageId = chat?.messages.first?.id ?? 0 - let result = await Result { try await qmsClient.loadChat(id, lastMessageId, defaultOffset) } - await send(.internal(.chatLoaded(result, .older))) + return .run { [id = state.chatId] send in + let result = await Result { try await qmsStore.loadOlder(dialogId: id) } + await send(.internal(.olderLoaded(result))) } case let .internal(.messageSendError(error)): @@ -186,56 +194,47 @@ public struct QMSFeature: Reducer, Sendable { await send(.delegate(.handleUrl(url))) } - case .internal(.loadChat): + case .internal(.sync): return .run { [id = state.chatId] send in - let result = await Result { try await qmsClient.loadChat(id, 0, defaultOffset) } - await send(.internal(.chatLoaded(result, .latest))) + let result = await Result { try await qmsStore.sync(dialogId: id) } + await send(.internal(.syncFinished(result))) + + // Chat is not marked as read if it failed to load + guard case .success = result, let snapshot = await qmsStore.snapshot(dialogId: id) else { return } + await notificationsClient.removeNotifications(ids: [id]) + await send(.delegate(.fullyRead(snapshot.chat.partnerId))) } - case let .internal(.chatLoaded(result, loadKind)): + case let .internal(.syncFinished(result)): state.draftSnapshot = "" state.isSending = false - state.isLoadingMore = false - switch result { - case let .success(chat): - let existingRemote = state.chat?.messages ?? [] - let mergeResult = mergeRemoteMessages( - existing: existingRemote, - incoming: chat.messages, - loadKind: loadKind - ) - - var mergedChat = chat - mergedChat.messages = mergeResult.messages - - state.messages = makeLocalMessages( - from: mergeResult.messages, - chat: mergedChat, - currentUserId: state.userSession?.userId ?? 0 - ) - state.chat = mergedChat - - if mergeResult.messages.count >= chat.totalCount { - state.hasMoreOlderMessages = false - } else if loadKind == .older, mergeResult.uniqueIncomingCount == 0 { - state.hasMoreOlderMessages = false - } else { - state.hasMoreOlderMessages = true - } - - case let .failure(error): + if case let .failure(error) = result { analyticsClient.capture(error) - state.alert = .somethingWentWrong + // Failed background refresh of a shown chat is not worth an alert + if state.chat == nil { + state.alert = .somethingWentWrong + } } - analyticsClient.reportFullyDisplayed() - // Chat is not marked as read if it failed to load - guard case let .success(chat) = result else { return .none } - return .run { [chatId = chat.id, userId = chat.partnerId] send in - await notificationsClient.removeNotifications(ids: [chatId]) - await send(.delegate(.fullyRead(userId))) + return .none + + case let .internal(.olderLoaded(result)): + state.isLoadingMore = false + if case let .failure(error) = result { + analyticsClient.capture(error) } + return .none + + case let .internal(.snapshotUpdated(snapshot)): + state.chat = snapshot.chat + state.hasMoreOlderMessages = snapshot.hasMoreOlder + state.messages = makeLocalMessages( + from: snapshot.chat.messages, + chat: snapshot.chat, + currentUserId: state.userSession?.userId ?? 0 + ) + return .none case .binding: return .none @@ -249,41 +248,6 @@ public struct QMSFeature: Reducer, Sendable { // MARK: - Shared Logic - private struct RemoteMergeResult { - let messages: [QMSMessage] - let uniqueIncomingCount: Int - } - - private func mergeRemoteMessages( - existing: [QMSMessage], - incoming: [QMSMessage], - loadKind _: LoadKind - ) -> RemoteMergeResult { - let existingIds = Set(existing.map(\.id)) - var seenIncomingIds = Set() - var uniqueIncomingCount = 0 - - for message in incoming { - if !existingIds.contains(message.id), seenIncomingIds.insert(message.id).inserted { - uniqueIncomingCount += 1 - } - } - - var messagesById = Dictionary(uniqueKeysWithValues: existing.map { ($0.id, $0) }) - for message in incoming { - messagesById[message.id] = message - } - - let mergedMessages = messagesById.values.sorted { - if $0.date == $1.date { - return $0.id < $1.id - } - return $0.date < $1.date - } - - return RemoteMergeResult(messages: mergedMessages, uniqueIncomingCount: uniqueIncomingCount) - } - private func makeLocalMessages( from remoteMessages: [QMSMessage], chat: QMSChat, diff --git a/Modules/Sources/SettingsFeature/SettingsFeature.swift b/Modules/Sources/SettingsFeature/SettingsFeature.swift index ee20395b..9bb2d963 100644 --- a/Modules/Sources/SettingsFeature/SettingsFeature.swift +++ b/Modules/Sources/SettingsFeature/SettingsFeature.swift @@ -9,6 +9,7 @@ import UIKit import ComposableArchitecture import PasteboardClient import CacheClient +import QMSClient import TCAExtensions import PersistenceKeys import Models @@ -121,6 +122,7 @@ public struct SettingsFeature: Reducer, Sendable { @Dependency(\.pasteboardClient) var pasteboardClient @Dependency(\.analyticsClient) var analyticsClient @Dependency(\.cacheClient) var cacheClient + @Dependency(\.qmsStore) var qmsStore @Dependency(\.openURL) var openURL // MARK: - Body @@ -183,6 +185,7 @@ public struct SettingsFeature: Reducer, Sendable { return .run { send in do { try await cacheClient.removeAll() + await qmsStore.removeAll() } catch { await send(._somethingWentWrong(error)) } diff --git a/Modules/Tests/QMSClientTests/QMSStoreTests.swift b/Modules/Tests/QMSClientTests/QMSStoreTests.swift new file mode 100644 index 00000000..ea9f8d67 --- /dev/null +++ b/Modules/Tests/QMSClientTests/QMSStoreTests.swift @@ -0,0 +1,267 @@ +// +// QMSStoreTests.swift +// QMSClientTests +// + +import ConcurrencyExtras +import Foundation +import Models +import Testing + +@testable import QMSClient + +// MARK: - Helpers + +private func message(_ id: Int, date: TimeInterval? = nil) -> QMSMessage { + QMSMessage(id: id, senderId: 1, date: Date(timeIntervalSince1970: date ?? TimeInterval(id)), text: "\(id)", attachments: []) +} + +private func chat(id: Int = 7, total: Int, messages: [Int]) -> QMSChat { + QMSChat( + id: id, creationDate: .distantPast, lastMessageDate: .distantPast, name: "Dialog", + partnerId: 42, partnerName: "Partner", flag: 0, avatarUrl: nil, unknownId1: 0, + totalCount: total, unknownId2: 0, lastMessageId: messages.max() ?? 0, unreadCount: 0, + messages: messages.map { message($0) } + ) +} + +/// Request made by the store: last message id and offset +private struct Request: Equatable { + let lastMessageId: Int + let offset: Int +} + +// MARK: - Merge + +@Suite("QMS dialog merge") +struct QMSDialogMergeTests { + + @Test("Latest page is merged by id and sorted") + func latest() { + let result = QMSDialogMerge.merge( + existing: [1, 2, 3].map { message($0) }, + page: [3, 4, 2].map { message($0) }, + kind: .latest, + pageSize: 30 + ) + #expect(result.messages.map(\.id) == [1, 2, 3, 4]) + #expect(result.newCount == 1) + } + + @Test("Updated message replaces the known one") + func update() { + var edited = message(2) + edited = QMSMessage(id: 2, senderId: 1, date: edited.date, text: "edited", attachments: []) + let result = QMSDialogMerge.merge(existing: [1, 2].map { message($0) }, page: [edited], kind: .latest, pageSize: 30) + #expect(result.messages.map(\.text) == ["1", "edited"]) + #expect(result.newCount == 0) + } + + @Test("Full latest page after a gap drops known messages") + func gap() { + let result = QMSDialogMerge.merge( + existing: [1, 2].map { message($0) }, + page: [10, 11, 12].map { message($0) }, + kind: .latest, + pageSize: 3 + ) + #expect(result.messages.map(\.id) == [10, 11, 12]) + } + + @Test("Not full latest page keeps known messages") + func noGap() { + let result = QMSDialogMerge.merge( + existing: [1, 2].map { message($0) }, + page: [10, 11].map { message($0) }, + kind: .latest, + pageSize: 3 + ) + #expect(result.messages.map(\.id) == [1, 2, 10, 11]) + } + + @Test("Older page is prepended") + func older() { + let result = QMSDialogMerge.merge( + existing: [10, 11].map { message($0) }, + page: [7, 8, 9].map { message($0) }, + kind: .older, + pageSize: 3 + ) + #expect(result.messages.map(\.id) == [7, 8, 9, 10, 11]) + #expect(result.newCount == 3) + } +} + +// MARK: - Store + +@Suite("QMS store") +struct QMSStoreTests { + + @Test("Sync publishes merged snapshot and caches it") + func sync() async throws { + let cache = QMSDialogCache.inMemory + let store = QMSStore(loadChat: { id, _, _ in chat(id: id, total: 2, messages: [1, 2]) }, cache: cache) + + let stream = await store.observe(dialogId: 7) + try await store.sync(dialogId: 7) + + var iterator = stream.makeAsyncIterator() + let snapshot = try #require(await iterator.next()) + #expect(snapshot.chat.messages.map(\.id) == [1, 2]) + #expect(snapshot.hasMoreOlder == false) + #expect(await cache.load(7) == snapshot) + } + + @Test("Cached snapshot is shown before network") + func cachedFirst() async throws { + let cache = QMSDialogCache.inMemory + let cached = QMSDialogSnapshot(chat: chat(total: 5, messages: [1, 2]), hasMoreOlder: true) + await cache.save(cached) + let store = QMSStore(loadChat: { _, _, _ in throw CancellationError() }, cache: cache) + + var iterator = await store.observe(dialogId: 7).makeAsyncIterator() + #expect(await iterator.next() == cached) + } + + @Test("Syncs during a running sync are coalesced into one extra request") + func coalescing() async throws { + let requests = LockIsolated(0) + let (gate, gateContinuation) = AsyncStream.makeStream(of: Void.self) + + let store = QMSStore( + loadChat: { id, _, _ in + let number = requests.withValue { $0 += 1; return $0 } + if number == 1 { + // Hold the first request until other syncs are queued + for await _ in gate { break } + } + return chat(id: id, total: 1, messages: [number]) + }, + cache: .inMemory + ) + + let first = Task { try await store.sync(dialogId: 7) } + while requests.value == 0 { await Task.yield() } + + let others = (0..<5).map { _ in Task { try await store.sync(dialogId: 7) } } + // Let all of them reach the store before releasing the first request + for _ in 0..<200 { await Task.yield() } + gateContinuation.yield() + + try await first.value + for task in others { try await task.value } + + #expect(requests.value == 2) + #expect(await store.snapshot(dialogId: 7)?.chat.messages.map(\.id) == [1, 2]) + } + + @Test("Older page uses the oldest known message and stops when nothing new") + func loadOlder() async throws { + let requests = LockIsolated<[Request]>([]) + let store = QMSStore( + loadChat: { id, lastMessageId, offset in + requests.withValue { $0.append(Request(lastMessageId: lastMessageId, offset: offset)) } + switch lastMessageId { + case 0: return chat(id: id, total: 10, messages: [5, 6]) + case 5: return chat(id: id, total: 10, messages: [3, 4]) + default: return chat(id: id, total: 10, messages: [3]) + } + }, + cache: .inMemory, + pageSize: 2 + ) + + try await store.sync(dialogId: 7) + try await store.loadOlder(dialogId: 7) + #expect(await store.snapshot(dialogId: 7)?.chat.messages.map(\.id) == [3, 4, 5, 6]) + #expect(await store.snapshot(dialogId: 7)?.hasMoreOlder == true) + + try await store.loadOlder(dialogId: 7) + #expect(await store.snapshot(dialogId: 7)?.hasMoreOlder == false) + + // No more requests once there is nothing older + try await store.loadOlder(dialogId: 7) + + #expect(requests.value == [ + Request(lastMessageId: 0, offset: -2), + Request(lastMessageId: 5, offset: -2), + Request(lastMessageId: 3, offset: -2), + ]) + } + + @Test("Failed sync throws and keeps the store usable") + func failure() async throws { + let shouldFail = LockIsolated(true) + let store = QMSStore( + loadChat: { id, _, _ in + if shouldFail.value { throw URLError(.notConnectedToInternet) } + return chat(id: id, total: 1, messages: [1]) + }, + cache: .inMemory + ) + + await #expect(throws: URLError.self) { try await store.sync(dialogId: 7) } + + shouldFail.setValue(false) + try await store.sync(dialogId: 7) + #expect(await store.snapshot(dialogId: 7)?.chat.messages.map(\.id) == [1]) + } + + @Test("Remove all drops memory and cache") + func removeAll() async throws { + let cache = QMSDialogCache.inMemory + let store = QMSStore(loadChat: { id, _, _ in chat(id: id, total: 1, messages: [1]) }, cache: cache) + try await store.sync(dialogId: 7) + + await store.removeAll() + + #expect(await store.snapshot(dialogId: 7) == nil) + #expect(await cache.load(7) == nil) + } +} + +// MARK: - File cache + +@Suite("QMS dialog file cache") +struct QMSDialogFileCacheTests { + + let root = URL.temporaryDirectory.appending(path: "QMSCacheTests-\(UUID().uuidString)") + + @Test("Snapshots are stored per user and trimmed") + func roundTrip() async throws { + let userId = LockIsolated(1) + let cache = QMSDialogCache.files(root: root, userId: { userId.value }) + defer { try? FileManager.default.removeItem(at: root) } + + let count = QMSDialogCache.maxStoredMessages + 10 + let snapshot = QMSDialogSnapshot(chat: chat(total: count, messages: Array(1...count)), hasMoreOlder: false) + await cache.save(snapshot) + + let loaded = try #require(await cache.load(7)) + #expect(loaded.chat.messages.count == QMSDialogCache.maxStoredMessages) + #expect(loaded.chat.messages.last?.id == count) + #expect(loaded.hasMoreOlder == true) + + userId.setValue(2) + #expect(await cache.load(7) == nil) + + userId.setValue(nil) + #expect(await cache.load(7) == nil) + + userId.setValue(1) + await cache.removeAll() + #expect(await cache.load(7) == nil) + } + + @Test("Broken file is ignored") + func brokenFile() async throws { + let cache = QMSDialogCache.files(root: root, userId: { 1 }) + defer { try? FileManager.default.removeItem(at: root) } + + let url = root.appending(path: "1/7.json") + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("garbage".utf8).write(to: url) + + #expect(await cache.load(7) == nil) + } +} diff --git a/Project.swift b/Project.swift index 948983ad..ed012e1b 100644 --- a/Project.swift +++ b/Project.swift @@ -601,6 +601,7 @@ let project = Project( .Internal.Models, .Internal.PasteboardClient, .Internal.PersistenceKeys, + .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, .SPM.SFSafeSymbols, @@ -833,6 +834,7 @@ let project = Project( .Internal.Models, .Internal.ParsingClient, .Internal.NotificationsClient, + .Internal.PersistenceKeys, .SPM.PDAPI, .SPM.TCA ] @@ -954,6 +956,25 @@ let project = Project( ) ), + .target( + name: "QMSClientTests", + destinations: App.destinations, + product: .unitTests, + bundleId: App.bundleId + ".QMSClient.Tests", + deploymentTargets: App.deploymentTargets, + infoPlist: .default, + sources: ["Modules/Tests/QMSClientTests/**"], + dependencies: [ + .Internal.Models, + .Internal.QMSClient, + .SPM.TCA, + ], + settings: .settings( + base: .targetSettings.merging(.sharingAliasFix), + defaultSettings: .recommended + ) + ), + // .target( // name: "ForPDATests", // destinations: .iOS, From 773b0212d3452d2ec956ad8f0d3d932b41896cb7 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:46:19 +0100 Subject: [PATCH 03/12] Replace ExyteChat with own UICollectionView chat feed - QMSChatCollectionView: diffable data source with self-sizing UIHostingConfiguration cells; keeps the visible message in place when older pages are prepended, sticks to the bottom on new messages and keyboard, interactive keyboard dismiss, copy context menu - Feed rows (day headers, sender groups, avatars, read status) are built by QMSChatItemsBuilder off the main thread; BB rendering is cached per message text in QMSMessageRenderer instead of running on every redraw - New input bar with multiline field, scroll to bottom button - Remove ExyteChat package - Add QMSFeatureTests for items builder and renderer Co-Authored-By: Claude Opus 5.5 --- .../Analytics/QMSFeature+Analytics.swift | 6 +- .../Chat/QMSChatCollectionView.swift | 260 ++++++++++++++++++ .../Sources/QMSFeature/Chat/QMSChatItem.swift | 151 ++++++++++ .../Sources/QMSFeature/Chat/QMSChatRows.swift | 150 ++++++++++ .../QMSFeature/Models/ChatAction.swift | 21 -- Modules/Sources/QMSFeature/QMSFeature.swift | 91 +++--- Modules/Sources/QMSFeature/QMSScreen.swift | 196 ++++++------- .../Resources/Localizable.xcstrings | 32 +++ .../QMSChatItemsBuilderTests.swift | 135 +++++++++ Project.swift | 21 +- Tuist/Package.resolved | 65 +---- Tuist/Package.swift | 1 - 12 files changed, 873 insertions(+), 256 deletions(-) create mode 100644 Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift create mode 100644 Modules/Sources/QMSFeature/Chat/QMSChatItem.swift create mode 100644 Modules/Sources/QMSFeature/Chat/QMSChatRows.swift delete mode 100644 Modules/Sources/QMSFeature/Models/ChatAction.swift create mode 100644 Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift diff --git a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index 62ab8b8b..f71d82f4 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -17,13 +17,13 @@ extension QMSFeature { @Dependency(\.analyticsClient) var analytics var body: some Reducer { - Reduce { _, action in + Reduce { state, action in switch action { case .view(.onAppear), .internal, .delegate, .binding, .alert: break - case let .view(.sendMessageButtonTapped(draft)): - analytics.log(QMSEvent.sendMessageTapped(isEmpty: draft.text.isEmpty)) + case .view(.sendMessageButtonTapped): + analytics.log(QMSEvent.sendMessageTapped(isEmpty: state.draftText.isEmpty)) case .view(.loadMoreTriggered): analytics.log(QMSEvent.loadMoreTriggered) diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift new file mode 100644 index 00000000..23b13105 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -0,0 +1,260 @@ +// +// QMSChatCollectionView.swift +// QMSFeature +// + +import SwiftUI +import UIKit + +/// Chat feed on UICollectionView: diffable updates, keeps position when older messages are prepended, +/// sticks to the bottom when new messages arrive or keyboard appears. +struct QMSChatCollectionView: UIViewControllerRepresentable { + + let items: [QMSChatItem] + let hasMoreOlder: Bool + /// Changing this value scrolls the feed to the bottom + let scrollToBottomRequest: Int + let onLoadOlder: () -> Void + let onURL: (URL) -> Void + let onAtBottomChanged: (Bool) -> Void + + func makeUIViewController(context: Context) -> QMSChatViewController { + QMSChatViewController() + } + + func updateUIViewController(_ controller: QMSChatViewController, context: Context) { + controller.onLoadOlder = onLoadOlder + controller.onURL = onURL + controller.onAtBottomChanged = onAtBottomChanged + controller.update(items: items, hasMoreOlder: hasMoreOlder) + controller.handleScrollToBottomRequest(scrollToBottomRequest) + } +} + +final class QMSChatViewController: UIViewController, UICollectionViewDelegate { + + var onLoadOlder: () -> Void = {} + var onURL: (URL) -> Void = { _ in } + var onAtBottomChanged: (Bool) -> Void = { _ in } + + private var collectionView: UICollectionView! + private var dataSource: UICollectionViewDiffableDataSource! + + private var items: [String: QMSChatItem] = [:] + private var orderedIds: [String] = [] + private var hasMoreOlder = false + private var scrollToBottomRequest = 0 + + private var isAtBottom = true { + didSet { + if oldValue != isAtBottom { onAtBottomChanged(isAtBottom) } + } + } + private var lastBoundsHeight: CGFloat = 0 + + /// Distance from the top at which older messages are requested + private let loadOlderThreshold: CGFloat = 600 + private let bottomTolerance: CGFloat = 60 + + // MARK: - Lifecycle + + override func viewDidLoad() { + super.viewDidLoad() + + collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: Self.makeLayout()) + collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + collectionView.backgroundColor = .clear + collectionView.keyboardDismissMode = .interactive + collectionView.alwaysBounceVertical = true + collectionView.delegate = self + view.addSubview(collectionView) + + let registration = UICollectionView.CellRegistration { [weak self] cell, _, id in + guard let self, let item = self.items[id] else { return } + cell.contentConfiguration = UIHostingConfiguration { self.row(for: item) } + .margins(.all, 0) + .minSize(height: 0) + } + dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { collectionView, indexPath, id in + collectionView.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: id) + } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + // Keyboard or input bar changed the height, keep the newest message visible + if collectionView.bounds.height != lastBoundsHeight { + lastBoundsHeight = collectionView.bounds.height + if isAtBottom { + scrollToBottom(animated: false) + } + } + } + + private static func makeLayout() -> UICollectionViewLayout { + let size = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(60)) + let item = NSCollectionLayoutItem(layoutSize: size) + let group = NSCollectionLayoutGroup.vertical(layoutSize: size, subitems: [item]) + let section = NSCollectionLayoutSection(group: group) + section.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0) + return UICollectionViewCompositionalLayout(section: section) + } + + @ViewBuilder + private func row(for item: QMSChatItem) -> some View { + Group { + switch item.kind { + case .loadingOlder: + QMSLoadingRow() + case let .day(date): + QMSDayRow(date: date) + case let .message(message): + QMSMessageRow(message: message) + } + } + .environment(\.openURL, OpenURLAction { [weak self] url in + self?.onURL(url) + return .handled + }) + } + + // MARK: - Update + + func update(items newItems: [QMSChatItem], hasMoreOlder: Bool) { + self.hasMoreOlder = hasMoreOlder + let newIds = newItems.map(\.id) + let newById = Dictionary(newItems.map { ($0.id, $0) }, uniquingKeysWith: { _, last in last }) + + guard newIds != orderedIds || newById != items else { return } + + let isInitial = orderedIds.isEmpty + let wasAtBottom = isAtBottom + let anchor = isInitial || wasAtBottom ? nil : topVisibleAnchor() + + let changedIds = newIds.filter { id in + if let old = items[id] { return old != newById[id] } + return false + } + + items = newById + orderedIds = newIds + + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(newIds) + snapshot.reconfigureItems(changedIds) + dataSource.apply(snapshot, animatingDifferences: false) + + collectionView.layoutIfNeeded() + if isInitial || wasAtBottom { + scrollToBottom(animated: false) + } else if let anchor { + restore(anchor) + } + updateIsAtBottom() + loadOlderIfNeeded() + } + + func handleScrollToBottomRequest(_ request: Int) { + guard request != scrollToBottomRequest else { return } + scrollToBottomRequest = request + scrollToBottom(animated: true) + } + + // MARK: - Scrolling + + private struct Anchor { + let id: String + /// Item top relative to the visible content top + let offset: CGFloat + } + + private func topVisibleAnchor() -> Anchor? { + let visibleTop = collectionView.contentOffset.y + collectionView.adjustedContentInset.top + let candidates = collectionView.indexPathsForVisibleItems + .compactMap { indexPath -> (String, CGRect)? in + guard let id = dataSource.itemIdentifier(for: indexPath), + let frame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else { return nil } + return (id, frame) + } + .filter { $0.1.maxY > visibleTop } + .sorted { $0.1.minY < $1.1.minY } + guard let (id, frame) = candidates.first else { return nil } + return Anchor(id: id, offset: frame.minY - visibleTop) + } + + private func restore(_ anchor: Anchor) { + // Cells above the anchor have estimated heights until they are laid out, + // so a couple of passes are needed for the position to settle + for _ in 0..<3 { + guard let indexPath = dataSource.indexPath(for: anchor.id), + let frame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else { return } + let y = frame.minY - anchor.offset - collectionView.adjustedContentInset.top + guard abs(collectionView.contentOffset.y - y) > 0.5 else { return } + collectionView.setContentOffset(CGPoint(x: 0, y: y), animated: false) + collectionView.layoutIfNeeded() + } + } + + private func scrollToBottom(animated: Bool) { + guard let last = orderedIds.last, let indexPath = dataSource.indexPath(for: last) else { return } + collectionView.scrollToItem(at: indexPath, at: .bottom, animated: animated) + if !animated { + // Real cell heights replace estimated ones after the first pass + collectionView.layoutIfNeeded() + collectionView.scrollToItem(at: indexPath, at: .bottom, animated: false) + } + } + + private func updateIsAtBottom() { + let visibleBottom = collectionView.contentOffset.y + collectionView.bounds.height - collectionView.adjustedContentInset.bottom + isAtBottom = visibleBottom >= collectionView.contentSize.height - bottomTolerance + } + + private func loadOlderIfNeeded() { + guard hasMoreOlder, !orderedIds.isEmpty, orderedIds.first != QMSChatItem.loadingOlder.id else { return } + let distanceToTop = collectionView.contentOffset.y + collectionView.adjustedContentInset.top + if distanceToTop < loadOlderThreshold { + onLoadOlder() + } + } + + // MARK: - UIScrollViewDelegate + + func scrollViewDidScroll(_ scrollView: UIScrollView) { + guard scrollView.isTracking || scrollView.isDecelerating else { return } + updateIsAtBottom() + loadOlderIfNeeded() + } + + func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { + updateIsAtBottom() + } + + // MARK: - UICollectionViewDelegate + + func collectionView( + _ collectionView: UICollectionView, + contextMenuConfigurationForItemsAt indexPaths: [IndexPath], + point: CGPoint + ) -> UIContextMenuConfiguration? { + guard let indexPath = indexPaths.first, + let id = dataSource.itemIdentifier(for: indexPath), + case let .message(message) = items[id]?.kind else { return nil } + + return UIContextMenuConfiguration(actionProvider: { _ in + UIMenu(children: [ + UIAction( + title: String(localized: "Copy", bundle: .module), + image: UIImage(systemName: "doc.on.doc") + ) { _ in + UIPasteboard.general.string = message.plainText + } + ]) + }) + } + + func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { + false + } +} diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift new file mode 100644 index 00000000..95f787c3 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift @@ -0,0 +1,151 @@ +// +// QMSChatItem.swift +// QMSFeature +// + +import Foundation +import Models + +/// Row of the chat feed. +public struct QMSChatItem: Identifiable, Equatable, Sendable { + + public enum Kind: Equatable, Sendable { + case loadingOlder + case day(Date) + case message(QMSChatMessage) + } + + public let id: String + public let kind: Kind + + static let loadingOlder = QMSChatItem(id: "loading", kind: .loadingOlder) + + static func day(_ date: Date) -> QMSChatItem { + QMSChatItem(id: "day-\(Int(date.timeIntervalSince1970))", kind: .day(date)) + } + + static func message(_ message: QMSChatMessage) -> QMSChatItem { + QMSChatItem(id: "message-\(message.id)", kind: .message(message)) + } +} + +public struct QMSChatMessage: Equatable, Sendable { + + public enum Status: Equatable, Sendable { + case none + case sent + case read + } + + public let id: Int + /// Rendered BB text, computed once per message text + public let text: AttributedString + public let date: Date + public let isMine: Bool + public let status: Status + /// Partner avatar is shown at the last message of a group + public let avatarUrl: URL? + public let isFirstInGroup: Bool + public let isLastInGroup: Bool + + /// Text for copying + public var plainText: String { + String(text.characters) + } +} + +// MARK: - Builder + +enum QMSChatItemsBuilder { + + /// - Parameters: + /// - render: converts raw message text to displayed text + static func build( + messages: [QMSMessage], + chat: QMSChat, + currentUserId: Int, + isLoadingOlder: Bool, + calendar: Calendar = .current, + render: (QMSMessage) -> AttributedString + ) -> [QMSChatItem] { + var items: [QMSChatItem] = [] + items.reserveCapacity(messages.count + 8) + if isLoadingOlder { + items.append(.loadingOlder) + } + + // Last `unreadCount` messages of the current user are not read by partner yet + let unreadStart = max(messages.count - chat.unreadCount, 0) + + for (index, message) in messages.enumerated() { + let previous = index > 0 ? messages[index - 1] : nil + let next = index + 1 < messages.count ? messages[index + 1] : nil + + let isNewDay = previous.map { !calendar.isDate($0.date, inSameDayAs: message.date) } ?? true + if isNewDay { + items.append(.day(calendar.startOfDay(for: message.date))) + } + + let isFirstInGroup = isNewDay || previous?.senderId != message.senderId + let isLastInGroup = next.map { + $0.senderId != message.senderId || !calendar.isDate($0.date, inSameDayAs: message.date) + } ?? true + + let isMine = message.senderId == currentUserId + let status: QMSChatMessage.Status = isMine ? (index >= unreadStart ? .sent : .read) : .none + + items.append(.message(QMSChatMessage( + id: message.id, + text: render(message), + date: message.date, + isMine: isMine, + status: status, + avatarUrl: isMine || !isLastInGroup ? nil : (chat.avatarUrl ?? Links.defaultQMSAvatar), + isFirstInGroup: isFirstInGroup, + isLastInGroup: isLastInGroup + ))) + } + return items + } +} + +// MARK: - Renderer + +/// Caches rendered message texts, BB rendering is the most expensive part of building the feed. +final class QMSMessageRenderer: @unchecked Sendable { + + static let shared = QMSMessageRenderer() + + private struct Key: Hashable { + let id: Int + let text: String + } + + private let lock = NSLock() + private var cache: [Key: AttributedString] = [:] + private let limit: Int + private let renderText: (String) -> AttributedString + + init(limit: Int = 3000, renderText: @escaping (String) -> AttributedString = { QMSBuilder(text: $0).build() }) { + self.limit = limit + self.renderText = renderText + } + + func render(_ message: QMSMessage) -> AttributedString { + let key = Key(id: message.id, text: message.processedText) + if let cached = lock.withLock({ cache[key] }) { + return cached + } + var rendered = renderText(key.text) + for (link, range) in rendered.runs[\.link] where link != nil { + rendered[range].underlineStyle = .single + } + lock.withLock { + if cache.count >= limit { + cache.removeAll(keepingCapacity: true) + } + cache[key] = rendered + } + return rendered + } +} diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift new file mode 100644 index 00000000..f7005a9a --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -0,0 +1,150 @@ +// +// QMSChatRows.swift +// QMSFeature +// + +import NukeUI +import SharedUI +import SwiftUI + +// MARK: - Message + +struct QMSMessageRow: View { + + let message: QMSChatMessage + + private let avatarSize: CGFloat = 32 + + var body: some View { + HStack(alignment: .bottom, spacing: 8) { + if message.isMine { + Spacer(minLength: 48) + } else { + avatar + } + + bubble + + if !message.isMine { + Spacer(minLength: 48) + } + } + .padding(.horizontal, 12) + .padding(.top, message.isFirstInGroup ? 6 : 1) + .padding(.bottom, message.isLastInGroup ? 6 : 1) + } + + @ViewBuilder + private var avatar: some View { + if let url = message.avatarUrl { + LazyImage(url: url) { state in + AvatarImage(state) { + Color(.Background.quaternary) + } + } + .frame(width: avatarSize, height: avatarSize) + .clipShape(Circle()) + } else { + Color.clear.frame(width: avatarSize, height: avatarSize) + } + } + + private var bubble: some View { + BubbleLayout { + Text(message.text) + .foregroundStyle(Color(.Labels.primary)) + .tint(Color(.Theme.primary)) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + + HStack(spacing: 3) { + Text(message.date, format: .dateTime.hour().minute()) + .font(.caption2) + .foregroundStyle(Color(.systemGray)) + + switch message.status { + case .none: + EmptyView() + case .sent: + Image(systemName: "checkmark") + .font(.caption2.weight(.semibold)) + .foregroundStyle(Color(.systemGray)) + case .read: + Image(systemName: "checkmark.circle.fill") + .font(.caption2) + .foregroundStyle(Color(.Theme.primary)) + } + } + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .background(Color(.Background.quaternary), in: .rect(cornerRadius: 18)) + } +} + +/// Text on top aligned to leading, footer below aligned to trailing, +/// width is the widest of them so short messages don't stretch the bubble. +private struct BubbleLayout: Layout { + + var spacing: CGFloat = 2 + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard subviews.count == 2 else { return .zero } + let text = subviews[0].sizeThatFits(ProposedViewSize(width: proposal.width, height: nil)) + let footer = subviews[1].sizeThatFits(.unspecified) + let width = min(max(text.width, footer.width), proposal.width ?? .infinity) + return CGSize(width: width, height: text.height + spacing + footer.height) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard subviews.count == 2 else { return } + let text = subviews[0].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil)) + let footer = subviews[1].sizeThatFits(.unspecified) + subviews[0].place( + at: CGPoint(x: bounds.minX, y: bounds.minY), + proposal: ProposedViewSize(width: bounds.width, height: text.height) + ) + subviews[1].place( + at: CGPoint(x: bounds.maxX, y: bounds.minY + text.height + spacing), + anchor: .topTrailing, + proposal: .unspecified + ) + } +} + +// MARK: - Day + +struct QMSDayRow: View { + + let date: Date + + var body: some View { + Text(title) + .font(.caption) + .foregroundStyle(Color(.systemGray)) + .frame(maxWidth: .infinity) + .padding(.vertical, 10) + } + + private var title: String { + let calendar = Calendar.current + if calendar.isDateInToday(date) { + return String(localized: "Today", bundle: .module) + } + if calendar.isDateInYesterday(date) { + return String(localized: "Yesterday", bundle: .module) + } + let title = date.formatted(.dateTime.weekday(.wide).day().month(.wide).year()) + return title.prefix(1).uppercased() + title.dropFirst() + } +} + +// MARK: - Loading + +struct QMSLoadingRow: View { + var body: some View { + ProgressView() + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + } +} diff --git a/Modules/Sources/QMSFeature/Models/ChatAction.swift b/Modules/Sources/QMSFeature/Models/ChatAction.swift deleted file mode 100644 index 934ee528..00000000 --- a/Modules/Sources/QMSFeature/Models/ChatAction.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// ChatAction.swift -// ForPDA -// -// Created by Ilia Lubianoi on 29.11.2025. -// - -import ExyteChat -import SwiftUI - -enum ChatAction: MessageMenuAction { - case copy - - func title() -> String { - return String(localized: "Copy", bundle: .module) - } - - func icon() -> Image { - return Image(systemSymbol: .clipboard) - } -} diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index 0140ad05..d481f72f 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -14,7 +14,6 @@ import Models import AnalyticsClient import NotificationsClient import TCAExtensions -import ExyteChat @Reducer public struct QMSFeature: Reducer, Sendable { @@ -24,6 +23,7 @@ public struct QMSFeature: Reducer, Sendable { private enum CancelID: Hashable { case observe case triggers + case render } // MARK: - State @@ -37,7 +37,10 @@ public struct QMSFeature: Reducer, Sendable { public let chatId: Int public var chat: QMSChat? - public var messages: [Message] = [] + /// Feed rows, built in background from `chat` + public var items: [QMSChatItem] = [] + /// Incremented to scroll the feed to the newest message + var scrollToBottomRequest = 0 var hasMoreOlderMessages = true var isLoadingMore = false @@ -72,7 +75,7 @@ public struct QMSFeature: Reducer, Sendable { case view(View) public enum View { case onAppear - case sendMessageButtonTapped(DraftMessage) + case sendMessageButtonTapped case loadMoreTriggered case urlTapped(URL) } @@ -83,6 +86,7 @@ public struct QMSFeature: Reducer, Sendable { case syncFinished(Result) case olderLoaded(Result) case snapshotUpdated(QMSDialogSnapshot) + case itemsBuilt([QMSChatItem]) case messageSendError(any Error) } @@ -140,14 +144,16 @@ public struct QMSFeature: Reducer, Sendable { .cancellable(id: CancelID.triggers, cancelInFlight: true) ]) - case let .view(.sendMessageButtonTapped(draftMessage)): - guard !state.isSending, !draftMessage.text.isEmpty else { return .none } + case .view(.sendMessageButtonTapped): + let text = state.draftText.trimmingCharacters(in: .whitespacesAndNewlines) + guard !state.isSending, !text.isEmpty else { return .none } + state.draftSnapshot = state.draftText state.draftText = "" - state.draftSnapshot = draftMessage.text state.isSending = true + state.scrollToBottomRequest += 1 - return .run { [chatId = state.chatId, message = draftMessage.text] send in + return .run { [chatId = state.chatId, message = text] send in try await qmsClient.sendMessage(chatId: chatId, message: message) // Don't rely on socket event, it may never come for the current chat await send(.internal(.sync)) @@ -158,10 +164,13 @@ public struct QMSFeature: Reducer, Sendable { case .view(.loadMoreTriggered): guard !state.isLoadingMore, state.hasMoreOlderMessages else { return .none } state.isLoadingMore = true - return .run { [id = state.chatId] send in - let result = await Result { try await qmsStore.loadOlder(dialogId: id) } - await send(.internal(.olderLoaded(result))) - } + return .merge( + buildItems(state), + .run { [id = state.chatId] send in + let result = await Result { try await qmsStore.loadOlder(dialogId: id) } + await send(.internal(.olderLoaded(result))) + } + ) case let .internal(.messageSendError(error)): state.isSending = false @@ -224,16 +233,15 @@ public struct QMSFeature: Reducer, Sendable { if case let .failure(error) = result { analyticsClient.capture(error) } - return .none + return buildItems(state) case let .internal(.snapshotUpdated(snapshot)): state.chat = snapshot.chat state.hasMoreOlderMessages = snapshot.hasMoreOlder - state.messages = makeLocalMessages( - from: snapshot.chat.messages, - chat: snapshot.chat, - currentUserId: state.userSession?.userId ?? 0 - ) + return buildItems(state) + + case let .internal(.itemsBuilt(items)): + state.items = items return .none case .binding: @@ -248,39 +256,22 @@ public struct QMSFeature: Reducer, Sendable { // MARK: - Shared Logic - private func makeLocalMessages( - from remoteMessages: [QMSMessage], - chat: QMSChat, - currentUserId: Int - ) -> [Message] { - var localMessages = remoteMessages.map { remoteMessage in - let isCurrentUser = currentUserId == remoteMessage.senderId - let user = User( - id: String(remoteMessage.senderId), - name: isCurrentUser ? "You" : chat.partnerName, - avatarURL: isCurrentUser ? nil : chat.avatarUrl ?? Links.defaultQMSAvatar, - isCurrentUser: isCurrentUser + /// Builds feed rows off the main thread, BB rendering of new messages may take a while + private func buildItems(_ state: State) -> Effect { + guard let chat = state.chat else { return .none } + return .run { [ + userId = state.userSession?.userId ?? 0, + isLoadingOlder = state.isLoadingMore + ] send in + let items = QMSChatItemsBuilder.build( + messages: chat.messages, + chat: chat, + currentUserId: userId, + isLoadingOlder: isLoadingOlder, + render: QMSMessageRenderer.shared.render ) - - return Message( - id: String(remoteMessage.id), - user: user, - status: .none, - createdAt: remoteMessage.date, - text: remoteMessage.processedText - ) - } - - for index in localMessages.indices { - guard localMessages[index].user.isCurrentUser else { continue } - localMessages[index].status = .read + await send(.internal(.itemsBuilt(items))) } - - for index in localMessages.indices.suffix(chat.unreadCount) { - guard localMessages[index].user.isCurrentUser else { continue } - localMessages[index].status = .sent - } - - return localMessages - } + .cancellable(id: CancelID.render, cancelInFlight: true) } +} diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 15624e7e..2c13f756 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -9,84 +9,53 @@ import SwiftUI import ComposableArchitecture import SharedUI import SFSafeSymbols -import ExyteChat @ViewAction(for: QMSFeature.self) public struct QMSScreen: View { - + // MARK: - Properties - + @Perception.Bindable public var store: StoreOf - @Environment(\.tintColor) private var tintColor @Environment(\.backgroundColors) private var backgroundColors - + + @State private var isAtBottom = true + @State private var localScrollRequest = 0 + // MARK: - Init - + public init(store: StoreOf) { self.store = store } - + // MARK: - Body - + public var body: some View { WithPerceptionTracking { - ZStack { - backgroundColors.primary - .ignoresSafeArea() - - if store.chat != nil { - ChatView(messages: store.messages) { message in - // send(.sendMessageButtonTapped(message)) - } inputViewBuilder: { text, _, _, inputViewStyle, inputViewActionClosure, _ in - WithPerceptionTracking { - Group { - switch inputViewStyle { - case .message: - InputView(text: text) - case .signature: - EmptyView() - } - } - } - } messageMenuAction: { (action: ChatAction, _, message) in - if case .copy = action { - UIPasteboard.general.string = message.text + VStack(spacing: 0) { + ZStack(alignment: .bottomTrailing) { + if store.chat != nil { + QMSChatCollectionView( + items: store.items, + hasMoreOlder: store.hasMoreOlderMessages, + scrollToBottomRequest: store.scrollToBottomRequest + localScrollRequest, + onLoadOlder: { send(.loadMoreTriggered) }, + onURL: { send(.urlTapped($0)) }, + onAtBottomChanged: { isAtBottom = $0 } + ) + + if !isAtBottom { + ScrollToBottomButton() } + } else { + PDALoader() + .frame(width: 24, height: 24) + .frame(maxWidth: .infinity, maxHeight: .infinity) } - .keyboardDismissMode(.interactive) - .enableLoadMore { _ in - await send(.loadMoreTriggered) - } - .linkPreviewsDisabled() - .messageUseStyler { string in - return QMSBuilder(text: string).build() - } - .setAvailableInputs([.text]) - .chatTheme( - ChatTheme( - colors: ChatTheme - .Colors( - mainBG: backgroundColors.primary, - messageMyBG: Color(.Background.quaternary), - messageMyText: Color(.Labels.primary), - messageMyTimeText: Color(.systemGray), - messageFriendBG: Color(.Background.quaternary), - messageFriendText: Color(.Labels.primary), - messageFriendTimeText: Color(.systemGray), - statusGray: Color(.Theme.primary), - sendButtonBackground: Color(.Theme.primary) - ) - ) - ) - .environment(\.openURL, OpenURLAction(handler: { url in - send(.urlTapped(url)) - return .handled - })) - } else { - PDALoader() - .frame(width: 24, height: 24) } + + InputBar() } + .background(backgroundColors.primary.ignoresSafeArea()) .navigationTitle(store.title) ._toolbarTitleDisplayMode(.inline) .alert($store.scope(\.$alert, action: \.alert)) @@ -95,48 +64,62 @@ public struct QMSScreen: View { } } } - - private func InputView(text: Binding) -> some View { - HStack { - #if DEBUG - if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" { - Button(String("+")) { text.wrappedValue += "text" } - .buttonStyle(.borderedProminent) - } - #endif - - TextField(String(""), text: text, prompt: Text("qms.textfield.placeholder", bundle: .module)) - .padding() - .background(Color(.Background.quaternary), in: .rect(cornerRadius: 16)) - + + // MARK: - Scroll To Bottom + + private func ScrollToBottomButton() -> some View { + Button { + localScrollRequest += 1 + } label: { + Image(systemSymbol: .chevronDown) + .font(.body.weight(.semibold)) + .foregroundStyle(Color(.Theme.primary)) + .frame(width: 40, height: 40) + .background(Color(.Background.quaternary), in: Circle()) + } + .padding(12) + .transition(.opacity) + } + + // MARK: - Input + + private func InputBar() -> some View { + let canSend = !store.isSending && !store.draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + return HStack(alignment: .bottom, spacing: 8) { + TextField( + String(""), + text: $store.draftText, + prompt: Text("qms.textfield.placeholder", bundle: .module), + axis: .vertical + ) + .lineLimit(1...6) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(Color(.Background.quaternary), in: .rect(cornerRadius: 20)) + Button { - if !text.wrappedValue.isEmpty { - send(.sendMessageButtonTapped( - DraftMessage(text: text.wrappedValue, medias: [], giphyMedia: nil, recording: nil, replyMessage: nil, createdAt: .now) - )) - } + send(.sendMessageButtonTapped) } label: { - Circle() - .tint(Color(.Theme.primary)) - .frame(width: 44, height: 44) - .overlay { - if store.isSending { - ProgressView() - .progressViewStyle(.circular) - .tint(.white) - } else { - Image(systemSymbol: .arrowUp) - .bold() - .tint(.white) - } + ZStack { + Circle() + .fill(Color(.Theme.primary)) + if store.isSending { + ProgressView() + .tint(.white) + } else { + Image(systemSymbol: .arrowUp) + .font(.body.weight(.bold)) + .foregroundStyle(.white) } + } + .frame(width: 40, height: 40) + .opacity(canSend || store.isSending ? 1 : 0.5) } - .disabled(store.isSending) + .disabled(!canSend) } - .padding() + .padding(.horizontal, 12) + .padding(.vertical, 8) .animation(.default, value: store.isSending) - .animation(.default, value: text.wrappedValue) - .bind(text, to: $store.draftText) } } @@ -145,33 +128,16 @@ public struct QMSScreen: View { #Preview { @Shared(.userSession) var userSession $userSession.withLock { $0 = .init(userId: 1, token: "", isHidden: false) } - + return NavigationStack { QMSScreen( store: Store( initialState: QMSFeature.State(chatId: 0) ) { QMSFeature() - } withDependencies: { _ in - } ) } .environment(\.tintColor, Color(.Theme.primary)) .environment(\.locale, Locale(identifier: "en")) } - -#Preview("Error On Send") { - @Shared(.userSession) var userSession - $userSession.withLock { $0 = .init(userId: 1, token: "", isHidden: false) } - - return QMSScreen( - store: Store(initialState: QMSFeature.State(chatId: 0)) { - QMSFeature() - } withDependencies: { - $0.qmsClient = .errorOnSend - } - ) - .environment(\.tintColor, Color(.Theme.primary)) - .environment(\.locale, Locale(identifier: "en")) -} diff --git a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings index 541e4af4..bcdbf030 100644 --- a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings @@ -17,6 +17,38 @@ } } }, + "Today" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Today" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Сегодня" + } + } + } + }, + "Yesterday" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Yesterday" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вчера" + } + } + } + }, "qms.textfield.placeholder" : { "localizations" : { "en" : { diff --git a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift new file mode 100644 index 00000000..68fc5639 --- /dev/null +++ b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift @@ -0,0 +1,135 @@ +// +// QMSChatItemsBuilderTests.swift +// QMSFeatureTests +// + +import Foundation +import Models +import Testing + +@testable import QMSFeature + +@Suite("QMS chat items builder") +struct QMSChatItemsBuilderTests { + + private var calendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + return calendar + } + + /// 2026-12-01 00:00 UTC + private let day1: TimeInterval = 1796083200 + private let me = 1 + private let partner = 2 + + private func message(_ id: Int, from sender: Int, at time: TimeInterval) -> QMSMessage { + QMSMessage(id: id, senderId: sender, date: Date(timeIntervalSince1970: time), text: "m\(id)", attachments: []) + } + + private func chat(_ messages: [QMSMessage], unread: Int = 0) -> QMSChat { + QMSChat( + id: 7, creationDate: .distantPast, lastMessageDate: .distantPast, name: "Dialog", + partnerId: partner, partnerName: "Partner", flag: 0, avatarUrl: URL(string: "https://4pda.to/a.jpg"), + unknownId1: 0, totalCount: messages.count, unknownId2: 0, lastMessageId: 0, unreadCount: unread, + messages: messages + ) + } + + private func build(_ messages: [QMSMessage], unread: Int = 0, isLoadingOlder: Bool = false) -> [QMSChatItem] { + QMSChatItemsBuilder.build( + messages: messages, + chat: chat(messages, unread: unread), + currentUserId: me, + isLoadingOlder: isLoadingOlder, + calendar: calendar, + render: { AttributedString($0.text) } + ) + } + + private func messages(in items: [QMSChatItem]) -> [QMSChatMessage] { + items.compactMap { if case let .message(message) = $0.kind { message } else { nil } } + } + + @Test("Day headers are inserted when the day changes") + func dayHeaders() { + let items = build([ + message(1, from: partner, at: day1 + 100), + message(2, from: me, at: day1 + 200), + message(3, from: me, at: day1 + 86400 + 100), + ]) + #expect(items.map(\.id) == [ + "day-\(Int(day1))", "message-1", "message-2", + "day-\(Int(day1 + 86400))", "message-3", + ]) + } + + @Test("Messages are grouped by sender and partner avatar is shown at the last one") + func groups() { + let result = messages(in: build([ + message(1, from: partner, at: day1 + 1), + message(2, from: partner, at: day1 + 2), + message(3, from: me, at: day1 + 3), + message(4, from: partner, at: day1 + 4), + ])) + #expect(result.map(\.isFirstInGroup) == [true, false, true, true]) + #expect(result.map(\.isLastInGroup) == [false, true, true, true]) + #expect(result.map { $0.avatarUrl != nil } == [false, true, false, true]) + #expect(result.map(\.isMine) == [false, false, true, false]) + } + + @Test("Own messages among the last unread ones are sent, others are read") + func statuses() { + let result = messages(in: build([ + message(1, from: me, at: day1 + 1), + message(2, from: partner, at: day1 + 2), + message(3, from: me, at: day1 + 3), + message(4, from: me, at: day1 + 4), + ], unread: 2)) + #expect(result.map(\.status) == [.read, .none, .sent, .sent]) + } + + @Test("Loading row goes first while older messages are loading") + func loadingRow() { + let items = build([message(1, from: me, at: day1)], isLoadingOlder: true) + #expect(items.first?.id == QMSChatItem.loadingOlder.id) + } + + @Test("Empty dialog has no rows") + func empty() { + #expect(build([]).isEmpty) + } +} + +@Suite("QMS message renderer") +struct QMSMessageRendererTests { + + @Test("Text is rendered once per message text") + func cache() { + var renders = 0 + let renderer = QMSMessageRenderer { text in + renders += 1 + return AttributedString(text) + } + let original = QMSMessage(id: 1, senderId: 1, date: .now, text: "a", attachments: []) + let edited = QMSMessage(id: 1, senderId: 1, date: .now, text: "b", attachments: []) + + _ = renderer.render(original) + _ = renderer.render(original) + #expect(renders == 1) + + #expect(String(renderer.render(edited).characters) == "b") + #expect(renders == 2) + } + + @Test("Links are underlined") + func links() { + let renderer = QMSMessageRenderer { _ in + var text = AttributedString("link") + text.link = URL(string: "https://4pda.to") + return text + } + let rendered = renderer.render(QMSMessage(id: 1, senderId: 1, date: .now, text: "", attachments: [])) + #expect(rendered.runs.first?.underlineStyle == .single) + } +} diff --git a/Project.swift b/Project.swift index ed012e1b..009aa48d 100644 --- a/Project.swift +++ b/Project.swift @@ -529,7 +529,6 @@ let project = Project( .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, - .SPM.ExyteChat, .SPM.NukeUI, .SPM.SFSafeSymbols, .SPM.SkeletonUI, @@ -975,6 +974,25 @@ let project = Project( ) ), + .target( + name: "QMSFeatureTests", + destinations: App.destinations, + product: .unitTests, + bundleId: App.bundleId + ".QMSFeature.Tests", + deploymentTargets: App.deploymentTargets, + infoPlist: .default, + sources: ["Modules/Tests/QMSFeatureTests/**"], + dependencies: [ + .Internal.Models, + .Internal.QMSFeature, + .SPM.TCA, + ], + settings: .settings( + base: .targetSettings.merging(.sharingAliasFix), + defaultSettings: .recommended + ) + ), + // .target( // name: "ForPDATests", // destinations: .iOS, @@ -1415,7 +1433,6 @@ extension TargetDependency.SPM { static let AlertToast = TargetDependency.external(name: "AlertToast") static let Cache = TargetDependency.external(name: "Cache") static let CustomDump = TargetDependency.external(name: "CustomDump") - static let ExyteChat = TargetDependency.external(name: "ExyteChat") static let MemberwiseInit = TargetDependency.external(name: "MemberwiseInit") static let Nuke = TargetDependency.external(name: "Nuke") static let NukeUI = TargetDependency.external(name: "NukeUI") diff --git a/Tuist/Package.resolved b/Tuist/Package.resolved index fb387edd..a38d3edd 100644 --- a/Tuist/Package.resolved +++ b/Tuist/Package.resolved @@ -1,15 +1,6 @@ { - "originHash" : "aad7312c9991e400bbb30d24a50c6d068c56fcc6581a50299923fea4528bcbe2", + "originHash" : "2d12c2d439ca10a3eed3c6989d62d816901ecaab274b6a036c25363f69f36846", "pins" : [ - { - "identity" : "activityindicatorview", - "kind" : "remoteSourceControl", - "location" : "https://github.com/exyte/ActivityIndicatorView", - "state" : { - "revision" : "36140867802ae4a1d2b11490bcbbefe058001d14", - "version" : "1.2.1" - } - }, { "identity" : "alerttoast", "kind" : "remoteSourceControl", @@ -19,15 +10,6 @@ "revision" : "d0f7d6bafd3e8ffe99afba4995822d24aee044fb" } }, - { - "identity" : "anchoredpopup", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SubvertDev/AnchoredPopup", - "state" : { - "branch" : "main", - "revision" : "c409740455e14866a223715ed285da33cfd0f044" - } - }, { "identity" : "cache", "kind" : "remoteSourceControl", @@ -37,15 +19,6 @@ "version" : "7.4.0" } }, - { - "identity" : "chat", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SubvertDev/Chat", - "state" : { - "branch" : "main", - "revision" : "63020101082251cbb6e2ed3248ed92611e2688ab" - } - }, { "identity" : "combine-schedulers", "kind" : "remoteSourceControl", @@ -55,42 +28,6 @@ "version" : "1.2.2" } }, - { - "identity" : "giphy-ios-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/Giphy/giphy-ios-sdk", - "state" : { - "revision" : "f7a8edf513ab14147ef33c942b10b45cdac1e765", - "version" : "2.3.0" - } - }, - { - "identity" : "kingfisher", - "kind" : "remoteSourceControl", - "location" : "https://github.com/onevcat/Kingfisher", - "state" : { - "revision" : "e227df15448d2ad1a5d4e4c49722a71c68f9058a", - "version" : "8.7.0" - } - }, - { - "identity" : "libwebp-xcode", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SDWebImage/libwebp-Xcode", - "state" : { - "revision" : "0d60654eeefd5d7d2bef3835804892c40225e8b2", - "version" : "1.5.0" - } - }, - { - "identity" : "mediapicker", - "kind" : "remoteSourceControl", - "location" : "https://github.com/SubvertDev/MediaPicker", - "state" : { - "branch" : "main", - "revision" : "199f445c1efa65291160d9589ad8509848130783" - } - }, { "identity" : "nuke", "kind" : "remoteSourceControl", diff --git a/Tuist/Package.swift b/Tuist/Package.swift index 00f325a2..58e495f8 100644 --- a/Tuist/Package.swift +++ b/Tuist/Package.swift @@ -96,7 +96,6 @@ let package = Package( // Forks & stuff .package(url: "https://github.com/SubvertDev/AlertToast.git", revision: "d0f7d6b"), - .package(url: "https://github.com/SubvertDev/Chat", branch: "main"), .package(url: "https://github.com/SubvertDev/PDAPI_SPM.git", exact: "0.8.8"), .package(url: "https://github.com/SubvertDev/RichTextKit.git", branch: "main"), ] From fbf486fd4bcc56bc85c62e2819b306e17c188bf7 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:50:43 +0100 Subject: [PATCH 04/12] Lift only the message bubble in the chat context menu Message rows report their bubble frame, and the context menu uses it as the visible path of the targeted preview instead of the whole full width row. The screen background goes under the preview since bubble color is translucent. Co-Authored-By: Claude Opus 5.5 --- .../Chat/QMSChatCollectionView.swift | 40 ++++++++++++++++++- .../Sources/QMSFeature/Chat/QMSChatRows.swift | 9 +++++ Modules/Sources/QMSFeature/QMSScreen.swift | 1 + 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift index 23b13105..db1f30e4 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -14,6 +14,8 @@ struct QMSChatCollectionView: UIViewControllerRepresentable { let hasMoreOlder: Bool /// Changing this value scrolls the feed to the bottom let scrollToBottomRequest: Int + /// Opaque screen background, bubbles are translucent and need it under the context menu preview + let background: Color let onLoadOlder: () -> Void let onURL: (URL) -> Void let onAtBottomChanged: (Bool) -> Void @@ -26,6 +28,7 @@ struct QMSChatCollectionView: UIViewControllerRepresentable { controller.onLoadOlder = onLoadOlder controller.onURL = onURL controller.onAtBottomChanged = onAtBottomChanged + controller.previewBackgroundColor = UIColor(background) controller.update(items: items, hasMoreOlder: hasMoreOlder) controller.handleScrollToBottomRequest(scrollToBottomRequest) } @@ -36,11 +39,14 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { var onLoadOlder: () -> Void = {} var onURL: (URL) -> Void = { _ in } var onAtBottomChanged: (Bool) -> Void = { _ in } + var previewBackgroundColor: UIColor = .systemBackground private var collectionView: UICollectionView! private var dataSource: UICollectionViewDiffableDataSource! private var items: [String: QMSChatItem] = [:] + /// Bubble frames in cell coordinates, reported by message rows + private var bubbleFrames: [String: CGRect] = [:] private var orderedIds: [String] = [] private var hasMoreOlder = false private var scrollToBottomRequest = 0 @@ -109,7 +115,9 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { case let .day(date): QMSDayRow(date: date) case let .message(message): - QMSMessageRow(message: message) + QMSMessageRow(message: message) { [weak self] frame in + self?.bubbleFrames[item.id] = frame + } } } .environment(\.openURL, OpenURLAction { [weak self] url in @@ -138,6 +146,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { items = newById orderedIds = newIds + bubbleFrames = bubbleFrames.filter { newById[$0.key] != nil } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) @@ -254,6 +263,35 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { }) } + func collectionView( + _ collectionView: UICollectionView, + contextMenuConfiguration configuration: UIContextMenuConfiguration, + highlightPreviewForItemAt indexPath: IndexPath + ) -> UITargetedPreview? { + bubblePreview(at: indexPath) + } + + func collectionView( + _ collectionView: UICollectionView, + contextMenuConfiguration configuration: UIContextMenuConfiguration, + dismissalPreviewForItemAt indexPath: IndexPath + ) -> UITargetedPreview? { + bubblePreview(at: indexPath) + } + + /// Lifts only the message bubble instead of the whole full width row + private func bubblePreview(at indexPath: IndexPath) -> UITargetedPreview? { + guard let cell = collectionView.cellForItem(at: indexPath), + let id = dataSource.itemIdentifier(for: indexPath), + let frame = bubbleFrames[id], + cell.bounds.contains(frame) else { return nil } + + let parameters = UIPreviewParameters() + parameters.visiblePath = UIBezierPath(roundedRect: frame, cornerRadius: 18) + parameters.backgroundColor = previewBackgroundColor + return UITargetedPreview(view: cell, parameters: parameters) + } + func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { false } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift index f7005a9a..5800549b 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -12,8 +12,11 @@ import SwiftUI struct QMSMessageRow: View { let message: QMSChatMessage + /// Bubble frame in row coordinates, used to highlight only the bubble in context menu + var onBubbleFrame: (CGRect) -> Void = { _ in } private let avatarSize: CGFloat = 32 + private static let coordinateSpace = "QMSMessageRow" var body: some View { HStack(alignment: .bottom, spacing: 8) { @@ -24,6 +27,11 @@ struct QMSMessageRow: View { } bubble + .onGeometryChange(for: CGRect.self) { proxy in + proxy.frame(in: .named(Self.coordinateSpace)) + } action: { frame in + onBubbleFrame(frame) + } if !message.isMine { Spacer(minLength: 48) @@ -32,6 +40,7 @@ struct QMSMessageRow: View { .padding(.horizontal, 12) .padding(.top, message.isFirstInGroup ? 6 : 1) .padding(.bottom, message.isLastInGroup ? 6 : 1) + .coordinateSpace(name: Self.coordinateSpace) } @ViewBuilder diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 2c13f756..5221393f 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -38,6 +38,7 @@ public struct QMSScreen: View { items: store.items, hasMoreOlder: store.hasMoreOlderMessages, scrollToBottomRequest: store.scrollToBottomRequest + localScrollRequest, + background: backgroundColors.primary, onLoadOlder: { send(.loadMoreTriggered) }, onURL: { send(.urlTapped($0)) }, onAtBottomChanged: { isAtBottom = $0 } From c3e83f1ab2051f2032714f140446fed66422094b Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:59:15 +0100 Subject: [PATCH 05/12] Add QMS outgoing message queue and attachments - QMSStore.send shows the message in the dialog right away with sending state; on failure it stays as failed with retry and discard, after success it is replaced by the real message on the next sync - Outgoing messages are saved with the dialog cache; messages that were sending when the app closed come back as failed, so nothing is resent without the user knowing - Chat feed shows sending and failed states, tap on a failed message retries it, context menu has Retry and Delete - Attach button opens UploadBox with QMS storage (isQms), uploaded files are sent with the message as attachment ids - Add tests for the queue and outgoing rows Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/QMSClient/QMSClient.swift | 10 +- .../QMSClient/QMSOutgoingMessage.swift | 50 +++++++ Modules/Sources/QMSClient/QMSStore.swift | 131 ++++++++++++++++- .../Analytics/QMSFeature+Analytics.swift | 3 +- .../Chat/QMSChatCollectionView.swift | 51 +++++-- .../Sources/QMSFeature/Chat/QMSChatItem.swift | 49 +++++-- .../Sources/QMSFeature/Chat/QMSChatRows.swift | 19 +++ Modules/Sources/QMSFeature/QMSFeature.swift | 85 +++++++---- Modules/Sources/QMSFeature/QMSScreen.swift | 98 ++++++++----- .../Resources/Localizable.xcstrings | 48 +++++++ .../Resources/Localizable.xcstrings | 10 ++ .../UploadBoxFeature/UploadBoxFeature.swift | 8 +- .../UploadBoxFeature/UploadBoxView.swift | 10 +- .../Tests/QMSClientTests/QMSStoreTests.swift | 134 ++++++++++++++++++ .../QMSChatItemsBuilderTests.swift | 41 +++++- Project.swift | 1 + 16 files changed, 647 insertions(+), 101 deletions(-) create mode 100644 Modules/Sources/QMSClient/QMSOutgoingMessage.swift diff --git a/Modules/Sources/QMSClient/QMSClient.swift b/Modules/Sources/QMSClient/QMSClient.swift index 7f3d6e6c..4ef0ab0a 100644 --- a/Modules/Sources/QMSClient/QMSClient.swift +++ b/Modules/Sources/QMSClient/QMSClient.swift @@ -21,7 +21,7 @@ public struct QMSClient: Sendable { public var createChat: @Sendable (_ opponentId: Int, _ title: String, _ message: String) async throws -> String public var deleteAllChats: @Sendable (_ userId: Int) async throws -> String public var deleteChat: @Sendable (_ chatId: Int) async throws -> String - public var sendMessage: @Sendable (_ chatId: Int, _ message: String) async throws -> Void + public var sendMessage: @Sendable (_ chatId: Int, _ message: String, _ attachments: [Int]) async throws -> Void public var deleteMessage: @Sendable (_ chatId: Int, _ messageId: Int, _ forAll: Bool) async throws -> String public var blacklist: @Sendable () async throws -> String public var addToBlacklist: @Sendable (_ id: Int, _ add: Bool) async throws -> String @@ -69,8 +69,8 @@ extension QMSClient: DependencyKey { return response }, - sendMessage: { chatId, message in - let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: [])) + sendMessage: { chatId, message, attachments in + let _ = try await api.send(QMSCommand.Message.send(message: message, dialogId: chatId, attaches: attachments)) }, deleteMessage: { chatId, messageId, forAll in @@ -117,7 +117,7 @@ extension QMSClient: DependencyKey { deleteChat: { _ in return "" }, - sendMessage: { chatId, message in + sendMessage: { chatId, message, _ in return try await mock.sendQMSMessage(chatId: chatId, message: message) }, deleteMessage: { _, _, _ in @@ -146,7 +146,7 @@ extension QMSClient: DependencyKey { createChat: unimplemented(), deleteAllChats: unimplemented(), deleteChat: unimplemented(), - sendMessage: { chatId, message in + sendMessage: { chatId, message, _ in return try await mock.sendQMSMessage(chatId: chatId, message: message) }, deleteMessage: unimplemented(), diff --git a/Modules/Sources/QMSClient/QMSOutgoingMessage.swift b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift new file mode 100644 index 00000000..192bdf81 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift @@ -0,0 +1,50 @@ +// +// QMSOutgoingMessage.swift +// QMSClient +// + +import Foundation + +/// Message the user sent that is not confirmed by the server yet. +public struct QMSOutgoingMessage: Equatable, Sendable, Codable, Identifiable { + + public enum State: String, Equatable, Sendable, Codable { + case sending + case failed + /// Server accepted it, waiting for the dialog sync to bring the real message + case sent + } + + public struct Attachment: Equatable, Sendable, Codable { + public let id: Int + public let name: String + + public init(id: Int, name: String) { + self.id = id + self.name = name + } + } + + public let id: UUID + public let text: String + public let attachments: [Attachment] + public let date: Date + public var state: State + + public init(id: UUID, text: String, attachments: [Attachment], date: Date, state: State) { + self.id = id + self.text = text + self.attachments = attachments + self.date = date + self.state = state + } + + /// Text in the same format as `QMSMessage.processedText`, so it renders the same way + public var processedText: String { + let attachmentsText = attachments + .map { "[attachment=\($0.name),\($0.id)]" } + .joined(separator: "\n\n") + if attachmentsText.isEmpty { return text } + return text.isEmpty ? attachmentsText : attachmentsText + "\n\n" + text + } +} diff --git a/Modules/Sources/QMSClient/QMSStore.swift b/Modules/Sources/QMSClient/QMSStore.swift index 10151314..785c9ef6 100644 --- a/Modules/Sources/QMSClient/QMSStore.swift +++ b/Modules/Sources/QMSClient/QMSStore.swift @@ -13,10 +13,25 @@ public struct QMSDialogSnapshot: Equatable, Sendable, Codable { public var chat: QMSChat /// There are messages older than the oldest loaded one public var hasMoreOlder: Bool + /// Messages sent from this device that are not in `chat.messages` yet, oldest first + public var outgoing: [QMSOutgoingMessage] - public init(chat: QMSChat, hasMoreOlder: Bool) { + public init(chat: QMSChat, hasMoreOlder: Bool, outgoing: [QMSOutgoingMessage] = []) { self.chat = chat self.hasMoreOlder = hasMoreOlder + self.outgoing = outgoing + } + + private enum CodingKeys: String, CodingKey { + case chat, hasMoreOlder, outgoing + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + chat = try container.decode(QMSChat.self, forKey: .chat) + hasMoreOlder = try container.decode(Bool.self, forKey: .hasMoreOlder) + // Absent in caches written before outgoing messages existed + outgoing = try container.decodeIfPresent([QMSOutgoingMessage].self, forKey: .outgoing) ?? [] } } @@ -29,10 +44,14 @@ public struct QMSDialogSnapshot: Equatable, Sendable, Codable { public actor QMSStore { public typealias LoadChat = @Sendable (_ id: Int, _ lastMessageId: Int, _ offset: Int) async throws -> QMSChat + public typealias SendMessage = @Sendable (_ dialogId: Int, _ text: String, _ attachmentIds: [Int]) async throws -> Void private let loadChat: LoadChat + private let sendMessage: SendMessage private let cache: QMSDialogCache private let pageSize: Int + private let now: @Sendable () -> Date + private let makeId: @Sendable () -> UUID private var snapshots: [Int: QMSDialogSnapshot] = [:] private var observers: [Int: [UUID: AsyncStream.Continuation]] = [:] @@ -41,10 +60,20 @@ public actor QMSStore { private var pendingSync: Set = [] private var olderTasks: [Int: Task] = [:] - public init(loadChat: @escaping LoadChat, cache: QMSDialogCache, pageSize: Int = 30) { + public init( + loadChat: @escaping LoadChat, + sendMessage: @escaping SendMessage = { _, _, _ in }, + cache: QMSDialogCache, + pageSize: Int = 30, + now: @escaping @Sendable () -> Date = { Date() }, + makeId: @escaping @Sendable () -> UUID = { UUID() } + ) { self.loadChat = loadChat + self.sendMessage = sendMessage self.cache = cache self.pageSize = pageSize + self.now = now + self.makeId = makeId } // MARK: - Observe @@ -62,7 +91,19 @@ public actor QMSStore { Task { await self?.removeObserver(dialogId: dialogId, token: token) } } - if snapshots[dialogId] == nil, let cached = await cache.load(dialogId) { + if snapshots[dialogId] == nil, var cached = await cache.load(dialogId) { + // App was closed in the middle of sending, it's unknown whether it reached the server, + // so the user decides to retry or discard + cached.outgoing = cached.outgoing.compactMap { message in + switch message.state { + case .sent: return nil + case .failed: return message + case .sending: + var message = message + message.state = .failed + return message + } + } // Could be filled by sync while cache was loading if snapshots[dialogId] == nil { snapshots[dialogId] = cached @@ -126,6 +167,65 @@ public actor QMSStore { try await task.value } + // MARK: - Send + + /// Shows the message in the dialog right away and sends it. + /// On failure the message stays in the dialog as failed until `retry` or `discard`. + @discardableResult + public func send( + dialogId: Int, + text: String, + attachments: [QMSOutgoingMessage.Attachment] = [] + ) async -> UUID? { + guard snapshots[dialogId] != nil else { return nil } + let message = QMSOutgoingMessage( + id: makeId(), + text: text, + attachments: attachments, + date: now(), + state: .sending + ) + await updateSnapshot(dialogId) { $0.outgoing.append(message) } + await deliver(dialogId: dialogId, messageId: message.id) + return message.id + } + + public func retry(dialogId: Int, messageId: UUID) async { + guard outgoingMessage(dialogId: dialogId, id: messageId)?.state == .failed else { return } + await updateOutgoing(dialogId: dialogId, id: messageId) { $0.state = .sending } + await deliver(dialogId: dialogId, messageId: messageId) + } + + public func discard(dialogId: Int, messageId: UUID) async { + guard outgoingMessage(dialogId: dialogId, id: messageId)?.state == .failed else { return } + await updateSnapshot(dialogId) { $0.outgoing.removeAll { $0.id == messageId } } + } + + private func deliver(dialogId: Int, messageId: UUID) async { + guard let message = outgoingMessage(dialogId: dialogId, id: messageId) else { return } + do { + try await sendMessage(dialogId, message.text, message.attachments.map(\.id)) + } catch { + await updateOutgoing(dialogId: dialogId, id: messageId) { $0.state = .failed } + return + } + await updateOutgoing(dialogId: dialogId, id: messageId) { $0.state = .sent } + // Brings the real message, which replaces the sent one. If it fails, + // the next sync will do it, the message is on the server already. + try? await sync(dialogId: dialogId) + } + + private func outgoingMessage(dialogId: Int, id: UUID) -> QMSOutgoingMessage? { + snapshots[dialogId]?.outgoing.first { $0.id == id } + } + + private func updateOutgoing(dialogId: Int, id: UUID, _ update: (inout QMSOutgoingMessage) -> Void) async { + await updateSnapshot(dialogId) { snapshot in + guard let index = snapshot.outgoing.firstIndex(where: { $0.id == id }) else { return } + update(&snapshot.outgoing[index]) + } + } + // MARK: - Remove /// Drops everything, e.g. on logout or cache clearing. @@ -157,11 +257,26 @@ public actor QMSStore { var mergedChat = chat mergedChat.messages = merge.messages - let snapshot = QMSDialogSnapshot(chat: mergedChat, hasMoreOlder: hasMoreOlder) - guard snapshot != existing else { return } + var outgoing = existing?.outgoing ?? [] + if kind == .latest { + // Latest page contains messages the server accepted before this request + outgoing.removeAll { $0.state == .sent } + } + let snapshot = QMSDialogSnapshot(chat: mergedChat, hasMoreOlder: hasMoreOlder, outgoing: outgoing) + await publish(snapshot, replacing: existing) + } - snapshots[chat.id] = snapshot - for continuation in observers[chat.id, default: [:]].values { + private func updateSnapshot(_ dialogId: Int, _ update: (inout QMSDialogSnapshot) -> Void) async { + guard var snapshot = snapshots[dialogId] else { return } + let existing = snapshot + update(&snapshot) + await publish(snapshot, replacing: existing) + } + + private func publish(_ snapshot: QMSDialogSnapshot, replacing existing: QMSDialogSnapshot?) async { + guard snapshot != existing else { return } + snapshots[snapshot.chat.id] = snapshot + for continuation in observers[snapshot.chat.id, default: [:]].values { continuation.yield(snapshot) } await cache.save(snapshot) @@ -182,6 +297,7 @@ extension QMSStore: DependencyKey { @Dependency(\.qmsClient) var qmsClient return QMSStore( loadChat: { try await qmsClient.loadChat($0, $1, $2) }, + sendMessage: { try await qmsClient.sendMessage($0, $1, $2) }, cache: .liveValue ) } @@ -190,6 +306,7 @@ extension QMSStore: DependencyKey { @Dependency(\.qmsClient) var qmsClient return QMSStore( loadChat: { try await qmsClient.loadChat($0, $1, $2) }, + sendMessage: { try await qmsClient.sendMessage($0, $1, $2) }, cache: .inMemory ) } diff --git a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index f71d82f4..b34958eb 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -19,7 +19,8 @@ extension QMSFeature { var body: some Reducer { Reduce { state, action in switch action { - case .view(.onAppear), .internal, .delegate, .binding, .alert: + case .view(.onAppear), .view(.attachButtonTapped), .view(.retryMessageTapped), + .view(.discardMessageTapped), .internal, .delegate, .binding, .alert, .upload: break case .view(.sendMessageButtonTapped): diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift index db1f30e4..3f298047 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -19,6 +19,8 @@ struct QMSChatCollectionView: UIViewControllerRepresentable { let onLoadOlder: () -> Void let onURL: (URL) -> Void let onAtBottomChanged: (Bool) -> Void + let onRetry: (UUID) -> Void + let onDiscard: (UUID) -> Void func makeUIViewController(context: Context) -> QMSChatViewController { QMSChatViewController() @@ -28,6 +30,8 @@ struct QMSChatCollectionView: UIViewControllerRepresentable { controller.onLoadOlder = onLoadOlder controller.onURL = onURL controller.onAtBottomChanged = onAtBottomChanged + controller.onRetry = onRetry + controller.onDiscard = onDiscard controller.previewBackgroundColor = UIColor(background) controller.update(items: items, hasMoreOlder: hasMoreOlder) controller.handleScrollToBottomRequest(scrollToBottomRequest) @@ -39,6 +43,8 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { var onLoadOlder: () -> Void = {} var onURL: (URL) -> Void = { _ in } var onAtBottomChanged: (Bool) -> Void = { _ in } + var onRetry: (UUID) -> Void = { _ in } + var onDiscard: (UUID) -> Void = { _ in } var previewBackgroundColor: UIColor = .systemBackground private var collectionView: UICollectionView! @@ -115,9 +121,15 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { case let .day(date): QMSDayRow(date: date) case let .message(message): - QMSMessageRow(message: message) { [weak self] frame in - self?.bubbleFrames[item.id] = frame - } + QMSMessageRow( + message: message, + onBubbleFrame: { [weak self] frame in + self?.bubbleFrames[item.id] = frame + }, + onRetry: { [weak self] in + if let id = message.outgoingId { self?.onRetry(id) } + } + ) } } .environment(\.openURL, OpenURLAction { [weak self] url in @@ -251,15 +263,32 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { let id = dataSource.itemIdentifier(for: indexPath), case let .message(message) = items[id]?.kind else { return nil } - return UIContextMenuConfiguration(actionProvider: { _ in - UIMenu(children: [ - UIAction( - title: String(localized: "Copy", bundle: .module), - image: UIImage(systemName: "doc.on.doc") + return UIContextMenuConfiguration(actionProvider: { [weak self] _ in + var actions: [UIAction] = [] + if message.status == .failed, let id = message.outgoingId { + actions.append(UIAction( + title: String(localized: "Retry", bundle: .module), + image: UIImage(systemName: "arrow.clockwise") ) { _ in - UIPasteboard.general.string = message.plainText - } - ]) + self?.onRetry(id) + }) + } + actions.append(UIAction( + title: String(localized: "Copy", bundle: .module), + image: UIImage(systemName: "doc.on.doc") + ) { _ in + UIPasteboard.general.string = message.plainText + }) + if message.status == .failed, let id = message.outgoingId { + actions.append(UIAction( + title: String(localized: "Delete", bundle: .module), + image: UIImage(systemName: "trash"), + attributes: .destructive + ) { _ in + self?.onDiscard(id) + }) + } + return UIMenu(children: actions) }) } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift index 95f787c3..6fa70462 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift @@ -5,6 +5,7 @@ import Foundation import Models +import QMSClient /// Row of the chat feed. public struct QMSChatItem: Identifiable, Equatable, Sendable { @@ -25,7 +26,10 @@ public struct QMSChatItem: Identifiable, Equatable, Sendable { } static func message(_ message: QMSChatMessage) -> QMSChatItem { - QMSChatItem(id: "message-\(message.id)", kind: .message(message)) + if let outgoingId = message.outgoingId { + return QMSChatItem(id: "outgoing-\(outgoingId.uuidString)", kind: .message(message)) + } + return QMSChatItem(id: "message-\(message.id)", kind: .message(message)) } } @@ -33,11 +37,16 @@ public struct QMSChatMessage: Equatable, Sendable { public enum Status: Equatable, Sendable { case none + case sending + case failed case sent case read } + /// Server id, 0 for messages that are not confirmed yet public let id: Int + /// Local id of a message sent from this device and not confirmed by the server yet + public var outgoingId: UUID? = nil /// Rendered BB text, computed once per message text public let text: AttributedString public let date: Date @@ -62,11 +71,12 @@ enum QMSChatItemsBuilder { /// - render: converts raw message text to displayed text static func build( messages: [QMSMessage], + outgoing: [QMSOutgoingMessage] = [], chat: QMSChat, currentUserId: Int, isLoadingOlder: Bool, calendar: Calendar = .current, - render: (QMSMessage) -> AttributedString + render: (_ id: Int, _ text: String) -> AttributedString ) -> [QMSChatItem] { var items: [QMSChatItem] = [] items.reserveCapacity(messages.count + 8) @@ -77,9 +87,23 @@ enum QMSChatItemsBuilder { // Last `unreadCount` messages of the current user are not read by partner yet let unreadStart = max(messages.count - chat.unreadCount, 0) - for (index, message) in messages.enumerated() { - let previous = index > 0 ? messages[index - 1] : nil - let next = index + 1 < messages.count ? messages[index + 1] : nil + // Outgoing messages go last, as messages of the current user + struct Row { + let id: Int + let outgoing: QMSOutgoingMessage? + let senderId: Int + let date: Date + let text: String + } + let rows = messages.map { + Row(id: $0.id, outgoing: nil, senderId: $0.senderId, date: $0.date, text: $0.processedText) + } + outgoing.map { + Row(id: 0, outgoing: $0, senderId: currentUserId, date: $0.date, text: $0.processedText) + } + + for (index, message) in rows.enumerated() { + let previous = index > 0 ? rows[index - 1] : nil + let next = index + 1 < rows.count ? rows[index + 1] : nil let isNewDay = previous.map { !calendar.isDate($0.date, inSameDayAs: message.date) } ?? true if isNewDay { @@ -92,11 +116,18 @@ enum QMSChatItemsBuilder { } ?? true let isMine = message.senderId == currentUserId - let status: QMSChatMessage.Status = isMine ? (index >= unreadStart ? .sent : .read) : .none + let status: QMSChatMessage.Status + switch message.outgoing?.state { + case .sending: status = .sending + case .failed: status = .failed + case .sent: status = .sent + case nil: status = isMine ? (index >= unreadStart ? .sent : .read) : .none + } items.append(.message(QMSChatMessage( id: message.id, - text: render(message), + outgoingId: message.outgoing?.id, + text: render(message.id, message.text), date: message.date, isMine: isMine, status: status, @@ -131,8 +162,8 @@ final class QMSMessageRenderer: @unchecked Sendable { self.renderText = renderText } - func render(_ message: QMSMessage) -> AttributedString { - let key = Key(id: message.id, text: message.processedText) + func render(id: Int, text: String) -> AttributedString { + let key = Key(id: id, text: text) if let cached = lock.withLock({ cache[key] }) { return cached } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift index 5800549b..97006e19 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -14,6 +14,8 @@ struct QMSMessageRow: View { let message: QMSChatMessage /// Bubble frame in row coordinates, used to highlight only the bubble in context menu var onBubbleFrame: (CGRect) -> Void = { _ in } + /// Tap on a message that failed to send + var onRetry: () -> Void = {} private let avatarSize: CGFloat = 32 private static let coordinateSpace = "QMSMessageRow" @@ -32,6 +34,15 @@ struct QMSMessageRow: View { } action: { frame in onBubbleFrame(frame) } + .opacity(message.status == .sending ? 0.7 : 1) + .overlay { + // Only failed messages react to taps, others keep links tappable + if message.status == .failed { + Color.clear + .contentShape(Rectangle()) + .onTapGesture(perform: onRetry) + } + } if !message.isMine { Spacer(minLength: 48) @@ -74,6 +85,14 @@ struct QMSMessageRow: View { switch message.status { case .none: EmptyView() + case .sending: + Image(systemName: "clock") + .font(.caption2) + .foregroundStyle(Color(.systemGray)) + case .failed: + Image(systemName: "exclamationmark.circle.fill") + .font(.caption) + .foregroundStyle(.red) case .sent: Image(systemName: "checkmark") .font(.caption2.weight(.semibold)) diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index d481f72f..9d7a0900 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -14,6 +14,7 @@ import Models import AnalyticsClient import NotificationsClient import TCAExtensions +import UploadBoxFeature @Reducer public struct QMSFeature: Reducer, Sendable { @@ -42,12 +43,27 @@ public struct QMSFeature: Reducer, Sendable { /// Incremented to scroll the feed to the newest message var scrollToBottomRequest = 0 + /// Messages sent from this device and not confirmed by the server yet + public var outgoing: [QMSOutgoingMessage] = [] + var hasMoreOlderMessages = true var isLoadingMore = false - var isSending = false var draftText = "" - var draftSnapshot = "" + var upload = UploadBoxFeature.State.qms + var isAttachmentsShown = false + + var uploadedAttachments: [QMSOutgoingMessage.Attachment] { + upload.files.compactMap { file in + guard let id = file.serverId, file.uploadingError == nil else { return nil } + return QMSOutgoingMessage.Attachment(id: id, name: file.name) + } + } + + var canSend: Bool { + let hasText = !draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + return !upload.isAnyFileUploading && (hasText || !uploadedAttachments.isEmpty) + } public var title: String { if let chat { @@ -76,6 +92,9 @@ public struct QMSFeature: Reducer, Sendable { public enum View { case onAppear case sendMessageButtonTapped + case attachButtonTapped + case retryMessageTapped(UUID) + case discardMessageTapped(UUID) case loadMoreTriggered case urlTapped(URL) } @@ -87,9 +106,10 @@ public struct QMSFeature: Reducer, Sendable { case olderLoaded(Result) case snapshotUpdated(QMSDialogSnapshot) case itemsBuilt([QMSChatItem]) - case messageSendError(any Error) } + case upload(UploadBoxFeature.Action) + case delegate(Delegate) public enum Delegate { case handleUrl(URL) @@ -110,9 +130,13 @@ public struct QMSFeature: Reducer, Sendable { public var body: some Reducer { BindingReducer() + Scope(state: \.upload, action: \.upload) { + UploadBoxFeature() + } + Reduce { state, action in switch action { - case .alert, .delegate: + case .alert, .delegate, .upload: return .none case .view(.onAppear): @@ -145,20 +169,32 @@ public struct QMSFeature: Reducer, Sendable { ]) case .view(.sendMessageButtonTapped): + guard state.canSend else { return .none } let text = state.draftText.trimmingCharacters(in: .whitespacesAndNewlines) - guard !state.isSending, !text.isEmpty else { return .none } + let attachments = state.uploadedAttachments - state.draftSnapshot = state.draftText + // Message shows up in the feed right away, failures stay there with retry state.draftText = "" - state.isSending = true + state.upload = .qms + state.isAttachmentsShown = false state.scrollToBottomRequest += 1 - return .run { [chatId = state.chatId, message = text] send in - try await qmsClient.sendMessage(chatId: chatId, message: message) - // Don't rely on socket event, it may never come for the current chat - await send(.internal(.sync)) - } catch: { error, send in - await send(.internal(.messageSendError(error))) + return .run { [chatId = state.chatId] _ in + await qmsStore.send(dialogId: chatId, text: text, attachments: attachments) + } + + case .view(.attachButtonTapped): + state.isAttachmentsShown.toggle() + return .none + + case let .view(.retryMessageTapped(id)): + return .run { [chatId = state.chatId] _ in + await qmsStore.retry(dialogId: chatId, messageId: id) + } + + case let .view(.discardMessageTapped(id)): + return .run { [chatId = state.chatId] _ in + await qmsStore.discard(dialogId: chatId, messageId: id) } case .view(.loadMoreTriggered): @@ -172,13 +208,6 @@ public struct QMSFeature: Reducer, Sendable { } ) - case let .internal(.messageSendError(error)): - state.isSending = false - state.draftText = state.draftSnapshot - state.alert = .somethingWentWrong - analyticsClient.capture(error) - return .none - case let .view(.urlTapped(url)): guard url.absoluteString.contains("act=findpost"), let components = URLComponents(url: url, resolvingAgainstBaseURL: false), @@ -215,9 +244,6 @@ public struct QMSFeature: Reducer, Sendable { } case let .internal(.syncFinished(result)): - state.draftSnapshot = "" - state.isSending = false - if case let .failure(error) = result { analyticsClient.capture(error) // Failed background refresh of a shown chat is not worth an alert @@ -238,6 +264,7 @@ public struct QMSFeature: Reducer, Sendable { case let .internal(.snapshotUpdated(snapshot)): state.chat = snapshot.chat state.hasMoreOlderMessages = snapshot.hasMoreOlder + state.outgoing = snapshot.outgoing return buildItems(state) case let .internal(.itemsBuilt(items)): @@ -261,10 +288,12 @@ public struct QMSFeature: Reducer, Sendable { guard let chat = state.chat else { return .none } return .run { [ userId = state.userSession?.userId ?? 0, - isLoadingOlder = state.isLoadingMore + isLoadingOlder = state.isLoadingMore, + outgoing = state.outgoing ] send in let items = QMSChatItemsBuilder.build( messages: chat.messages, + outgoing: outgoing, chat: chat, currentUserId: userId, isLoadingOlder: isLoadingOlder, @@ -275,3 +304,11 @@ public struct QMSFeature: Reducer, Sendable { .cancellable(id: CancelID.render, cancelInFlight: true) } } + +private extension UploadBoxFeature.State { + static var qms: Self { + var state = UploadBoxFeature.State(type: .bbPanel) + state.isQms = true + return state + } +} diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 5221393f..131ae045 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -9,6 +9,7 @@ import SwiftUI import ComposableArchitecture import SharedUI import SFSafeSymbols +import UploadBoxFeature @ViewAction(for: QMSFeature.self) public struct QMSScreen: View { @@ -41,7 +42,9 @@ public struct QMSScreen: View { background: backgroundColors.primary, onLoadOlder: { send(.loadMoreTriggered) }, onURL: { send(.urlTapped($0)) }, - onAtBottomChanged: { isAtBottom = $0 } + onAtBottomChanged: { isAtBottom = $0 }, + onRetry: { send(.retryMessageTapped($0)) }, + onDiscard: { send(.discardMessageTapped($0)) } ) if !isAtBottom { @@ -85,42 +88,71 @@ public struct QMSScreen: View { // MARK: - Input private func InputBar() -> some View { - let canSend = !store.isSending && !store.draftText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - return HStack(alignment: .bottom, spacing: 8) { - TextField( - String(""), - text: $store.draftText, - prompt: Text("qms.textfield.placeholder", bundle: .module), - axis: .vertical - ) - .lineLimit(1...6) - .padding(.horizontal, 14) - .padding(.vertical, 10) - .background(Color(.Background.quaternary), in: .rect(cornerRadius: 20)) - - Button { - send(.sendMessageButtonTapped) - } label: { - ZStack { - Circle() - .fill(Color(.Theme.primary)) - if store.isSending { - ProgressView() - .tint(.white) - } else { - Image(systemSymbol: .arrowUp) - .font(.body.weight(.bold)) - .foregroundStyle(.white) + VStack(spacing: 0) { + if store.isAttachmentsShown { + UploadBoxView(store: store.scope(state: \.upload, action: \.upload)) + .padding(.horizontal, 12) + .padding(.top, 8) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } + + HStack(alignment: .bottom, spacing: 8) { + Button { + send(.attachButtonTapped) + } label: { + Image(systemSymbol: .paperclip) + .font(.body.weight(.semibold)) + .foregroundStyle(Color(.Theme.primary)) + .frame(width: 40, height: 40) + .overlay(alignment: .topTrailing) { + let count = store.upload.files.count + if count > 0 { + Text(count, format: .number) + .font(.caption2.bold()) + .foregroundStyle(.white) + .padding(4) + .background(Color(.Theme.primary), in: Circle()) + } + } + } + .accessibilityLabel(Text("Attach files", bundle: .module)) + + TextField( + String(""), + text: $store.draftText, + prompt: Text("qms.textfield.placeholder", bundle: .module), + axis: .vertical + ) + .lineLimit(1...6) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(Color(.Background.quaternary), in: .rect(cornerRadius: 20)) + + Button { + send(.sendMessageButtonTapped) + } label: { + ZStack { + Circle() + .fill(Color(.Theme.primary)) + if store.upload.isAnyFileUploading { + ProgressView() + .tint(.white) + } else { + Image(systemSymbol: .arrowUp) + .font(.body.weight(.bold)) + .foregroundStyle(.white) + } } + .frame(width: 40, height: 40) + .opacity(store.canSend || store.upload.isAnyFileUploading ? 1 : 0.5) } - .frame(width: 40, height: 40) - .opacity(canSend || store.isSending ? 1 : 0.5) + .disabled(!store.canSend) } - .disabled(!canSend) + .padding(.horizontal, 12) + .padding(.vertical, 8) } - .padding(.horizontal, 12) - .padding(.vertical, 8) - .animation(.default, value: store.isSending) + .animation(.default, value: store.isAttachmentsShown) + .animation(.default, value: store.upload.isAnyFileUploading) } } diff --git a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings index bcdbf030..eddc4e63 100644 --- a/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/QMSFeature/Resources/Localizable.xcstrings @@ -1,6 +1,22 @@ { "sourceLanguage" : "en", "strings" : { + "Attach files" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Attach files" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Прикрепить файлы" + } + } + } + }, "Copy" : { "localizations" : { "en" : { @@ -17,6 +33,38 @@ } } }, + "Delete" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Delete" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить" + } + } + } + }, + "Retry" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Retry" + } + }, + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Повторить" + } + } + } + }, "Today" : { "localizations" : { "en" : { diff --git a/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings b/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings index 065a21cf..57bcfb48 100644 --- a/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings +++ b/Modules/Sources/UploadBoxFeature/Resources/Localizable.xcstrings @@ -141,6 +141,16 @@ } } }, + "The selected files will be sent along with the message." : { + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Выбранные файлы будут отправлены вместе с сообщением." + } + } + } + }, "Try Again" : { "localizations" : { "ru" : { diff --git a/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift b/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift index 0f269b82..9d4f66a0 100644 --- a/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift +++ b/Modules/Sources/UploadBoxFeature/UploadBoxFeature.swift @@ -61,11 +61,13 @@ public struct UploadBoxFeature: Reducer, Sendable { @Presents public var destination: Destination.State? let type: UploadBoxType + /// Files for private messages are uploaded to a separate QMS storage + public var isQms = false public var allowedExtensions: [String] public var files: [UploadBoxFile] var uploadQueue: [UploadBoxFile.FileSource] = [] - var isAnyFileUploading = false + public internal(set) var isAnyFileUploading = false public var filesCount: Int { return files.count @@ -337,7 +339,7 @@ public struct UploadBoxFeature: Reducer, Sendable { case let .internal(.uploadFile(file, url)): state.isAnyFileUploading = true - return .run(priority: .userInitiated, name: file.name) { send in + return .run(priority: .userInitiated, name: file.name) { [isQms = state.isQms] send in if file.type == .file { guard url.startAccessingSecurityScopedResource() else { await send(.view(.fileUploadCanceled(file.id, .noAccessToSSR))) @@ -358,7 +360,7 @@ public struct UploadBoxFeature: Reducer, Sendable { return } - let request = UploadRequest(fileName: file.name, fileData: data, isQms: false) + let request = UploadRequest(fileName: file.name, fileData: data, isQms: isQms) await send(.delegate(.someFileUploading)) diff --git a/Modules/Sources/UploadBoxFeature/UploadBoxView.swift b/Modules/Sources/UploadBoxFeature/UploadBoxView.swift index b4946272..c139f23f 100644 --- a/Modules/Sources/UploadBoxFeature/UploadBoxView.swift +++ b/Modules/Sources/UploadBoxFeature/UploadBoxView.swift @@ -147,8 +147,14 @@ public struct UploadBoxView: View { .font(.body) .foregroundStyle(Color(.Labels.teritary)) - Text("The selected file will be inserted into the text as code wherever your cursor is located. Or it will also be automatically added to the end of the post.", bundle: .module) - .font(.footnote) + Group { + if store.isQms { + Text("The selected files will be sent along with the message.", bundle: .module) + } else { + Text("The selected file will be inserted into the text as code wherever your cursor is located. Or it will also be automatically added to the end of the post.", bundle: .module) + } + } + .font(.footnote) .foregroundStyle(Color(.Labels.teritary)) } .padding(.leading, 6) diff --git a/Modules/Tests/QMSClientTests/QMSStoreTests.swift b/Modules/Tests/QMSClientTests/QMSStoreTests.swift index ea9f8d67..e6e4cf0e 100644 --- a/Modules/Tests/QMSClientTests/QMSStoreTests.swift +++ b/Modules/Tests/QMSClientTests/QMSStoreTests.swift @@ -265,3 +265,137 @@ struct QMSDialogFileCacheTests { #expect(await cache.load(7) == nil) } } + +// MARK: - Outgoing + +@Suite("QMS store outgoing messages") +struct QMSStoreOutgoingTests { + + private struct SendError: Error {} + + /// Server keeps sent messages, latest page returns all of them + private final class Server: @unchecked Sendable { + let messages = LockIsolated<[Int]>([1]) + let failSend = LockIsolated(false) + let sent = LockIsolated<[String]>([]) + + func load(_ id: Int) -> QMSChat { + chat(id: id, total: messages.value.count, messages: messages.value) + } + + func send(_ text: String) throws { + if failSend.value { throw SendError() } + sent.withValue { $0.append(text) } + messages.withValue { $0.append(($0.last ?? 0) + 1) } + } + } + + private func makeStore(_ server: Server, cache: QMSDialogCache = .inMemory) -> QMSStore { + QMSStore( + loadChat: { id, _, _ in server.load(id) }, + sendMessage: { _, text, _ in try server.send(text) }, + cache: cache + ) + } + + @Test("Sent message is replaced by the real one after sync") + func sendSuccess() async throws { + let server = Server() + let store = makeStore(server) + try await store.sync(dialogId: 7) + + await store.send(dialogId: 7, text: "hello") + + let snapshot = try #require(await store.snapshot(dialogId: 7)) + #expect(snapshot.outgoing.isEmpty) + #expect(snapshot.chat.messages.map(\.id) == [1, 2]) + #expect(server.sent.value == ["hello"]) + } + + @Test("Message is visible while sending") + func visibleWhileSending() async throws { + let server = Server() + let (gate, open) = AsyncStream.makeStream(of: Void.self) + let store = QMSStore( + loadChat: { id, _, _ in server.load(id) }, + sendMessage: { _, text, _ in + for await _ in gate { break } + try server.send(text) + }, + cache: .inMemory + ) + try await store.sync(dialogId: 7) + + let sending = Task { await store.send(dialogId: 7, text: "hello") } + var outgoing: [QMSOutgoingMessage] = [] + while outgoing.isEmpty { + await Task.yield() + outgoing = await store.snapshot(dialogId: 7)?.outgoing ?? [] + } + #expect(outgoing.map(\.state) == [.sending]) + #expect(outgoing.map(\.text) == ["hello"]) + + open.yield() + await sending.value + #expect(await store.snapshot(dialogId: 7)?.outgoing.isEmpty == true) + } + + @Test("Failed message stays, retry sends it, discard removes it") + func failureRetryDiscard() async throws { + let server = Server() + server.failSend.setValue(true) + let store = makeStore(server) + try await store.sync(dialogId: 7) + + let first = try #require(await store.send(dialogId: 7, text: "first")) + let second = try #require(await store.send(dialogId: 7, text: "second")) + #expect(await store.snapshot(dialogId: 7)?.outgoing.map(\.state) == [.failed, .failed]) + + server.failSend.setValue(false) + await store.retry(dialogId: 7, messageId: first) + #expect(await store.snapshot(dialogId: 7)?.outgoing.map(\.id) == [second]) + #expect(server.sent.value == ["first"]) + + await store.discard(dialogId: 7, messageId: second) + #expect(await store.snapshot(dialogId: 7)?.outgoing.isEmpty == true) + #expect(server.sent.value == ["first"]) + } + + @Test("Message interrupted by app termination comes back as failed") + func restoredAsFailed() async throws { + let cache = QMSDialogCache.inMemory + let interrupted = QMSOutgoingMessage(id: UUID(), text: "a", attachments: [], date: .now, state: .sending) + let accepted = QMSOutgoingMessage(id: UUID(), text: "b", attachments: [], date: .now, state: .sent) + await cache.save(QMSDialogSnapshot( + chat: chat(total: 1, messages: [1]), + hasMoreOlder: false, + outgoing: [interrupted, accepted] + )) + let store = makeStore(Server(), cache: cache) + + var iterator = await store.observe(dialogId: 7).makeAsyncIterator() + let snapshot = try #require(await iterator.next()) + #expect(snapshot.outgoing.map(\.id) == [interrupted.id]) + #expect(snapshot.outgoing.map(\.state) == [.failed]) + } + + @Test("Attachments are sent with the message") + func attachments() async throws { + let ids = LockIsolated<[Int]>([]) + let store = QMSStore( + loadChat: { id, _, _ in chat(id: id, total: 1, messages: [1]) }, + sendMessage: { _, _, attachmentIds in ids.setValue(attachmentIds) }, + cache: .inMemory + ) + try await store.sync(dialogId: 7) + await store.send(dialogId: 7, text: "", attachments: [.init(id: 5, name: "a.jpg"), .init(id: 6, name: "b.zip")]) + #expect(ids.value == [5, 6]) + } + + @Test("Old cache without outgoing messages still loads") + func oldCacheFormat() throws { + let old = #"{"chat":{"id":7,"creationDate":0,"lastMessageDate":0,"name":"D","partnerId":1,"partnerName":"P","flag":0,"unknownId1":0,"totalCount":0,"unknownId2":0,"lastMessageId":0,"unreadCount":0,"messages":[]},"hasMoreOlder":false}"# + let snapshot = try JSONDecoder().decode(QMSDialogSnapshot.self, from: Data(old.utf8)) + #expect(snapshot.outgoing.isEmpty) + } +} diff --git a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift index 68fc5639..13dd2ef4 100644 --- a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift +++ b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift @@ -5,6 +5,7 @@ import Foundation import Models +import QMSClient import Testing @testable import QMSFeature @@ -36,14 +37,20 @@ struct QMSChatItemsBuilderTests { ) } - private func build(_ messages: [QMSMessage], unread: Int = 0, isLoadingOlder: Bool = false) -> [QMSChatItem] { + private func build( + _ messages: [QMSMessage], + outgoing: [QMSOutgoingMessage] = [], + unread: Int = 0, + isLoadingOlder: Bool = false + ) -> [QMSChatItem] { QMSChatItemsBuilder.build( messages: messages, + outgoing: outgoing, chat: chat(messages, unread: unread), currentUserId: me, isLoadingOlder: isLoadingOlder, calendar: calendar, - render: { AttributedString($0.text) } + render: { _, text in AttributedString(text) } ) } @@ -95,6 +102,28 @@ struct QMSChatItemsBuilderTests { #expect(items.first?.id == QMSChatItem.loadingOlder.id) } + @Test("Outgoing messages go last with their state and join the own group") + func outgoing() { + let sending = QMSOutgoingMessage( + id: UUID(), text: "new", attachments: [], date: Date(timeIntervalSince1970: day1 + 10), state: .sending + ) + let failed = QMSOutgoingMessage( + id: UUID(), text: "", attachments: [.init(id: 5, name: "a.jpg")], + date: Date(timeIntervalSince1970: day1 + 11), state: .failed + ) + let items = build([message(1, from: me, at: day1 + 1)], outgoing: [sending, failed]) + + #expect(items.map(\.id) == [ + "day-\(Int(day1))", "message-1", + "outgoing-\(sending.id.uuidString)", "outgoing-\(failed.id.uuidString)", + ]) + let result = messages(in: items) + #expect(result.map(\.status) == [.read, .sending, .failed]) + #expect(result.map(\.outgoingId) == [nil, sending.id, failed.id]) + #expect(result.map(\.isLastInGroup) == [false, false, true]) + #expect(result.last?.plainText == "[attachment=a.jpg,5]") + } + @Test("Empty dialog has no rows") func empty() { #expect(build([]).isEmpty) @@ -114,11 +143,11 @@ struct QMSMessageRendererTests { let original = QMSMessage(id: 1, senderId: 1, date: .now, text: "a", attachments: []) let edited = QMSMessage(id: 1, senderId: 1, date: .now, text: "b", attachments: []) - _ = renderer.render(original) - _ = renderer.render(original) + _ = renderer.render(id: original.id, text: original.text) + _ = renderer.render(id: original.id, text: original.text) #expect(renders == 1) - #expect(String(renderer.render(edited).characters) == "b") + #expect(String(renderer.render(id: edited.id, text: edited.text).characters) == "b") #expect(renders == 2) } @@ -129,7 +158,7 @@ struct QMSMessageRendererTests { text.link = URL(string: "https://4pda.to") return text } - let rendered = renderer.render(QMSMessage(id: 1, senderId: 1, date: .now, text: "", attachments: [])) + let rendered = renderer.render(id: 1, text: "") #expect(rendered.runs.first?.underlineStyle == .single) } } diff --git a/Project.swift b/Project.swift index 009aa48d..e13e4dcd 100644 --- a/Project.swift +++ b/Project.swift @@ -529,6 +529,7 @@ let project = Project( .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, + .Internal.UploadBoxFeature, .SPM.NukeUI, .SPM.SFSafeSymbols, .SPM.SkeletonUI, From ebf650c3665e7a076d4ac80725bf7fd408c321b8 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:03:13 +0100 Subject: [PATCH 06/12] Move QMS dialog list to QMSListStore - QMSListStore keeps the list in memory and on disk, so the list opens instantly and refreshes in background; dialogs of a partner are kept when the list response comes without them - List syncs are coalesced, repeated loads of a partner's dialogs share one request - QMSListFeature observes the store; long-running effects are cancellable, so returning from a chat no longer adds another unread subscription - Expanded partners are tracked by user id instead of row index, so the right groups stay expanded after the list is reordered - Failure to load one partner's dialogs no longer turns the whole screen into an error, and a failed refresh keeps the cached list - List cache is removed on logout and on cache clearing Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/AppFeature/AppFeature.swift | 2 + Modules/Sources/QMSClient/QMSListStore.swift | 227 ++++++++++++++++++ .../Analytics/QMSListFeature+Analytics.swift | 3 + .../QMSListFeature/QMSListFeature.swift | 151 +++++------- .../QMSListFeature/QMSListScreen.swift | 7 +- .../SettingsFeature/SettingsFeature.swift | 2 + .../QMSClientTests/QMSListStoreTests.swift | 130 ++++++++++ Project.swift | 1 - 8 files changed, 434 insertions(+), 89 deletions(-) create mode 100644 Modules/Sources/QMSClient/QMSListStore.swift create mode 100644 Modules/Tests/QMSClientTests/QMSListStoreTests.swift diff --git a/Modules/Sources/AppFeature/AppFeature.swift b/Modules/Sources/AppFeature/AppFeature.swift index 2d23e1b4..fb1cc715 100644 --- a/Modules/Sources/AppFeature/AppFeature.swift +++ b/Modules/Sources/AppFeature/AppFeature.swift @@ -178,6 +178,7 @@ public struct AppFeature: Reducer, Sendable { @Dependency(\.apiClient) private var apiClient @Dependency(\.cacheClient) private var cacheClient @Dependency(\.qmsStore) private var qmsStore + @Dependency(\.qmsListStore) private var qmsListStore @Dependency(\.toastClient) private var toastClient @Dependency(\.hapticClient) private var hapticClient @Dependency(\.analyticsClient) private var analyticsClient @@ -406,6 +407,7 @@ public struct AppFeature: Reducer, Sendable { state.profileBadges = 0 return .run { _ in await qmsStore.removeAll() + await qmsListStore.removeAll() notificationsClient.setNotificationContext(context: nil) await notificationsClient.removeNotifications( categories: [.qmsMessage, .newTopic, .newPost, .forumMention, .siteMention] diff --git a/Modules/Sources/QMSClient/QMSListStore.swift b/Modules/Sources/QMSClient/QMSListStore.swift new file mode 100644 index 00000000..4bcf4433 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSListStore.swift @@ -0,0 +1,227 @@ +// +// QMSListStore.swift +// QMSClient +// + +import ComposableArchitecture +import Foundation +import Models +import PersistenceKeys + +/// Single source of truth for the list of QMS partners and their dialogs. +/// +/// - Shows cached list instantly and refreshes it in background +/// - Keeps dialogs of a partner when the list response comes without them +/// - Coalesces list syncs and per partner loads +public actor QMSListStore { + + public typealias LoadList = @Sendable () async throws -> QMSList + public typealias LoadUser = @Sendable (_ id: Int) async throws -> QMSUser + + private let loadList: LoadList + private let loadUser: LoadUser + private let cache: QMSListCache + + private var list: QMSList? + private var observers: [UUID: AsyncStream.Continuation] = [:] + + private var syncTask: Task? + private var isSyncPending = false + private var userTasks: [Int: Task] = [:] + + public init(loadList: @escaping LoadList, loadUser: @escaping LoadUser, cache: QMSListCache) { + self.loadList = loadList + self.loadUser = loadUser + self.cache = cache + } + + // MARK: - Observe + + /// Stream of the list. Yields known (in memory or cached) list right away. + public func observe() async -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream(of: QMSList.self, bufferingPolicy: .bufferingNewest(1)) + let token = UUID() + observers[token] = continuation + continuation.onTermination = { [weak self] _ in + Task { await self?.removeObserver(token) } + } + if list == nil, let cached = await cache.load(), list == nil { + list = cached + } + if let list { + continuation.yield(list) + } + return stream + } + + public func currentList() -> QMSList? { + list + } + + // MARK: - Sync + + /// Loads the list. Calls during a running sync lead to at most one extra request. + public func sync() async throws { + if let syncTask { + isSyncPending = true + try await syncTask.value + return + } + let task = Task { try await self.runSync() } + syncTask = task + try await task.value + } + + private func runSync() async throws { + defer { + syncTask = nil + isSyncPending = false + } + repeat { + isSyncPending = false + let fresh = try await loadList() + await publish(merged(fresh)) + } while isSyncPending + } + + /// Loads dialogs of a partner. Repeated calls while loading wait for the same request. + public func loadDialogs(userId: Int) async throws { + if let running = userTasks[userId] { + try await running.value + return + } + let task = Task { + defer { self.userTasks[userId] = nil } + let user = try await self.loadUser(userId) + await self.apply(user) + } + userTasks[userId] = task + try await task.value + } + + public func removeAll() async { + list = nil + await cache.removeAll() + } + + // MARK: - Private + + /// List response may come without dialogs of a partner, known ones are kept then + private func merged(_ fresh: QMSList) -> QMSList { + guard let list else { return fresh } + let knownChats = Dictionary(list.users.map { ($0.id, $0.chats) }, uniquingKeysWith: { first, _ in first }) + var result = fresh + for index in result.users.indices where result.users[index].chats.isEmpty { + result.users[index].chats = knownChats[result.users[index].id] ?? [] + } + return result + } + + private func apply(_ user: QMSUser) async { + guard var updated = list, + let index = updated.users.firstIndex(where: { $0.id == user.id }) else { return } + updated.users[index].chats = user.chats.sorted { $0.lastMessageDate > $1.lastMessageDate } + await publish(updated) + } + + private func publish(_ new: QMSList) async { + guard new != list else { return } + list = new + for continuation in observers.values { + continuation.yield(new) + } + await cache.save(new) + } + + private func removeObserver(_ token: UUID) { + observers[token] = nil + } +} + +// MARK: - Cache + +public struct QMSListCache: Sendable { + public var load: @Sendable () async -> QMSList? + public var save: @Sendable (QMSList) async -> Void + public var removeAll: @Sendable () async -> Void + + public init( + load: @escaping @Sendable () async -> QMSList?, + save: @escaping @Sendable (QMSList) async -> Void, + removeAll: @escaping @Sendable () async -> Void + ) { + self.load = load + self.save = save + self.removeAll = removeAll + } + + public static var liveValue: QMSListCache { + let root = URL.cachesDirectory.appending(path: "QMS", directoryHint: .isDirectory) + return file(root: root) { + @Shared(.userSession) var userSession + return userSession?.userId + } + } + + /// Stored next to dialog caches, in the folder of the current user + static func file(root: URL, userId: @escaping @Sendable () -> Int?) -> QMSListCache { + let url: @Sendable () -> URL? = { + userId().map { root.appending(path: "\($0)/list.json", directoryHint: .notDirectory) } + } + return QMSListCache( + load: { + guard let url = url(), let data = try? Data(contentsOf: url) else { return nil } + return try? JSONDecoder().decode(QMSList.self, from: data) + }, + save: { list in + guard let url = url(), let data = try? JSONEncoder().encode(list) else { return } + try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try? data.write(to: url, options: .atomic) + }, + removeAll: { + guard let url = url() else { return } + try? FileManager.default.removeItem(at: url) + } + ) + } + + public static var inMemory: QMSListCache { + let storage = LockIsolated(nil) + return QMSListCache( + load: { storage.value }, + save: { storage.setValue($0) }, + removeAll: { storage.setValue(nil) } + ) + } +} + +// MARK: - Dependency + +extension QMSListStore: DependencyKey { + public static var liveValue: QMSListStore { + @Dependency(\.qmsClient) var qmsClient + return QMSListStore( + loadList: { try await qmsClient.loadChatList() }, + loadUser: { try await qmsClient.loadUser(id: $0) }, + cache: .liveValue + ) + } + + public static var testValue: QMSListStore { + @Dependency(\.qmsClient) var qmsClient + return QMSListStore( + loadList: { try await qmsClient.loadChatList() }, + loadUser: { try await qmsClient.loadUser(id: $0) }, + cache: .inMemory + ) + } + + public static var previewValue: QMSListStore { testValue } +} + +extension DependencyValues { + public var qmsListStore: QMSListStore { + get { self[QMSListStore.self] } + set { self[QMSListStore.self] = newValue } + } +} diff --git a/Modules/Sources/QMSListFeature/Analytics/QMSListFeature+Analytics.swift b/Modules/Sources/QMSListFeature/Analytics/QMSListFeature+Analytics.swift index 205e993f..44ae2b1b 100644 --- a/Modules/Sources/QMSListFeature/Analytics/QMSListFeature+Analytics.swift +++ b/Modules/Sources/QMSListFeature/Analytics/QMSListFeature+Analytics.swift @@ -47,6 +47,9 @@ extension QMSListFeature { case .view(.userRowTapped): analytics.log(QMSListEvent.userTapped(isExpandable: true)) + case .view(.userExpansionChanged): + break + case let .view(.userContextMenu(userContextAction, _)): switch userContextAction { case .createChatButtonTapped: diff --git a/Modules/Sources/QMSListFeature/QMSListFeature.swift b/Modules/Sources/QMSListFeature/QMSListFeature.swift index 7e43a6f3..06a36774 100644 --- a/Modules/Sources/QMSListFeature/QMSListFeature.swift +++ b/Modules/Sources/QMSListFeature/QMSListFeature.swift @@ -5,7 +5,6 @@ // Created by Ilia Lubianoi on 17.11.2024. // -import CacheClient import CreateChatFeature import ComposableArchitecture import Foundation @@ -37,7 +36,9 @@ public struct QMSListFeature: Reducer, Sendable { var viewState: ViewState public var qms: QMSList? var goTo: Int? - var expandedGroups: [Bool] = [] + var didHandleGoTo = false + /// Partners whose dialogs are shown, by user id so it survives list reordering + var expandedUserIds: Set = [] var pendingUserLoads: [Int: Int] = [:] public init( @@ -72,6 +73,7 @@ public struct QMSListFeature: Reducer, Sendable { case onAppear case onRefresh case userRowTapped(Int) + case userExpansionChanged(Int, Bool) case userContextMenu(UserContextMenu, QMSUser) case chatRowTapped(Int) case chatContextMenu(ChatContextMenu, Int, Int) // ChatID, UserID @@ -91,9 +93,10 @@ public struct QMSListFeature: Reducer, Sendable { public enum Internal { case loadQMS case loadQMSAfterChatCreated(userId: Int) - case qmsLoaded(Result) + case qmsLoaded(Result) + case listUpdated(QMSList) case loadUser(_ id: Int) - case userLoaded(userId: Int, Result) + case userLoaded(userId: Int, Result) } case delegate(Delegate) @@ -107,31 +110,18 @@ public struct QMSListFeature: Reducer, Sendable { @Dependency(\.notificationsClient) private var notificationsClient @Dependency(\.analyticsClient) private var analyticsClient - @Dependency(\.cacheClient) private var cacheClient @Dependency(\.qmsClient) private var qmsClient + @Dependency(\.qmsListStore) private var qmsListStore + + private enum CancelID: Hashable { + case observe + case unread + } // MARK: - Body public var body: some Reducer { BindingReducer() - .onChange(of: \.expandedGroups) { oldState, state in - .run { [after = state.expandedGroups, qms = state.qms] send in - func changedIndex(before: [Bool], after: [Bool]) -> Int? { - guard before.count == after.count else { return nil } - for index in before.indices { - if before[index] == false && after[index] == true { - return index - } - } - return nil - } - if let index = changedIndex(before: oldState, after: after), - let userId = qms?.users[index].userId, - userId != 0 { - await send(.internal(.loadUser(userId))) - } - } - } Reduce { state, action in switch action { @@ -159,30 +149,44 @@ public struct QMSListFeature: Reducer, Sendable { // MARK: - View case .view(.onAppear): - return .run { send in - await send(.internal(.loadQMS)) + // onAppear fires again when returning from a chat, long-running effects are restarted, not duplicated + return .merge( + .run { send in + for await list in await qmsListStore.observe() { + await send(.internal(.listUpdated(list))) + } + } + .cancellable(id: CancelID.observe, cancelInFlight: true), - // TODO: Does this cancel on feature removal? - for await unread in notificationsClient.unreadPublisher().values.dropFirst() { - guard unread.qmsUnreadCount > 0 else { continue } - await send(.internal(.loadQMS)) + .send(.internal(.loadQMS)), + + .run { send in + for await unread in notificationsClient.unreadPublisher().values.dropFirst() { + guard unread.qmsUnreadCount > 0 else { continue } + await send(.internal(.loadQMS)) + } } - } + .cancellable(id: CancelID.unread, cancelInFlight: true) + ) case .view(.onRefresh): return .run { send in - await send(.internal(.loadQMS)) + let result = await Result { try await qmsListStore.sync() } + await send(.internal(.qmsLoaded(result))) } case let .view(.userRowTapped(userId)): - guard let qms = state.qms else { return .none } - guard let index = qms.users.firstIndex(where: { $0.id == userId }) else { return .none } + let isExpanded = state.expandedUserIds.contains(userId) + return .send(.view(.userExpansionChanged(userId, !isExpanded))) - state.expandedGroups[index].toggle() - - return .run { send in - guard userId != 0 else { return } - await send(.internal(.loadUser(userId))) + case let .view(.userExpansionChanged(userId, isExpanded)): + if isExpanded { + state.expandedUserIds.insert(userId) + // Dialogs are refreshed on every expand, cached ones are shown meanwhile + return userId == 0 ? .none : .send(.internal(.loadUser(userId))) + } else { + state.expandedUserIds.remove(userId) + return .none } case let .view(.userContextMenu(userContextAction, user)): @@ -239,57 +243,43 @@ public struct QMSListFeature: Reducer, Sendable { case .internal(.loadQMS): return .run { send in - let result = await Result { try await qmsClient.loadChatList() } + let result = await Result { try await qmsListStore.sync() } await send(.internal(.qmsLoaded(result))) } case let .internal(.loadQMSAfterChatCreated(userId)): return .run { send in - let qmsResult = await Result { try await qmsClient.loadChatList() } - await send(.internal(.qmsLoaded(qmsResult))) - - guard case .success = qmsResult else { return } + let result = await Result { try await qmsListStore.sync() } + await send(.internal(.qmsLoaded(result))) + guard case .success = result else { return } await send(.internal(.loadUser(userId))) } case let .internal(.qmsLoaded(result)): - switch result { - case let .success(qms): - var qms = qms - // customDump(qms) - - if state.expandedGroups.count != qms.users.count { - let previousExpandedGroups = state.expandedGroups - state.expandedGroups = qms.users.indices.map { index in - previousExpandedGroups.indices.contains(index) ? previousExpandedGroups[index] : false - } - } - - for (index, user) in qms.users.enumerated() where user.chats.isEmpty { - if let cachedChats = cacheClient.getQMSChats(user.id) { - qms.users[index].chats = cachedChats - } - } - - state.qms = qms - state.viewState = qms.users.isEmpty ? .empty : .loaded(qms) - - if let goTo = state.goTo, let index = qms.users.firstIndex(where: { $0.id == goTo }) { - state.expandedGroups[index] = true - return .send(.internal(.loadUser(goTo))) + if case let .failure(error) = result { + analyticsClient.capture(error) + // Cached list stays on screen if refresh failed + if state.qms == nil { + state.viewState = .error } - - case let .failure(error): - print(error) - state.viewState = .error } analyticsClient.reportFullyDisplayed() return .none + case let .internal(.listUpdated(qms)): + state.qms = qms + state.viewState = qms.users.isEmpty ? .empty : .loaded(qms) + + if !state.didHandleGoTo, let goTo = state.goTo, qms.users.contains(where: { $0.id == goTo }) { + state.didHandleGoTo = true + return .send(.view(.userExpansionChanged(goTo, true))) + } + return .none + case let .internal(.loadUser(userId)): state.pendingUserLoads[userId, default: 0] += 1 return .run { send in - let result = await Result { try await qmsClient.loadUser(id: userId) } + let result = await Result { try await qmsListStore.loadDialogs(userId: userId) } await send(.internal(.userLoaded(userId: userId, result))) } @@ -299,20 +289,9 @@ public struct QMSListFeature: Reducer, Sendable { } else { state.pendingUserLoads.removeValue(forKey: userId) } - - switch result { - case let .success(user): - if var qms = state.qms, - let index = qms.users.firstIndex(where: { $0.id == user.id }) { - qms.users[index].chats = user.chats.sorted(by: { $0.lastMessageDate > $1.lastMessageDate }) - state.qms = qms - cacheClient.setQMSChats(qms.users[index].id, user.chats) - state.viewState = .loaded(qms) - } - - case let .failure(error): - print(error) - state.viewState = .error + // Failure of one partner's dialogs doesn't break the whole list + if case let .failure(error) = result { + analyticsClient.capture(error) } return .none diff --git a/Modules/Sources/QMSListFeature/QMSListScreen.swift b/Modules/Sources/QMSListFeature/QMSListScreen.swift index c6fa583b..bdacae16 100644 --- a/Modules/Sources/QMSListFeature/QMSListScreen.swift +++ b/Modules/Sources/QMSListFeature/QMSListScreen.swift @@ -41,9 +41,12 @@ public struct QMSListScreen: View { case let .loaded(qms): ScrollViewReader { proxy in QMSList { - ForEach(Array(qms.users.enumerated()), id: \.1) { index, user in + ForEach(qms.users) { user in WithPerceptionTracking { - DisclosureGroup(isExpanded: $store.expandedGroups[index]) { + DisclosureGroup(isExpanded: Binding( + get: { store.expandedUserIds.contains(user.id) }, + set: { send(.userExpansionChanged(user.id, $0)) } + )) { ExpandedUserContent(user) } label: { UserRow(user) diff --git a/Modules/Sources/SettingsFeature/SettingsFeature.swift b/Modules/Sources/SettingsFeature/SettingsFeature.swift index 9bb2d963..32614c65 100644 --- a/Modules/Sources/SettingsFeature/SettingsFeature.swift +++ b/Modules/Sources/SettingsFeature/SettingsFeature.swift @@ -123,6 +123,7 @@ public struct SettingsFeature: Reducer, Sendable { @Dependency(\.analyticsClient) var analyticsClient @Dependency(\.cacheClient) var cacheClient @Dependency(\.qmsStore) var qmsStore + @Dependency(\.qmsListStore) var qmsListStore @Dependency(\.openURL) var openURL // MARK: - Body @@ -186,6 +187,7 @@ public struct SettingsFeature: Reducer, Sendable { do { try await cacheClient.removeAll() await qmsStore.removeAll() + await qmsListStore.removeAll() } catch { await send(._somethingWentWrong(error)) } diff --git a/Modules/Tests/QMSClientTests/QMSListStoreTests.swift b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift new file mode 100644 index 00000000..233ddbb0 --- /dev/null +++ b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift @@ -0,0 +1,130 @@ +// +// QMSListStoreTests.swift +// QMSClientTests +// + +import ConcurrencyExtras +import Foundation +import Models +import Testing + +@testable import QMSClient + +private func dialog(_ id: Int, date: TimeInterval = 0) -> QMSChatInfo { + QMSChatInfo( + id: id, creationDate: .distantPast, lastMessageDate: Date(timeIntervalSince1970: date), + name: "Dialog \(id)", totalCount: 1, unreadCount: 0, lastMessageId: 0 + ) +} + +private func user(_ id: Int, chats: [QMSChatInfo] = []) -> QMSUser { + QMSUser( + userId: id, name: "User \(id)", flag: 0, avatarUrl: nil, + lastSeenOnline: .distantPast, lastMessageDate: .distantPast, unreadCount: 0, chats: chats + ) +} + +@Suite("QMS list store") +struct QMSListStoreTests { + + @Test("Dialogs of a partner survive a list sync without them") + func keepsDialogs() async throws { + let store = QMSListStore( + loadList: { QMSList(users: [user(1), user(2)]) }, + loadUser: { user($0, chats: [dialog(10, date: 1), dialog(11, date: 2)]) }, + cache: .inMemory + ) + try await store.sync() + try await store.loadDialogs(userId: 1) + try await store.sync() + + let list = try #require(await store.currentList()) + // Newest dialog first + #expect(list.users.first?.chats.map(\.id) == [11, 10]) + #expect(list.users.last?.chats.isEmpty == true) + } + + @Test("Cached list is shown before network") + func cachedFirst() async throws { + let cache = QMSListCache.inMemory + await cache.save(QMSList(users: [user(5)])) + let store = QMSListStore( + loadList: { throw CancellationError() }, + loadUser: { _ in throw CancellationError() }, + cache: cache + ) + var iterator = await store.observe().makeAsyncIterator() + #expect(await iterator.next()?.users.map(\.id) == [5]) + } + + @Test("Syncs during a running sync are coalesced into one extra request") + func coalescing() async throws { + let requests = LockIsolated(0) + let (gate, open) = AsyncStream.makeStream(of: Void.self) + let store = QMSListStore( + loadList: { + let number = requests.withValue { $0 += 1; return $0 } + if number == 1 { + for await _ in gate { break } + } + return QMSList(users: [user(number)]) + }, + loadUser: { user($0) }, + cache: .inMemory + ) + + let first = Task { try await store.sync() } + while requests.value == 0 { await Task.yield() } + let others = (0..<5).map { _ in Task { try await store.sync() } } + for _ in 0..<200 { await Task.yield() } + open.yield() + + try await first.value + for task in others { try await task.value } + #expect(requests.value == 2) + #expect(await store.currentList()?.users.map(\.id) == [2]) + } + + @Test("Repeated dialog loads of the same partner make one request") + func userLoadDeduplication() async throws { + let requests = LockIsolated(0) + let (gate, open) = AsyncStream.makeStream(of: Void.self) + let store = QMSListStore( + loadList: { QMSList(users: [user(1)]) }, + loadUser: { id in + requests.withValue { $0 += 1 } + for await _ in gate { break } + return user(id, chats: [dialog(10)]) + }, + cache: .inMemory + ) + try await store.sync() + + let loads = (0..<3).map { _ in Task { try await store.loadDialogs(userId: 1) } } + while requests.value == 0 { await Task.yield() } + for _ in 0..<200 { await Task.yield() } + open.yield() + for task in loads { try await task.value } + + #expect(requests.value == 1) + #expect(await store.currentList()?.users.first?.chats.map(\.id) == [10]) + } + + @Test("List cache is stored per user") + func fileCache() async throws { + let root = URL.temporaryDirectory.appending(path: "QMSListCacheTests-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: root) } + let userId = LockIsolated(1) + let cache = QMSListCache.file(root: root, userId: { userId.value }) + + await cache.save(QMSList(users: [user(3, chats: [dialog(30)])])) + #expect(await cache.load()?.users.first?.chats.map(\.id) == [30]) + + userId.setValue(2) + #expect(await cache.load() == nil) + + userId.setValue(1) + await cache.removeAll() + #expect(await cache.load() == nil) + } +} diff --git a/Project.swift b/Project.swift index e13e4dcd..9fa6173c 100644 --- a/Project.swift +++ b/Project.swift @@ -505,7 +505,6 @@ let project = Project( name: "QMSListFeature", dependencies: [ .Internal.AnalyticsClient, - .Internal.CacheClient, .Internal.CreateChatFeature, .Internal.Models, .Internal.NotificationsClient, From 16f1d9157fa6cde129741e8ce3f09b9c778e3159 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:06:50 +0100 Subject: [PATCH 07/12] Render QMS BB blocks with TopicView Messages with quotes, code, spoilers and other BB blocks are built into TopicNodeBuilder nodes in background, together with formatted text, and cached per message. Such messages are drawn with TopicView like forum posts; plain formatted messages keep the fast Text path. Attachments referenced in the text are passed to the builder, the rest stay as download links above the text. Based on the BB rendering from SubvertDev/ForPDA#66. Co-Authored-By: Claude Opus 5.5 --- .../QMSClient/QMSOutgoingMessage.swift | 2 +- .../Chat/QMSChatCollectionView.swift | 3 + .../Sources/QMSFeature/Chat/QMSChatItem.swift | 141 ++++++++++++++---- .../Sources/QMSFeature/Chat/QMSChatRows.swift | 20 ++- Modules/Sources/QMSFeature/QMSFeature.swift | 2 +- .../QMSChatItemsBuilderTests.swift | 81 +++++++--- Project.swift | 2 + 7 files changed, 194 insertions(+), 57 deletions(-) diff --git a/Modules/Sources/QMSClient/QMSOutgoingMessage.swift b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift index 192bdf81..85681dab 100644 --- a/Modules/Sources/QMSClient/QMSOutgoingMessage.swift +++ b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift @@ -15,7 +15,7 @@ public struct QMSOutgoingMessage: Equatable, Sendable, Codable, Identifiable { case sent } - public struct Attachment: Equatable, Sendable, Codable { + public struct Attachment: Hashable, Sendable, Codable { public let id: Int public let name: String diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift index 3f298047..4f0c3c6f 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -128,6 +128,9 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { }, onRetry: { [weak self] in if let id = message.outgoingId { self?.onRetry(id) } + }, + onURL: { [weak self] url in + self?.onURL(url) } ) } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift index 6fa70462..776bcbdb 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift @@ -6,6 +6,8 @@ import Foundation import Models import QMSClient +import SharedUI +import TopicBuilder /// Row of the chat feed. public struct QMSChatItem: Identifiable, Equatable, Sendable { @@ -57,6 +59,9 @@ public struct QMSChatMessage: Equatable, Sendable { public let isFirstInGroup: Bool public let isLastInGroup: Bool + /// BB blocks (quotes, code, spoilers...) of a message that is not just formatted text, nil otherwise + public var nodes: [UITopicType]? = nil + /// Text for copying public var plainText: String { String(text.characters) @@ -76,7 +81,7 @@ enum QMSChatItemsBuilder { currentUserId: Int, isLoadingOlder: Bool, calendar: Calendar = .current, - render: (_ id: Int, _ text: String) -> AttributedString + render: (QMSRenderInput) -> QMSRenderedText ) -> [QMSChatItem] { var items: [QMSChatItem] = [] items.reserveCapacity(messages.count + 8) @@ -89,16 +94,29 @@ enum QMSChatItemsBuilder { // Outgoing messages go last, as messages of the current user struct Row { - let id: Int let outgoing: QMSOutgoingMessage? let senderId: Int let date: Date - let text: String + let input: QMSRenderInput + var id: Int { input.id } } - let rows = messages.map { - Row(id: $0.id, outgoing: nil, senderId: $0.senderId, date: $0.date, text: $0.processedText) - } + outgoing.map { - Row(id: 0, outgoing: $0, senderId: currentUserId, date: $0.date, text: $0.processedText) + let rows = messages.map { message in + let inline = message.inlineAttachmentIds + return Row(outgoing: nil, senderId: message.senderId, date: message.date, input: QMSRenderInput( + id: message.id, + text: message.text, + inlineAttachments: message.attachments.filter { inline.contains($0.id) }, + linkedAttachments: message.attachments + .filter { !inline.contains($0.id) } + .map { QMSOutgoingMessage.Attachment(id: $0.id, name: $0.name) } + )) + } + outgoing.map { message in + Row(outgoing: message, senderId: currentUserId, date: message.date, input: QMSRenderInput( + id: 0, + text: message.text, + inlineAttachments: [], + linkedAttachments: message.attachments + )) } for (index, message) in rows.enumerated() { @@ -124,16 +142,18 @@ enum QMSChatItemsBuilder { case nil: status = isMine ? (index >= unreadStart ? .sent : .read) : .none } + let rendered = render(message.input) items.append(.message(QMSChatMessage( id: message.id, outgoingId: message.outgoing?.id, - text: render(message.id, message.text), + text: rendered.text, date: message.date, isMine: isMine, status: status, avatarUrl: isMine || !isLastInGroup ? nil : (chat.avatarUrl ?? Links.defaultQMSAvatar), isFirstInGroup: isFirstInGroup, - isLastInGroup: isLastInGroup + isLastInGroup: isLastInGroup, + nodes: rendered.nodes ))) } return items @@ -142,41 +162,104 @@ enum QMSChatItemsBuilder { // MARK: - Renderer -/// Caches rendered message texts, BB rendering is the most expensive part of building the feed. -final class QMSMessageRenderer: @unchecked Sendable { - - static let shared = QMSMessageRenderer() - - private struct Key: Hashable { - let id: Int - let text: String +/// What a message bubble is rendered from. +struct QMSRenderInput: Hashable, Sendable { + let id: Int + /// Raw BB text + let text: String + /// Attachments referenced in the text itself + let inlineAttachments: [Attachment] + /// Attachments not referenced in the text, shown as download links above it + let linkedAttachments: [QMSOutgoingMessage.Attachment] + + var linksText: String { + linkedAttachments.map { "[attachment=\($0.name),\($0.id)]" }.joined(separator: "\n\n") } + + /// Text with links, rendered as formatted text + var processedText: String { + let links = linksText + if links.isEmpty { return text } + return text.isEmpty ? links : links + "\n\n" + text + } +} + +struct QMSRenderedText: Equatable, Sendable { + /// Formatted text, also used for copying + let text: AttributedString + /// Present only when the message has BB blocks that formatted text can't show + let nodes: [UITopicType]? +} +/// Caches rendered messages, BB rendering is the most expensive part of building the feed. +final class QMSMessageRenderer: @unchecked Sendable { + + static let shared = QMSMessageRenderer() + private let lock = NSLock() - private var cache: [Key: AttributedString] = [:] + private var cache: [QMSRenderInput: QMSRenderedText] = [:] private let limit: Int private let renderText: (String) -> AttributedString - - init(limit: Int = 3000, renderText: @escaping (String) -> AttributedString = { QMSBuilder(text: $0).build() }) { + private let buildNodes: (String, [Attachment]) -> [UITopicType] + + init( + limit: Int = 3000, + renderText: @escaping (String) -> AttributedString = { QMSBuilder(text: $0).build() }, + buildNodes: @escaping (String, [Attachment]) -> [UITopicType] = { text, attachments in + TopicNodeBuilder(text: text, attachments: attachments).build() + } + ) { self.limit = limit self.renderText = renderText + self.buildNodes = buildNodes } - - func render(id: Int, text: String) -> AttributedString { - let key = Key(id: id, text: text) - if let cached = lock.withLock({ cache[key] }) { + + func render(_ input: QMSRenderInput) -> QMSRenderedText { + if let cached = lock.withLock({ cache[input] }) { return cached } - var rendered = renderText(key.text) - for (link, range) in rendered.runs[\.link] where link != nil { - rendered[range].underlineStyle = .single - } + let rendered = QMSRenderedText(text: underlineLinks(renderText(input.processedText)), nodes: nodes(for: input)) lock.withLock { if cache.count >= limit { cache.removeAll(keepingCapacity: true) } - cache[key] = rendered + cache[input] = rendered } return rendered } + + private func nodes(for input: QMSRenderInput) -> [UITopicType]? { + guard !input.text.isEmpty else { return nil } + let nodes = buildNodes(input.text, input.inlineAttachments) + if nodes.count == 1, case .text = nodes[0] { + // Just formatted text, fast path renders it + return nil + } + let links = input.linksText + return links.isEmpty ? nodes : [.text(underlineLinks(renderText(links)))] + nodes + } + + private func underlineLinks(_ text: AttributedString) -> AttributedString { + var text = text + for (link, range) in text.runs[\.link] where link != nil { + text[range].underlineStyle = .single + } + return text + } +} + +// MARK: - Helpers + +extension QMSMessage { + /// Ids of attachments referenced in the text via `[attachment="id:name"]` + var inlineAttachmentIds: Set { + guard text.contains("attachment") else { return [] } + let regex = try? NSRegularExpression(pattern: #"\[attachment=(?:"|")?(\d+)"#, options: .caseInsensitive) + let range = NSRange(text.startIndex..., in: text) + let ids = regex?.matches(in: text, range: range).compactMap { match -> Int? in + guard let idRange = Range(match.range(at: 1), in: text) else { return nil } + return Int(text[idRange]) + } ?? [] + return Set(ids) + } } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift index 97006e19..25bce1c5 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -16,6 +16,8 @@ struct QMSMessageRow: View { var onBubbleFrame: (CGRect) -> Void = { _ in } /// Tap on a message that failed to send var onRetry: () -> Void = {} + /// Links and images inside BB blocks, plain text links go through `openURL` environment + var onURL: (URL) -> Void = { _ in } private let avatarSize: CGFloat = 32 private static let coordinateSpace = "QMSMessageRow" @@ -71,11 +73,19 @@ struct QMSMessageRow: View { private var bubble: some View { BubbleLayout { - Text(message.text) - .foregroundStyle(Color(.Labels.primary)) - .tint(Color(.Theme.primary)) - .multilineTextAlignment(.leading) - .fixedSize(horizontal: false, vertical: true) + if let nodes = message.nodes { + VStack(alignment: .leading, spacing: 6) { + ForEach(nodes, id: \.self) { node in + TopicView(type: node, nestLevel: 3, userSession: nil, onUrlTap: onURL, onImageTap: onURL) + } + } + } else { + Text(message.text) + .foregroundStyle(Color(.Labels.primary)) + .tint(Color(.Theme.primary)) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } HStack(spacing: 3) { Text(message.date, format: .dateTime.hour().minute()) diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index 9d7a0900..deeb82b4 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -297,7 +297,7 @@ public struct QMSFeature: Reducer, Sendable { chat: chat, currentUserId: userId, isLoadingOlder: isLoadingOlder, - render: QMSMessageRenderer.shared.render + render: QMSMessageRenderer.shared.render(_:) ) await send(.internal(.itemsBuilt(items))) } diff --git a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift index 13dd2ef4..fc0983ed 100644 --- a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift +++ b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift @@ -50,7 +50,7 @@ struct QMSChatItemsBuilderTests { currentUserId: me, isLoadingOlder: isLoadingOlder, calendar: calendar, - render: { _, text in AttributedString(text) } + render: { QMSRenderedText(text: AttributedString($0.processedText), nodes: nil) } ) } @@ -132,33 +132,72 @@ struct QMSChatItemsBuilderTests { @Suite("QMS message renderer") struct QMSMessageRendererTests { - - @Test("Text is rendered once per message text") + + private func input(_ text: String, id: Int = 1, links: [QMSOutgoingMessage.Attachment] = []) -> QMSRenderInput { + QMSRenderInput(id: id, text: text, inlineAttachments: [], linkedAttachments: links) + } + + @Test("Message is rendered once per input") func cache() { var renders = 0 - let renderer = QMSMessageRenderer { text in - renders += 1 - return AttributedString(text) - } - let original = QMSMessage(id: 1, senderId: 1, date: .now, text: "a", attachments: []) - let edited = QMSMessage(id: 1, senderId: 1, date: .now, text: "b", attachments: []) - - _ = renderer.render(id: original.id, text: original.text) - _ = renderer.render(id: original.id, text: original.text) + let renderer = QMSMessageRenderer( + renderText: { text in + renders += 1 + return AttributedString(text) + }, + buildNodes: { text, _ in [.text(AttributedString(text))] } + ) + _ = renderer.render(input("a")) + _ = renderer.render(input("a")) #expect(renders == 1) - - #expect(String(renderer.render(id: edited.id, text: edited.text).characters) == "b") + + #expect(String(renderer.render(input("b")).text.characters) == "b") #expect(renders == 2) } - + @Test("Links are underlined") func links() { - let renderer = QMSMessageRenderer { _ in - var text = AttributedString("link") - text.link = URL(string: "https://4pda.to") - return text + let renderer = QMSMessageRenderer( + renderText: { _ in + var text = AttributedString("link") + text.link = URL(string: "https://4pda.to") + return text + }, + buildNodes: { _, _ in [] } + ) + #expect(renderer.render(input("")).text.runs.first?.underlineStyle == .single) + } + + @Test("Plain formatted text uses the fast path") + func plainText() { + let renderer = QMSMessageRenderer() + #expect(renderer.render(input("[b]bold[/b] text")).nodes == nil) + } + + @Test("Quote and code become blocks, linked files go first") + func blocks() throws { + let renderer = QMSMessageRenderer() + let rendered = renderer.render(input( + "[quote]Quote[/quote]\n[code]print(1)[/code]", + links: [.init(id: 5, name: "a.zip")] + )) + let nodes = try #require(rendered.nodes) + guard case let .text(links) = nodes.first else { + Issue.record("Expected links text first, got \(nodes)") + return } - let rendered = renderer.render(id: 1, text: "") - #expect(rendered.runs.first?.underlineStyle == .single) + #expect(String(links.characters) == "a.zip") + #expect(nodes.contains { if case .quote = $0 { true } else { false } }) + #expect(nodes.contains { if case .code = $0 { true } else { false } }) + } + + @Test("Inline attachment ids are found in text") + func inlineAttachments() { + let message = QMSMessage( + id: 1, senderId: 1, date: .now, + text: #"see [attachment="12:pic.jpg"] and [attachment="13:a.zip"]"#, + attachments: [] + ) + #expect(message.inlineAttachmentIds == [12, 13]) } } diff --git a/Project.swift b/Project.swift index 9fa6173c..d1f8da12 100644 --- a/Project.swift +++ b/Project.swift @@ -528,6 +528,7 @@ let project = Project( .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, + .Internal.TopicBuilder, .Internal.UploadBoxFeature, .SPM.NukeUI, .SPM.SFSafeSymbols, @@ -985,6 +986,7 @@ let project = Project( dependencies: [ .Internal.Models, .Internal.QMSFeature, + .Internal.SharedUI, .SPM.TCA, ], settings: .settings( From 0554ad9661e49eaa9f5383e56b34f24cdb513b59 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 07:04:29 +0100 Subject: [PATCH 08/12] Refresh open QMS chat on socket event with flag 2 Flag 2 means the last API request was this chat, so the chat is most likely open, yet the event was dropped and a new message from the partner didn't show up until the next sync. Now it emits the same chat event as flag 1; unread state still isn't touched for it. Co-Authored-By: Claude Opus 5.5 --- Modules/Sources/NotificationsClient/NotificationsClient.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Modules/Sources/NotificationsClient/NotificationsClient.swift b/Modules/Sources/NotificationsClient/NotificationsClient.swift index d57f80e3..6252a41c 100644 --- a/Modules/Sources/NotificationsClient/NotificationsClient.swift +++ b/Modules/Sources/NotificationsClient/NotificationsClient.swift @@ -138,7 +138,9 @@ extension NotificationsClient: DependencyKey { eventSubject.send(.qms(notification.id)) case 2: - // Last api request was the chat of this message + // Last api request was the chat of this message, so it's likely open: + // it still has to load the new message + eventSubject.send(.qms(notification.id)) // No need to mark it processed to avoid unread sync return false From 3be89fc52978c0c1cb561293f8971b09125842bb Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:03:03 +0100 Subject: [PATCH 09/12] Tidy up QMS store, parsing and list --- .../NotificationsClient.swift | 4 +- .../ParsingClient/Parsers/QMS/JSONValue.swift | 10 ++-- .../Sources/QMSClient/QMSDialogCache.swift | 17 ++++--- .../Sources/QMSClient/QMSDialogMerge.swift | 17 +++---- Modules/Sources/QMSClient/QMSListStore.swift | 16 ++----- .../QMSClient/QMSOutgoingMessage.swift | 17 ++----- Modules/Sources/QMSClient/QMSStore.swift | 47 ++++++++----------- .../QMSListFeature/QMSListFeature.swift | 8 ++-- .../ParsingClientTests/QMSParserTests.swift | 4 +- .../QMSClientTests/QMSListStoreTests.swift | 4 +- .../Tests/QMSClientTests/QMSStoreTests.swift | 4 +- 11 files changed, 64 insertions(+), 84 deletions(-) diff --git a/Modules/Sources/NotificationsClient/NotificationsClient.swift b/Modules/Sources/NotificationsClient/NotificationsClient.swift index 6252a41c..eb905617 100644 --- a/Modules/Sources/NotificationsClient/NotificationsClient.swift +++ b/Modules/Sources/NotificationsClient/NotificationsClient.swift @@ -138,8 +138,8 @@ extension NotificationsClient: DependencyKey { eventSubject.send(.qms(notification.id)) case 2: - // Last api request was the chat of this message, so it's likely open: - // it still has to load the new message + // Last api request was the chat of this message, so it's most likely open + // and only has to load the new message, no banner needed eventSubject.send(.qms(notification.id)) // No need to mark it processed to avoid unread sync return false diff --git a/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift b/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift index 90d5775c..9b9a48c6 100644 --- a/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift +++ b/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift @@ -1,11 +1,13 @@ // // JSONValue.swift -// ParsingClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Foundation -/// Any JSON value, used for parts of positional responses that are parsed by legacy `[Any]` based parsers. +/// Lets `Decodable` responses hand nested parts over to the older `[Any]` based parsers. enum JSONValue: Decodable, Equatable, Sendable { case null case bool(Bool) @@ -34,7 +36,7 @@ enum JSONValue: Decodable, Equatable, Sendable { } } - /// Value in the same shape `JSONSerialization` produces. + /// Same shape as `JSONSerialization` produces var anyValue: Any { switch self { case .null: return NSNull() @@ -48,7 +50,6 @@ enum JSONValue: Decodable, Equatable, Sendable { } } -/// Element of a positional array that is not used. struct SkippedValue: Decodable { init(from decoder: any Decoder) throws { _ = try decoder.singleValueContainer().decode(JSONValue.self) @@ -72,7 +73,6 @@ extension UnkeyedDecodingContainer { } extension JSONDecoder { - /// Decodes API response string, wrapping any failure into `ParsingError`. static func decodeResponse(_ type: T.Type, from string: String) throws -> T { guard let data = string.data(using: .utf8) else { throw ParsingError.failedToCreateDataFromString diff --git a/Modules/Sources/QMSClient/QMSDialogCache.swift b/Modules/Sources/QMSClient/QMSDialogCache.swift index ac3ca2ad..2024755d 100644 --- a/Modules/Sources/QMSClient/QMSDialogCache.swift +++ b/Modules/Sources/QMSClient/QMSDialogCache.swift @@ -1,15 +1,16 @@ // // QMSDialogCache.swift -// QMSClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // -import Dependencies +import ComposableArchitecture import Foundation import Models import PersistenceKeys -import ComposableArchitecture -/// Disk storage of dialog snapshots, one file per dialog in a folder of the current user. +/// One file per dialog in a folder of the current user. public struct QMSDialogCache: Sendable { public var load: @Sendable (_ dialogId: Int) async -> QMSDialogSnapshot? public var save: @Sendable (_ snapshot: QMSDialogSnapshot) async -> Void @@ -28,7 +29,6 @@ public struct QMSDialogCache: Sendable { extension QMSDialogCache { - /// How many newest messages of a dialog are kept on disk static let maxStoredMessages = 300 public static var liveValue: QMSDialogCache { @@ -39,7 +39,6 @@ extension QMSDialogCache { } } - /// - Parameter userId: current user, nothing is read or written without it static func files(root: URL, userId: @escaping @Sendable () -> Int?) -> QMSDialogCache { let storage = FileStorage(root: root) return QMSDialogCache( @@ -72,7 +71,7 @@ extension QMSDialogCache { } } -/// Serializes disk access so writes of the same dialog never interleave. +// Actor so that writes of the same dialog never interleave private actor FileStorage { let root: URL @@ -84,7 +83,7 @@ private actor FileStorage { let url = fileURL(userId: userId, dialogId: dialogId) guard let data = try? Data(contentsOf: url) else { return nil } guard let snapshot = try? JSONDecoder().decode(QMSDialogSnapshot.self, from: data) else { - // Outdated format or broken file, it will be rewritten on next sync + // Outdated format or broken file, sync will write a new one try? FileManager.default.removeItem(at: url) return nil } @@ -100,7 +99,7 @@ private actor FileStorage { ) try JSONEncoder().encode(snapshot).write(to: url, options: .atomic) } catch { - // Cache is optional, the dialog is loaded from network anyway + // Not critical, the dialog is loaded from network anyway } } diff --git a/Modules/Sources/QMSClient/QMSDialogMerge.swift b/Modules/Sources/QMSClient/QMSDialogMerge.swift index e8a34be4..8d17c59e 100644 --- a/Modules/Sources/QMSClient/QMSDialogMerge.swift +++ b/Modules/Sources/QMSClient/QMSDialogMerge.swift @@ -1,30 +1,26 @@ // // QMSDialogMerge.swift -// QMSClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Foundation import Models -/// Pure merge logic of a dialog page into already known messages. enum QMSDialogMerge { enum PageKind: Equatable, Sendable { - /// Newest messages of the dialog case latest - /// Messages older than the oldest known message case older } struct Result: Equatable { - /// Messages sorted from oldest to newest, unique by id let messages: [QMSMessage] - /// Count of messages from the page that were not known before + /// How many messages of the page were not known before let newCount: Int } - /// - Parameters: - /// - pageSize: requested page size, used to detect a gap between known messages and the latest page static func merge( existing: [QMSMessage], page: [QMSMessage], @@ -33,8 +29,9 @@ enum QMSDialogMerge { ) -> Result { var base = existing - // Latest page is full and doesn't touch known messages, so there may be - // unknown messages in between. Drop known ones to never show a hole. + // A full latest page that doesn't overlap known messages means there may be + // a gap between them. Better to drop the old ones than to show a hole. + // Pagination will load them again. if kind == .latest, page.count >= pageSize, let oldestInPage = page.map(\.id).min(), diff --git a/Modules/Sources/QMSClient/QMSListStore.swift b/Modules/Sources/QMSClient/QMSListStore.swift index 4bcf4433..314c12c5 100644 --- a/Modules/Sources/QMSClient/QMSListStore.swift +++ b/Modules/Sources/QMSClient/QMSListStore.swift @@ -1,6 +1,8 @@ // // QMSListStore.swift -// QMSClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // import ComposableArchitecture @@ -8,11 +10,7 @@ import Foundation import Models import PersistenceKeys -/// Single source of truth for the list of QMS partners and their dialogs. -/// -/// - Shows cached list instantly and refreshes it in background -/// - Keeps dialogs of a partner when the list response comes without them -/// - Coalesces list syncs and per partner loads +/// Keeps the list of QMS partners in memory and on disk. Same coalescing as `QMSStore`. public actor QMSListStore { public typealias LoadList = @Sendable () async throws -> QMSList @@ -37,7 +35,6 @@ public actor QMSListStore { // MARK: - Observe - /// Stream of the list. Yields known (in memory or cached) list right away. public func observe() async -> AsyncStream { let (stream, continuation) = AsyncStream.makeStream(of: QMSList.self, bufferingPolicy: .bufferingNewest(1)) let token = UUID() @@ -60,7 +57,6 @@ public actor QMSListStore { // MARK: - Sync - /// Loads the list. Calls during a running sync lead to at most one extra request. public func sync() async throws { if let syncTask { isSyncPending = true @@ -84,7 +80,6 @@ public actor QMSListStore { } while isSyncPending } - /// Loads dialogs of a partner. Repeated calls while loading wait for the same request. public func loadDialogs(userId: Int) async throws { if let running = userTasks[userId] { try await running.value @@ -106,7 +101,7 @@ public actor QMSListStore { // MARK: - Private - /// List response may come without dialogs of a partner, known ones are kept then + // List response usually comes without dialogs, they are loaded per partner, so known ones are kept private func merged(_ fresh: QMSList) -> QMSList { guard let list else { return fresh } let knownChats = Dictionary(list.users.map { ($0.id, $0.chats) }, uniquingKeysWith: { first, _ in first }) @@ -163,7 +158,6 @@ public struct QMSListCache: Sendable { } } - /// Stored next to dialog caches, in the folder of the current user static func file(root: URL, userId: @escaping @Sendable () -> Int?) -> QMSListCache { let url: @Sendable () -> URL? = { userId().map { root.appending(path: "\($0)/list.json", directoryHint: .notDirectory) } diff --git a/Modules/Sources/QMSClient/QMSOutgoingMessage.swift b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift index 85681dab..3371be68 100644 --- a/Modules/Sources/QMSClient/QMSOutgoingMessage.swift +++ b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift @@ -1,17 +1,19 @@ // // QMSOutgoingMessage.swift -// QMSClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Foundation -/// Message the user sent that is not confirmed by the server yet. +/// Message sent from this device that is not in the dialog on the server yet. public struct QMSOutgoingMessage: Equatable, Sendable, Codable, Identifiable { public enum State: String, Equatable, Sendable, Codable { case sending case failed - /// Server accepted it, waiting for the dialog sync to bring the real message + /// Accepted by the server, stays until the next sync brings the real message case sent } @@ -38,13 +40,4 @@ public struct QMSOutgoingMessage: Equatable, Sendable, Codable, Identifiable { self.date = date self.state = state } - - /// Text in the same format as `QMSMessage.processedText`, so it renders the same way - public var processedText: String { - let attachmentsText = attachments - .map { "[attachment=\($0.name),\($0.id)]" } - .joined(separator: "\n\n") - if attachmentsText.isEmpty { return text } - return text.isEmpty ? attachmentsText : attachmentsText + "\n\n" + text - } } diff --git a/Modules/Sources/QMSClient/QMSStore.swift b/Modules/Sources/QMSClient/QMSStore.swift index 785c9ef6..48866e35 100644 --- a/Modules/Sources/QMSClient/QMSStore.swift +++ b/Modules/Sources/QMSClient/QMSStore.swift @@ -1,19 +1,18 @@ // // QMSStore.swift -// QMSClient +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Dependencies import Foundation import Models -/// State of a single dialog as the store knows it. public struct QMSDialogSnapshot: Equatable, Sendable, Codable { - /// Dialog info with merged messages sorted from oldest to newest + /// Messages are sorted from oldest to newest public var chat: QMSChat - /// There are messages older than the oldest loaded one public var hasMoreOlder: Bool - /// Messages sent from this device that are not in `chat.messages` yet, oldest first public var outgoing: [QMSOutgoingMessage] public init(chat: QMSChat, hasMoreOlder: Bool, outgoing: [QMSOutgoingMessage] = []) { @@ -30,17 +29,16 @@ public struct QMSDialogSnapshot: Equatable, Sendable, Codable { let container = try decoder.container(keyedBy: CodingKeys.self) chat = try container.decode(QMSChat.self, forKey: .chat) hasMoreOlder = try container.decode(Bool.self, forKey: .hasMoreOlder) - // Absent in caches written before outgoing messages existed + // Not present in caches written by earlier builds outgoing = try container.decodeIfPresent([QMSOutgoingMessage].self, forKey: .outgoing) ?? [] } } -/// Single source of truth for QMS dialogs. +/// Keeps QMS dialogs in memory and on disk, all screens read dialogs from here. /// -/// - Shows cached dialog instantly and refreshes it in background -/// - Merges pages by message id instead of replacing everything -/// - Coalesces sync requests: any number of triggers during a running sync -/// (socket events, scene activation, pull to refresh) lead to at most one extra request +/// Sync can be triggered from many places at once (socket events, app activation, sending), +/// so syncs of one dialog are coalesced: whatever comes during a running sync results in +/// a single extra request after it. public actor QMSStore { public typealias LoadChat = @Sendable (_ id: Int, _ lastMessageId: Int, _ offset: Int) async throws -> QMSChat @@ -78,8 +76,7 @@ public actor QMSStore { // MARK: - Observe - /// Stream of dialog snapshots. Yields known (in memory or cached) snapshot right away. - /// Doesn't load anything by itself, call `sync(dialogId:)` for that. + /// Yields the known snapshot right away. Doesn't load anything, call `sync(dialogId:)` for that. public func observe(dialogId: Int) async -> AsyncStream { let (stream, continuation) = AsyncStream.makeStream( of: QMSDialogSnapshot.self, @@ -92,8 +89,8 @@ public actor QMSStore { } if snapshots[dialogId] == nil, var cached = await cache.load(dialogId) { - // App was closed in the middle of sending, it's unknown whether it reached the server, - // so the user decides to retry or discard + // App was killed while sending, we can't know if the message reached the server, + // so it's up to the user to retry or discard it cached.outgoing = cached.outgoing.compactMap { message in switch message.state { case .sent: return nil @@ -104,7 +101,7 @@ public actor QMSStore { return message } } - // Could be filled by sync while cache was loading + // Sync could finish while the cache was loading if snapshots[dialogId] == nil { snapshots[dialogId] = cached } @@ -121,8 +118,6 @@ public actor QMSStore { // MARK: - Sync - /// Loads the newest messages of the dialog and merges them in. - /// If a sync of this dialog is already running, waits for it and makes sure one more request happens after it. public func sync(dialogId: Int) async throws { if let running = syncTasks[dialogId] { pendingSync.insert(dialogId) @@ -135,7 +130,6 @@ public actor QMSStore { } private func runSync(dialogId: Int) async throws { - // Runs synchronously on exit, so no caller can join a finished task defer { syncTasks[dialogId] = nil pendingSync.remove(dialogId) @@ -149,7 +143,6 @@ public actor QMSStore { // MARK: - Older - /// Loads a page of messages older than the oldest known one. Repeated calls while loading are ignored. public func loadOlder(dialogId: Int) async throws { if let running = olderTasks[dialogId] { try await running.value @@ -169,8 +162,8 @@ public actor QMSStore { // MARK: - Send - /// Shows the message in the dialog right away and sends it. - /// On failure the message stays in the dialog as failed until `retry` or `discard`. + /// The message shows up in the dialog right away. If sending fails it stays there + /// as failed until `retry` or `discard`. @discardableResult public func send( dialogId: Int, @@ -210,8 +203,8 @@ public actor QMSStore { return } await updateOutgoing(dialogId: dialogId, id: messageId) { $0.state = .sent } - // Brings the real message, which replaces the sent one. If it fails, - // the next sync will do it, the message is on the server already. + // Brings the real message in place of the sent one. A failure here is fine, + // the message is on the server and the next sync will bring it. try? await sync(dialogId: dialogId) } @@ -228,7 +221,7 @@ public actor QMSStore { // MARK: - Remove - /// Drops everything, e.g. on logout or cache clearing. + /// Logout and cache clearing public func removeAll() async { snapshots = [:] await cache.removeAll() @@ -249,7 +242,7 @@ public actor QMSStore { if merge.messages.count >= chat.totalCount { hasMoreOlder = false } else if kind == .older { - // Server returned nothing new, stop paginating to avoid endless requests + // Nothing new from the server, stop here instead of requesting the same page forever hasMoreOlder = merge.newCount > 0 } else { hasMoreOlder = true @@ -259,7 +252,7 @@ public actor QMSStore { mergedChat.messages = merge.messages var outgoing = existing?.outgoing ?? [] if kind == .latest { - // Latest page contains messages the server accepted before this request + // Sent messages are in this page already outgoing.removeAll { $0.state == .sent } } let snapshot = QMSDialogSnapshot(chat: mergedChat, hasMoreOlder: hasMoreOlder, outgoing: outgoing) diff --git a/Modules/Sources/QMSListFeature/QMSListFeature.swift b/Modules/Sources/QMSListFeature/QMSListFeature.swift index 06a36774..987c1ae9 100644 --- a/Modules/Sources/QMSListFeature/QMSListFeature.swift +++ b/Modules/Sources/QMSListFeature/QMSListFeature.swift @@ -37,7 +37,7 @@ public struct QMSListFeature: Reducer, Sendable { public var qms: QMSList? var goTo: Int? var didHandleGoTo = false - /// Partners whose dialogs are shown, by user id so it survives list reordering + // By user id, not index, the list gets reordered on every new message var expandedUserIds: Set = [] var pendingUserLoads: [Int: Int] = [:] @@ -149,7 +149,7 @@ public struct QMSListFeature: Reducer, Sendable { // MARK: - View case .view(.onAppear): - // onAppear fires again when returning from a chat, long-running effects are restarted, not duplicated + // Called again after returning from a chat, cancelInFlight keeps effects from duplicating return .merge( .run { send in for await list in await qmsListStore.observe() { @@ -182,7 +182,7 @@ public struct QMSListFeature: Reducer, Sendable { case let .view(.userExpansionChanged(userId, isExpanded)): if isExpanded { state.expandedUserIds.insert(userId) - // Dialogs are refreshed on every expand, cached ones are shown meanwhile + // Cached dialogs are shown while fresh ones load return userId == 0 ? .none : .send(.internal(.loadUser(userId))) } else { state.expandedUserIds.remove(userId) @@ -258,7 +258,6 @@ public struct QMSListFeature: Reducer, Sendable { case let .internal(.qmsLoaded(result)): if case let .failure(error) = result { analyticsClient.capture(error) - // Cached list stays on screen if refresh failed if state.qms == nil { state.viewState = .error } @@ -289,7 +288,6 @@ public struct QMSListFeature: Reducer, Sendable { } else { state.pendingUserLoads.removeValue(forKey: userId) } - // Failure of one partner's dialogs doesn't break the whole list if case let .failure(error) = result { analyticsClient.capture(error) } diff --git a/Modules/Tests/ParsingClientTests/QMSParserTests.swift b/Modules/Tests/ParsingClientTests/QMSParserTests.swift index f802b9ad..263e262e 100644 --- a/Modules/Tests/ParsingClientTests/QMSParserTests.swift +++ b/Modules/Tests/ParsingClientTests/QMSParserTests.swift @@ -1,6 +1,8 @@ // // QMSParserTests.swift -// ParsingClientTests +// ForPDA +// +// Created by va1mont on 05.12.2026. // import CustomDump diff --git a/Modules/Tests/QMSClientTests/QMSListStoreTests.swift b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift index 233ddbb0..6c32d9bf 100644 --- a/Modules/Tests/QMSClientTests/QMSListStoreTests.swift +++ b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift @@ -1,6 +1,8 @@ // // QMSListStoreTests.swift -// QMSClientTests +// ForPDA +// +// Created by va1mont on 05.12.2026. // import ConcurrencyExtras diff --git a/Modules/Tests/QMSClientTests/QMSStoreTests.swift b/Modules/Tests/QMSClientTests/QMSStoreTests.swift index e6e4cf0e..29f6fd33 100644 --- a/Modules/Tests/QMSClientTests/QMSStoreTests.swift +++ b/Modules/Tests/QMSClientTests/QMSStoreTests.swift @@ -1,6 +1,8 @@ // // QMSStoreTests.swift -// QMSClientTests +// ForPDA +// +// Created by va1mont on 05.12.2026. // import ConcurrencyExtras From 47bbca46c3b215f13cd0bd2592fc096cd7b9a85a Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:03:03 +0100 Subject: [PATCH 10/12] Show QMS images in full and files as cards Images open in the gallery with all images of the dialog. Split chat item models, feed builder and renderer into separate files. --- .../Analytics/QMSFeature+Analytics.swift | 2 +- .../QMSFeature/Chat/QMSAttachmentViews.swift | 126 ++++++++++ .../Chat/QMSChatCollectionView.swift | 39 +-- .../Sources/QMSFeature/Chat/QMSChatItem.swift | 238 +++--------------- .../QMSFeature/Chat/QMSChatItemsBuilder.swift | 137 ++++++++++ .../Sources/QMSFeature/Chat/QMSChatRows.swift | 110 ++++---- .../QMSFeature/Chat/QMSMessageRenderer.swift | 79 ++++++ Modules/Sources/QMSFeature/QMSFeature.swift | 32 ++- Modules/Sources/QMSFeature/QMSScreen.swift | 5 + .../QMSChatItemsBuilderTests.swift | 47 ++-- Project.swift | 1 + 11 files changed, 528 insertions(+), 288 deletions(-) create mode 100644 Modules/Sources/QMSFeature/Chat/QMSAttachmentViews.swift create mode 100644 Modules/Sources/QMSFeature/Chat/QMSChatItemsBuilder.swift create mode 100644 Modules/Sources/QMSFeature/Chat/QMSMessageRenderer.swift diff --git a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index b34958eb..7459468a 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -20,7 +20,7 @@ extension QMSFeature { Reduce { state, action in switch action { case .view(.onAppear), .view(.attachButtonTapped), .view(.retryMessageTapped), - .view(.discardMessageTapped), .internal, .delegate, .binding, .alert, .upload: + .view(.discardMessageTapped), .view(.imageTapped), .internal, .delegate, .binding, .alert, .upload: break case .view(.sendMessageButtonTapped): diff --git a/Modules/Sources/QMSFeature/Chat/QMSAttachmentViews.swift b/Modules/Sources/QMSFeature/Chat/QMSAttachmentViews.swift new file mode 100644 index 00000000..d2779460 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSAttachmentViews.swift @@ -0,0 +1,126 @@ +// +// QMSAttachmentViews.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import NukeUI +import SFSafeSymbols +import SharedUI +import SwiftUI + +// MARK: - Image + +struct QMSImageView: View { + + let image: QMSChatImage + let onTap: (URL) -> Void + + private let maxWidth: CGFloat = 240 + private let maxHeight: CGFloat = 320 + + var body: some View { + LazyImage(url: image.url) { state in + if let container = state.imageContainer, container.type == .gif, + let gif = GifView(container: container) { + gif + } else if let picture = state.image { + picture.resizable().scaledToFit() + } else { + Color(.Background.quaternary) + } + } + .frame(width: size.width, height: size.height) + .clipShape(.rect(cornerRadius: 12)) + .contentShape(.rect) + .onTapGesture { + onTap(image.url) + } + } + + // Size is known before loading, so the feed doesn't jump when the image arrives + private var size: CGSize { + guard image.width > 0, image.height > 0 else { + return CGSize(width: maxWidth, height: maxWidth * 3 / 4) + } + let width = CGFloat(image.width) + let height = CGFloat(image.height) + let scale = min(maxWidth / width, maxHeight / height, 1) + return CGSize(width: max(width * scale, 60), height: max(height * scale, 60)) + } +} + +// MARK: - File + +struct QMSFileView: View { + + let file: QMSChatFile + let onTap: (URL) -> Void + + var body: some View { + Button { + if let url = file.url { onTap(url) } + } label: { + HStack(spacing: 10) { + Image(systemSymbol: symbol) + .font(.system(size: 18, weight: .medium)) + .foregroundStyle(.white) + .frame(width: 40, height: 40) + .background(Color(.Theme.primary), in: .rect(cornerRadius: 10)) + + VStack(alignment: .leading, spacing: 2) { + Text(file.name) + .font(.subheadline.weight(.medium)) + .foregroundStyle(Color(.Labels.primary)) + .lineLimit(2) + .truncationMode(.middle) + .multilineTextAlignment(.leading) + + Text(details) + .font(.caption) + .foregroundStyle(Color(.systemGray)) + .lineLimit(1) + } + + Spacer(minLength: 0) + + Image(systemSymbol: .arrowDownCircle) + .font(.title3) + .foregroundStyle(Color(.Theme.primary)) + } + .padding(8) + .frame(width: 240) + .background(Color(.systemGray).opacity(0.12), in: .rect(cornerRadius: 12)) + .contentShape(.rect) + } + .buttonStyle(.plain) + } + + private var details: String { + [file.fileExtension.isEmpty ? nil : file.fileExtension, file.size] + .compactMap { $0 } + .joined(separator: " · ") + } + + private var symbol: SFSymbol { + switch file.fileExtension.lowercased() { + case "zip", "rar", "7z", "tar", "gz", "bz2", "xz": + return .docZipper + case "pdf", "doc", "docx", "rtf", "odt": + return .docRichtext + case "txt", "log", "md", "json", "xml", "ini", "cfg": + return .docPlaintext + case "apk", "ipa", "exe", "dmg", "deb", "msi": + return .shippingbox + case "mp3", "wav", "flac", "m4a", "ogg", "aac": + return .musicNote + case "mp4", "mov", "avi", "mkv", "webm": + return .film + case "jpg", "jpeg", "png", "gif", "webp", "heic", "bmp": + return .photo + default: + return .doc + } + } +} diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift index 4f0c3c6f..0fdc650d 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -1,23 +1,27 @@ // // QMSChatCollectionView.swift -// QMSFeature +// ForPDA +// +// Created by va1mont on 05.12.2026. // +import SFSafeSymbols import SwiftUI import UIKit -/// Chat feed on UICollectionView: diffable updates, keeps position when older messages are prepended, -/// sticks to the bottom when new messages arrive or keyboard appears. +// On iOS 16 SwiftUI scroll views can't keep the position when older messages are inserted above, +// and get slow on long dialogs, so the feed is a collection view with SwiftUI cells. struct QMSChatCollectionView: UIViewControllerRepresentable { let items: [QMSChatItem] let hasMoreOlder: Bool - /// Changing this value scrolls the feed to the bottom + /// Any change scrolls the feed to the bottom let scrollToBottomRequest: Int - /// Opaque screen background, bubbles are translucent and need it under the context menu preview + /// Bubbles are translucent, the context menu preview needs an opaque background under them let background: Color let onLoadOlder: () -> Void let onURL: (URL) -> Void + let onImage: (URL) -> Void let onAtBottomChanged: (Bool) -> Void let onRetry: (UUID) -> Void let onDiscard: (UUID) -> Void @@ -29,6 +33,7 @@ struct QMSChatCollectionView: UIViewControllerRepresentable { func updateUIViewController(_ controller: QMSChatViewController, context: Context) { controller.onLoadOlder = onLoadOlder controller.onURL = onURL + controller.onImage = onImage controller.onAtBottomChanged = onAtBottomChanged controller.onRetry = onRetry controller.onDiscard = onDiscard @@ -42,6 +47,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { var onLoadOlder: () -> Void = {} var onURL: (URL) -> Void = { _ in } + var onImage: (URL) -> Void = { _ in } var onAtBottomChanged: (Bool) -> Void = { _ in } var onRetry: (UUID) -> Void = { _ in } var onDiscard: (UUID) -> Void = { _ in } @@ -51,7 +57,6 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { private var dataSource: UICollectionViewDiffableDataSource! private var items: [String: QMSChatItem] = [:] - /// Bubble frames in cell coordinates, reported by message rows private var bubbleFrames: [String: CGRect] = [:] private var orderedIds: [String] = [] private var hasMoreOlder = false @@ -64,7 +69,6 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { } private var lastBoundsHeight: CGFloat = 0 - /// Distance from the top at which older messages are requested private let loadOlderThreshold: CGFloat = 600 private let bottomTolerance: CGFloat = 60 @@ -94,7 +98,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() - // Keyboard or input bar changed the height, keep the newest message visible + // Keyboard or input bar resized the feed if collectionView.bounds.height != lastBoundsHeight { lastBoundsHeight = collectionView.bounds.height if isAtBottom { @@ -131,6 +135,9 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { }, onURL: { [weak self] url in self?.onURL(url) + }, + onImage: { [weak self] url in + self?.onImage(url) } ) } @@ -189,7 +196,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { private struct Anchor { let id: String - /// Item top relative to the visible content top + /// From the top of the visible area to the top of the item let offset: CGFloat } @@ -208,8 +215,8 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { } private func restore(_ anchor: Anchor) { - // Cells above the anchor have estimated heights until they are laid out, - // so a couple of passes are needed for the position to settle + // Cells above the anchor have estimated heights until laid out, + // it takes a couple of passes for the offset to settle for _ in 0..<3 { guard let indexPath = dataSource.indexPath(for: anchor.id), let frame = collectionView.layoutAttributesForItem(at: indexPath)?.frame else { return } @@ -224,7 +231,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { guard let last = orderedIds.last, let indexPath = dataSource.indexPath(for: last) else { return } collectionView.scrollToItem(at: indexPath, at: .bottom, animated: animated) if !animated { - // Real cell heights replace estimated ones after the first pass + // Same as above, estimated heights are replaced after the first pass collectionView.layoutIfNeeded() collectionView.scrollToItem(at: indexPath, at: .bottom, animated: false) } @@ -271,21 +278,21 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { if message.status == .failed, let id = message.outgoingId { actions.append(UIAction( title: String(localized: "Retry", bundle: .module), - image: UIImage(systemName: "arrow.clockwise") + image: UIImage(systemSymbol: .arrowClockwise) ) { _ in self?.onRetry(id) }) } actions.append(UIAction( title: String(localized: "Copy", bundle: .module), - image: UIImage(systemName: "doc.on.doc") + image: UIImage(systemSymbol: .docOnDoc) ) { _ in UIPasteboard.general.string = message.plainText }) if message.status == .failed, let id = message.outgoingId { actions.append(UIAction( title: String(localized: "Delete", bundle: .module), - image: UIImage(systemName: "trash"), + image: UIImage(systemSymbol: .trash), attributes: .destructive ) { _ in self?.onDiscard(id) @@ -311,7 +318,7 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { bubblePreview(at: indexPath) } - /// Lifts only the message bubble instead of the whole full width row + // Lift only the bubble, not the whole row private func bubblePreview(at indexPath: IndexPath) -> UITargetedPreview? { guard let cell = collectionView.cellForItem(at: indexPath), let id = dataSource.itemIdentifier(for: indexPath), diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift index 776bcbdb..605eaec1 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift @@ -1,15 +1,14 @@ // // QMSChatItem.swift -// QMSFeature +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Foundation import Models -import QMSClient import SharedUI -import TopicBuilder -/// Row of the chat feed. public struct QMSChatItem: Identifiable, Equatable, Sendable { public enum Kind: Equatable, Sendable { @@ -35,6 +34,8 @@ public struct QMSChatItem: Identifiable, Equatable, Sendable { } } +// MARK: - Message + public struct QMSChatMessage: Equatable, Sendable { public enum Status: Equatable, Sendable { @@ -45,221 +46,62 @@ public struct QMSChatMessage: Equatable, Sendable { case read } - /// Server id, 0 for messages that are not confirmed yet + /// 0 until the server confirms the message public let id: Int - /// Local id of a message sent from this device and not confirmed by the server yet public var outgoingId: UUID? = nil - /// Rendered BB text, computed once per message text public let text: AttributedString public let date: Date public let isMine: Bool public let status: Status - /// Partner avatar is shown at the last message of a group + /// Set only on the last message of a partner's group public let avatarUrl: URL? public let isFirstInGroup: Bool public let isLastInGroup: Bool - - /// BB blocks (quotes, code, spoilers...) of a message that is not just formatted text, nil otherwise + /// nil when the message is plain formatted text and `text` is enough to show it public var nodes: [UITopicType]? = nil + public var images: [QMSChatImage] = [] + public var files: [QMSChatFile] = [] - /// Text for copying public var plainText: String { String(text.characters) } } -// MARK: - Builder - -enum QMSChatItemsBuilder { - - /// - Parameters: - /// - render: converts raw message text to displayed text - static func build( - messages: [QMSMessage], - outgoing: [QMSOutgoingMessage] = [], - chat: QMSChat, - currentUserId: Int, - isLoadingOlder: Bool, - calendar: Calendar = .current, - render: (QMSRenderInput) -> QMSRenderedText - ) -> [QMSChatItem] { - var items: [QMSChatItem] = [] - items.reserveCapacity(messages.count + 8) - if isLoadingOlder { - items.append(.loadingOlder) - } - - // Last `unreadCount` messages of the current user are not read by partner yet - let unreadStart = max(messages.count - chat.unreadCount, 0) - - // Outgoing messages go last, as messages of the current user - struct Row { - let outgoing: QMSOutgoingMessage? - let senderId: Int - let date: Date - let input: QMSRenderInput - var id: Int { input.id } - } - let rows = messages.map { message in - let inline = message.inlineAttachmentIds - return Row(outgoing: nil, senderId: message.senderId, date: message.date, input: QMSRenderInput( - id: message.id, - text: message.text, - inlineAttachments: message.attachments.filter { inline.contains($0.id) }, - linkedAttachments: message.attachments - .filter { !inline.contains($0.id) } - .map { QMSOutgoingMessage.Attachment(id: $0.id, name: $0.name) } - )) - } + outgoing.map { message in - Row(outgoing: message, senderId: currentUserId, date: message.date, input: QMSRenderInput( - id: 0, - text: message.text, - inlineAttachments: [], - linkedAttachments: message.attachments - )) - } - - for (index, message) in rows.enumerated() { - let previous = index > 0 ? rows[index - 1] : nil - let next = index + 1 < rows.count ? rows[index + 1] : nil - - let isNewDay = previous.map { !calendar.isDate($0.date, inSameDayAs: message.date) } ?? true - if isNewDay { - items.append(.day(calendar.startOfDay(for: message.date))) - } - - let isFirstInGroup = isNewDay || previous?.senderId != message.senderId - let isLastInGroup = next.map { - $0.senderId != message.senderId || !calendar.isDate($0.date, inSameDayAs: message.date) - } ?? true - - let isMine = message.senderId == currentUserId - let status: QMSChatMessage.Status - switch message.outgoing?.state { - case .sending: status = .sending - case .failed: status = .failed - case .sent: status = .sent - case nil: status = isMine ? (index >= unreadStart ? .sent : .read) : .none - } - - let rendered = render(message.input) - items.append(.message(QMSChatMessage( - id: message.id, - outgoingId: message.outgoing?.id, - text: rendered.text, - date: message.date, - isMine: isMine, - status: status, - avatarUrl: isMine || !isLastInGroup ? nil : (chat.avatarUrl ?? Links.defaultQMSAvatar), - isFirstInGroup: isFirstInGroup, - isLastInGroup: isLastInGroup, - nodes: rendered.nodes - ))) - } - return items - } -} - -// MARK: - Renderer +// MARK: - Attachments -/// What a message bubble is rendered from. -struct QMSRenderInput: Hashable, Sendable { - let id: Int - /// Raw BB text - let text: String - /// Attachments referenced in the text itself - let inlineAttachments: [Attachment] - /// Attachments not referenced in the text, shown as download links above it - let linkedAttachments: [QMSOutgoingMessage.Attachment] - - var linksText: String { - linkedAttachments.map { "[attachment=\($0.name),\($0.id)]" }.joined(separator: "\n\n") - } - - /// Text with links, rendered as formatted text - var processedText: String { - let links = linksText - if links.isEmpty { return text } - return text.isEmpty ? links : links + "\n\n" + text +public struct QMSChatImage: Hashable, Sendable { + public let id: Int + public let url: URL + public let fullUrl: URL? + public let width: Int + public let height: Int + + init?(_ attachment: Attachment) { + guard attachment.type == .image, let metadata = attachment.metadata else { return nil } + id = attachment.id + url = metadata.url + fullUrl = metadata.fullUrl + width = metadata.width + height = metadata.height } } -struct QMSRenderedText: Equatable, Sendable { - /// Formatted text, also used for copying - let text: AttributedString - /// Present only when the message has BB blocks that formatted text can't show - let nodes: [UITopicType]? -} - -/// Caches rendered messages, BB rendering is the most expensive part of building the feed. -final class QMSMessageRenderer: @unchecked Sendable { - - static let shared = QMSMessageRenderer() - - private let lock = NSLock() - private var cache: [QMSRenderInput: QMSRenderedText] = [:] - private let limit: Int - private let renderText: (String) -> AttributedString - private let buildNodes: (String, [Attachment]) -> [UITopicType] - - init( - limit: Int = 3000, - renderText: @escaping (String) -> AttributedString = { QMSBuilder(text: $0).build() }, - buildNodes: @escaping (String, [Attachment]) -> [UITopicType] = { text, attachments in - TopicNodeBuilder(text: text, attachments: attachments).build() - } - ) { - self.limit = limit - self.renderText = renderText - self.buildNodes = buildNodes - } - - func render(_ input: QMSRenderInput) -> QMSRenderedText { - if let cached = lock.withLock({ cache[input] }) { - return cached - } - let rendered = QMSRenderedText(text: underlineLinks(renderText(input.processedText)), nodes: nodes(for: input)) - lock.withLock { - if cache.count >= limit { - cache.removeAll(keepingCapacity: true) - } - cache[input] = rendered - } - return rendered - } - - private func nodes(for input: QMSRenderInput) -> [UITopicType]? { - guard !input.text.isEmpty else { return nil } - let nodes = buildNodes(input.text, input.inlineAttachments) - if nodes.count == 1, case .text = nodes[0] { - // Just formatted text, fast path renders it - return nil - } - let links = input.linksText - return links.isEmpty ? nodes : [.text(underlineLinks(renderText(links)))] + nodes - } - - private func underlineLinks(_ text: AttributedString) -> AttributedString { - var text = text - for (link, range) in text.runs[\.link] where link != nil { - text[range].underlineStyle = .single - } - return text +public struct QMSChatFile: Hashable, Sendable { + public let id: Int + public let name: String + /// Unknown until the server confirms the message + public let size: String? + public let url: URL? + + init(id: Int, name: String, size: String?) { + self.id = id + self.name = name + self.size = size + let encodedName = name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? name + self.url = URL(string: "https://4pda.to/forum/dl/post/\(id)/\(encodedName)") } -} - -// MARK: - Helpers -extension QMSMessage { - /// Ids of attachments referenced in the text via `[attachment="id:name"]` - var inlineAttachmentIds: Set { - guard text.contains("attachment") else { return [] } - let regex = try? NSRegularExpression(pattern: #"\[attachment=(?:"|")?(\d+)"#, options: .caseInsensitive) - let range = NSRange(text.startIndex..., in: text) - let ids = regex?.matches(in: text, range: range).compactMap { match -> Int? in - guard let idRange = Range(match.range(at: 1), in: text) else { return nil } - return Int(text[idRange]) - } ?? [] - return Set(ids) + var fileExtension: String { + (name as NSString).pathExtension.uppercased() } } diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatItemsBuilder.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItemsBuilder.swift new file mode 100644 index 00000000..46ef3441 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItemsBuilder.swift @@ -0,0 +1,137 @@ +// +// QMSChatItemsBuilder.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Models +import QMSClient +import SharedUI + +enum QMSChatItemsBuilder { + + static func build( + messages: [QMSMessage], + outgoing: [QMSOutgoingMessage] = [], + chat: QMSChat, + currentUserId: Int, + isLoadingOlder: Bool, + calendar: Calendar = .current, + render: (QMSRenderInput) -> QMSRenderedText + ) -> [QMSChatItem] { + var items: [QMSChatItem] = [] + items.reserveCapacity(messages.count + 8) + if isLoadingOlder { + items.append(.loadingOlder) + } + + // Server doesn't send read state per message, only how many of the last ones are unread + let unreadStart = max(messages.count - chat.unreadCount, 0) + + let rows = messages.map(Row.init) + outgoing.map { Row($0, senderId: currentUserId) } + + for (index, row) in rows.enumerated() { + let previous = index > 0 ? rows[index - 1] : nil + let next = index + 1 < rows.count ? rows[index + 1] : nil + + let isNewDay = previous.map { !calendar.isDate($0.date, inSameDayAs: row.date) } ?? true + if isNewDay { + items.append(.day(calendar.startOfDay(for: row.date))) + } + + let isFirstInGroup = isNewDay || previous?.senderId != row.senderId + let isLastInGroup = next.map { + $0.senderId != row.senderId || !calendar.isDate($0.date, inSameDayAs: row.date) + } ?? true + + let isMine = row.senderId == currentUserId + let status: QMSChatMessage.Status + switch row.outgoing?.state { + case .sending: status = .sending + case .failed: status = .failed + case .sent: status = .sent + case nil: status = isMine ? (index >= unreadStart ? .sent : .read) : .none + } + + let rendered = render(row.input) + items.append(.message(QMSChatMessage( + id: row.input.id, + outgoingId: row.outgoing?.id, + text: rendered.text, + date: row.date, + isMine: isMine, + status: status, + avatarUrl: isMine || !isLastInGroup ? nil : (chat.avatarUrl ?? Links.defaultQMSAvatar), + isFirstInGroup: isFirstInGroup, + isLastInGroup: isLastInGroup, + nodes: rendered.nodes, + images: row.images, + files: row.files + ))) + } + return items + } +} + +// MARK: - Row + +private struct Row { + let outgoing: QMSOutgoingMessage? + let senderId: Int + let date: Date + let input: QMSRenderInput + var images: [QMSChatImage] = [] + var files: [QMSChatFile] = [] + + init(_ message: QMSMessage) { + // Attachments referenced in the text are drawn in place, the rest go above the text + let inlineIds = message.inlineAttachmentIds + let attached = message.attachments.filter { !inlineIds.contains($0.id) } + let images = attached.compactMap(QMSChatImage.init) + let imageIds = Set(images.map(\.id)) + + outgoing = nil + senderId = message.senderId + date = message.date + input = QMSRenderInput( + id: message.id, + text: message.text, + inlineAttachments: message.attachments.filter { inlineIds.contains($0.id) } + ) + self.images = images + files = attached + .filter { !imageIds.contains($0.id) } + .map { QMSChatFile(id: $0.id, name: $0.name, size: $0.size > 0 ? $0.sizeString : nil) } + } + + init(_ message: QMSOutgoingMessage, senderId: Int) { + // Image previews are unknown until the server confirms the message, so everything is a file for now + outgoing = message + self.senderId = senderId + date = message.date + input = QMSRenderInput(id: 0, text: message.text, inlineAttachments: []) + files = message.attachments.map { QMSChatFile(id: $0.id, name: $0.name, size: nil) } + } +} + +// MARK: - Inline attachments + +extension QMSMessage { + /// Ids from `[attachment="id:name"]` tags in the text + var inlineAttachmentIds: Set { + guard text.contains("attachment") else { return [] } + let range = NSRange(text.startIndex..., in: text) + let ids = Self.inlineAttachmentRegex.matches(in: text, range: range).compactMap { match -> Int? in + guard let idRange = Range(match.range(at: 1), in: text) else { return nil } + return Int(text[idRange]) + } + return Set(ids) + } + + private static let inlineAttachmentRegex = try! NSRegularExpression( + pattern: #"\[attachment=(?:"|")?(\d+)"#, + options: .caseInsensitive + ) +} diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift index 25bce1c5..effd11d3 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -1,9 +1,12 @@ // // QMSChatRows.swift -// QMSFeature +// ForPDA +// +// Created by va1mont on 05.12.2026. // import NukeUI +import SFSafeSymbols import SharedUI import SwiftUI @@ -12,12 +15,12 @@ import SwiftUI struct QMSMessageRow: View { let message: QMSChatMessage - /// Bubble frame in row coordinates, used to highlight only the bubble in context menu + /// Bubble frame in row coordinates, the context menu lifts only the bubble var onBubbleFrame: (CGRect) -> Void = { _ in } - /// Tap on a message that failed to send var onRetry: () -> Void = {} - /// Links and images inside BB blocks, plain text links go through `openURL` environment + /// Links from BB blocks and file cards, links in plain text go through `openURL` var onURL: (URL) -> Void = { _ in } + var onImage: (URL) -> Void = { _ in } private let avatarSize: CGFloat = 32 private static let coordinateSpace = "QMSMessageRow" @@ -38,7 +41,7 @@ struct QMSMessageRow: View { } .opacity(message.status == .sending ? 0.7 : 1) .overlay { - // Only failed messages react to taps, others keep links tappable + // Covers links only for failed messages, there a tap means retry if message.status == .failed { Color.clear .contentShape(Rectangle()) @@ -73,77 +76,88 @@ struct QMSMessageRow: View { private var bubble: some View { BubbleLayout { - if let nodes = message.nodes { - VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 6) { + ForEach(message.images, id: \.id) { image in + QMSImageView(image: image, onTap: onImage) + } + ForEach(message.files, id: \.id) { file in + QMSFileView(file: file, onTap: onURL) + } + if let nodes = message.nodes { ForEach(nodes, id: \.self) { node in - TopicView(type: node, nestLevel: 3, userSession: nil, onUrlTap: onURL, onImageTap: onURL) + TopicView(type: node, nestLevel: 3, userSession: nil, onUrlTap: onURL, onImageTap: onImage) } + } else if !message.text.characters.isEmpty || (message.images.isEmpty && message.files.isEmpty) { + Text(message.text) + .foregroundStyle(Color(.Labels.primary)) + .tint(Color(.Theme.primary)) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) } - } else { - Text(message.text) - .foregroundStyle(Color(.Labels.primary)) - .tint(Color(.Theme.primary)) - .multilineTextAlignment(.leading) - .fixedSize(horizontal: false, vertical: true) } - + HStack(spacing: 3) { Text(message.date, format: .dateTime.hour().minute()) .font(.caption2) .foregroundStyle(Color(.systemGray)) - - switch message.status { - case .none: - EmptyView() - case .sending: - Image(systemName: "clock") - .font(.caption2) - .foregroundStyle(Color(.systemGray)) - case .failed: - Image(systemName: "exclamationmark.circle.fill") - .font(.caption) - .foregroundStyle(.red) - case .sent: - Image(systemName: "checkmark") - .font(.caption2.weight(.semibold)) - .foregroundStyle(Color(.systemGray)) - case .read: - Image(systemName: "checkmark.circle.fill") - .font(.caption2) - .foregroundStyle(Color(.Theme.primary)) - } + statusIcon } } .padding(.horizontal, 12) .padding(.vertical, 8) .background(Color(.Background.quaternary), in: .rect(cornerRadius: 18)) } + + @ViewBuilder + private var statusIcon: some View { + switch message.status { + case .none: + EmptyView() + case .sending: + Image(systemSymbol: .clock) + .font(.caption2) + .foregroundStyle(Color(.systemGray)) + case .failed: + Image(systemSymbol: .exclamationmarkCircleFill) + .font(.caption) + .foregroundStyle(.red) + case .sent: + Image(systemSymbol: .checkmark) + .font(.caption2.weight(.semibold)) + .foregroundStyle(Color(.systemGray)) + case .read: + Image(systemSymbol: .checkmarkCircleFill) + .font(.caption2) + .foregroundStyle(Color(.Theme.primary)) + } + } } -/// Text on top aligned to leading, footer below aligned to trailing, -/// width is the widest of them so short messages don't stretch the bubble. +// MARK: - Bubble Layout + +/// Content on top, time under it on the trailing edge. The bubble is as wide as the wider +/// of them, so a short message doesn't stretch to the full width. private struct BubbleLayout: Layout { - + var spacing: CGFloat = 2 - + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { guard subviews.count == 2 else { return .zero } - let text = subviews[0].sizeThatFits(ProposedViewSize(width: proposal.width, height: nil)) + let content = subviews[0].sizeThatFits(ProposedViewSize(width: proposal.width, height: nil)) let footer = subviews[1].sizeThatFits(.unspecified) - let width = min(max(text.width, footer.width), proposal.width ?? .infinity) - return CGSize(width: width, height: text.height + spacing + footer.height) + let width = min(max(content.width, footer.width), proposal.width ?? .infinity) + return CGSize(width: width, height: content.height + spacing + footer.height) } - + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { guard subviews.count == 2 else { return } - let text = subviews[0].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil)) - let footer = subviews[1].sizeThatFits(.unspecified) + let content = subviews[0].sizeThatFits(ProposedViewSize(width: bounds.width, height: nil)) subviews[0].place( at: CGPoint(x: bounds.minX, y: bounds.minY), - proposal: ProposedViewSize(width: bounds.width, height: text.height) + proposal: ProposedViewSize(width: bounds.width, height: content.height) ) subviews[1].place( - at: CGPoint(x: bounds.maxX, y: bounds.minY + text.height + spacing), + at: CGPoint(x: bounds.maxX, y: bounds.minY + content.height + spacing), anchor: .topTrailing, proposal: .unspecified ) diff --git a/Modules/Sources/QMSFeature/Chat/QMSMessageRenderer.swift b/Modules/Sources/QMSFeature/Chat/QMSMessageRenderer.swift new file mode 100644 index 00000000..c25e6ff7 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSMessageRenderer.swift @@ -0,0 +1,79 @@ +// +// QMSMessageRenderer.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Models +import SharedUI +import TopicBuilder + +struct QMSRenderInput: Hashable, Sendable { + let id: Int + let text: String + let inlineAttachments: [Attachment] +} + +struct QMSRenderedText: Equatable, Sendable { + let text: AttributedString + let nodes: [UITopicType]? +} + +/// BB rendering is the slowest part of building the feed, and the feed is rebuilt +/// on every snapshot, so each message is rendered once and taken from the cache after that. +final class QMSMessageRenderer: @unchecked Sendable { + + static let shared = QMSMessageRenderer() + + private let lock = NSLock() + private var cache: [QMSRenderInput: QMSRenderedText] = [:] + private let limit: Int + private let renderText: (String) -> AttributedString + private let buildNodes: (String, [Attachment]) -> [UITopicType] + + init( + limit: Int = 3000, + renderText: @escaping (String) -> AttributedString = { QMSBuilder(text: $0).build() }, + buildNodes: @escaping (String, [Attachment]) -> [UITopicType] = { text, attachments in + TopicNodeBuilder(text: text, attachments: attachments).build() + } + ) { + self.limit = limit + self.renderText = renderText + self.buildNodes = buildNodes + } + + func render(_ input: QMSRenderInput) -> QMSRenderedText { + if let cached = lock.withLock({ cache[input] }) { + return cached + } + let rendered = QMSRenderedText(text: underlineLinks(renderText(input.text)), nodes: nodes(for: input)) + lock.withLock { + if cache.count >= limit { + cache.removeAll(keepingCapacity: true) + } + cache[input] = rendered + } + return rendered + } + + private func nodes(for input: QMSRenderInput) -> [UITopicType]? { + guard !input.text.isEmpty else { return nil } + let nodes = buildNodes(input.text, input.inlineAttachments) + // Plain formatted text is cheaper to show as a single Text + if nodes.count == 1, case .text = nodes[0] { + return nil + } + return nodes + } + + private func underlineLinks(_ text: AttributedString) -> AttributedString { + var text = text + for (link, range) in text.runs[\.link] where link != nil { + text[range].underlineStyle = .single + } + return text + } +} diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index deeb82b4..72087104 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -7,6 +7,7 @@ import Foundation import ComposableArchitecture +import GalleryFeature import APIClient import QMSClient import PersistenceKeys @@ -38,12 +39,8 @@ public struct QMSFeature: Reducer, Sendable { public let chatId: Int public var chat: QMSChat? - /// Feed rows, built in background from `chat` public var items: [QMSChatItem] = [] - /// Incremented to scroll the feed to the newest message var scrollToBottomRequest = 0 - - /// Messages sent from this device and not confirmed by the server yet public var outgoing: [QMSOutgoingMessage] = [] var hasMoreOlderMessages = true @@ -52,6 +49,7 @@ public struct QMSFeature: Reducer, Sendable { var draftText = "" var upload = UploadBoxFeature.State.qms var isAttachmentsShown = false + var gallery: GalleryModel? var uploadedAttachments: [QMSOutgoingMessage.Attachment] { upload.files.compactMap { file in @@ -97,6 +95,7 @@ public struct QMSFeature: Reducer, Sendable { case discardMessageTapped(UUID) case loadMoreTriggered case urlTapped(URL) + case imageTapped(URL) } case `internal`(Internal) @@ -119,7 +118,6 @@ public struct QMSFeature: Reducer, Sendable { // MARK: - Dependencies - @Dependency(\.qmsClient) private var qmsClient @Dependency(\.qmsStore) private var qmsStore @Dependency(\.analyticsClient) private var analyticsClient @Dependency(\.notificationCenter) private var notificationCenter @@ -140,7 +138,7 @@ public struct QMSFeature: Reducer, Sendable { return .none case .view(.onAppear): - // onAppear fires again when returning from pushed screens, so long-running effects are restarted, not duplicated + // Called again after returning from pushed screens, cancelInFlight keeps effects from duplicating return .merge([ .run { [id = state.chatId] send in for await snapshot in await qmsStore.observe(dialogId: id) { @@ -173,7 +171,6 @@ public struct QMSFeature: Reducer, Sendable { let text = state.draftText.trimmingCharacters(in: .whitespacesAndNewlines) let attachments = state.uploadedAttachments - // Message shows up in the feed right away, failures stay there with retry state.draftText = "" state.upload = .qms state.isAttachmentsShown = false @@ -208,6 +205,21 @@ public struct QMSFeature: Reducer, Sendable { } ) + case let .view(.imageTapped(url)): + // Whole dialog goes to the gallery so it can be swiped through + let images = (state.chat?.messages ?? []) + .flatMap(\.attachments) + .compactMap { attachment -> (id: Int, url: URL)? in + guard attachment.type == .image, let metadata = attachment.metadata else { return nil } + return (attachment.id, metadata.url) + } + if let index = images.firstIndex(where: { $0.url == url }) { + state.gallery = GalleryModel(urls: images.map(\.url), ids: images.map(\.id), selectedId: index) + } else { + state.gallery = GalleryModel(urls: [url], selectedId: 0) + } + return .none + case let .view(.urlTapped(url)): guard url.absoluteString.contains("act=findpost"), let components = URLComponents(url: url, resolvingAgainstBaseURL: false), @@ -237,7 +249,7 @@ public struct QMSFeature: Reducer, Sendable { let result = await Result { try await qmsStore.sync(dialogId: id) } await send(.internal(.syncFinished(result))) - // Chat is not marked as read if it failed to load + // Don't mark as read what the user hasn't seen guard case .success = result, let snapshot = await qmsStore.snapshot(dialogId: id) else { return } await notificationsClient.removeNotifications(ids: [id]) await send(.delegate(.fullyRead(snapshot.chat.partnerId))) @@ -246,7 +258,7 @@ public struct QMSFeature: Reducer, Sendable { case let .internal(.syncFinished(result)): if case let .failure(error) = result { analyticsClient.capture(error) - // Failed background refresh of a shown chat is not worth an alert + // Background refresh failures don't deserve an alert while the chat is on screen if state.chat == nil { state.alert = .somethingWentWrong } @@ -283,7 +295,7 @@ public struct QMSFeature: Reducer, Sendable { // MARK: - Shared Logic - /// Builds feed rows off the main thread, BB rendering of new messages may take a while + // Off the main thread, rendering BB of new messages takes a while private func buildItems(_ state: State) -> Effect { guard let chat = state.chat else { return .none } return .run { [ diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 131ae045..5a2b808a 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -10,6 +10,7 @@ import ComposableArchitecture import SharedUI import SFSafeSymbols import UploadBoxFeature +import GalleryFeature @ViewAction(for: QMSFeature.self) public struct QMSScreen: View { @@ -42,6 +43,7 @@ public struct QMSScreen: View { background: backgroundColors.primary, onLoadOlder: { send(.loadMoreTriggered) }, onURL: { send(.urlTapped($0)) }, + onImage: { send(.imageTapped($0)) }, onAtBottomChanged: { isAtBottom = $0 }, onRetry: { send(.retryMessageTapped($0)) }, onDiscard: { send(.discardMessageTapped($0)) } @@ -63,6 +65,9 @@ public struct QMSScreen: View { .navigationTitle(store.title) ._toolbarTitleDisplayMode(.inline) .alert($store.scope(\.$alert, action: \.alert)) + .fullScreenCover(item: $store.gallery) { model in + TabViewGallery(model: model) + } .onAppear { send(.onAppear) } diff --git a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift index fc0983ed..50a56061 100644 --- a/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift +++ b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift @@ -1,6 +1,8 @@ // // QMSChatItemsBuilderTests.swift -// QMSFeatureTests +// ForPDA +// +// Created by va1mont on 05.12.2026. // import Foundation @@ -50,7 +52,7 @@ struct QMSChatItemsBuilderTests { currentUserId: me, isLoadingOlder: isLoadingOlder, calendar: calendar, - render: { QMSRenderedText(text: AttributedString($0.processedText), nodes: nil) } + render: { QMSRenderedText(text: AttributedString($0.text), nodes: nil) } ) } @@ -121,7 +123,30 @@ struct QMSChatItemsBuilderTests { #expect(result.map(\.status) == [.read, .sending, .failed]) #expect(result.map(\.outgoingId) == [nil, sending.id, failed.id]) #expect(result.map(\.isLastInGroup) == [false, false, true]) - #expect(result.last?.plainText == "[attachment=a.jpg,5]") + #expect(result.last?.plainText == "") + #expect(result.last?.files.map(\.name) == ["a.jpg"]) + #expect(result.last?.files.first?.size == nil) + } + + @Test("Images are shown in full, files as cards, inline attachments stay in text") + func images() { + func attachment(_ id: Int, _ type: Models.Attachment.AttachmentType, metadata: Bool = true) -> Models.Attachment { + Models.Attachment( + id: id, type: type, name: "f\(id)", size: 1, + metadata: metadata ? .init(width: 800, height: 600, url: URL(string: "https://4pda.to/\(id).jpg")!) : nil, + downloadCount: nil + ) + } + let message = QMSMessage( + id: 1, senderId: partner, date: Date(timeIntervalSince1970: day1), + text: #"[attachment="3:f3"]"#, + attachments: [attachment(1, .image), attachment(2, .file, metadata: false), attachment(3, .image)] + ) + let result = messages(in: build([message])) + #expect(result.first?.images.map(\.id) == [1]) + #expect(result.first?.images.first?.width == 800) + #expect(result.first?.files.map(\.id) == [2]) + #expect(result.first?.files.first?.url?.absoluteString == "https://4pda.to/forum/dl/post/2/f2") } @Test("Empty dialog has no rows") @@ -133,8 +158,8 @@ struct QMSChatItemsBuilderTests { @Suite("QMS message renderer") struct QMSMessageRendererTests { - private func input(_ text: String, id: Int = 1, links: [QMSOutgoingMessage.Attachment] = []) -> QMSRenderInput { - QMSRenderInput(id: id, text: text, inlineAttachments: [], linkedAttachments: links) + private func input(_ text: String, id: Int = 1) -> QMSRenderInput { + QMSRenderInput(id: id, text: text, inlineAttachments: []) } @Test("Message is rendered once per input") @@ -174,19 +199,11 @@ struct QMSMessageRendererTests { #expect(renderer.render(input("[b]bold[/b] text")).nodes == nil) } - @Test("Quote and code become blocks, linked files go first") + @Test("Quote and code become blocks") func blocks() throws { let renderer = QMSMessageRenderer() - let rendered = renderer.render(input( - "[quote]Quote[/quote]\n[code]print(1)[/code]", - links: [.init(id: 5, name: "a.zip")] - )) + let rendered = renderer.render(input("[quote]Quote[/quote]\n[code]print(1)[/code]")) let nodes = try #require(rendered.nodes) - guard case let .text(links) = nodes.first else { - Issue.record("Expected links text first, got \(nodes)") - return - } - #expect(String(links.characters) == "a.zip") #expect(nodes.contains { if case .quote = $0 { true } else { false } }) #expect(nodes.contains { if case .code = $0 { true } else { false } }) } diff --git a/Project.swift b/Project.swift index d1f8da12..1f1fb885 100644 --- a/Project.swift +++ b/Project.swift @@ -522,6 +522,7 @@ let project = Project( .Internal.APIClient, .Internal.AnalyticsClient, .Internal.BBBuilder, + .Internal.GalleryFeature, .Internal.Models, .Internal.NotificationsClient, .Internal.PersistenceKeys, From c456fb4d0f3b37baaeeeeaafcb14d8f35ed02b91 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:40:29 +0100 Subject: [PATCH 11/12] Hide QMS keyboard on feed tap --- .../Sources/QMSFeature/Chat/QMSChatCollectionView.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift index 0fdc650d..a2300c69 100644 --- a/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -85,6 +85,11 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { collectionView.delegate = self view.addSubview(collectionView) + // Doesn't cancel touches, so links, images and the context menu keep working + let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) + tap.cancelsTouchesInView = false + collectionView.addGestureRecognizer(tap) + let registration = UICollectionView.CellRegistration { [weak self] cell, _, id in guard let self, let item = self.items[id] else { return } cell.contentConfiguration = UIHostingConfiguration { self.row(for: item) } @@ -107,6 +112,10 @@ final class QMSChatViewController: UIViewController, UICollectionViewDelegate { } } + @objc private func hideKeyboard() { + view.window?.endEditing(true) + } + private static func makeLayout() -> UICollectionViewLayout { let size = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(60)) let item = NSCollectionLayoutItem(layoutSize: size) From aaa71ef57bcdcfe525c3886f567d7b28a0f4ffc7 Mon Sep 17 00:00:00 2001 From: va1mont <46992151+va1mont@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:40:29 +0100 Subject: [PATCH 12/12] Add BB panel to QMS composer The composer is a UITextView: TextField doesn't expose the selection before iOS 18, and tags have to wrap it. Tags are applied by the text view itself, so keys typed before the state catches up aren't lost. The panel sits under the field, above it the selection edit menu covers the buttons. --- .../Sources/BBPanelFeature/BBPanelView.swift | 7 +- .../Analytics/QMSFeature+Analytics.swift | 2 +- .../Composer/QMSComposerTextView.swift | 131 +++++++++++++++++ .../QMSFeature/Composer/QMSTagInsertion.swift | 41 ++++++ Modules/Sources/QMSFeature/QMSFeature.swift | 20 ++- Modules/Sources/QMSFeature/QMSScreen.swift | 134 +++++++++++------- .../QMSTagInsertionTests.swift | 57 ++++++++ Project.swift | 1 + 8 files changed, 338 insertions(+), 55 deletions(-) create mode 100644 Modules/Sources/QMSFeature/Composer/QMSComposerTextView.swift create mode 100644 Modules/Sources/QMSFeature/Composer/QMSTagInsertion.swift create mode 100644 Modules/Tests/QMSFeatureTests/QMSTagInsertionTests.swift diff --git a/Modules/Sources/BBPanelFeature/BBPanelView.swift b/Modules/Sources/BBPanelFeature/BBPanelView.swift index 9e6969ec..8fb358ef 100644 --- a/Modules/Sources/BBPanelFeature/BBPanelView.swift +++ b/Modules/Sources/BBPanelFeature/BBPanelView.swift @@ -21,10 +21,13 @@ public struct BBPanelView: View { @State private var selectedColor: Color = .clear + private let backgroundColor: Color? + // MARK: - Init - public init(store: StoreOf) { + public init(store: StoreOf, backgroundColor: Color? = nil) { self.store = store + self.backgroundColor = backgroundColor } // MARK: - Body @@ -77,7 +80,7 @@ public struct BBPanelView: View { } .background { RoundedRectangle(cornerRadius: isLiquidGlass ? 28 : 14) - .fill(backgroundColors.primary) + .fill(backgroundColor ?? backgroundColors.primary) } .onAppear { send(.onAppear) diff --git a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index 7459468a..8072bdb2 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -20,7 +20,7 @@ extension QMSFeature { Reduce { state, action in switch action { case .view(.onAppear), .view(.attachButtonTapped), .view(.retryMessageTapped), - .view(.discardMessageTapped), .view(.imageTapped), .internal, .delegate, .binding, .alert, .upload: + .view(.discardMessageTapped), .view(.imageTapped), .internal, .delegate, .binding, .alert, .upload, .bbPanel: break case .view(.sendMessageButtonTapped): diff --git a/Modules/Sources/QMSFeature/Composer/QMSComposerTextView.swift b/Modules/Sources/QMSFeature/Composer/QMSComposerTextView.swift new file mode 100644 index 00000000..b56aaf5c --- /dev/null +++ b/Modules/Sources/QMSFeature/Composer/QMSComposerTextView.swift @@ -0,0 +1,131 @@ +// +// QMSComposerTextView.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import SwiftUI +import UIKit + +/// SwiftUI `TextField` doesn't expose the selection before iOS 18, and BB tags have to wrap it. +struct QMSComposerTextView: UIViewRepresentable { + + @Binding var text: String + @Binding var isFocused: Bool + let tagInsertion: QMSTagInsertion? + let placeholder: String + var maxLines = 6 + + func makeUIView(context: Context) -> UITextView { + let view = UITextView() + view.delegate = context.coordinator + view.font = .preferredFont(forTextStyle: .body) + view.adjustsFontForContentSizeCategory = true + view.backgroundColor = .clear + view.textContainerInset = .zero + view.textContainer.lineFragmentPadding = 0 + view.isScrollEnabled = false + // BB attributes need straight quotes: [url="..."] + view.smartQuotesType = .no + view.smartDashesType = .no + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.text = text + + addPlaceholder(context.coordinator.placeholderLabel, to: view) + return view + } + + func updateUIView(_ view: UITextView, context: Context) { + let coordinator = context.coordinator + coordinator.parent = self + + // Text changes from outside only when the draft is reset after sending + if view.text != text, view.markedTextRange == nil { + view.text = text + coordinator.placeholderLabel.isHidden = !text.isEmpty + } + if let tagInsertion, tagInsertion.id != coordinator.appliedTagId { + coordinator.appliedTagId = tagInsertion.id + // Applied on the next run loop: the edit reports back to the state, which can't change mid-update + DispatchQueue.main.async { Self.apply(tagInsertion, to: view) } + } + if isFocused, !view.isFirstResponder { + // Becoming first responder in the middle of a view update is ignored + DispatchQueue.main.async { view.becomeFirstResponder() } + } + } + + func sizeThatFits(_ proposal: ProposedViewSize, uiView view: UITextView, context: Context) -> CGSize? { + guard let width = proposal.width, width.isFinite, width > 0 else { return nil } + + let lineHeight = view.font?.lineHeight ?? 20 + let maxHeight = ceil(lineHeight * CGFloat(maxLines)) + let fittingHeight = ceil(view.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height) + + // Grows with the text up to `maxLines`, scrolls after that + view.isScrollEnabled = fittingHeight > maxHeight + return CGSize(width: width, height: min(max(fittingHeight, ceil(lineHeight)), maxHeight)) + } + + func makeCoordinator() -> Coordinator { + // A request left in the state from before the view was recreated must not be applied again + Coordinator(parent: self, appliedTagId: tagInsertion?.id) + } + + /// Goes through the text input system like typing does: the keyboard stays in sync and the edit can be undone + private static func apply(_ insertion: QMSTagInsertion, to view: UITextView) { + let edit = insertion.edit(in: view.text, selection: view.selectedRange) + guard let start = view.position(from: view.beginningOfDocument, offset: edit.range.location), + let end = view.position(from: start, offset: edit.range.length), + let range = view.textRange(from: start, to: end) + else { return } + + view.replace(range, withText: edit.replacement) + view.selectedRange = edit.selection + } + + private func addPlaceholder(_ label: UILabel, to view: UITextView) { + label.text = placeholder + label.font = view.font + label.adjustsFontForContentSizeCategory = true + label.textColor = .placeholderText + label.isHidden = !text.isEmpty + label.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(label) + NSLayoutConstraint.activate([ + label.topAnchor.constraint(equalTo: view.topAnchor), + label.leadingAnchor.constraint(equalTo: view.leadingAnchor) + ]) + } +} + +// MARK: - Coordinator + +extension QMSComposerTextView { + + final class Coordinator: NSObject, UITextViewDelegate { + + var parent: QMSComposerTextView + var appliedTagId: Int? + let placeholderLabel = UILabel() + + init(parent: QMSComposerTextView, appliedTagId: Int?) { + self.parent = parent + self.appliedTagId = appliedTagId + } + + func textViewDidChange(_ textView: UITextView) { + placeholderLabel.isHidden = !textView.text.isEmpty + parent.text = textView.text + } + + func textViewDidBeginEditing(_ textView: UITextView) { + if !parent.isFocused { parent.isFocused = true } + } + + func textViewDidEndEditing(_ textView: UITextView) { + if parent.isFocused { parent.isFocused = false } + } + } +} diff --git a/Modules/Sources/QMSFeature/Composer/QMSTagInsertion.swift b/Modules/Sources/QMSFeature/Composer/QMSTagInsertion.swift new file mode 100644 index 00000000..a7c70725 --- /dev/null +++ b/Modules/Sources/QMSFeature/Composer/QMSTagInsertion.swift @@ -0,0 +1,41 @@ +// +// QMSTagInsertion.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation + +/// A request to wrap the composer selection in a BB tag pair. +/// +/// The text view applies it itself: it owns the live text and selection, while the state +/// lags behind until the next view update, and keys typed in between would be lost. +struct QMSTagInsertion: Equatable { + + struct Edit: Equatable { + let range: NSRange + let replacement: String + let selection: NSRange + } + + /// Changes with every tap, so the same tag twice in a row is applied twice + let id: Int + let open: String + let close: String + + /// Wraps the selection, or puts an empty pair at the caret. The wrapped text stays selected, + /// so several tags can be applied in a row. Ranges are UTF-16, the way UITextView reports them. + func edit(in text: String, selection: NSRange) -> Edit { + let source = text as NSString + let location = min(max(selection.location, 0), source.length) + let length = min(max(selection.length, 0), source.length - location) + let range = NSRange(location: location, length: length) + + return Edit( + range: range, + replacement: open + source.substring(with: range) + close, + selection: NSRange(location: location + (open as NSString).length, length: length) + ) + } +} diff --git a/Modules/Sources/QMSFeature/QMSFeature.swift b/Modules/Sources/QMSFeature/QMSFeature.swift index 72087104..6070ac92 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -6,6 +6,7 @@ // import Foundation +import BBPanelFeature import ComposableArchitecture import GalleryFeature import APIClient @@ -47,6 +48,9 @@ public struct QMSFeature: Reducer, Sendable { var isLoadingMore = false var draftText = "" + var isComposerFocused = false + var tagInsertion: QMSTagInsertion? + var bbPanel = BBPanelFeature.State(for: .qms) var upload = UploadBoxFeature.State.qms var isAttachmentsShown = false var gallery: GalleryModel? @@ -108,6 +112,7 @@ public struct QMSFeature: Reducer, Sendable { } case upload(UploadBoxFeature.Action) + case bbPanel(BBPanelFeature.Action) case delegate(Delegate) public enum Delegate { @@ -132,9 +137,22 @@ public struct QMSFeature: Reducer, Sendable { UploadBoxFeature() } + Scope(state: \.bbPanel, action: \.bbPanel) { + BBPanelFeature() + } + Reduce { state, action in switch action { - case .alert, .delegate, .upload: + case let .bbPanel(.delegate(.tagTapped((open, close)))): + state.tagInsertion = QMSTagInsertion( + id: (state.tagInsertion?.id ?? 0) + 1, + open: open, + close: close + ) + state.isComposerFocused = true + return .none + + case .alert, .delegate, .upload, .bbPanel: return .none case .view(.onAppear): diff --git a/Modules/Sources/QMSFeature/QMSScreen.swift b/Modules/Sources/QMSFeature/QMSScreen.swift index 5a2b808a..523b0983 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -6,6 +6,7 @@ // import SwiftUI +import BBPanelFeature import ComposableArchitecture import SharedUI import SFSafeSymbols @@ -100,65 +101,96 @@ public struct QMSScreen: View { .padding(.top, 8) .transition(.move(edge: .bottom).combined(with: .opacity)) } - + HStack(alignment: .bottom, spacing: 8) { - Button { - send(.attachButtonTapped) - } label: { - Image(systemSymbol: .paperclip) - .font(.body.weight(.semibold)) - .foregroundStyle(Color(.Theme.primary)) - .frame(width: 40, height: 40) - .overlay(alignment: .topTrailing) { - let count = store.upload.files.count - if count > 0 { - Text(count, format: .number) - .font(.caption2.bold()) - .foregroundStyle(.white) - .padding(4) - .background(Color(.Theme.primary), in: Circle()) - } - } - } - .accessibilityLabel(Text("Attach files", bundle: .module)) - - TextField( - String(""), - text: $store.draftText, - prompt: Text("qms.textfield.placeholder", bundle: .module), - axis: .vertical - ) - .lineLimit(1...6) - .padding(.horizontal, 14) - .padding(.vertical, 10) - .background(Color(.Background.quaternary), in: .rect(cornerRadius: 20)) - - Button { - send(.sendMessageButtonTapped) - } label: { - ZStack { - Circle() - .fill(Color(.Theme.primary)) - if store.upload.isAnyFileUploading { - ProgressView() - .tint(.white) - } else { - Image(systemSymbol: .arrowUp) - .font(.body.weight(.bold)) - .foregroundStyle(.white) - } - } - .frame(width: 40, height: 40) - .opacity(store.canSend || store.upload.isAnyFileUploading ? 1 : 0.5) - } - .disabled(!store.canSend) + AttachButton() + Composer() + SendButton() } .padding(.horizontal, 12) .padding(.vertical, 8) + + // Under the field: above it the selection edit menu would cover the buttons + if store.isComposerFocused { + FormattingPanel() + } } .animation(.default, value: store.isAttachmentsShown) + .animation(.default, value: store.isComposerFocused) .animation(.default, value: store.upload.isAnyFileUploading) } + + private func AttachButton() -> some View { + Button { + send(.attachButtonTapped) + } label: { + Image(systemSymbol: .paperclip) + .font(.body.weight(.semibold)) + .foregroundStyle(Color(.Theme.primary)) + .frame(width: 40, height: 40) + .overlay(alignment: .topTrailing) { + let count = store.upload.files.count + if count > 0 { + Text(count, format: .number) + .font(.caption2.bold()) + .foregroundStyle(.white) + .padding(4) + .background(Color(.Theme.primary), in: Circle()) + } + } + } + .accessibilityLabel(Text("Attach files", bundle: .module)) + } + + private func Composer() -> some View { + QMSComposerTextView( + text: $store.draftText, + isFocused: $store.isComposerFocused, + tagInsertion: store.tagInsertion, + placeholder: String(localized: "qms.textfield.placeholder", bundle: .module) + ) + .frame(maxWidth: .infinity) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(Color(.Background.quaternary), in: .rect(cornerRadius: 20)) + // The text view covers only its lines, the padding around them should focus too + .contentShape(.rect(cornerRadius: 20)) + .onTapGesture { + store.isComposerFocused = true + } + } + + private func SendButton() -> some View { + Button { + send(.sendMessageButtonTapped) + } label: { + ZStack { + Circle() + .fill(Color(.Theme.primary)) + if store.upload.isAnyFileUploading { + ProgressView() + .tint(.white) + } else { + Image(systemSymbol: .arrowUp) + .font(.body.weight(.bold)) + .foregroundStyle(.white) + } + } + .frame(width: 40, height: 40) + .opacity(store.canSend || store.upload.isAnyFileUploading ? 1 : 0.5) + } + .disabled(!store.canSend) + } + + private func FormattingPanel() -> some View { + BBPanelView( + store: store.scope(state: \.bbPanel, action: \.bbPanel), + backgroundColor: Color(.Background.quaternary) + ) + .padding(.horizontal, 12) + .padding(.bottom, 8) + .transition(.opacity) + } } // MARK: - Previews diff --git a/Modules/Tests/QMSFeatureTests/QMSTagInsertionTests.swift b/Modules/Tests/QMSFeatureTests/QMSTagInsertionTests.swift new file mode 100644 index 00000000..48267b53 --- /dev/null +++ b/Modules/Tests/QMSFeatureTests/QMSTagInsertionTests.swift @@ -0,0 +1,57 @@ +// +// QMSTagInsertionTests.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Testing + +@testable import QMSFeature + +@Suite("QMS tag insertion") +struct QMSTagInsertionTests { + + private func apply(_ open: String, _ close: String, to text: String, selection: NSRange) -> (String, NSRange) { + let edit = QMSTagInsertion(id: 0, open: open, close: close).edit(in: text, selection: selection) + let result = (text as NSString).replacingCharacters(in: edit.range, with: edit.replacement) + return (result, edit.selection) + } + + @Test("Empty pair goes to the caret, caret ends up inside it") + func insertsPairAtCaret() { + let (text, selection) = apply("[b]", "[/b]", to: "hello world", selection: NSRange(location: 6, length: 0)) + #expect(text == "hello [b][/b]world") + #expect(selection == NSRange(location: 9, length: 0)) + } + + @Test("Selection is wrapped and stays selected") + func wrapsSelection() { + let (text, selection) = apply("[i]", "[/i]", to: "hello world", selection: NSRange(location: 6, length: 5)) + #expect(text == "hello [i]world[/i]") + #expect(selection == NSRange(location: 9, length: 5)) + } + + @Test("Works on empty text") + func emptyText() { + let (text, selection) = apply("[quote]", "[/quote]", to: "", selection: NSRange(location: 0, length: 0)) + #expect(text == "[quote][/quote]") + #expect(selection == NSRange(location: 7, length: 0)) + } + + @Test("Ranges are counted in UTF-16 like UITextView does") + func countsUTF16() { + // The emoji takes two UTF-16 units, the selection starts right after it + let (text, selection) = apply("[s]", "[/s]", to: "😀ab", selection: NSRange(location: 2, length: 2)) + #expect(text == "😀[s]ab[/s]") + #expect(selection == NSRange(location: 5, length: 2)) + } + + @Test("Selection out of text bounds is clamped") + func clampsStaleSelection() { + let (text, selection) = apply("[u]", "[/u]", to: "ab", selection: NSRange(location: 10, length: 3)) + #expect(text == "ab[u][/u]") + #expect(selection == NSRange(location: 5, length: 0)) + } +} diff --git a/Project.swift b/Project.swift index 1f1fb885..4fa6321d 100644 --- a/Project.swift +++ b/Project.swift @@ -522,6 +522,7 @@ let project = Project( .Internal.APIClient, .Internal.AnalyticsClient, .Internal.BBBuilder, + .Internal.BBPanelFeature, .Internal.GalleryFeature, .Internal.Models, .Internal.NotificationsClient,