SPB Git

Repository Public

OutboxView.swift 15.6 KB 236 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/OutboxView.swift3// Description: The outbox — what is still on this device (local drafts, queued messages, unsent items of a mailbox that was removed) and4// what the server tracks for the recent sends (held for undo, scheduled, accepted, delivered, deferred, bounced or failed, per recipient5// with the SMTP reply). Honest wording throughout: « accepté » and « remis » are only ever shown when the server said so.6import SPMailCore7import SwiftUI89struct OutboxView: View {10    let scene: MailScene11    @State private var exported: ExportedFile?12    @State private var deleting: OutboxItem?13    private var model: AppModel { scene.app }1415    static func stateLabel(_ item: OutboxItem) -> (text: String, icon: String, color: SPToken) {16        switch item.state {17        case .draft: (item.serverEmailId == nil ? L("Brouillon (sur cet appareil)") : L("Brouillon"), "doc", SPColor.text3)18        case .queuedOffline: (L("En attente (hors ligne)"), "clock.arrow.circlepath", SPColor.warn)19        case .sending: (L("Envoi au serveur…"), "arrow.up.circle", SPColor.info)20        case .accepted: (L("Accepté pour livraison"), "checkmark.circle", SPColor.ok)21        case .failed:22            // a temporary failure is retried by the engine: say so, and when23            if item.failureKind == .retryable {24                (item.nextAttemptAt.map { L("Échec temporaire — nouvel essai à \($0.formatted(date: .omitted, time: .shortened))") } ?? L("Échec temporaire — nouvel essai automatique"), "clock.arrow.circlepath", SPColor.warn)25            } else { (L("Refusé par le serveur"), "exclamationmark.triangle", SPColor.danger) }26        }27    }28    /// An unsent item whose mailbox is gone: it cannot leave from here any more, and it says so instead of « en attente ».29    static func orphanLabel(_ item: OutboxItem) -> (text: String, icon: String, color: SPToken) {30        (item.state == .draft ? L("Boîte retirée — brouillon conservé sur cet appareil") : L("Boîte retirée — message non envoyé, conservé sur cet appareil"), "tray.and.arrow.up", SPColor.warn)31    }32    /// What the receiving server reported for one recipient — kept apart from « accepté ».33    static func deliveryLabel(_ s: DeliveryStatus) -> (text: String, color: SPToken) {34        switch s.delivered {35        case .queued: (L("en file d’attente"), SPColor.text3)36        case .yes: (L("remis au serveur du destinataire"), SPColor.ok)37        case .no: (L("non remis"), SPColor.danger)38        case .unknown: (L("état inconnu"), SPColor.text3)39        }40    }41    /// The headline state of a server-tracked send. A held message reads « Envoi dans N s »; a scheduled one carries its date; everything42    /// else is the server's own status (« Remis » only for `delivered`).43    static func outboundLabel(_ o: OutboundStatus, now: Date = Date()) -> (text: String, icon: String, color: SPToken) {44        if OutboundTracker.isHeld(o, now: now), let until = o.undoUntil { return (L("Envoi dans \(max(0, Int(ceil(until.timeIntervalSince(now))))) s"), "paperplane", SPColor.info) }45        if o.status == "scheduled" {46            if let at = o.sendAt, at > now { return (L("Programmé pour le \(at.formatted(date: .abbreviated, time: .shortened))"), "clock", SPColor.info) }47            return (L("Envoi au serveur…"), "arrow.up.circle", SPColor.info) // the hold or the date has passed: the server is submitting it48        }49        return OutboundLabels.label(o.status)50    }51    /// One recipient of a server-tracked send; the SMTP reply is shown when the delivery did not (or not yet) succeed.52    static func recipientLabel(_ r: OutboundStatus.Recipient) -> (text: String, color: SPToken, reply: String?) {53        let l = OutboundLabels.label(r.status)54        let showsReply = ["deferred", "bounced", "failed"].contains(r.status)55        return (l.text, l.color, showsReply ? r.smtpReply.flatMap { $0.isEmpty ? nil : $0 } : nil)56    }5758    var body: some View {59        // what still needs this device first (drafts, queued or refused messages, items of a removed mailbox), then what the server60        // tracks, then the history of the sends that went through the JMAP outbox61        let waiting = model.outbox.filter { $0.state != .accepted }, sentHere = model.outbox.filter { $0.state == .accepted }, tracked = model.outbound.items62        let local = model.outbox63        List {64            if !waiting.isEmpty {65                Section { ForEach(waiting) { item in localRow(item) } } header: { if !tracked.isEmpty || !sentHere.isEmpty { Text("Sur cet appareil") } }66            }67            if !tracked.isEmpty || model.outbound.notice != nil {68                Section {69                    if let n = model.outbound.notice { Label(n, systemImage: "wifi.slash").font(.footnote).foregroundStyle(SPColor.warn).listRowBackground(Color.clear) }70                    ForEach(tracked) { o in OutboundRow(item: o, title: model.outbound.title(for: o), app: model) }71                } header: { Text("Suivi par le serveur") } footer: {72                    if !tracked.isEmpty { Text("« Accepté » : le serveur de courrier a pris le message. « Remis » : le serveur du destinataire l’a accepté — ce n’est pas une confirmation de lecture.") }73                }74            }75            if !sentHere.isEmpty {76                Section { ForEach(sentHere) { item in localRow(item) } } header: { if !tracked.isEmpty || !waiting.isEmpty { Text("Envoyés par la file de cet appareil") } }77            }78        }79        .listStyle(.plain)80        .scrollContentBackground(.hidden)81        .background(SPColor.bg)82        .overlay {83            if local.isEmpty, tracked.isEmpty, model.outbound.notice == nil { SPEmptyState(icon: "arrow.up.circle", title: L("Rien en attente"), message: L("Les brouillons locaux, les messages en attente et l’état des envois récents apparaissent ici.")) }84        }85        .navigationTitle("Boîte d’envoi")86        .refreshable { await scene.refresh(); await model.outbound.reload(force: true) }87        .task { await model.outbound.reload(force: true) }88        .onAppear { model.compose.outboxScreens += 1 }89        .onDisappear { model.compose.outboxScreens = max(0, model.compose.outboxScreens - 1) }90        .toolbar {91            ToolbarItem(placement: .primaryAction) { Button { Task { await scene.compose(.new) } } label: { Label("Nouveau message", systemImage: "square.and.pencil") } }92            ToolbarItem { Button { Task { await scene.refresh(); await model.outbound.reload(force: true) } } label: { Label("Actualiser", systemImage: "arrow.clockwise") }.help("Réessayer les envois en attente et actualiser l’état des envois") }93        }94        .fileExporter(isPresented: Binding(get: { exported != nil }, set: { if !$0 { exported = nil } }), document: exported.map { FileURLDocument(url: $0.url) }, contentType: .data, defaultFilename: exported?.url.lastPathComponent) { _ in exported = nil }95        .confirmationDialog("Supprimer ce message non envoyé ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible, presenting: deleting) { item in96            Button("Supprimer", role: .destructive) { Task { await model.deleteOrphan(item) } }97            Button("Annuler", role: .cancel) {}98        } message: { _ in Text("Sa boîte a été retirée de ce compte : il n’en existe aucune autre copie. Exportez-le d’abord si vous voulez le garder.") }99    }100101    // MARK: local items102103    private func localRow(_ item: OutboxItem) -> some View {104        let orphan = model.isOrphan(item)105        let s = orphan ? Self.orphanLabel(item) : Self.stateLabel(item)106        return VStack(alignment: .leading, spacing: 4) {107            HStack {108                Text(item.message.subject.isEmpty ? L("(sans objet)") : item.message.subject).font(.headline).lineLimit(1)109                Spacer()110                Text(item.updatedAt.listLabel).font(.subheadline).foregroundStyle(SPColor.text3)111            }112            Text(item.message.recipients.map(\.displayName).joined(separator: ", ")).font(.subheadline).foregroundStyle(SPColor.text3).lineLimit(1)113            Label(s.text, systemImage: s.icon).font(.subheadline).foregroundStyle(s.color)114            if orphan {115                Text("De \(item.message.from.email) — cette boîte n’est plus dans votre compte. Le message ne peut plus partir d’ici.").font(.footnote).foregroundStyle(SPColor.text3).fixedSize(horizontal: false, vertical: true)116                HStack(spacing: SPSpacing.l) {117                    Button { export(item) } label: { Label("Exporter en .eml…", systemImage: "square.and.arrow.up") }118                    Button(role: .destructive) { deleting = item } label: { Label("Supprimer", systemImage: "trash") }119                }120                .buttonStyle(.borderless).font(.subheadline)121            } else {122                if item.state == .failed, let e = item.lastError, !e.isEmpty { Text(e).font(.footnote).foregroundStyle(SPColor.danger) }123                if item.state == .accepted {124                    ForEach(item.delivery.keys.sorted(), id: \.self) { rcpt in125                        if let d = item.delivery[rcpt] {126                            let l = Self.deliveryLabel(d)127                            // the address on its own line (a narrow column would break it in the middle), its state under it128                            VStack(alignment: .leading, spacing: 1) {129                                Text(rcpt).font(.footnote).lineLimit(1).truncationMode(.middle)130                                Text(l.text).font(.footnote).foregroundStyle(l.color)131                                if d.delivered == .no { Text(d.smtpReply).font(.footnote).foregroundStyle(SPColor.text3).lineLimit(2) }132                            }133                        }134                    }135                    if item.delivery.isEmpty { Text("État de livraison pas encore connu").font(.footnote).foregroundStyle(SPColor.text3) }136                }137            }138        }139        .padding(.vertical, 5)140        .contentShape(Rectangle())141        .listRowBackground(Color.clear)142        .listRowSeparatorTint(nil)143        .contextMenu { menu(item, orphan: orphan) }144        .swipeActions { Button(role: .destructive) { if orphan { deleting = item } else { remove(item) } } label: { Label(orphan ? L("Supprimer") : L("Retirer"), systemImage: "trash") } }145        .onTapGesture(count: 2) { if !orphan, item.state == .draft || item.state == .failed { Task { await scene.compose(.outboxItem(item)) } } }146        .accessibilityElement(children: orphan ? .contain : .combine)147    }148149    @ViewBuilder private func menu(_ item: OutboxItem, orphan: Bool) -> some View {150        if orphan {151            Button("Exporter en .eml…") { export(item) }152            Button("Supprimer", role: .destructive) { deleting = item }153        } else {154            if item.state == .draft || item.state == .failed { Button("Modifier") { Task { await scene.compose(.outboxItem(item)) } } }155            if item.state == .queuedOffline || item.state == .failed { Button("Réessayer maintenant") { Task { await model.retry(item) } } }156            if item.state == .accepted, item.hasDeliveryFailure { Button("Renvoyer") { Task { await model.retry(item) } } }157            Button(item.state == .accepted ? L("Retirer de la liste") : L("Supprimer"), role: .destructive) { remove(item) }158        }159    }160    private func remove(_ item: OutboxItem) {161        Task {162            if item.state == .accepted { try? await model.store?.deleteOutbox(item.id) } else { await model.engines[item.account]?.discardDraft(id: item.id) }163            await model.reloadOutbox()164        }165    }166    private func export(_ item: OutboxItem) {167        Task {168            do { exported = ExportedFile(url: try await model.exportEML(of: item)) } catch { model.toast = Toast(message: L("L’export a échoué : ") + error.localizedDescription, kind: .error) }169        }170    }171}172173/// A file ready for the save panel.174struct ExportedFile: Identifiable {175    let id = UUID()176    let url: URL177}178179/// One server-tracked send: its state, then each recipient with what the server reported for it.180struct OutboundRow: View {181    let item: OutboundStatus182    let title: String?183    let app: AppModel184    @State private var undoing = false185186    var body: some View {187        let recipients = item.recipients.map(\.address).joined(separator: ", ")188        VStack(alignment: .leading, spacing: 4) {189            HStack {190                Text(title.map { $0.isEmpty ? L("(sans objet)") : $0 } ?? recipients).font(.headline).lineLimit(1)191                Spacer()192                if let d = item.updatedAt ?? item.createdAt { Text(d.listLabel).font(.subheadline).foregroundStyle(SPColor.text3) }193            }194            if title != nil { Text(recipients).font(.subheadline).foregroundStyle(SPColor.text3).lineLimit(1) }195            if OutboundTracker.isHeld(item) {196                // the countdown follows the clock; when it ends the row shows what the server did, never an assumption197                TimelineView(.periodic(from: .now, by: 1)) { context in198                    let l = OutboxView.outboundLabel(item, now: context.date)199                    HStack(spacing: SPSpacing.l) {200                        Label(l.text, systemImage: l.icon).font(.subheadline).foregroundStyle(l.color).monospacedDigit()201                        if OutboundTracker.isHeld(item, now: context.date) {202                            Button(L("Annuler l’envoi")) { undoing = true; Task { await app.compose.undo(item.id); undoing = false } }203                                .buttonStyle(.borderless).font(.subheadline.weight(.semibold)).disabled(undoing)204                        }205                    }206                }207            } else {208                let l = OutboxView.outboundLabel(item)209                Label(l.text, systemImage: l.icon).font(.subheadline).foregroundStyle(l.color)210            }211            if ["failed", "queued", "deferred"].contains(item.status), let e = item.lastError, !e.isEmpty { Text(e).font(.footnote).foregroundStyle(item.status == "failed" ? SPColor.danger : SPColor.text3).lineLimit(3) }212            // per recipient once the message left the hold: one line each, the SMTP reply when the delivery did not succeed213            if ["sent", "delivered", "deferred", "bounced", "failed"].contains(item.status) {214                // (a single recipient whose state is the headline's, with nothing more to say, is not repeated)215                ForEach(item.recipients.filter { r in item.recipients.count > 1 || r.status != item.status || OutboxView.recipientLabel(r).reply != nil }, id: \.address) { r in216                    let l = OutboxView.recipientLabel(r)217                    VStack(alignment: .leading, spacing: 1) {218                        Text(r.address).font(.footnote).lineLimit(1).truncationMode(.middle)219                        Text(l.text).font(.footnote).foregroundStyle(l.color)220                        if let reply = l.reply { Text(reply).font(.footnote).foregroundStyle(SPColor.text3).lineLimit(3).textSelection(.enabled) }221                    }222                }223            }224        }225        .padding(.vertical, 5)226        .listRowBackground(Color.clear)227        .listRowSeparatorTint(nil)228        .contextMenu {229            if OutboundTracker.isHeld(item) { Button("Annuler l’envoi") { Task { await app.compose.undo(item.id) } } }230            if item.isFinal || item.status == "sent" { Button("Retirer de la liste", role: .destructive) { app.outbound.hide(item.id) } }231        }232        .swipeActions { if item.isFinal || item.status == "sent" { Button(role: .destructive) { app.outbound.hide(item.id) } label: { Label("Retirer", systemImage: "trash") } } }233        .accessibilityElement(children: .contain)234    }235}236
Files main
Menu

Theme