SPB Git

Repository Public

Reader.swift 32.7 KB 533 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Reader.swift3// Description: Conversation reader — header details, SPF/DKIM/DMARC badges and spoofing warning, remote-image opt-in, « dark reading », attachments (thumbnails,4// Quick Look, save, share, dangerous types), link destination prompt, .eml export, customisable toolbar (macOS) and thumb-reach bottom bar (iPhone).5import QuickLook6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers910struct LinkPrompt: Identifiable {11    let id = UUID()12    let url: URL13    let verdict: LinkSafety.Verdict14}1516struct DataDocument: FileDocument {17    static let readableContentTypes: [UTType] = [.data]18    var data: Data19    init(data: Data) { self.data = data }20    init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }21    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }22}2324/// Drag a message out of the app as an `.eml` file (the original RFC 5322 message, downloaded on demand).25struct EMLTransfer: Transferable {26    let email: EmailSummary27    let export: @Sendable (EmailSummary) async throws -> URL28    static var transferRepresentation: some TransferRepresentation {29        FileRepresentation(exportedContentType: .emailMessage) { item in SentTransferredFile(try await item.export(item.email)) }30    }31}3233struct ReaderView: View {34    @Bindable var scene: MailScene35    @State private var linkPrompt: LinkPrompt?36    @State private var preview: URL?37    @State private var exportDoc: DataDocument?38    @State private var exportName = ""39    @State private var dangerous: BodyPart?40    @State private var working = false41    #if os(macOS)42    @SceneStorage("spm.inspector") private var showInspector = false43    #else44    @Environment(\.horizontalSizeClass) private var sizeClass45    #endif4647    private var app: AppModel { scene.app }48    private var reader: ReaderState { scene.reader }4950    var body: some View {51        Group {52            if reader.isEmpty {53                if scene.list.selectedIds.count > 1 { BulkSelectionView(scene: scene) } else if scene.next.selection.count > 1 { RemoteBulkView(scene: scene) } else { SPEmptyState(icon: "envelope.open", title: L("Aucun message sélectionné")) }54            } else {55                ScrollView {56                    LazyVStack(alignment: .leading, spacing: SPSpacing.l) {57                        Text(reader.conversation.last?.subject.isEmpty == false ? reader.conversation.last!.subject : L("(sans objet)"))58                            .font(SPFont.title).foregroundStyle(SPColor.text).textSelection(.enabled).padding(.horizontal, SPSpacing.xxl).padding(.top, SPSpacing.xl)59                            .fixedSize(horizontal: false, vertical: true)60                            .accessibilityAddTraits(.isHeader)61                        ReaderLabelChips(scene: scene).padding(.horizontal, SPSpacing.xxl)62                        ReaderIntelligence(scene: scene).padding(.horizontal, SPSpacing.l)63                        ForEach(reader.conversation) { email in64                            MessageCard(scene: scene, email: email, expanded: email.id == (reader.focusedEmailId ?? reader.conversation.last?.id), onLink: handleLink,65                                        onPreview: { part in open(part) }, onSave: { part in save(part) })66                        }67                    }68                    .padding(.bottom, SPSpacing.x3)69                    .frame(maxWidth: 920, alignment: .leading)70                    .frame(maxWidth: .infinity)71                }72                .id(reader.conversation.first?.threadId)73                .transition(.opacity)74            }75        }76        .background(SPColor.surface.ignoresSafeArea())77        .spAnimation(SPMotion.quick, value: reader.conversation.first?.threadId)78        #if os(macOS)79        .inspector(isPresented: $showInspector) { InspectorView(scene: scene).inspectorColumnWidth(min: 220, ideal: 264, max: 360) }80        .toolbar(id: "spm.reader") { ReaderToolbar(scene: scene, showInspector: $showInspector, exportEML: exportEML) }81        #if DEBUG82        .task { if AppConfig.screenshotScene == "inspector" { showInspector = true } }83        #endif84        #else85        .toolbar { ReaderToolbar(scene: scene, compact: sizeClass == .compact, exportEML: exportEML) }86        .toolbarBackground(.visible, for: .bottomBar)87        .navigationBarTitleDisplayMode(.inline)88        #endif89        .quickLookPreview($preview)90        .fileExporter(isPresented: Binding(get: { exportDoc != nil }, set: { if !$0 { exportDoc = nil } }), document: exportDoc, contentType: .data, defaultFilename: exportName) { _ in exportDoc = nil }91        .confirmationDialog(linkTitle, isPresented: Binding(get: { linkPrompt != nil }, set: { if !$0 { linkPrompt = nil } }), titleVisibility: .visible, presenting: linkPrompt) { p in92            Button("Ouvrir dans le navigateur") { openExternally(p.url) }93            Button("Copier le lien") { copy(p.url.absoluteString) }94            Button("Annuler", role: .cancel) {}95        } message: { p in Text(linkMessage(p)) }96        .confirmationDialog("Ce type de fichier peut exécuter du code à l’ouverture.", isPresented: Binding(get: { dangerous != nil }, set: { if !$0 { dangerous = nil } }), titleVisibility: .visible, presenting: dangerous) { part in97            Button("Enregistrer quand même…", role: .destructive) { save(part, confirmed: true) }98            Button("Annuler", role: .cancel) {}99        } message: { part in Text("« \(part.displayName) » ne sera pas ouvert par SP Mail. Ne l’enregistrez que si vous faites confiance à l’expéditeur.") }100        .overlay(alignment: .top) { if working { ProgressView().controlSize(.small).padding(8).spGlass(Capsule()).padding(.top, 8) } }101        // a message window has no main view around it: it presents the Next pickers itself102        .modifier(DetachedPresenters(scene: scene))103    }104105    private var linkTitle: String {106        switch linkPrompt?.verdict {107        case .mismatch: L("Attention : ce lien ne mène pas où il le prétend")108        case .suspicious: L("Attention : adresse inhabituelle")109        default: L("Ouvrir ce lien ?")110        }111    }112    private func linkMessage(_ p: LinkPrompt) -> String {113        let shown = String(p.url.absoluteString.prefix(300))114        switch p.verdict {115        case .mismatch(let text, let actual): return L("Le texte affiche « \(text) », mais la destination réelle est « \(actual) ».") + "\n\n" + shown116        case .suspicious(let reason):117            let why = reason == "ip" ? L("La destination est une adresse IP.") : reason == "credentials" ? L("L’adresse contient un nom d’utilisateur avant le site réel.") : L("Le nom du site utilise des caractères codés (imitation possible).")118            return why + "\n\n" + shown119        case .ok: return L("Destination : ") + shown120        }121    }122123    private func handleLink(_ url: URL, _ links: [SanitizedHTML.Link]) {124        if url.scheme?.lowercased() == "mailto" { Task { await scene.compose(.mailto(url)) }; return }125        // the visible text of the link(s) with this destination decides whether a warning is shown126        let texts = links.filter { $0.href == url.absoluteString || URL(string: $0.href)?.absoluteString == url.absoluteString }.map(\.text)127        var verdict = LinkSafety.check(text: "", href: url.absoluteString)128        for t in texts { let v = LinkSafety.check(text: t, href: url.absoluteString); if v != .ok { verdict = v; break } }129        linkPrompt = LinkPrompt(url: url, verdict: verdict)130    }131    private func openExternally(_ url: URL) {132        #if os(macOS)133        NSWorkspace.shared.open(url)134        #else135        UIApplication.shared.open(url)136        #endif137    }138    private func copy(_ s: String) {139        #if os(macOS)140        NSPasteboard.general.clearContents(); NSPasteboard.general.setString(s, forType: .string)141        #else142        UIPasteboard.general.string = s143        #endif144    }145146    private func open(_ part: BodyPart) {147        if OutgoingAttachment.isDangerous(name: part.displayName, type: part.type) { dangerous = part; return }148        Task {149            working = true; defer { working = false }150            do { preview = try await scene.file(for: part) } catch { app.notice = app.describe(error) }151        }152    }153    private func save(_ part: BodyPart, confirmed: Bool = false) {154        if !confirmed, OutgoingAttachment.isDangerous(name: part.displayName, type: part.type) { dangerous = part; return }155        Task {156            working = true; defer { working = false }157            do {158                guard let engine = scene.engine else { return }159                exportName = part.displayName160                exportDoc = DataDocument(data: try await engine.fetchAttachment(part))161            } catch { app.notice = app.describe(error) }162        }163    }164    private func exportEML(_ email: EmailSummary) {165        Task {166            working = true; defer { working = false }167            do {168                guard let engine = scene.engine else { return }169                exportName = EMLExport.fileName(subject: email.subject, date: email.date)170                exportDoc = DataDocument(data: try await engine.exportEML(email))171            } catch { app.notice = app.describe(error) }172        }173    }174}175176/// Several conversations selected: the count and the bulk actions, in place of the reader.177struct BulkSelectionView: View {178    let scene: MailScene179    var body: some View {180        VStack(spacing: SPSpacing.xl) {181            Image(systemName: "square.stack.3d.up").font(.system(size: 34, weight: .light)).foregroundStyle(SPColor.text3)182            Text("\(scene.list.selectedIds.count) conversations sélectionnées").font(SPFont.headline).foregroundStyle(SPColor.text2)183            HStack(spacing: SPSpacing.m) {184                Button { Task { await scene.toggleRead() } } label: { Label("Lu / non lu", systemImage: "envelope.badge") }185                Button { Task { await scene.toggleFlag() } } label: { Label("Drapeau", systemImage: "flag") }186                Button { Task { await scene.perform(.archive) } } label: { Label("Archiver", systemImage: "archivebox") }187                Button(role: .destructive) { Task { await scene.perform(.delete) } } label: { Label("Supprimer", systemImage: "trash") }188            }189            .buttonStyle(.bordered)190        }191        .padding(SPSpacing.x3).frame(maxWidth: .infinity, maxHeight: .infinity)192    }193}194195// MARK: - toolbar196197/// The secondary actions shared by the « Plus » menus of both platforms.198struct ReaderMoreItems: View {199    let scene: MailScene200    let target: EmailSummary?201    let exportEML: (EmailSummary) -> Void202    var body: some View {203        Button { Task { await scene.toggleFlag() } } label: { Label("Drapeau", systemImage: "flag") }204        Button { Task { await scene.toggleRead() } } label: { Label("Lu / non lu", systemImage: "envelope.badge") }205        NextMenuItems(scene: scene, account: scene.activeAccount, ids: scene.list.selectedIds, keywords: scene.selectionKeywords) { action in Task { await scene.perform(action) } }206        Menu { MoveMenuItems(scene: scene, account: scene.activeAccount, ids: nil) } label: { Label("Déplacer vers", systemImage: "folder") }207        Button { Task { await scene.perform(.junk) } } label: { Label("Indésirable", systemImage: "xmark.bin") }208        if let e = target {209            if scene.app.next.has(.contacts), let sender = e.sender {210                Divider()211                Button { Task { await scene.addToContacts(sender) } } label: { Label("Ajouter l’expéditeur aux contacts", systemImage: "person.crop.circle.badge.plus") }212            }213            Divider()214            Button { exportEML(e) } label: { Label("Enregistrer le message (.eml)…", systemImage: "square.and.arrow.down") }215            ShareLink(item: EMLTransfer(email: e, export: { [scene] m in try await scene.emlFile(for: m) }), preview: SharePreview(e.subject.isEmpty ? "message.eml" : e.subject)) { Label("Partager le message…", systemImage: "square.and.arrow.up") }216        }217    }218}219220#if os(macOS)221/// The unified toolbar of the Mac reader. Every item has an identifier: « Personnaliser la barre d’outils… » lets the person add, remove222/// and reorder them, and the layout is saved by the system.223struct ReaderToolbar: CustomizableToolbarContent {224    let scene: MailScene225    @Binding var showInspector: Bool226    let exportEML: (EmailSummary) -> Void227228    var body: some CustomizableToolbarContent {229        let target = scene.replyTarget()230        let none = !scene.hasSelection231        ToolbarItem(id: "reply") {232            Button { if let e = target { Task { await scene.compose(.reply(e)) } } } label: { Label("Répondre", systemImage: "arrowshape.turn.up.left") }.help("Répondre (⌘R)").disabled(target == nil)233        }234        ToolbarItem(id: "replyAll") {235            Button { if let e = target { Task { await scene.compose(.replyAll(e)) } } } label: { Label("Répondre à tous", systemImage: "arrowshape.turn.up.left.2") }.help("Répondre à tous (⇧⌘R)").disabled(target == nil)236        }237        ToolbarItem(id: "forward") {238            Button { if let e = target { Task { await scene.compose(.forward(e)) } } } label: { Label("Transférer", systemImage: "arrowshape.turn.up.right") }.help("Transférer (⇧⌘F)").disabled(target == nil)239        }240        ToolbarItem(id: "archive") {241            Button { Task { await scene.perform(.archive) } } label: { Label("Archiver", systemImage: "archivebox") }.help("Archiver (⌃⌘A)").disabled(none)242        }243        ToolbarItem(id: "delete") {244            Button { Task { await scene.perform(.delete) } } label: { Label("Supprimer", systemImage: "trash") }.help("Supprimer (⌘⌫)").disabled(none)245        }246        ToolbarItem(id: "junk", showsByDefault: false) {247            Button { Task { await scene.perform(.junk) } } label: { Label("Indésirable", systemImage: "xmark.bin") }.help("Indésirable (⇧⌘J)").disabled(none)248        }249        ToolbarItem(id: "flag", showsByDefault: false) {250            Button { Task { await scene.toggleFlag() } } label: { Label("Drapeau", systemImage: "flag") }.help("Drapeau (⇧⌘L)").disabled(none)251        }252        ToolbarItem(id: "read", showsByDefault: false) {253            Button { Task { await scene.toggleRead() } } label: { Label("Lu / non lu", systemImage: "envelope.badge") }.help("Marquer comme lu / non lu (⇧⌘U)").disabled(none)254        }255        ToolbarItem(id: "move") {256            Menu { MoveMenuItems(scene: scene, account: scene.activeAccount, ids: nil) } label: { Label("Déplacer vers", systemImage: "folder") }.help("Déplacer vers").disabled(none)257        }258        ToolbarItem(id: "label", showsByDefault: scene.app.next.has(.labels)) {259            Menu { LabelMenuItems(scene: scene, keywords: scene.selectionKeywords) { action in Task { await scene.perform(action) } } } label: { Label("Libellés", systemImage: "tag") }.help("Libellés").disabled(none || !scene.app.next.has(.labels))260        }261        ToolbarItem(id: "snooze", showsByDefault: scene.app.next.has(.snooze)) {262            Button { Task { await scene.snooze(ids: scene.list.selectedIds) } } label: { Label("Mettre en veille", systemImage: "clock") }.help("Mettre en veille (⌃⌘Z)").disabled(none || !scene.app.next.has(.snooze))263        }264        ToolbarItem(id: "remind", showsByDefault: false) {265            Button { scene.remindSelection() } label: { Label("Me le rappeler", systemImage: "bell") }.help("Me le rappeler (⌃⌘R)").disabled(target == nil || !scene.app.next.has(.reminders))266        }267        ToolbarItem(id: "pin", showsByDefault: false) {268            Button { Task { await scene.togglePin() } } label: { Label("Épingler", systemImage: "pin") }.help("Épingler ou désépingler (⇧⌘P)").disabled(none)269        }270        ToolbarItem(id: "refresh", showsByDefault: false) {271            Button { Task { await scene.refresh() } } label: { Label("Relever le courrier", systemImage: "arrow.clockwise") }.help("Relever le courrier (⇧⌘N)")272        }273        ToolbarItem(id: "more") {274            Menu { ReaderMoreItems(scene: scene, target: target, exportEML: exportEML) } label: { Label("Plus", systemImage: "ellipsis.circle") }.disabled(none)275        }276        ToolbarItem(id: "inspector") {277            Button { showInspector.toggle() } label: { Label("Inspecteur", systemImage: "sidebar.trailing") }.help("Afficher ou masquer l’inspecteur (⌃⌘I)")278        }279    }280}281#else282/// iPhone: the actions sit in a bottom bar, within reach of the thumb. iPad: in the navigation bar, where a pointer and a keyboard expect them.283struct ReaderToolbar: ToolbarContent {284    let scene: MailScene285    let compact: Bool286    let exportEML: (EmailSummary) -> Void287288    var body: some ToolbarContent {289        let target = scene.replyTarget()290        let none = !scene.hasSelection291        if compact {292            ToolbarItemGroup(placement: .bottomBar) {293                Menu {294                    Button { if let e = target { Task { await scene.compose(.replyAll(e)) } } } label: { Label("Répondre à tous", systemImage: "arrowshape.turn.up.left.2") }295                    Button { if let e = target { Task { await scene.compose(.forward(e)) } } } label: { Label("Transférer", systemImage: "arrowshape.turn.up.right") }296                } label: { Label("Répondre", systemImage: "arrowshape.turn.up.left") } primaryAction: { if let e = target { Task { await scene.compose(.reply(e)) } } }297                    .disabled(target == nil)298                Spacer()299                Button { SPHaptics.selection(); Task { await scene.perform(.archive) } } label: { Label("Archiver", systemImage: "archivebox") }.disabled(none)300                Spacer()301                Menu { MoveMenuItems(scene: scene, account: scene.activeAccount, ids: nil) } label: { Label("Déplacer vers", systemImage: "folder") }.disabled(none)302                Spacer()303                Button(role: .destructive) { SPHaptics.selection(); Task { await scene.perform(.delete) } } label: { Label("Supprimer", systemImage: "trash") }.disabled(none)304                Spacer()305                Menu { ReaderMoreItems(scene: scene, target: target, exportEML: exportEML) } label: { Label("Plus", systemImage: "ellipsis.circle") }.disabled(none)306            }307        } else {308            ToolbarItemGroup(placement: .primaryAction) {309                Button { if let e = target { Task { await scene.compose(.reply(e)) } } } label: { Label("Répondre", systemImage: "arrowshape.turn.up.left") }.disabled(target == nil)310                Button { if let e = target { Task { await scene.compose(.replyAll(e)) } } } label: { Label("Répondre à tous", systemImage: "arrowshape.turn.up.left.2") }.disabled(target == nil)311                Button { if let e = target { Task { await scene.compose(.forward(e)) } } } label: { Label("Transférer", systemImage: "arrowshape.turn.up.right") }.disabled(target == nil)312                Button { Task { await scene.perform(.archive) } } label: { Label("Archiver", systemImage: "archivebox") }.disabled(none)313                Button { Task { await scene.perform(.delete) } } label: { Label("Supprimer", systemImage: "trash") }.disabled(none)314                Menu { ReaderMoreItems(scene: scene, target: target, exportEML: exportEML) } label: { Label("Plus", systemImage: "ellipsis.circle") }.disabled(none)315            }316        }317    }318}319#endif320321// MARK: - message card322323struct MessageCard: View {324    let scene: MailScene325    let email: EmailSummary326    let expanded: Bool327    let onLink: (URL, [SanitizedHTML.Link]) -> Void328    let onPreview: (BodyPart) -> Void329    let onSave: (BodyPart) -> Void330    @State private var showDetails = false331    @Environment(\.colorScheme) private var scheme332    @Environment(\.dynamicTypeSize) private var typeSize333    /// Message text follows Dynamic Type: the preference is the size at the default setting.334    @ScaledMetric(relativeTo: .body) private var textScale: CGFloat = 1335336    private var app: AppModel { scene.app }337    private var reader: ReaderState { scene.reader }338    private var body_: EmailBody? { reader.bodies[email.id] }339    private var fontSize: CGFloat { (CGFloat(app.settings.bodyFontSize) * textScale).rounded() }340    /// Dark themes keep message HTML on a white sheet unless « Lecture sombre » is on (preference, or toggled for this message).341    private var darkReading: Bool { scheme == .dark && (app.settings.darkReading != reader.darkReadingToggled.contains(email.id)) }342343    var body: some View {344        VStack(alignment: .leading, spacing: SPSpacing.l) {345            header346            if expanded {347                if let b = body_ { content(b) } else if let e = reader.bodyErrors[email.id] {348                    Label(e, systemImage: "wifi.slash").font(SPFont.callout).foregroundStyle(SPColor.text2).padding(.vertical, SPSpacing.m)349                } else { BodySkeleton() }350            }351        }352        .padding(expanded ? SPSpacing.xl : SPSpacing.l)353        .background(expanded ? SPColor.surface : SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))354        .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.border, lineWidth: 0.5))355        .padding(.horizontal, SPSpacing.l)356        .task(id: expanded) { if expanded { await scene.loadBody(email.id) } }357        // sanitising happens once per message and image policy, off the main actor (never in `body`)358        .task(id: "\(body_ != nil)|\(reader.imagesAllowed.contains(email.id))") { if expanded { await reader.prepare(email.id) } }359    }360361    private var header: some View {362        VStack(alignment: .leading, spacing: SPSpacing.s) {363            HStack(alignment: .top, spacing: SPSpacing.l) {364                AvatarView(name: email.sender?.displayName, address: email.sender?.email ?? "", size: expanded ? 36 : 26)365                VStack(alignment: .leading, spacing: 2) {366                    if typeSize.isAccessibilitySize {367                        Text(email.sender?.displayName ?? L("(expéditeur inconnu)")).font(SPFont.headline).foregroundStyle(SPColor.text)368                        Text(email.date.formatted(date: .abbreviated, time: .shortened)).font(SPFont.caption).foregroundStyle(SPColor.text3)369                    } else {370                        HStack(alignment: .firstTextBaseline) {371                            Text(email.sender?.displayName ?? L("(expéditeur inconnu)")).font(SPFont.headline).foregroundStyle(SPColor.text).lineLimit(1)372                            if email.isFlagged { Image(systemName: "flag.fill").foregroundStyle(SPColor.star).imageScale(.small).accessibilityLabel(Text("Avec drapeau")) }373                            Spacer()374                            Text(email.date.formatted(date: .abbreviated, time: .shortened)).font(SPFont.caption).foregroundStyle(SPColor.text3)375                        }376                    }377                    if expanded {378                        Text(email.sender?.email ?? "").font(SPFont.callout).foregroundStyle(SPColor.text2).textSelection(.enabled)379                        Button { showDetails.toggle() } label: {380                            Text(L("À : ") + email.to.map(\.displayName).joined(separator: ", ") + (showDetails ? "" : " ›")).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(showDetails ? nil : 1).multilineTextAlignment(.leading)381                        }.buttonStyle(.plain).accessibilityHint(Text("Afficher les détails de l’en-tête"))382                    } else {383                        // earlier messages of the conversation: one-line cards384                        Text(email.preview).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(1)385                    }386                }387            }388            .contentShape(Rectangle())389            .onTapGesture { if !expanded { Task { await scene.focus(email.id) } } }390            .draggable(EMLTransfer(email: email, export: { [scene] m in try await scene.emlFile(for: m) })) { DragPreview(title: email.subject, count: 1) }391            .accessibilityElement(children: .combine)392            .accessibilityAddTraits(expanded ? [] : .isButton)393            if expanded, showDetails { details }394        }395    }396397    private var details: some View {398        Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 8, verticalSpacing: 3) {399            detail(L("De"), email.from)400            detail(L("À"), email.to)401            if !email.cc.isEmpty { detail(L("Cc"), email.cc) }402            if !email.bcc.isEmpty { detail(L("Cci"), email.bcc) }403            if !email.replyTo.isEmpty { detail(L("Répondre à"), email.replyTo) }404            GridRow { Text("Date").foregroundStyle(SPColor.text3); Text(email.date.formatted(date: .complete, time: .standard)) }405            GridRow { Text("Taille").foregroundStyle(SPColor.text3); Text(email.size.byteLabel) }406            if let id = email.messageId.first { GridRow { Text("Message-ID").foregroundStyle(SPColor.text3); Text(id).textSelection(.enabled) } }407        }.font(.footnote).foregroundStyle(SPColor.text2).padding(.leading, 48)408    }409    private func detail(_ label: String, _ list: [EmailAddress]) -> some View {410        GridRow { Text(label).foregroundStyle(SPColor.text3); Text(list.map(\.formatted).joined(separator: ", ")).textSelection(.enabled) }411    }412413    @ViewBuilder private func content(_ b: EmailBody) -> some View {414        let auth = AuthenticationSummary.parse(b.authenticationResults)415        let risk = auth.risk(fromDomain: email.sender?.domain ?? "")416        AuthBadges(auth: auth, risk: risk)417        if risk == .spoofingSuspected {418            Label("L’expéditeur n’a pas pu être authentifié : ce message prétend venir de « \(email.sender?.domain ?? "?") » sans le prouver. Méfiez-vous des liens et des pièces jointes.", systemImage: "exclamationmark.shield.fill")419                .font(SPFont.callout).padding(SPSpacing.l).frame(maxWidth: .infinity, alignment: .leading)420                .background(SPColor.dangerSoft, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous)).foregroundStyle(SPColor.danger)421        }422        if b.html != nil {423            let allowed = reader.imagesAllowed.contains(email.id)424            if let clean = reader.sanitizedHTML(email.id) {425                if clean.remoteImageCount > 0, !allowed {426                    HStack {427                        Label("Les images distantes sont bloquées (\(clean.remoteImageCount)).", systemImage: "photo.badge.exclamationmark").font(SPFont.callout).foregroundStyle(SPColor.text2)428                        Spacer()429                        Button("Afficher les images") { reader.imagesAllowed.insert(email.id) }.help("Chargées par le serveur SP Mail, jamais directement depuis l’expéditeur")430                    }431                    .padding(SPSpacing.m).background(SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))432                }433                if scheme == .dark {434                    Toggle(isOn: Binding(get: { darkReading }, set: { _ in reader.darkReadingToggled.formSymmetricDifference([email.id]) })) { Label("Lecture sombre", systemImage: "moon") }435                        .toggleStyle(.button).controlSize(.small).font(SPFont.caption)436                        .help("Afficher ce message sur fond sombre plutôt que sur une feuille blanche")437                }438                MessageBodyView(html: clean.html, emailId: email.id, allowRemoteImages: allowed, fontSize: Int(fontSize), dark: darkReading, fontFamily: app.settings.readingFont.cssFamily,439                                loader: loader(allowed: allowed)) { url in onLink(url, clean.links) }440                    .id("\(email.id)-\(allowed)")441                    // in a dark theme the HTML of a message stays on a white sheet unless dark reading is on442                    .padding(scheme == .dark && !darkReading ? SPSpacing.l : 0)443                    .background { if scheme == .dark && !darkReading { RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).fill(Color.white) } }444                attachments(b.visibleAttachments(htmlReferences: clean.cids))445            } else { BodySkeleton() }446        } else {447            // plain-text messages are rendered natively: 72-character measure, reading font, Dynamic Type448            Text(b.text ?? "").font(SPFont.reading(app.settings.readingFont, size: fontSize)).lineSpacing(fontSize * 0.35).foregroundStyle(SPColor.text)449                .textSelection(.enabled).frame(maxWidth: fontSize * 38, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)450            attachments(b.visibleAttachments())451        }452        if b.isTruncated { Label("Message très long : seul le début est affiché. Enregistrez le .eml pour tout lire.", systemImage: "scissors").font(.footnote).foregroundStyle(SPColor.text3) }453    }454455    private func loader(allowed: Bool) -> MailImageSchemeHandler.Loader {456        let engine = scene.engine, api = app.api, id = email.id457        return { url in458            if url.scheme == HTMLSanitizer.cidScheme, let engine { return try? await engine.inlineImage(emailId: id, cid: url.lastPathComponent) }459            if url.scheme == HTMLSanitizer.proxyScheme, allowed, let remote = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "u" })?.value {460                return try? await api.proxiedImage(remote)461            }462            return nil463        }464    }465466    @ViewBuilder private func attachments(_ parts: [BodyPart]) -> some View {467        if !parts.isEmpty {468            VStack(alignment: .leading, spacing: SPSpacing.s) {469                Text(parts.count == 1 ? L("1 pièce jointe") : L("\(parts.count) pièces jointes")).font(SPFont.callout.weight(.semibold)).foregroundStyle(SPColor.text2)470                LazyVGrid(columns: [GridItem(.adaptive(minimum: 240, maximum: 420), spacing: SPSpacing.m)], alignment: .leading, spacing: SPSpacing.m) {471                    ForEach(parts) { part in472                        let risky = OutgoingAttachment.isDangerous(name: part.displayName, type: part.type)473                        AttachmentChip(info: AttachmentInfo(id: part.id, name: part.displayName, type: part.type, size: part.size, isRisky: risky), file: { [scene] in try? await scene.file(for: part) }) {474                            Button { onPreview(part) } label: { Image(systemName: "eye").frame(minWidth: 28, minHeight: 28) }.help("Coup d’œil").accessibilityLabel(Text("Aperçu de \(part.displayName)")).disabled(risky)475                            Button { onSave(part) } label: { Image(systemName: "square.and.arrow.down").frame(minWidth: 28, minHeight: 28) }.help("Enregistrer sous…").accessibilityLabel(Text("Enregistrer \(part.displayName)"))476                        }477                        .onTapGesture(count: 2) { onPreview(part) }478                        .contextMenu {479                            Button { onPreview(part) } label: { Label("Coup d’œil", systemImage: "eye") }.disabled(risky)480                            Button { onSave(part) } label: { Label("Enregistrer sous…", systemImage: "square.and.arrow.down") }481                        }482                    }483                }484            }485        }486    }487}488489/// Placeholder while a body downloads or is being sanitised.490struct BodySkeleton: View {491    var body: some View {492        VStack(alignment: .leading, spacing: 9) {493            ForEach([0.92, 0.84, 0.97, 0.6], id: \.self) { w in494                GeometryReader { g in RoundedRectangle(cornerRadius: 4).fill(SPColor.surface3).frame(width: g.size.width * w, height: 10) }.frame(height: 10)495            }496        }497        .padding(.vertical, SPSpacing.m)498        .accessibilityLabel(Text("Chargement"))499    }500}501502struct AuthBadges: View {503    let auth: AuthenticationSummary504    let risk: AuthenticationSummary.Risk505506    private func badge(_ name: String, _ r: AuthenticationSummary.Result) -> some View {507        let color = r.isPass ? SPColor.ok : r.isFailure ? SPColor.danger : SPColor.text3508        let soft = r.isPass ? SPColor.okSoft : r.isFailure ? SPColor.dangerSoft : SPColor.surface2509        let symbol = r.isPass ? "checkmark.seal.fill" : r.isFailure ? "xmark.seal.fill" : "questionmark.circle"510        let word = r.isPass ? L("réussi") : r.isFailure ? L("échec") : r == .missing ? L("absent") : r.rawValue511        return StatusBadge(text: "\(name) \(word)", icon: symbol, color: color, soft: soft)512            .accessibilityLabel(Text("\(name) : \(word)"))513    }514515    var body: some View {516        if risk != .unknown {517            WrapLayout(spacing: 6) { badges }518        }519    }520    @ViewBuilder private var badges: some View {521        badge("SPF", auth.spf); badge("DKIM", auth.dkim); badge("DMARC", auth.dmarc)522        if risk == .authenticated { Text("Expéditeur authentifié").font(SPFont.caption).foregroundStyle(SPColor.text3) }523    }524}525526/// Presents the Next pickers (snooze, labels) from a message window; the main window does it once around its split view.527struct DetachedPresenters: ViewModifier {528    let scene: MailScene529    func body(content: Content) -> some View {530        if scene.isDetached { content.nextPresenters(scene) } else { content }531    }532}533
Files main
Menu

Theme