SPB Git

Repository Public

OrganizeViews.swift 31.7 KB 634 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/OrganizeViews.swift3// Description: Organising mail — the pin / labels / snooze / remind entries shared by every action menu, the label editor and picker,4// the snooze and reminder picker (popover on macOS and iPad, sheet with detents on iPhone), the « En veille » and « Suivis » lists,5// and the presenters a window attaches once.6import SPMailCore7import SwiftUI89// MARK: - row decoration1011extension ConversationRowData {12    /// Resolves what needs the Next services: label dots from the label keywords, the optional AI triage badge.13    @MainActor func decorated(by next: NextServices, account: String?, emailId: String? = nil) -> ConversationRowData {14        var d = self15        if !labelKeywords.isEmpty { d.labels = next.labels(for: labelKeywords).map { LabelPalette.index(forHex: $0.color) } }16        if let account, let emailId, let t = next.triage(account: account, emailId: emailId), t.category != .unknown, t.category != .other { d.badge = t.category.title }17        return d18    }19}2021extension TriageCategory {22    var title: String {23        switch self {24        case .personal: L("Personnel"); case .work: L("Travail"); case .newsletter: L("Infolettre"); case .notification: L("Notification")25        case .transaction: L("Transaction"); case .social: L("Social"); case .other, .unknown: L("Autre")26        }27    }28}2930extension SnoozePreset {31    var title: String {32        switch self {33        case .laterToday: L("Plus tard aujourd’hui"); case .tonight: L("Ce soir"); case .tomorrowMorning: L("Demain matin")34        case .thisWeekend: L("Ce week-end"); case .nextWeek: L("La semaine prochaine"); case .inAWeek: L("Dans une semaine")35        }36    }37    var icon: String {38        switch self {39        case .laterToday: "clock"; case .tonight: "moon"; case .tomorrowMorning: "sunrise"; case .thisWeekend: "sofa"; case .nextWeek: "briefcase"; case .inAWeek: "calendar"40        }41    }42}4344extension Date {45    /// « 15:30 » today, « ven. 08:00 » this week, « 28 nov. 08:00 » later.46    var snoozeLabel: String {47        let cal = Calendar.current48        if cal.isDateInToday(self) { return formatted(date: .omitted, time: .shortened) }49        if let days = cal.dateComponents([.day], from: cal.startOfDay(for: Date()), to: self).day, days < 7 { return formatted(.dateTime.weekday(.abbreviated).hour().minute()) }50        return formatted(.dateTime.day().month(.abbreviated).hour().minute())51    }52}5354// MARK: - menu entries5556/// Pin, labels, snooze and remind: the same entries in the context menu of a row, the « Plus » menus of the reader and the menu bar.57/// `apply` runs a keyword action on the right messages (the caller knows whether they are folder rows or rows of another mailbox).58struct NextMenuItems: View {59    let scene: MailScene60    let account: String?61    /// Head message ids, for snooze and reminders.62    let ids: Set<String>63    let keywords: [String]64    let apply: @MainActor (MailAction) -> Void6566    var body: some View {67        let next = scene.app.next68        let pinned = keywords.contains(NextKeyword.pinned)69        Button { apply(.pin(!pinned)) } label: { Label(pinned ? L("Désépingler") : L("Épingler"), systemImage: pinned ? "pin.slash" : "pin") }70        if next.has(.labels) {71            Menu { LabelMenuItems(scene: scene, keywords: keywords, apply: apply) } label: { Label("Libellés", systemImage: "tag") }72        }73        if next.has(.snooze), let account, !ids.isEmpty {74            Menu {75                ForEach(SnoozePresets().available(), id: \.preset) { item in76                    Button { Task { await scene.snoozeNow(ids: ids, account: account, until: item.date) } } label: { Label("\(item.preset.title) — \(item.date.snoozeLabel)", systemImage: item.preset.icon) }77                }78                Divider()79                Button { Task { await scene.snooze(ids: ids, account: account) } } label: { Label("Choisir une date…", systemImage: "calendar.badge.clock") }80            } label: { Label("Mettre en veille", systemImage: "clock") }81            .disabled(!next.isOnline)82        }83        if next.has(.reminders), let account, ids.count == 1 {84            Button { scene.next.snoozeRequest = SnoozeRequest(account: account, emailIds: Array(ids), mode: .remind) } label: { Label("Me le rappeler…", systemImage: "bell") }85                .disabled(!next.isOnline)86        }87    }88}8990struct LabelMenuItems: View {91    let scene: MailScene92    let keywords: [String]93    let apply: @MainActor (MailAction) -> Void94    var body: some View {95        let next = scene.app.next96        ForEach(next.labels) { label in97            let on = keywords.contains(label.keyword)98            Button { apply(.keyword(label.keyword, !on)) } label: { if on { Label(label.name, systemImage: "checkmark") } else { Text(label.name) } }99                .disabled(label.keyword.isEmpty) // created offline: no keyword until the server has it100        }101        if !next.labels.isEmpty { Divider() }102        Button { scene.next.labelEdit = LabelEditRequest(label: nil, apply: { created in if !created.keyword.isEmpty { apply(.keyword(created.keyword, true)) } }) } label: { Label("Nouveau libellé…", systemImage: "plus") }103    }104}105106extension MailScene {107    /// Snoozes at once with a preset (context menus); a conversation of the folder list is snoozed whole.108    func snoozeNow(ids: Set<String>, account: String, until: Date) async {109        let all = account == currentAccount && !readsRemote && !isUnified ? await targets(ids) : Array(ids)110        if await app.next.snooze(account: account, emailIds: all, until: until) { didSnooze(account: account, ids: Set(all).union(ids)) }111    }112    /// The snoozed messages left their folder: the lists of this window follow without waiting for the sync event.113    func didSnooze(account: String, ids: Set<String>) {114        list.selectedIds.subtract(ids)115        if reader.conversation.contains(where: { ids.contains($0.id) }), activeAccount == account { reader.clearConversation(); list.selectedIds = [] }116        unified.rows.removeAll { $0.account == account && ids.contains($0.email.id) }117        let gone = Set(next.search.rows.filter { $0.account == account && ids.contains($0.email.id) }.map(\.id))118        next.search.rows.removeAll { gone.contains($0.id) }119        next.selection.subtract(gone)120        Task { await reloadThreads() }121    }122}123124// MARK: - labels: chip row, editor, picker125126/// The label chips under the subject of the reader; each can be removed, a « + » adds one.127struct ReaderLabelChips: View {128    let scene: MailScene129    var body: some View {130        let next = scene.app.next131        let keywords = Array(Set(scene.reader.conversation.flatMap(\.keywords)))132        let labels = next.labels(for: keywords)133        if next.has(.labels), !labels.isEmpty {134            WrapLayout(spacing: 6) {135                ForEach(labels) { label in136                    Menu {137                        Button { scene.selection = .label(label.id) } label: { Label("Afficher ce libellé", systemImage: "tag") }138                        Button(role: .destructive) { Task { await scene.perform(.keyword(label.keyword, false), on: Set(scene.reader.conversation.map(\.id))) } } label: { Label("Retirer", systemImage: "xmark") }139                    } label: { LabelChip(name: label.name, paletteIndex: LabelPalette.index(forHex: label.color)) }140                    .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()141                    .accessibilityLabel(Text("Libellé \(label.name)"))142                }143            }144        }145    }146}147148struct LabelEditorSheet: View {149    let app: AppModel150    let request: LabelEditRequest151    @State private var name = ""152    @State private var color = LabelPalette.fallback153    @State private var confirmDelete = false154    @State private var saving = false155    @Environment(\.dismiss) private var dismiss156    @FocusState private var focused: Bool157158    private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) }159    private var nameTaken: Bool { app.next.labels.contains { $0.id != request.label?.id && $0.name.caseInsensitiveCompare(trimmed) == .orderedSame } }160161    var body: some View {162        NavigationStack {163            Form {164                Section {165                    TextField("Nom du libellé", text: $name).focused($focused)166                        .onChange(of: name) { _, v in if v.count > MailLabel.maxNameLength { name = String(v.prefix(MailLabel.maxNameLength)) } }167                        .onSubmit { if canSave { save() } }168                    if nameTaken { Text("Ce nom est déjà utilisé.").font(.footnote).foregroundStyle(SPColor.danger) }169                }170                Section("Couleur") {171                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: SPSpacing.m), count: 5), spacing: SPSpacing.l) {172                        ForEach(0..<LabelPalette.count, id: \.self) { n in swatch(n) }173                    }174                    .padding(.vertical, SPSpacing.xs)175                    LabeledContent("Aperçu") { LabelChip(name: trimmed.isEmpty ? L("Libellé") : trimmed, paletteIndex: LabelPalette.index(forHex: color)) }176                }177                if request.label != nil {178                    Section {179                        Button("Supprimer le libellé…", role: .destructive) { confirmDelete = true }180                    } footer: { Text("Supprimer un libellé ne touche pas aux messages.") }181                }182            }183            .formStyle(.grouped)184            .navigationTitle(request.label == nil ? L("Nouveau libellé") : L("Modifier le libellé"))185            #if os(iOS)186            .navigationBarTitleDisplayMode(.inline)187            #endif188            .toolbar {189                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }190                ToolbarItem(placement: .confirmationAction) { Button(request.label == nil ? L("Créer") : L("Enregistrer")) { save() }.disabled(!canSave) }191            }192            .confirmationDialog("Supprimer ce libellé ?", isPresented: $confirmDelete, titleVisibility: .visible) {193                Button("Supprimer", role: .destructive) { if let l = request.label { Task { await app.next.deleteLabel(l); dismiss() } } }194                Button("Annuler", role: .cancel) {}195            } message: { Text("Les messages qui le portent ne sont ni déplacés ni supprimés.") }196        }197        #if os(macOS)198        .frame(width: 380, height: request.label == nil ? 330 : 400)199        #else200        .presentationDetents([.medium, .large])201        #endif202        .spTheme(app.settings)203        .onAppear {204            name = request.label?.name ?? ""205            color = request.label?.color ?? LabelPalette.suggestion(existing: app.next.labels.map(\.color))206            focused = true207        }208    }209210    private func swatch(_ n: Int) -> some View {211        let selected = LabelPalette.index(forHex: color) == n212        return Button { color = LabelPalette.hex(n) } label: {213            ZStack {214                Circle().fill(LabelPalette.token(n)).frame(width: 28, height: 28)215                if selected {216                    Image(systemName: "checkmark").font(.caption.weight(.bold)).foregroundStyle(SPColor.surface)217                    Circle().stroke(SPColor.text, lineWidth: 2).frame(width: 34, height: 34)218                }219            }220            .frame(minWidth: 44, minHeight: 38)221            .contentShape(Rectangle())222        }223        .buttonStyle(.plain)224        .accessibilityLabel(Text("Couleur \(n + 1)"))225        .accessibilityAddTraits(selected ? .isSelected : [])226    }227228    private var canSave: Bool { !trimmed.isEmpty && !nameTaken && !saving }229    private func save() {230        saving = true231        Task {232            if let existing = request.label {233                await app.next.updateLabel(existing, name: trimmed == existing.name ? nil : trimmed, color: color.lowercased() == existing.color.lowercased() ? nil : color)234            } else if let created = await app.next.createLabel(name: trimmed, color: color) {235                request.apply?(created)236            }237            saving = false238            dismiss()239        }240    }241}242243/// Labels as a checklist (iPhone « Plus », toolbars): touch-sized rows instead of a nested menu.244struct LabelPickerSheet: View {245    let scene: MailScene246    let request: LabelPickRequest247    @State private var keywords: Set<String> = []248    @Environment(\.dismiss) private var dismiss249250    var body: some View {251        let next = scene.app.next252        NavigationStack {253            List {254                ForEach(next.labels) { label in255                    let on = keywords.contains(label.keyword)256                    Button {257                        if on { keywords.remove(label.keyword) } else { keywords.insert(label.keyword) }258                        request.apply(.keyword(label.keyword, !on))259                        SPHaptics.selection()260                    } label: {261                        HStack(spacing: SPSpacing.l) {262                            Circle().fill(LabelPalette.token(LabelPalette.index(forHex: label.color))).frame(width: 12, height: 12)263                            Text(label.name).foregroundStyle(SPColor.text)264                            Spacer()265                            if on { Image(systemName: "checkmark").foregroundStyle(SPColor.accent) }266                        }267                        .frame(minHeight: 30).contentShape(Rectangle())268                    }269                    .buttonStyle(.plain).disabled(label.keyword.isEmpty)270                    .accessibilityAddTraits(on ? .isSelected : [])271                }272                Button { dismiss(); scene.next.labelEdit = LabelEditRequest(label: nil, apply: { created in if !created.keyword.isEmpty { request.apply(.keyword(created.keyword, true)) } }) } label: { Label("Nouveau libellé…", systemImage: "plus") }273            }274            .navigationTitle("Libellés")275            #if os(iOS)276            .navigationBarTitleDisplayMode(.inline)277            #endif278            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }279        }280        #if os(macOS)281        .frame(width: 320, height: 380)282        #else283        .presentationDetents([.medium, .large])284        #endif285        .spTheme(scene.app.settings)286        .onAppear { keywords = Set(request.keywords) }287    }288}289290// MARK: - snooze and reminder picker291292struct SnoozePicker: View {293    let scene: MailScene294    let request: SnoozeRequest295    @State private var custom = Date().addingTimeInterval(86_400)296    @State private var onlyIfNoReply = true297    @State private var note = ""298    @State private var working = false299    @Environment(\.dismiss) private var dismiss300301    private var app: AppModel { scene.app }302    private var isReminder: Bool { switch request.mode { case .remind, .rescheduleReminder: true; default: false } }303    private var title: String {304        switch request.mode {305        case .snooze: request.emailIds.count > 1 ? L("Mettre \(request.emailIds.count) messages en veille") : L("Mettre en veille")306        case .remind: L("Me le rappeler")307        case .rescheduleSnooze: L("Reporter le réveil")308        case .rescheduleReminder: L("Reporter le rappel")309        }310    }311    private var presets: SnoozePresets { SnoozePresets() }312313    var body: some View {314        VStack(alignment: .leading, spacing: SPSpacing.l) {315            HStack {316                Label(title, systemImage: isReminder ? "bell" : "clock").font(SPFont.headline).foregroundStyle(SPColor.text)317                Spacer()318                if working { ProgressView().controlSize(.small) }319            }320            if !app.isOnline {321                Label(isReminder ? L("Les rappels sont gérés par le serveur : reconnectez-vous pour en créer un.") : L("La mise en veille est gérée par le serveur : reconnectez-vous pour l’utiliser."), systemImage: "wifi.slash")322                    .font(SPFont.callout).foregroundStyle(SPColor.warn).fixedSize(horizontal: false, vertical: true)323            }324            VStack(spacing: 2) {325                ForEach(presets.available(), id: \.preset) { item in326                    Button { choose(item.date) } label: {327                        HStack(spacing: SPSpacing.l) {328                            Image(systemName: item.preset.icon).frame(width: 22).foregroundStyle(SPColor.accent)329                            Text(item.preset.title).foregroundStyle(SPColor.text)330                            Spacer(minLength: SPSpacing.l)331                            Text(item.date.snoozeLabel).font(SPFont.caption).foregroundStyle(SPColor.text3)332                        }333                        .padding(.horizontal, SPSpacing.m).padding(.vertical, SPSpacing.m)334                        #if os(iOS)335                        .frame(minHeight: 44)336                        #endif337                        .contentShape(Rectangle())338                    }339                    .buttonStyle(.plain)340                    #if os(iOS)341                    .hoverEffect(.highlight)342                    #endif343                    .accessibilityLabel(Text("\(item.preset.title), \(item.date.formatted(date: .complete, time: .shortened))"))344                }345            }346            Divider().overlay(SPColor.border)347            HStack(spacing: SPSpacing.m) {348                DatePicker("Autre date", selection: $custom, in: Date().addingTimeInterval(60)..., displayedComponents: [.date, .hourAndMinute]).labelsHidden()349                    .accessibilityLabel(Text("Autre date"))350                Spacer(minLength: 0)351                Button("Choisir") { choose(custom) }.buttonStyle(.borderedProminent).disabled(!presets.isValidCustom(custom))352            }353            if case .remind = request.mode {354                Divider().overlay(SPColor.border)355                Toggle("Seulement si personne n’a répondu", isOn: $onlyIfNoReply)356                TextField("Note (facultatif)", text: $note, axis: .vertical).lineLimit(1...3).textFieldStyle(.roundedBorder)357                    .onChange(of: note) { _, v in if v.count > 500 { note = String(v.prefix(500)) } }358            }359        }360        .padding(SPSpacing.xl)361        .disabled(!app.isOnline || working)362        #if os(macOS)363        .frame(width: 340)364        #else365        .frame(minWidth: 320, idealWidth: 360, maxWidth: .infinity, alignment: .top)366        .frame(maxHeight: .infinity, alignment: .top)367        .presentationDetents([.medium, .large])368        .presentationDragIndicator(.visible)369        #endif370        .spTheme(app.settings)371        .onAppear { if let n = scene.next.reminderNote { note = n; scene.next.reminderNote = nil } }372    }373374    private func choose(_ date: Date) {375        working = true376        Task {377            let next = app.next378            switch request.mode {379            case .snooze:380                if await next.snooze(account: request.account, emailIds: request.emailIds, until: date) { scene.didSnooze(account: request.account, ids: Set(request.emailIds)) }381            case .remind:382                if let id = request.emailIds.first { _ = await next.remind(account: request.account, emailId: id, dueAt: date, onlyIfNoReply: onlyIfNoReply, note: note.trimmingCharacters(in: .whitespacesAndNewlines)) }383            case .rescheduleSnooze(let s): await next.reschedule(s, until: date)384            case .rescheduleReminder(let r): await next.rescheduleReminder(r, dueAt: date)385            }386            working = false387            SPHaptics.success()388            dismiss()389        }390    }391}392393// MARK: - « En veille » and « Suivis »394395/// A row of a server-side list (snooze, reminder): subject, correspondent, and when.396private struct DueRow: View {397    let subject: String398    let who: EmailAddress?399    let when: Date?400    let whenIcon: String401    var overdue = false402    var note: String?403    var mailbox: String?404    var isOpen = false405406    var body: some View {407        HStack(alignment: .top, spacing: SPSpacing.m) {408            AvatarView(name: who?.name, address: who?.email ?? "", size: 32)409            VStack(alignment: .leading, spacing: 2) {410                Text(who?.displayName ?? L("(expéditeur inconnu)")).font(SPFont.headline).foregroundStyle(SPColor.text).lineLimit(1)411                Text(subject.isEmpty ? L("(sans objet)") : subject).font(SPFont.callout).foregroundStyle(SPColor.text2).lineLimit(1)412                if let note, !note.isEmpty { Text(note).font(SPFont.callout).foregroundStyle(SPColor.text3).lineLimit(2) }413                HStack(spacing: SPSpacing.s) {414                    if let when { Label(when.snoozeLabel, systemImage: whenIcon).font(SPFont.caption).foregroundStyle(overdue ? SPColor.warn : SPColor.text3).lineLimit(1).fixedSize().accessibilityLabel(Text(when.formatted(date: .complete, time: .shortened))) }415                    if let mailbox { AddressChip(address: mailbox) }416                }417                .padding(.top, 1)418            }419            Spacer(minLength: 0)420        }421        .padding(.vertical, SPSpacing.m)422        .contentShape(Rectangle())423        .accessibilityElement(children: .combine)424        .accessibilityAddTraits(isOpen ? .isSelected : [])425    }426}427428struct SnoozedView: View {429    @Bindable var scene: MailScene430    var onOpen: () -> Void431    private var app: AppModel { scene.app }432433    var body: some View {434        let snoozes = app.next.snoozes435        List {436            if !app.isOnline { OfflineNote(text: L("Hors ligne — la mise en veille est gérée par le serveur ; cette liste peut être incomplète.")) }437            ForEach(snoozes) { s in438                Button { open(s) } label: {439                    DueRow(subject: s.subject, who: s.from, when: s.until, whenIcon: "clock", mailbox: app.accounts.count > 1 ? app.box(s.mailboxId)?.address : nil, isOpen: scene.next.openRowId == s.id)440                }441                .buttonStyle(.plain)442                .listRowBackground(RowSelectionBackground(isSelected: scene.next.openRowId == s.id))443                .listRowSeparator(.hidden)444                .listRowInsets(EdgeInsets(top: 0, leading: SPSpacing.xl, bottom: 0, trailing: SPSpacing.xl))445                .contextMenu { actions(s) }446                .swipeActions(edge: .trailing) {447                    Button { Task { await app.next.wake(s) } } label: { Label("Réveiller", systemImage: "sun.max") }.tint(SPColor.accent)448                    Button { scene.next.snoozeRequest = SnoozeRequest(account: s.mailboxId, emailIds: [s.emailId], mode: .rescheduleSnooze(s)) } label: { Label("Reporter", systemImage: "calendar.badge.clock") }.tint(SPColor.warn)449                }450                .accessibilityAction(named: Text("Réveiller maintenant")) { Task { await app.next.wake(s) } }451            }452        }453        .listStyle(.plain).scrollContentBackground(.hidden).background(SPColor.bg)454        .overlay { if snoozes.isEmpty { SPEmptyState(icon: "clock", title: L("Rien en veille"), message: L("Les messages mis en veille quittent la boîte de réception et y reviennent, non lus, à l’heure choisie.")) } }455        .navigationTitle("En veille")456        .refreshable { await app.next.reloadSnoozes() }457        .task { await app.next.reloadSnoozes() }458    }459460    @ViewBuilder private func actions(_ s: Snooze) -> some View {461        Button { Task { await app.next.wake(s) } } label: { Label("Réveiller maintenant", systemImage: "sun.max") }.disabled(!app.isOnline)462        Button { scene.next.snoozeRequest = SnoozeRequest(account: s.mailboxId, emailIds: [s.emailId], mode: .rescheduleSnooze(s)) } label: { Label("Reporter…", systemImage: "calendar.badge.clock") }.disabled(!app.isOnline)463    }464    private func open(_ s: Snooze) {465        Task { await scene.openRemote(account: s.mailboxId, emailId: s.emailId, rowId: s.id) }466        onOpen()467    }468}469470struct FollowUpsView: View {471    @Bindable var scene: MailScene472    var onOpen: () -> Void473    private var app: AppModel { scene.app }474475    var body: some View {476        let all = app.next.reminders477        let due = all.filter { $0.status == .due }, pending = all.filter { $0.status == .pending }478        List {479            if !app.isOnline { OfflineNote(text: L("Hors ligne — les rappels sont gérés par le serveur ; cette liste peut être incomplète.")) }480            if !due.isEmpty { Section { ForEach(due) { row($0) } } header: { SectionTitle(text: L("À traiter"), count: due.count) } }481            if !pending.isEmpty { Section { ForEach(pending) { row($0) } } header: { SectionTitle(text: L("À venir"), count: pending.count) } }482        }483        .listStyle(.plain).scrollContentBackground(.hidden).background(SPColor.bg)484        .overlay { if all.isEmpty { SPEmptyState(icon: "bell", title: L("Aucun suivi"), message: L("« Me le rappeler » sur un message le fait revenir ici à la date choisie — seulement si personne n’a répondu, si vous le voulez.")) } }485        .navigationTitle("Suivis")486        .refreshable { await app.next.reloadReminders() }487        .task { await app.next.reloadReminders() }488    }489490    @ViewBuilder private func row(_ r: Reminder) -> some View {491        Button { Task { await scene.openRemote(account: r.mailboxId, emailId: r.emailId, rowId: r.id) }; onOpen() } label: {492            DueRow(subject: r.subject, who: r.counterpart, when: r.dueAt, whenIcon: r.onlyIfNoReply ? "bell.badge" : "bell", overdue: r.status == .due, note: r.note,493                   mailbox: app.accounts.count > 1 ? app.box(r.mailboxId)?.address : nil, isOpen: scene.next.openRowId == r.id)494        }495        .buttonStyle(.plain)496        .listRowBackground(RowSelectionBackground(isSelected: scene.next.openRowId == r.id))497        .listRowSeparator(.hidden)498        .listRowInsets(EdgeInsets(top: 0, leading: SPSpacing.xl, bottom: 0, trailing: SPSpacing.xl))499        .contextMenu {500            Button { Task { await app.next.completeReminder(r) } } label: { Label("Marquer comme fait", systemImage: "checkmark.circle") }501            Button { scene.next.snoozeRequest = SnoozeRequest(account: r.mailboxId, emailIds: [r.emailId], mode: .rescheduleReminder(r)) } label: { Label("Reporter…", systemImage: "calendar.badge.clock") }502            Divider()503            Button(role: .destructive) { Task { await app.next.cancelReminder(r) } } label: { Label("Annuler le rappel", systemImage: "bell.slash") }504        }505        .swipeActions(edge: .trailing) {506            Button { Task { await app.next.completeReminder(r) } } label: { Label("Fait", systemImage: "checkmark.circle") }.tint(SPColor.ok)507            Button { scene.next.snoozeRequest = SnoozeRequest(account: r.mailboxId, emailIds: [r.emailId], mode: .rescheduleReminder(r)) } label: { Label("Reporter", systemImage: "calendar.badge.clock") }.tint(SPColor.warn)508        }509        .accessibilityAction(named: Text("Marquer comme fait")) { Task { await app.next.completeReminder(r) } }510    }511}512513/// The quiet « offline » line at the top of a list that needs the server.514struct OfflineNote: View {515    let text: String516    var body: some View {517        Label(text, systemImage: "wifi.slash").font(.footnote).foregroundStyle(SPColor.warn).listRowBackground(Color.clear).listRowSeparator(.hidden)518            #if os(macOS)519            .selectionDisabled()520            #endif521    }522}523524struct SectionTitle: View {525    let text: String526    var count: Int?527    var body: some View {528        HStack(spacing: SPSpacing.s) {529            Text(text).font(SPFont.caption).foregroundStyle(SPColor.text3).textCase(.uppercase)530            if let count { Text("\(count)").font(SPFont.caption).foregroundStyle(SPColor.text3) }531        }532        .accessibilityElement(children: .combine).accessibilityAddTraits(.isHeader)533    }534}535536// MARK: - presenters537538/// The sheets and popovers of the Next flows, attached once per window (main window, message window).539struct NextPresenters: ViewModifier {540    @Bindable var scene: MailScene541    #if os(macOS)542    @Environment(\.openWindow) private var openWindow543    #endif544545    func body(content: Content) -> some View {546        @Bindable var next = scene.next547        content548            .overlay(alignment: .top) {549                // the anchor of the snooze / reminder popover; on iPhone the popover adapts to a sheet with detents550                Color.clear.frame(width: 1, height: 1).allowsHitTesting(false).accessibilityHidden(true)551                    .popover(item: $next.snoozeRequest, arrowEdge: .top) { request in SnoozePicker(scene: scene, request: request) }552            }553            .sheet(item: $next.labelEdit) { request in LabelEditorSheet(app: scene.app, request: request) }554            .sheet(item: $next.labelPick) { request in LabelPickerSheet(scene: scene, request: request) }555            #if DEBUG556            .sheet(isPresented: Binding(get: { next.debugPane != nil }, set: { if !$0 { next.debugPane = nil } })) { DebugPane(app: scene.app, name: next.debugPane ?? "") }557            #endif558            #if os(macOS)559            .onChange(of: next.messageRequest) { _, ref in if let ref { openWindow(id: "message", value: ref); next.messageRequest = nil } }560            #else561            .sheet(item: Binding(get: { next.messageRequest.map(MessageSheetItem.init) }, set: { if $0 == nil { next.messageRequest = nil } })) { item in MessageSheet(app: scene.app, ref: item.ref) }562            #endif563    }564}565566extension View {567    func nextPresenters(_ scene: MailScene) -> some View { modifier(NextPresenters(scene: scene)) }568}569570#if os(iOS)571struct MessageSheetItem: Identifiable {572    let ref: MessageRef573    var id: String { "\(ref.account)/\(ref.emailId)" }574}575576/// A message (or its conversation) on its own, over the current screen: its own navigation state on the shared session.577struct MessageSheet: View {578    let app: AppModel579    let ref: MessageRef580    @State private var scene: MailScene?581    @State private var missing = false582    @Environment(\.dismiss) private var dismiss583584    var body: some View {585        NavigationStack {586            Group {587                if let scene, !scene.reader.isEmpty {588                    ReaderView(scene: scene)589                        .sheet(item: Binding(get: { scene.composeRequest.flatMap { app.composers[$0] } }, set: { if $0 == nil { scene.composeRequest = nil } })) { composer in590                            NavigationStack { ComposeView(model: composer) { scene.composeRequest = nil }.navigationBarTitleDisplayMode(.inline) }.interactiveDismissDisabled().spTheme(app.settings)591                        }592                        .onChange(of: scene.reader.isEmpty) { _, empty in if empty { dismiss() } }593                } else if missing {594                    SPEmptyState(icon: "envelope.open", title: L("Ce message n’est plus disponible."))595                } else { ProgressView() }596            }597            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() } } }598        }599        .toastHost(app)600        .spTheme(app.settings)601        .task {602            guard scene == nil else { return }603            let s = MailScene(app: app, detached: true)604            if await s.openDetached(ref) { scene = s } else { missing = true }605        }606    }607}608#endif609610#if DEBUG611/// Design captures only: one settings pane (or the dashboard customiser) on its own.612struct DebugPane: View {613    let app: AppModel614    let name: String615    var body: some View {616        Group {617            switch name {618            case "customize": DashboardCustomizer(app: app)619            case "ai": NavigationStack { IntelligenceSettings(model: app).navigationTitle("Intelligence") }620            case "vacation": NavigationStack { VacationSettings(model: app).navigationTitle("Réponse automatique") }621            case "rules": NavigationStack { RulesSettings(model: app).navigationTitle("Filtres et règles") }622            case "notifications": NavigationStack { NotificationSettings(model: app).navigationTitle("Notifications") }623            case "compose": NavigationStack { ComposeSettings(app: app).navigationTitle("Rédaction") }624            default: NavigationStack { StorageSettings(model: app).navigationTitle("Stockage") }625            }626        }627        #if os(macOS)628        .frame(width: name == "customize" ? 420 : 720, height: 560)629        #endif630        .spTheme(app.settings)631    }632}633#endif634
Files main
Menu

Theme