SPB Git

Repository Public

MailScene+Next.swift 23.0 KB 436 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/MailScene+Next.swift3// Description: SP Mail Next state of one window — operator search and the cross-mailbox lists built on it (labels, smart folders), multi-selection4// and bulk actions on rows of any mailbox, opening a message through the engine of ITS mailbox, pin / label helpers, picker requests.5import SPMailCore6import SwiftUI78// MARK: - rows of a cross-mailbox list910/// One row of a list that spans mailboxes (search results, a label, a smart folder, the unified inbox): the message and the mailbox that holds it.11struct RemoteRow: Identifiable, Hashable, Sendable {12    var id: String13    /// The SP Mail mailbox id; nil only for a unified row that could not be tied to an engine.14    var account: String?15    var email: EmailSummary16    /// Shown as a coloured chip: the address that received the message.17    var receivedBy: String?18    var threadCount = 119    /// A semantic (« par le sens ») hit rather than a keyword match.20    var semantic = false2122    init(id: String, account: String?, email: EmailSummary, receivedBy: String? = nil, threadCount: Int = 1, semantic: Bool = false) {23        self.id = id; self.account = account; self.email = email; self.receivedBy = receivedBy; self.threadCount = threadCount; self.semantic = semantic24    }25    init(_ r: SearchResult, receivedBy: String? = nil, semantic: Bool = false) {26        self.init(id: r.id, account: r.mailboxId, email: r.summary, receivedBy: receivedBy, threadCount: r.threadCount ?? 1, semantic: semantic)27    }28    init(_ m: UnifiedMessage) { self.init(id: m.id, account: m.account, email: m.email, receivedBy: m.receivingAddress) }29    static func rowId(_ account: String, _ emailId: String) -> String { "\(account):\(emailId)" }30}3132extension ThreadSummary {33    var isPinned: Bool { email.keywords.contains(NextKeyword.pinned) }34}3536// MARK: - search state3738@MainActor @Observable39final class RemoteSearchState {40    /// Terms the server parsed, shown as chips.41    var chips: [QueryChip] = []42    /// The token being typed (not yet a chip).43    var draft = ""44    var allMailboxes = true45    /// « Par le sens »: hybrid semantic search (only offered while the semantic feature is enabled).46    var semantic = false47    var rows: [RemoteRow] = []48    var cursor: String?49    var errors: [ParsedQuery.Issue] = []50    var isSearching = false51    var isLoadingMore = false52    /// Results come from the caches of this device (the server was not reached).53    var isOffline = false54    /// Which provider processed a semantic query — always stated.55    var provider: String?56    var failure: String?57    /// Name of the label or smart folder shown as a list; nil for a free search.58    var title: String?59    var savedSearchId: String?60    @ObservationIgnored var generation = 061    @ObservationIgnored var lastKey = ""6263    var query: String { [QueryBuilder(chips).query, draft.trimmingCharacters(in: .whitespaces)].filter { !$0.isEmpty }.joined(separator: " ") }64    var isEmpty: Bool { chips.isEmpty && draft.trimmingCharacters(in: .whitespaces).isEmpty }65    func clear() { generation += 1; lastKey = ""; chips = []; draft = ""; rows = []; cursor = nil; errors = []; isSearching = false; isOffline = false; provider = nil; failure = nil; title = nil; savedSearchId = nil; semantic = false }6667    static let recentsKey = "spm.recentSearches"68    static var recents: [String] { UserDefaults.standard.stringArray(forKey: recentsKey) ?? [] }69    static func remember(_ query: String) {70        let q = query.trimmingCharacters(in: .whitespaces)71        guard q.count >= 2 else { return }72        UserDefaults.standard.set(Array(([q] + recents.filter { $0.caseInsensitiveCompare(q) != .orderedSame }).prefix(8)), forKey: recentsKey)73    }74    static func forgetRecents() { UserDefaults.standard.removeObject(forKey: recentsKey) }75}7677/// The model-free smart filters offered above the inbox, and the optional AI « Important ».78enum InsightFilter: String, CaseIterable, Identifiable, Sendable {79    case needsReply, newsletters, unanswered, important80    var id: String { rawValue }81    var title: String {82        switch self { case .needsReply: L("À répondre"); case .newsletters: L("Infolettres"); case .unanswered: L("Sans réponse"); case .important: L("Important") }83    }84    var icon: String {85        switch self { case .needsReply: "arrowshape.turn.up.left"; case .newsletters: "newspaper"; case .unanswered: "hourglass"; case .important: "sparkles" }86    }87}8889// MARK: - per-window Next state9091@MainActor @Observable92final class NextSceneState {93    let search = RemoteSearchState()94    let contacts = ContactsState()95    let gallery = GalleryState()96    /// What the model answered for the conversation being read (only used while intelligence is enabled).97    let ai = ReaderAIState()98    #if DEBUG99    /// Design captures: a settings pane (or the dashboard customiser) shown on its own.100    var debugPane: String?101    #endif102    /// The note a reminder starts with (an action item of a summary).103    var reminderNote: String?104    /// Selected rows of the cross-mailbox list in front (search results, label, smart folder, unified inbox).105    var selection: Set<String> = []106    /// The row whose message the reader shows.107    var openRowId: String?108    /// Where « Annuler » of the search screen goes back to.109    var previousSelection: SidebarItem?110    var snoozeRequest: SnoozeRequest?111    var labelEdit: LabelEditRequest?112    /// Messages for which the label picker sheet is shown (iOS « Plus », toolbar).113    var labelPick: LabelPickRequest?114    var saveSearchRequest = false115    /// A message to show on its own (its window on macOS, a sheet on iOS / iPadOS).116    var messageRequest: MessageRef?117    /// The smart filter applied to the inbox list, and the rows it shows instead of the folder's.118    var insightFilter: InsightFilter?119    var insightRows: [ThreadSummary]?120    /// Bumped to give the keyboard focus to the search field.121    var focusToken = 0122123    func reset() {124        search.clear(); contacts.reset(); gallery.reset(); ai.reset(for: nil); ai.summary = nil; ai.replies = nil; reminderNote = nil125        selection = []; openRowId = nil; previousSelection = nil; snoozeRequest = nil; labelEdit = nil; labelPick = nil; saveSearchRequest = false; messageRequest = nil; insightFilter = nil; insightRows = nil126    }127}128129struct LabelPickRequest: Identifiable {130    let id = UUID()131    var keywords: [String]132    var apply: @MainActor (MailAction) -> Void133}134135// MARK: - scene behaviour136137extension MailScene {138    /// The reader shows a message opened through the engine of its own mailbox from a Next list (not the folder list of this window).139    var readsRemote: Bool {140        switch selection { case .label, .savedSearch, .search, .snoozed, .followUps, .contacts, .attachments, .dashboard: true; default: false }141    }142    /// Screens that take the whole width beside the sidebar (no list + reader pair).143    var isWideScreen: Bool { selection == .dashboard || selection == .attachments }144145    var nextTitle: String {146        switch selection {147        case .dashboard: L("Centre de commande")148        case .label(let id): app.next.label(id: id)?.name ?? L("Libellé")149        case .savedSearch(let id): app.next.savedSearch(id: id)?.name ?? L("Recherche enregistrée")150        case .search: L("Recherche")151        case .snoozed: L("En veille")152        case .followUps: L("Suivis")153        case .contacts: L("Contacts")154        case .attachments: L("Pièces jointes")155        default: ""156        }157    }158159    func nextDidSelectSidebar() {160        let s = next.search161        switch selection {162        case .label(let id):163            s.clear()164            guard let label = app.next.label(id: id) else { return }165            s.title = label.name; s.allMailboxes = true; s.chips = [QueryChip.label(label.name)]166            Task { await runRemoteSearch() }167        case .savedSearch(let id):168            s.clear()169            guard let saved = app.next.savedSearch(id: id) else { return }170            s.title = saved.name; s.savedSearchId = saved.id; s.draft = saved.query + " "171            if case .only(let ids) = saved.scope, ids == [currentAccount ?? ""] { s.allMailboxes = false } else { s.allMailboxes = true }172            Task { await runRemoteSearch(scope: saved.scope) }173        case .search:174            if s.title != nil { s.clear() }175            next.focusToken += 1176        case .snoozed: Task { await app.next.reloadSnoozes() }177        case .followUps: Task { await app.next.reloadReminders() }178        default: break179        }180    }181182    /// Opens the search screen (⌘F, the toolbar button, the command palette), optionally with a query.183    func openSearch(_ text: String? = nil) {184        guard app.next.has(.searchAll) || app.next.isAvailable else {185            // an older server: the historical local / JMAP search of the folder list186            if let text { search.text = text }187            focusSearchToken += 1188            return189        }190        if selection != .search {191            let everywhere = isUnified || app.accounts.count < 2192            next.previousSelection = selection; next.search.clear(); next.search.allMailboxes = everywhere; selection = .search193        }194        if let text { next.search.chips = []; next.search.draft = text + " "; Task { await runRemoteSearch() } }195        next.focusToken += 1196    }197    func closeSearch() {198        next.search.clear()199        selection = next.previousSelection ?? mailbox(.inbox).map { .mailbox($0.id) }200        next.previousSelection = nil201    }202203    private func searchScope() -> MailboxScope {204        if next.search.allMailboxes { return .all }205        return currentAccount.map { .only([$0]) } ?? .all206    }207    private func chipAddress(_ account: String) -> String? { app.accounts.count > 1 ? app.box(account)?.address.lowercased() : nil }208209    /// Parses the query on the server (chips, inline errors), then runs it. Offline: the local caches answer, and the list says so.210    func runRemoteSearch(scope fixed: MailboxScope? = nil, commit: Bool = false) async {211        let s = next.search212        let q = s.query213        s.generation += 1214        s.lastKey = s.runKey215        let generation = s.generation216        guard !q.isEmpty else { s.rows = []; s.cursor = nil; s.errors = []; s.isOffline = false; s.failure = nil; s.isSearching = false; return }217        s.isSearching = true218        defer { if generation == s.generation { s.isSearching = false } }219        let scope = fixed ?? searchScope()220        let api = app.next.api, typed = s.draft221        do {222            let parsed = try await api.parseQuery(q)223            guard generation == s.generation else { return }224            s.errors = parsed.errors225            guard parsed.isValid else { s.rows = []; s.cursor = nil; s.failure = nil; s.isOffline = false; return }226            // a finished token (followed by a space) or a committed query becomes chips: the server's reading, never a client-side parser227            if s.draft == typed, commit || typed.last?.isWhitespace == true || typed.isEmpty { s.chips = parsed.chips; s.draft = ""; s.lastKey = s.runKey }228            let semantic = s.semantic && app.next.aiEnabled(.semantic)229            let page = semantic ? try await api.semanticSearch(q, scope: scope, limit: 50) : try await api.search(SearchQuery(q, scope: scope, limit: 50, threads: app.settings.threaded))230            guard generation == s.generation else { return }231            s.rows = page.results.map { RemoteRow($0, receivedBy: chipAddress($0.mailboxId), semantic: semantic && $0.score != nil) }232            s.cursor = semantic ? nil : page.nextCursor233            s.provider = semantic ? app.next.providerLabel(provider: page.provider ?? "local", model: page.model ?? "") : nil234            s.isOffline = false; s.failure = nil235            if commit { RemoteSearchState.remember(q) }236        } catch let e where NextError.isOffline(e) {237            // offline: what the caches of this device hold, mailbox by mailbox, newest first238            var local: [RemoteRow] = []239            for box in app.accounts where scope.includes(box.id) {240                let hits = (try? await app.store?.search(box.id, text: q)) ?? []241                local += hits.map { RemoteRow(id: RemoteRow.rowId(box.id, $0.id), account: box.id, email: $0, receivedBy: chipAddress(box.id)) }242            }243            guard generation == s.generation else { return }244            s.rows = local.sorted { $0.email.receivedAt > $1.email.receivedAt }245            s.cursor = nil; s.isOffline = true; s.failure = nil; s.errors = []; s.provider = nil246        } catch let e where NextError.isUnauthorized(e) {247            await app.sessionRevoked()248        } catch {249            guard generation == s.generation, !(error is CancellationError) else { return }250            if (error as? APIError)?.code == "invalid_query" { s.errors = []; s.failure = L("Cette recherche n’est pas valide.") } else { s.failure = app.next.describe(error) }251            s.rows = []; s.cursor = nil252        }253    }254255    func loadMoreRemoteSearch(after row: RemoteRow) async {256        let s = next.search257        guard row.id == s.rows.last?.id, let cursor = s.cursor, !s.isLoadingMore, !s.isOffline else { return }258        s.isLoadingMore = true259        defer { s.isLoadingMore = false }260        let generation = s.generation261        var scope = searchScope()262        if let id = s.savedSearchId, let saved = app.next.savedSearch(id: id) { scope = saved.scope }263        guard let page = try? await app.next.api.search(SearchQuery(s.query, scope: scope, limit: 50, cursor: cursor, threads: app.settings.threaded)), generation == s.generation, cursor == s.cursor else { return }264        let known = Set(s.rows.map(\.id))265        s.rows += page.results.filter { !known.contains($0.id) }.map { RemoteRow($0, receivedBy: chipAddress($0.mailboxId)) }266        s.cursor = page.nextCursor267    }268269    // MARK: opening a message of any mailbox270271    /// Opens a message in the reader through the engine of ITS mailbox: every later action (flag, archive, reply) then acts on that mailbox.272    @discardableResult273    func openRemote(account: String, emailId: String, rowId: String? = nil, fallback: EmailSummary? = nil) async -> Bool {274        guard let engine = app.engines[account], let store = app.store else { return false }275        next.openRowId = rowId276        if reader.account != account { reader.clearBodies() }277        reader.account = account278        try? await engine.ensureCached(ids: [emailId])279        guard let head = ((try? await store.email(account, id: emailId)) ?? nil) ?? fallback else {280            reader.clearConversation(); list.selectedIds = []281            app.toast = Toast(message: L("Ce message n’est plus disponible."), kind: .info)282            return false283        }284        if head.isDraft { await compose(.serverDraft(head)); return true }285        let thread = app.settings.threaded ? ((try? await store.threadEmails(account, threadId: head.threadId)) ?? []).filter { !$0.isDraft } : []286        reader.conversation = thread.contains { $0.id == head.id } ? thread : [head]287        reader.focusedEmailId = head.id288        list.selectedIds = [head.id]289        await loadBody(head.id)290        if app.settings.threaded { await completeThread(head, account: account) }291        if app.settings.markReadOnOpen {292            let unread = reader.conversation.filter { !$0.isSeen }.map(\.id)293            if !unread.isEmpty { await engine.markSeen(true, ids: unread); nextDidPerform(.markRead(true), account: account, ids: Set(unread)) }294        }295        return true296    }297    @discardableResult298    func openRemote(_ row: RemoteRow) async -> Bool {299        guard let account = row.account else { return false }300        return await openRemote(account: account, emailId: row.email.id, rowId: row.id, fallback: row.email)301    }302303    /// Shows a message on its own: a message window on macOS, a sheet on iOS / iPadOS (dashboard items, contact history, attachment sources).304    func presentMessage(account: String, emailId: String) { next.messageRequest = MessageRef(account: account, emailId: emailId, conversation: app.settings.threaded) }305306    // MARK: actions on rows of any mailbox307308    /// An action on rows of a cross-mailbox list, each sent to the engine of the mailbox that holds the message (offline: queued there).309    func performRemote(_ action: MailAction, on rows: [RemoteRow]) async {310        for (account, group) in Dictionary(grouping: rows.filter { $0.account != nil }, by: { $0.account ?? "" }) {311            guard let engine = app.engines[account] else { continue }312            let ids = group.map(\.email.id)313            do {314                try? await engine.ensureCached(ids: ids)315                var before: [String: String] = [:]316                switch action { case .archive, .delete, .junk, .move: before = await origins(account: account, ids: ids); default: break }317                switch action {318                case .markRead(let v): await engine.markSeen(v, ids: ids)319                case .flag(let v): await engine.setFlagged(v, ids: ids)320                case .archive: try await engine.archive(ids: ids, folderName: L("Archives"))321                case .delete: try await engine.delete(ids: ids)322                case .junk: try await engine.markJunk(ids: ids)323                case .move(let box): await engine.move(ids: ids, to: box)324                case .keyword(let k, let v): await engine.setKeyword(k, v, ids: ids)325                }326                announceMove(action, account: account, origins: before, count: ids.count)327                nextDidPerform(action, account: account, ids: Set(ids))328            } catch { app.toast = Toast(message: app.describe(error) ?? "", kind: .error) }329        }330        switch action {331        case .archive, .delete, .junk, .move:332            let touched = Set(rows.map(\.id))333            next.selection.subtract(touched)334            if let open = next.openRowId, touched.contains(open) { next.openRowId = nil; reader.clearConversation(); list.selectedIds = [] }335        default: break336        }337    }338339    /// Sets or clears a keyword on messages of any mailbox (a label dropped on dragged rows).340    func applyKeyword(_ keyword: String, _ on: Bool, to messages: [(account: String, emailId: String)]) async {341        for (account, group) in Dictionary(grouping: messages, by: \.account) {342            guard let engine = app.engines[account] else { continue }343            let ids = group.map(\.emailId)344            try? await engine.ensureCached(ids: ids)345            await engine.setKeyword(keyword, on, ids: ids)346            unified.patch(account: account, ids: Set(ids)) { $0.setKeyword(keyword, on) }347            nextDidPerform(.keyword(keyword, on), account: account, ids: Set(ids))348        }349    }350351    /// Keeps the rows of the Next lists in step with an action that just ran on messages of `account`.352    func nextDidPerform(_ action: MailAction, account: String, ids: Set<String>) {353        let s = next.search354        func patch(_ change: (inout EmailSummary) -> Void) {355            for n in s.rows.indices where s.rows[n].account == account && ids.contains(s.rows[n].email.id) { change(&s.rows[n].email) }356        }357        switch action {358        case .archive, .delete, .junk, .move:359            next.insightRows?.removeAll { ids.contains($0.id) }360            guard readsRemote else { return }361            let gone = Set(s.rows.filter { $0.account == account && ids.contains($0.email.id) }.map(\.id))362            if !gone.isEmpty { s.rows.removeAll { gone.contains($0.id) }; next.selection.subtract(gone); if let open = next.openRowId, gone.contains(open) { next.openRowId = nil } }363        case .markRead(let v): patch { $0.setKeyword(Keyword.seen, v) }364        case .flag(let v): patch { $0.setKeyword(Keyword.flagged, v) }365        case .keyword(let k, let v): patch { $0.setKeyword(k, v) }366        }367    }368369    /// ⌥⌘↓ / ⌥⌘↑ in a Next list. Returns false when the selection is not one (the folder and unified lists handle it).370    func nextSelectAdjacent(_ delta: Int) -> Bool {371        switch selection { case .label, .savedSearch, .search: break; default: return false }372        let rows = next.search.rows373        guard !rows.isEmpty else { return true }374        let n = rows.firstIndex { $0.id == next.openRowId }.map { $0 + delta } ?? (delta > 0 ? 0 : rows.count - 1)375        guard rows.indices.contains(n) else { return true }376        next.selection = [rows[n].id]377        Task { await openRemote(rows[n]) }378        detailRequest += 1379        return true380    }381382    // MARK: pin and labels383384    /// The keywords of the message(s) an action menu is about: the open conversation, else the selected rows of the list.385    var selectionKeywords: [String] {386        if !reader.conversation.isEmpty { return Array(Set(reader.conversation.flatMap(\.keywords))) }387        return Array(Set(rows.filter { list.selectedIds.contains($0.id) }.flatMap(\.email.keywords)))388    }389    /// « Me le rappeler » on the message being read (or the selected row).390    func remindSelection() {391        guard let account = activeAccount, let id = replyTarget()?.id else { return }392        next.snoozeRequest = SnoozeRequest(account: account, emailIds: [id], mode: .remind)393    }394    func togglePin() async { await perform(.pin(!selectionKeywords.contains(NextKeyword.pinned))) }395396    // MARK: smart inbox filters397398    /// Inbox rows the AI triage marked important (only counted while the feature is on).399    var importantCount: Int {400        guard let account = currentAccount, app.next.aiEnabled(.triage) else { return 0 }401        return list.threads.filter { app.next.triage(account: account, emailId: $0.id)?.important == true }.count402    }403404    /// Shows the messages of a smart filter in place of the inbox rows (nil: back to the inbox).405    func applyInsight(_ filter: InsightFilter?) async {406        next.insightFilter = filter407        list.selectedIds = []; reader.clearConversation()408        guard let filter, let account = currentAccount else { next.insightRows = nil; return }409        let insights = app.next.insights[account]410        let results: [SearchResult]411        switch filter {412        case .needsReply: results = insights?.needsReply ?? []413        case .newsletters: results = insights?.newsletters ?? []414        case .unanswered: results = insights?.unansweredSent ?? []415        case .important:416            next.insightRows = list.threads.filter { app.next.triage(account: account, emailId: $0.id)?.important == true }417            return418        }419        // the engine must know these messages before they can be opened or acted on like any cached one420        try? await app.engines[account]?.ensureCached(ids: results.map(\.emailId))421        guard next.insightFilter == filter else { return }422        var rows: [ThreadSummary] = []423        for r in results {424            let e = ((try? await app.store?.email(account, id: r.emailId)) ?? nil) ?? r.summary425            rows.append(ThreadSummary(email: e, count: 1, unreadCount: e.isSeen ? 0 : 1, anyFlagged: e.isFlagged))426        }427        next.insightRows = rows428    }429430    /// Goes to the inbox of a mailbox (dashboard, command palette).431    func showInbox(of account: String) async {432        if account != currentAccount { await switchAccount(account) }433        selection = mailbox(.inbox).map { .mailbox($0.id) }434    }435}436
Files main
Menu

Theme