diff --git a/Modules/Sources/AppFeature/AppFeature.swift b/Modules/Sources/AppFeature/AppFeature.swift index f2325464..fb1cc715 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,8 @@ 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(\.qmsListStore) private var qmsListStore @Dependency(\.toastClient) private var toastClient @Dependency(\.hapticClient) private var hapticClient @Dependency(\.analyticsClient) private var analyticsClient @@ -403,6 +406,8 @@ public struct AppFeature: Reducer, Sendable { state.favoritesBadges = 0 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/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/NotificationsClient/NotificationsClient.swift b/Modules/Sources/NotificationsClient/NotificationsClient.swift index d57f80e3..eb905617 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 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 new file mode 100644 index 00000000..9b9a48c6 --- /dev/null +++ b/Modules/Sources/ParsingClient/Parsers/QMS/JSONValue.swift @@ -0,0 +1,86 @@ +// +// JSONValue.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation + +/// Lets `Decodable` responses hand nested parts over to the older `[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)) + } + } + + /// Same shape as `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) + } + } +} + +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 { + 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/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/QMSDialogCache.swift b/Modules/Sources/QMSClient/QMSDialogCache.swift new file mode 100644 index 00000000..2024755d --- /dev/null +++ b/Modules/Sources/QMSClient/QMSDialogCache.swift @@ -0,0 +1,115 @@ +// +// QMSDialogCache.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import ComposableArchitecture +import Foundation +import Models +import PersistenceKeys + +/// 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 { + + 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 + } + } + + 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([:]) } + ) + } +} + +// Actor so that 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, sync will write a new one + 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 { + // Not critical, 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..8d17c59e --- /dev/null +++ b/Modules/Sources/QMSClient/QMSDialogMerge.swift @@ -0,0 +1,56 @@ +// +// QMSDialogMerge.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Models + +enum QMSDialogMerge { + + enum PageKind: Equatable, Sendable { + case latest + case older + } + + struct Result: Equatable { + let messages: [QMSMessage] + /// How many messages of the page were not known before + let newCount: Int + } + + static func merge( + existing: [QMSMessage], + page: [QMSMessage], + kind: PageKind, + pageSize: Int + ) -> Result { + var base = existing + + // 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(), + 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/QMSListStore.swift b/Modules/Sources/QMSClient/QMSListStore.swift new file mode 100644 index 00000000..314c12c5 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSListStore.swift @@ -0,0 +1,221 @@ +// +// QMSListStore.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import ComposableArchitecture +import Foundation +import Models +import PersistenceKeys + +/// 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 + 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 + + 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 + + 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 + } + + 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 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 }) + 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 + } + } + + 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/QMSClient/QMSOutgoingMessage.swift b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift new file mode 100644 index 00000000..3371be68 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSOutgoingMessage.swift @@ -0,0 +1,43 @@ +// +// QMSOutgoingMessage.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation + +/// 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 + /// Accepted by the server, stays until the next sync brings the real message + case sent + } + + public struct Attachment: Hashable, 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 + } +} diff --git a/Modules/Sources/QMSClient/QMSStore.swift b/Modules/Sources/QMSClient/QMSStore.swift new file mode 100644 index 00000000..48866e35 --- /dev/null +++ b/Modules/Sources/QMSClient/QMSStore.swift @@ -0,0 +1,315 @@ +// +// QMSStore.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Dependencies +import Foundation +import Models + +public struct QMSDialogSnapshot: Equatable, Sendable, Codable { + /// Messages are sorted from oldest to newest + public var chat: QMSChat + public var hasMoreOlder: Bool + public var outgoing: [QMSOutgoingMessage] + + 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) + // Not present in caches written by earlier builds + outgoing = try container.decodeIfPresent([QMSOutgoingMessage].self, forKey: .outgoing) ?? [] + } +} + +/// Keeps QMS dialogs in memory and on disk, all screens read dialogs from here. +/// +/// 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 + 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]] = [:] + + private var syncTasks: [Int: Task] = [:] + private var pendingSync: Set = [] + private var olderTasks: [Int: Task] = [:] + + 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 + + /// 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, + 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, var cached = await cache.load(dialogId) { + // 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 + case .failed: return message + case .sending: + var message = message + message.state = .failed + return message + } + } + // Sync could finish while the 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 + + 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 { + 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 + + 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: - Send + + /// 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, + 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 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) + } + + 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 + + /// Logout and 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 { + // Nothing new from the server, stop here instead of requesting the same page forever + hasMoreOlder = merge.newCount > 0 + } else { + hasMoreOlder = true + } + + var mergedChat = chat + mergedChat.messages = merge.messages + var outgoing = existing?.outgoing ?? [] + if kind == .latest { + // Sent messages are in this page already + outgoing.removeAll { $0.state == .sent } + } + let snapshot = QMSDialogSnapshot(chat: mergedChat, hasMoreOlder: hasMoreOlder, outgoing: outgoing) + await publish(snapshot, replacing: existing) + } + + 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) + } + + 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) }, + sendMessage: { try await qmsClient.sendMessage($0, $1, $2) }, + cache: .liveValue + ) + } + + public static var testValue: QMSStore { + @Dependency(\.qmsClient) var qmsClient + return QMSStore( + loadChat: { try await qmsClient.loadChat($0, $1, $2) }, + sendMessage: { try await qmsClient.sendMessage($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/Analytics/QMSFeature+Analytics.swift b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift index 62ab8b8b..8072bdb2 100644 --- a/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift +++ b/Modules/Sources/QMSFeature/Analytics/QMSFeature+Analytics.swift @@ -17,13 +17,14 @@ 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: + case .view(.onAppear), .view(.attachButtonTapped), .view(.retryMessageTapped), + .view(.discardMessageTapped), .view(.imageTapped), .internal, .delegate, .binding, .alert, .upload, .bbPanel: 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/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 new file mode 100644 index 00000000..a2300c69 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatCollectionView.swift @@ -0,0 +1,346 @@ +// +// QMSChatCollectionView.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import SFSafeSymbols +import SwiftUI +import UIKit + +// 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 + /// Any change scrolls the feed to the bottom + let scrollToBottomRequest: Int + /// 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 + + func makeUIViewController(context: Context) -> QMSChatViewController { + QMSChatViewController() + } + + func updateUIViewController(_ controller: QMSChatViewController, context: Context) { + controller.onLoadOlder = onLoadOlder + controller.onURL = onURL + controller.onImage = onImage + controller.onAtBottomChanged = onAtBottomChanged + controller.onRetry = onRetry + controller.onDiscard = onDiscard + controller.previewBackgroundColor = UIColor(background) + controller.update(items: items, hasMoreOlder: hasMoreOlder) + controller.handleScrollToBottomRequest(scrollToBottomRequest) + } +} + +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 } + var previewBackgroundColor: UIColor = .systemBackground + + private var collectionView: UICollectionView! + private var dataSource: UICollectionViewDiffableDataSource! + + private var items: [String: QMSChatItem] = [:] + private var bubbleFrames: [String: CGRect] = [:] + 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 + + 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) + + // 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) } + .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 resized the feed + if collectionView.bounds.height != lastBoundsHeight { + lastBoundsHeight = collectionView.bounds.height + if isAtBottom { + scrollToBottom(animated: false) + } + } + } + + @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) + 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, + onBubbleFrame: { [weak self] frame in + self?.bubbleFrames[item.id] = frame + }, + onRetry: { [weak self] in + if let id = message.outgoingId { self?.onRetry(id) } + }, + onURL: { [weak self] url in + self?.onURL(url) + }, + onImage: { [weak self] url in + self?.onImage(url) + } + ) + } + } + .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 + bubbleFrames = bubbleFrames.filter { newById[$0.key] != nil } + + 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 + /// From the top of the visible area to the top of the item + 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 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 } + 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 { + // Same as above, estimated heights are replaced 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: { [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(systemSymbol: .arrowClockwise) + ) { _ in + self?.onRetry(id) + }) + } + actions.append(UIAction( + title: String(localized: "Copy", bundle: .module), + 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(systemSymbol: .trash), + attributes: .destructive + ) { _ in + self?.onDiscard(id) + }) + } + return UIMenu(children: actions) + }) + } + + 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) + } + + // 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), + 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/QMSChatItem.swift b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift new file mode 100644 index 00000000..605eaec1 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatItem.swift @@ -0,0 +1,107 @@ +// +// QMSChatItem.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Models +import SharedUI + +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 { + if let outgoingId = message.outgoingId { + return QMSChatItem(id: "outgoing-\(outgoingId.uuidString)", kind: .message(message)) + } + return QMSChatItem(id: "message-\(message.id)", kind: .message(message)) + } +} + +// MARK: - Message + +public struct QMSChatMessage: Equatable, Sendable { + + public enum Status: Equatable, Sendable { + case none + case sending + case failed + case sent + case read + } + + /// 0 until the server confirms the message + public let id: Int + public var outgoingId: UUID? = nil + public let text: AttributedString + public let date: Date + public let isMine: Bool + public let status: Status + /// Set only on the last message of a partner's group + public let avatarUrl: URL? + public let isFirstInGroup: Bool + public let isLastInGroup: Bool + /// 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] = [] + + public var plainText: String { + String(text.characters) + } +} + +// MARK: - Attachments + +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 + } +} + +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)") + } + + 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 new file mode 100644 index 00000000..effd11d3 --- /dev/null +++ b/Modules/Sources/QMSFeature/Chat/QMSChatRows.swift @@ -0,0 +1,202 @@ +// +// QMSChatRows.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import NukeUI +import SFSafeSymbols +import SharedUI +import SwiftUI + +// MARK: - Message + +struct QMSMessageRow: View { + + let message: QMSChatMessage + /// Bubble frame in row coordinates, the context menu lifts only the bubble + var onBubbleFrame: (CGRect) -> Void = { _ in } + var onRetry: () -> Void = {} + /// 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" + + var body: some View { + HStack(alignment: .bottom, spacing: 8) { + if message.isMine { + Spacer(minLength: 48) + } else { + avatar + } + + bubble + .onGeometryChange(for: CGRect.self) { proxy in + proxy.frame(in: .named(Self.coordinateSpace)) + } action: { frame in + onBubbleFrame(frame) + } + .opacity(message.status == .sending ? 0.7 : 1) + .overlay { + // Covers links only for failed messages, there a tap means retry + if message.status == .failed { + Color.clear + .contentShape(Rectangle()) + .onTapGesture(perform: onRetry) + } + } + + if !message.isMine { + Spacer(minLength: 48) + } + } + .padding(.horizontal, 12) + .padding(.top, message.isFirstInGroup ? 6 : 1) + .padding(.bottom, message.isLastInGroup ? 6 : 1) + .coordinateSpace(name: Self.coordinateSpace) + } + + @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 { + 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: 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) + } + } + + HStack(spacing: 3) { + Text(message.date, format: .dateTime.hour().minute()) + .font(.caption2) + .foregroundStyle(Color(.systemGray)) + 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)) + } + } +} + +// 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 content = subviews[0].sizeThatFits(ProposedViewSize(width: proposal.width, height: nil)) + let footer = subviews[1].sizeThatFits(.unspecified) + 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 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: content.height) + ) + subviews[1].place( + at: CGPoint(x: bounds.maxX, y: bounds.minY + content.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/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/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/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/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..6070ac92 100644 --- a/Modules/Sources/QMSFeature/QMSFeature.swift +++ b/Modules/Sources/QMSFeature/QMSFeature.swift @@ -6,7 +6,9 @@ // import Foundation +import BBPanelFeature import ComposableArchitecture +import GalleryFeature import APIClient import QMSClient import PersistenceKeys @@ -14,20 +16,17 @@ import Models import AnalyticsClient import NotificationsClient import TCAExtensions -import ExyteChat +import UploadBoxFeature @Reducer 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 + case render } // MARK: - State @@ -41,14 +40,32 @@ public struct QMSFeature: Reducer, Sendable { public let chatId: Int public var chat: QMSChat? - public var messages: [Message] = [] + public var items: [QMSChatItem] = [] + var scrollToBottomRequest = 0 + public var outgoing: [QMSOutgoingMessage] = [] var hasMoreOlderMessages = true var isLoadingMore = false - var isSending = false var draftText = "" - var draftSnapshot = "" + var isComposerFocused = false + var tagInsertion: QMSTagInsertion? + var bbPanel = BBPanelFeature.State(for: .qms) + var upload = UploadBoxFeature.State.qms + var isAttachmentsShown = false + var gallery: GalleryModel? + + 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,18 +93,27 @@ public struct QMSFeature: Reducer, Sendable { case view(View) public enum View { case onAppear - case sendMessageButtonTapped(DraftMessage) + case sendMessageButtonTapped + case attachButtonTapped + case retryMessageTapped(UUID) + case discardMessageTapped(UUID) case loadMoreTriggered case urlTapped(URL) + case imageTapped(URL) } case `internal`(Internal) public enum Internal { - case loadChat - case chatLoaded(Result, LoadKind) - case messageSendError(any Error) + case sync + case syncFinished(Result) + case olderLoaded(Result) + case snapshotUpdated(QMSDialogSnapshot) + case itemsBuilt([QMSChatItem]) } + case upload(UploadBoxFeature.Action) + case bbPanel(BBPanelFeature.Action) + case delegate(Delegate) public enum Delegate { case handleUrl(URL) @@ -97,7 +123,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 @@ -107,57 +133,109 @@ public struct QMSFeature: Reducer, Sendable { public var body: some Reducer { BindingReducer() + Scope(state: \.upload, action: \.upload) { + UploadBoxFeature() + } + + Scope(state: \.bbPanel, action: \.bbPanel) { + BBPanelFeature() + } + Reduce { state, action in switch action { - case .alert, .delegate: + 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): + // Called again after returning from pushed screens, cancelInFlight keeps effects from duplicating 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)): - guard !state.isSending, !draftMessage.text.isEmpty else { return .none } + case .view(.sendMessageButtonTapped): + guard state.canSend else { return .none } + let text = state.draftText.trimmingCharacters(in: .whitespacesAndNewlines) + let attachments = state.uploadedAttachments state.draftText = "" - state.draftSnapshot = draftMessage.text - state.isSending = true + state.upload = .qms + state.isAttachmentsShown = false + state.scrollToBottomRequest += 1 - return .run { [chatId = state.chatId, message = draftMessage.text] send in - try await qmsClient.sendMessage(chatId: chatId, message: message) - } 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): - 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 .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 - state.draftText = state.draftSnapshot - state.alert = .somethingWentWrong - analyticsClient.capture(error) + 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)): @@ -184,55 +262,44 @@ 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))) + + // 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))) } - case let .internal(.chatLoaded(result, loadKind)): - 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 - ) - 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): + case let .internal(.syncFinished(result)): + if case let .failure(error) = result { analyticsClient.capture(error) - state.alert = .somethingWentWrong + // Background refresh failures don't deserve an alert while the chat is on screen + if state.chat == nil { + state.alert = .somethingWentWrong + } } - analyticsClient.reportFullyDisplayed() - return .run { [userId = state.chat!.partnerId] send in - let ids = (try? result.get().id).map { [$0] } ?? [] - await notificationsClient.removeNotifications(ids: ids) - 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 buildItems(state) + + 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)): + state.items = items + return .none case .binding: return .none @@ -246,74 +313,32 @@ 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, - 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 - ) - - return Message( - id: String(remoteMessage.id), - user: user, - status: .none, - createdAt: remoteMessage.date, - text: remoteMessage.processedText + // 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 { [ + userId = state.userSession?.userId ?? 0, + isLoadingOlder = state.isLoadingMore, + outgoing = state.outgoing + ] send in + let items = QMSChatItemsBuilder.build( + messages: chat.messages, + outgoing: outgoing, + chat: chat, + currentUserId: userId, + isLoadingOlder: isLoadingOlder, + render: QMSMessageRenderer.shared.render(_:) ) + await send(.internal(.itemsBuilt(items))) } - - for index in localMessages.indices { - guard localMessages[index].user.isCurrentUser else { continue } - localMessages[index].status = .read - } - - 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) } +} + +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 15624e7e..523b0983 100644 --- a/Modules/Sources/QMSFeature/QMSScreen.swift +++ b/Modules/Sources/QMSFeature/QMSScreen.swift @@ -6,137 +6,190 @@ // import SwiftUI +import BBPanelFeature import ComposableArchitecture import SharedUI import SFSafeSymbols -import ExyteChat +import UploadBoxFeature +import GalleryFeature @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, + 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)) } + ) + + 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)) + .fullScreenCover(item: $store.gallery) { model in + TabViewGallery(model: model) + } .onAppear { send(.onAppear) } } } - - 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) + + // 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 { + 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) { + 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() } - #endif - - TextField(String(""), text: text, prompt: Text("qms.textfield.placeholder", bundle: .module)) - .padding() - .background(Color(.Background.quaternary), in: .rect(cornerRadius: 16)) - - Button { - if !text.wrappedValue.isEmpty { - send(.sendMessageButtonTapped( - DraftMessage(text: text.wrappedValue, medias: [], giphyMedia: nil, recording: nil, replyMessage: nil, createdAt: .now) - )) + } + .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()) + } } - } label: { + } + .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() - .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) - } - } + .fill(Color(.Theme.primary)) + if store.upload.isAnyFileUploading { + ProgressView() + .tint(.white) + } else { + Image(systemSymbol: .arrowUp) + .font(.body.weight(.bold)) + .foregroundStyle(.white) + } } - .disabled(store.isSending) + .frame(width: 40, height: 40) + .opacity(store.canSend || store.upload.isAnyFileUploading ? 1 : 0.5) } - .padding() - .animation(.default, value: store.isSending) - .animation(.default, value: text.wrappedValue) - .bind(text, to: $store.draftText) + .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) } } @@ -145,33 +198,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..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,70 @@ } } }, + "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" : { + "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/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..987c1ae9 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 + // By user id, not index, the list gets reordered on every new message + 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)) + // Called again after returning from a chat, cancelInFlight keeps effects from duplicating + 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) + // Cached dialogs are shown while fresh ones load + return userId == 0 ? .none : .send(.internal(.loadUser(userId))) + } else { + state.expandedUserIds.remove(userId) + return .none } case let .view(.userContextMenu(userContextAction, user)): @@ -239,57 +243,42 @@ 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) + 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 +288,8 @@ 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 + 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 ee20395b..32614c65 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,8 @@ public struct SettingsFeature: Reducer, Sendable { @Dependency(\.pasteboardClient) var pasteboardClient @Dependency(\.analyticsClient) var analyticsClient @Dependency(\.cacheClient) var cacheClient + @Dependency(\.qmsStore) var qmsStore + @Dependency(\.qmsListStore) var qmsListStore @Dependency(\.openURL) var openURL // MARK: - Body @@ -183,6 +186,8 @@ public struct SettingsFeature: Reducer, Sendable { return .run { send in do { try await cacheClient.removeAll() + await qmsStore.removeAll() + await qmsListStore.removeAll() } catch { await send(._somethingWentWrong(error)) } 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/ParsingClientTests/QMSParserTests.swift b/Modules/Tests/ParsingClientTests/QMSParserTests.swift new file mode 100644 index 00000000..263e262e --- /dev/null +++ b/Modules/Tests/ParsingClientTests/QMSParserTests.swift @@ -0,0 +1,194 @@ +// +// QMSParserTests.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +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/Modules/Tests/QMSClientTests/QMSListStoreTests.swift b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift new file mode 100644 index 00000000..6c32d9bf --- /dev/null +++ b/Modules/Tests/QMSClientTests/QMSListStoreTests.swift @@ -0,0 +1,132 @@ +// +// QMSListStoreTests.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +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/Modules/Tests/QMSClientTests/QMSStoreTests.swift b/Modules/Tests/QMSClientTests/QMSStoreTests.swift new file mode 100644 index 00000000..29f6fd33 --- /dev/null +++ b/Modules/Tests/QMSClientTests/QMSStoreTests.swift @@ -0,0 +1,403 @@ +// +// QMSStoreTests.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +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) + } +} + +// 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 new file mode 100644 index 00000000..50a56061 --- /dev/null +++ b/Modules/Tests/QMSFeatureTests/QMSChatItemsBuilderTests.swift @@ -0,0 +1,220 @@ +// +// QMSChatItemsBuilderTests.swift +// ForPDA +// +// Created by va1mont on 05.12.2026. +// + +import Foundation +import Models +import QMSClient +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], + 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: { QMSRenderedText(text: AttributedString($0.text), nodes: nil) } + ) + } + + 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("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 == "") + #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") + func empty() { + #expect(build([]).isEmpty) + } +} + +@Suite("QMS message renderer") +struct QMSMessageRendererTests { + + private func input(_ text: String, id: Int = 1) -> QMSRenderInput { + QMSRenderInput(id: id, text: text, inlineAttachments: []) + } + + @Test("Message is rendered once per input") + func cache() { + var renders = 0 + 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(input("b")).text.characters) == "b") + #expect(renders == 2) + } + + @Test("Links are underlined") + func links() { + 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") + func blocks() throws { + let renderer = QMSMessageRenderer() + let rendered = renderer.render(input("[quote]Quote[/quote]\n[code]print(1)[/code]")) + let nodes = try #require(rendered.nodes) + #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/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 785371eb..4fa6321d 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, @@ -523,13 +522,16 @@ let project = Project( .Internal.APIClient, .Internal.AnalyticsClient, .Internal.BBBuilder, + .Internal.BBPanelFeature, + .Internal.GalleryFeature, .Internal.Models, .Internal.NotificationsClient, .Internal.PersistenceKeys, .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, - .SPM.ExyteChat, + .Internal.TopicBuilder, + .Internal.UploadBoxFeature, .SPM.NukeUI, .SPM.SFSafeSymbols, .SPM.SkeletonUI, @@ -601,6 +603,7 @@ let project = Project( .Internal.Models, .Internal.PasteboardClient, .Internal.PersistenceKeys, + .Internal.QMSClient, .Internal.SharedUI, .Internal.TCAExtensions, .SPM.SFSafeSymbols, @@ -833,6 +836,7 @@ let project = Project( .Internal.Models, .Internal.ParsingClient, .Internal.NotificationsClient, + .Internal.PersistenceKeys, .SPM.PDAPI, .SPM.TCA ] @@ -934,6 +938,64 @@ 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: "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: "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, + .Internal.SharedUI, + .SPM.TCA, + ], + settings: .settings( + base: .targetSettings.merging(.sharingAliasFix), + defaultSettings: .recommended + ) + ), // .target( // name: "ForPDATests", @@ -1375,7 +1437,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"), ]