Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Model/SceneStates.swift3// Description: The cohesive pieces of per-window state extracted from the former god object: message list and selection, search, unified list, conversation reader.4import SPMailCore5import SwiftUI67// MARK: - list and selection89@MainActor @Observable10final class ListState {11 var threads: [ThreadSummary] = []12 var limit = 20013 var isLoadingMore = false14 var selectedIds: Set<String> = []15 /// True until the first load of the current folder returned (skeleton rows instead of « Aucun message »).16 var isLoading = false17 @ObservationIgnored var generation = 01819 func reset() { threads = []; selectedIds = []; limit = 200; isLoadingMore = false; isLoading = false }20}2122// MARK: - search2324@MainActor @Observable25final class SearchState {26 var text = ""27 var unreadOnly = false28 var attachmentsOnly = false29 var results: [EmailSummary]?30 var isOffline = false31 var isSearching = false3233 var trimmed: String { text.trimmingCharacters(in: .whitespaces) }34 var isActive: Bool { results != nil }35 func clear() { text = ""; results = nil; isOffline = false }36 /// Search results presented as one-message conversations.37 var rows: [ThreadSummary]? { results.map { $0.map { ThreadSummary(email: $0, count: 1, unreadCount: $0.isSeen ? 0 : 1, anyFlagged: $0.isFlagged) } } }38}3940// MARK: - unified list (all mailboxes)4142@MainActor @Observable43final class UnifiedState {44 /// Rows come from the server; offline, from the merge of the local caches.45 var rows: [UnifiedMessage] = []46 var cursor: String?47 var isOffline = false48 var isLoading = false49 var selection: String?50 @ObservationIgnored var generation = 051 @ObservationIgnored var refresh: Task<Void, Never>?5253 func reset() { rows = []; cursor = nil; selection = nil; isOffline = false; isLoading = false; refresh?.cancel(); refresh = nil }54 func patch(account: String, ids: Set<String>, _ change: (inout EmailSummary) -> Void) {55 for n in rows.indices where rows[n].account == account && ids.contains(rows[n].email.id) { change(&rows[n].email) }56 }57 func patch(rowIds: Set<String>, _ change: (inout EmailSummary) -> Void) {58 for n in rows.indices where rowIds.contains(rows[n].id) { change(&rows[n].email) }59 }60 func deliveredTo(account: String, emailId: String) -> [String] { rows.first { $0.account == account && $0.email.id == emailId }?.deliveredTo ?? [] }61}6263// MARK: - conversation reader6465@MainActor @Observable66final class ReaderState {67 var conversation: [EmailSummary] = []68 var focusedEmailId: String?69 /// The mailbox of the message being read when it was opened from the unified list or in its own window (nil = the scene's mailbox).70 var account: String?71 var bodies: [String: EmailBody] = [:]72 var bodyErrors: [String: String] = [:]73 /// Messages for which the reader chose « Afficher les images » — per message, for this session only.74 var imagesAllowed: Set<String> = []75 /// Messages for which « Lecture sombre » was toggled against the preference — per message, for this session only.76 var darkReadingToggled: Set<String> = []77 /// Sanitised HTML per message and image policy: computed once, off the main actor, never inside a view body.78 private(set) var sanitized: [String: SanitizedHTML] = [:]79 @ObservationIgnored private var sanitizing: Set<String> = []8081 var focusedEmail: EmailSummary? { conversation.first { $0.id == focusedEmailId } ?? conversation.last }82 var isEmpty: Bool { conversation.isEmpty }8384 func clearConversation() { conversation = []; focusedEmailId = nil }85 func clearBodies() { bodies = [:]; bodyErrors = [:]; imagesAllowed = []; darkReadingToggled = []; sanitized = [:]; sanitizing = [] }86 func reset() { clearConversation(); clearBodies(); account = nil }8788 static func sanitizeKey(_ id: String, allowImages: Bool) -> String { "\(id)|\(allowImages ? 1 : 0)" }89 func sanitizedHTML(_ id: String) -> SanitizedHTML? { sanitized[Self.sanitizeKey(id, allowImages: imagesAllowed.contains(id))] }9091 /// Sanitises the HTML body of a message for the current image policy, once, on a background executor.92 func prepare(_ id: String) async {93 guard let html = bodies[id]?.html else { return }94 let allow = imagesAllowed.contains(id), key = Self.sanitizeKey(id, allowImages: allow)95 guard sanitized[key] == nil, !sanitizing.contains(key) else { return }96 sanitizing.insert(key)97 let clean = await Task.detached(priority: .userInitiated) { HTMLSanitizer.sanitize(html, allowRemoteImages: allow) }.value98 sanitizing.remove(key)99 // the body may have been dropped (account switch) while the sanitiser ran100 if bodies[id]?.html == html { sanitized[key] = clean }101 }102103 func loadBody(_ id: String, engine: SyncEngine?, describe: (Error) -> String?) async {104 guard bodies[id] == nil, let engine else { return }105 do {106 bodies[id] = try await engine.body(for: id)107 bodyErrors[id] = nil108 await prepare(id)109 } catch let e as APIError where e.isOffline {110 bodyErrors[id] = L("Ce message n’a pas été téléchargé avant la perte de connexion.")111 } catch { bodyErrors[id] = describe(error) }112 }113}114115// MARK: - toast116117/// A short status message, with at most one action (Undo).118struct Toast: Identifiable, Equatable {119 enum Kind: Sendable { case info, success, warning, error }120 let id = UUID()121 var message: String122 var kind: Kind = .info123 var actionTitle: String?124 var action: (@MainActor () async -> Void)?125 static func == (a: Toast, b: Toast) -> Bool { a.id == b.id }126}127