SPB Git

Repository Public

DashboardView.swift 18.1 KB 314 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/DashboardView.swift3// Description: The Command Center — a first-class sidebar entry (never the default screen): inbox overview, what needs attention, scheduled4// sends, pending replies, recent attachments, important contacts, storage, delivery issues and sync status. Widgets can be hidden and5// reordered (synchronised preference `dashboard`); every item navigates to what it shows.6import SPMailCore7import SwiftUI89/// Where a dashboard item leads.10enum DashboardTarget: Equatable {11    case inbox(String), followUps, flagged, snoozed, needsReply, scheduled, outbox, attachments, contacts12    case message(account: String, emailId: String)13}1415extension MailScene {16    /// « Tapping any item navigates to it. »17    func navigate(_ target: DashboardTarget) async {18        switch target {19        case .inbox(let account): await showInbox(of: account)20        case .followUps: selection = .followUps21        case .flagged: selection = .unified(.flagged)22        case .snoozed: selection = .snoozed23        case .scheduled: selection = .scheduled24        case .outbox: selection = .outbox25        case .attachments: selection = .attachments26        case .contacts: selection = .contacts27        case .needsReply:28            if let account = currentAccount { await showInbox(of: account); await app.next.loadInsights(account: account); await applyInsight(.needsReply) }29        case .message(let account, let emailId): presentMessage(account: account, emailId: emailId)30        }31    }32}3334struct DashboardView: View {35    @Bindable var scene: MailScene36    @State private var note: String?37    @State private var loading = false38    @State private var customizing = false39    @Environment(\.horizontalSizeClass) private var sizeClass4041    private var app: AppModel { scene.app }42    private var next: NextServices { app.next }43    private func go(_ target: DashboardTarget) { Task { await scene.navigate(target) } }4445    var body: some View {46        ScrollView {47            VStack(alignment: .leading, spacing: SPSpacing.xl) {48                header49                if let dashboard = next.dashboard {50                    let widgets = next.dashboardLayout.visible51                    if widgets.isEmpty {52                        SPEmptyState(icon: "square.grid.2x2", title: L("Tous les widgets sont masqués"), actionTitle: L("Personnaliser…"), action: { customizing = true }).frame(minHeight: 260)53                    } else {54                        LazyVGrid(columns: [GridItem(.adaptive(minimum: sizeClass == .compact ? 280 : 340), spacing: SPSpacing.xl, alignment: .top)], alignment: .leading, spacing: SPSpacing.xl) {55                            ForEach(widgets) { widget in card(widget, dashboard) }56                        }57                    }58                } else if loading {59                    ProgressView().frame(maxWidth: .infinity, minHeight: 240)60                } else {61                    SPErrorState(message: note ?? L("Le centre de commande n’a pas pu être chargé.")) { Task { await load(fresh: true) } }.frame(minHeight: 260)62                }63            }64            .padding(SPSpacing.x3)65            .frame(maxWidth: 1180, alignment: .leading)66            .frame(maxWidth: .infinity)67        }68        .background(SPColor.bg.ignoresSafeArea())69        .navigationTitle("Centre de commande")70        .refreshable { await load(fresh: true) }71        .task { await load(fresh: false) }72        .toolbar {73            ToolbarItem(placement: .primaryAction) { Button { Task { await load(fresh: true) } } label: { Label("Actualiser", systemImage: "arrow.clockwise") }.help("Actualiser") }74            ToolbarItem(placement: .primaryAction) { Button { customizing = true } label: { Label("Personnaliser", systemImage: "slider.horizontal.3") }.help("Choisir et ordonner les widgets") }75        }76        .sheet(isPresented: $customizing) { DashboardCustomizer(app: app) }77    }7879    private func load(fresh: Bool) async {80        loading = true81        note = await next.loadDashboard(fresh: fresh)82        if let account = scene.currentAccount { await next.loadInsights(account: account) }83        loading = false84    }8586    private var header: some View {87        VStack(alignment: .leading, spacing: SPSpacing.xs) {88            HStack(alignment: .firstTextBaseline, spacing: SPSpacing.l) {89                Text("\(next.dashboard?.totalUnread ?? app.totalInboxUnread)").font(SPFont.display).foregroundStyle(SPColor.text).contentTransition(.numericText())90                Text((next.dashboard?.totalUnread ?? app.totalInboxUnread) == 1 ? L("message non lu") : L("messages non lus")).font(SPFont.title).foregroundStyle(SPColor.text2)91                Spacer()92                if loading, next.dashboard != nil { ProgressView().controlSize(.small) }93            }94            .accessibilityElement(children: .combine)95            if let note { Label(note, systemImage: "wifi.slash").font(.footnote).foregroundStyle(SPColor.warn) } else if let at = next.dashboard?.generatedAt {96                Text("À jour à \(at.formatted(date: .omitted, time: .shortened))").font(SPFont.caption).foregroundStyle(SPColor.text3)97            }98        }99    }100101    // MARK: widgets102103    @ViewBuilder private func card(_ widget: DashboardWidget, _ d: Dashboard) -> some View {104        switch widget {105        case .inbox:106            DashboardWidgetCard(title: widget.title, icon: widget.icon) {107                if d.inbox.isEmpty { empty(L("Aucune boîte")) }108                rows(d.inbox) { box in109                    line(icon: "tray", title: box.address, value: box.unread > 0 ? "\(box.unread)" : nil, detail: box.total == 1 ? L("1 message") : L("\(box.total) messages"), emphasised: box.unread > 0) { go(.inbox(box.mailboxId)) }110                }111            }112        case .attention:113            let needsReply = scene.currentAccount.flatMap { next.insights[$0]?.needsReply } ?? []114            DashboardWidgetCard(title: widget.title, icon: widget.icon) {115                LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: SPSpacing.m) {116                    tile(d.attention.remindersDue, L("Rappels dus"), "bell", warn: true) { go(.followUps) }117                    tile(d.attention.flagged, L("Avec drapeau"), "flag") { go(.flagged) }118                    tile(d.attention.snoozedToday, L("Réveils aujourd’hui"), "clock") { go(.snoozed) }119                    tile(max(d.attention.unanswered, needsReply.count), L("À répondre"), "arrowshape.turn.up.left") { go(.needsReply) }120                }121                if !needsReply.isEmpty {122                    Divider().overlay(SPColor.border)123                    rows(Array(needsReply.prefix(3))) { m in message(m) }124                }125            }126        case .scheduled:127            DashboardWidgetCard(title: widget.title, icon: widget.icon, actionTitle: d.scheduled.isEmpty ? nil : L("Tout voir"), action: { go(.scheduled) }) {128                if d.scheduled.isEmpty { empty(L("Aucun envoi programmé")) }129                rows(Array(d.scheduled.prefix(4))) { o in130                    line(icon: "clock", title: o.subject?.isEmpty == false ? o.subject! : o.recipients.map(\.address).joined(separator: ", "), value: nil,131                         detail: o.sendAt.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? "") { go(.scheduled) }132                }133            }134        case .pendingReplies:135            DashboardWidgetCard(title: widget.title, icon: widget.icon) {136                if d.pendingReplies.isEmpty { empty(L("Personne n’attend votre réponse")) }137                rows(Array(d.pendingReplies.prefix(5))) { m in message(m) }138            }139        case .recentAttachments:140            DashboardWidgetCard(title: widget.title, icon: widget.icon, actionTitle: d.recentAttachments.isEmpty ? nil : L("Galerie"), action: { go(.attachments) }) {141                if d.recentAttachments.isEmpty { empty(L("Aucune pièce jointe récente")) }142                rows(Array(d.recentAttachments.prefix(5))) { a in143                    line(icon: a.info.glyph, title: a.info.name, value: nil, detail: [a.size.byteLabel, a.from?.displayName].compactMap { $0 }.joined(separator: " · ")) { go(.message(account: a.mailboxId, emailId: a.emailId)) }144                }145            }146        case .contacts:147            DashboardWidgetCard(title: widget.title, icon: widget.icon, actionTitle: L("Contacts"), action: { go(.contacts) }) {148                if d.topContacts.isEmpty { empty(L("Aucun contact pour l’instant")) }149                rows(Array(d.topContacts.prefix(5))) { c in150                    Button { scene.showContact(c) } label: {151                        HStack(spacing: SPSpacing.m) {152                            AvatarView(name: c.name, address: c.primaryEmail ?? c.name, size: 26)153                            Text(c.displayName).font(SPFont.callout).foregroundStyle(SPColor.text).lineLimit(1)154                            if c.vip { Image(systemName: "crown.fill").imageScale(.small).foregroundStyle(SPColor.star) }155                            Spacer(minLength: SPSpacing.m)156                            Text("\(c.stats.received + c.stats.sent)").font(SPFont.caption).foregroundStyle(SPColor.text3)157                        }.frame(minHeight: 30).contentShape(Rectangle())158                    }159                    .buttonStyle(.plain).accessibilityLabel(Text("\(c.displayName), \(c.stats.received + c.stats.sent) messages"))160                }161            }162        case .storage:163            DashboardWidgetCard(title: widget.title, icon: widget.icon) {164                if d.storage.isEmpty { empty(L("Aucune donnée de stockage")) }165                rows(d.storage) { s in StorageMeter(title: app.box(s.mailboxId)?.address ?? s.mailboxId, used: s.usedBytes, quota: s.quotaBytes) }166            }167        case .deliveryIssues:168            DashboardWidgetCard(title: widget.title, icon: widget.icon) {169                if d.deliveryIssues.isEmpty { Label("Aucun problème de livraison", systemImage: "checkmark.circle").font(SPFont.callout).foregroundStyle(SPColor.ok) }170                rows(Array(d.deliveryIssues.prefix(4))) { o in171                    let label = OutboundLabels.label(o.status)172                    line(icon: label.icon, title: o.recipients.map(\.address).joined(separator: ", "), value: nil, detail: o.lastError?.isEmpty == false ? o.lastError! : label.text, tint: label.color) { go(.outbox) }173                }174            }175        case .sync:176            DashboardWidgetCard(title: widget.title, icon: widget.icon, actionTitle: L("Relever"), action: { Task { await scene.refresh() } }) {177                status(d.sync.isHealthy ? L("Serveur de courrier joignable") : L("Serveur de courrier injoignable"), ok: d.sync.isHealthy)178                if let lag = d.sync.watcherLagMs { status(lag < 60_000 ? L("Réception à jour") : L("Réception en retard de \(lag / 1000) s"), ok: lag < 60_000) }179                status(d.sync.push == "configured" ? L("Notifications poussées configurées") : L("Notifications poussées désactivées sur le serveur"), ok: d.sync.push == "configured", neutral: d.sync.push != "configured")180                let local = app.sync.display181                status(local == .synced ? L("Cet appareil est synchronisé") : localStatus(local), ok: local == .synced, neutral: local == .syncing)182            }183        }184    }185186    private func localStatus(_ d: SyncStatusModel.Display) -> String {187        switch d {188        case .synced: L("Cet appareil est synchronisé"); case .syncing: L("Synchronisation")189        case .offline(let n): n > 0 ? L("Hors ligne · \(n) en attente") : L("Hors ligne"); case .error(let m): m190        }191    }192193    private func rows<Data: RandomAccessCollection, V: View>(_ data: Data, @ViewBuilder _ content: @escaping (Data.Element) -> V) -> some View where Data.Element: Identifiable {194        VStack(alignment: .leading, spacing: SPSpacing.xs) { ForEach(data) { content($0) } }195    }196    private func empty(_ text: String) -> some View { Text(text).font(SPFont.callout).foregroundStyle(SPColor.text3) }197198    private func line(icon: String, title: String, value: String?, detail: String, emphasised: Bool = false, tint: SPToken = SPColor.text3, action: @escaping () -> Void) -> some View {199        Button(action: action) {200            HStack(spacing: SPSpacing.m) {201                Image(systemName: icon).frame(width: 20).foregroundStyle(tint).symbolRenderingMode(.hierarchical)202                VStack(alignment: .leading, spacing: 0) {203                    Text(title).font(SPFont.callout).fontWeight(emphasised ? .semibold : .regular).foregroundStyle(SPColor.text).lineLimit(1).truncationMode(.middle)204                    if !detail.isEmpty { Text(detail).font(SPFont.caption).foregroundStyle(SPColor.text3).lineLimit(1) }205                }206                Spacer(minLength: SPSpacing.m)207                if let value { Text(value).font(SPFont.caption).foregroundStyle(SPColor.onAccent).padding(.horizontal, 7).padding(.vertical, 2).background(SPColor.accent, in: Capsule()) }208                Image(systemName: "chevron.right").font(.caption2.weight(.semibold)).foregroundStyle(SPColor.text3)209            }210            .frame(minHeight: 34).contentShape(Rectangle())211        }212        .buttonStyle(.plain)213        #if os(iOS)214        .hoverEffect(.highlight)215        #endif216        .accessibilityLabel(Text([title, value ?? "", detail].filter { !$0.isEmpty }.joined(separator: ", ")))217    }218219    private func message(_ m: SearchResult) -> some View {220        line(icon: m.isUnread ? "envelope.badge" : "envelope", title: m.subject.isEmpty ? L("(sans objet)") : m.subject, value: nil,221             detail: [m.from.first?.displayName, m.receivedAt?.listLabel].compactMap { $0 }.joined(separator: " · "), emphasised: m.isUnread) { go(.message(account: m.mailboxId, emailId: m.emailId)) }222    }223224    private func tile(_ count: Int, _ label: String, _ icon: String, warn: Bool = false, action: @escaping () -> Void) -> some View {225        Button(action: action) {226            VStack(alignment: .leading, spacing: 2) {227                HStack {228                    Text("\(count)").font(.title2.weight(.bold).monospacedDigit()).foregroundStyle(count > 0 && warn ? SPColor.warn : SPColor.text)229                    Spacer()230                    Image(systemName: icon).foregroundStyle(count > 0 && warn ? SPColor.warn : SPColor.text3)231                }232                Text(label).font(SPFont.caption).foregroundStyle(SPColor.text2).lineLimit(1)233            }234            .padding(SPSpacing.l).frame(maxWidth: .infinity, alignment: .leading)235            .background(count > 0 && warn ? SPColor.warnSoft : SPColor.surface2, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))236            .contentShape(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))237        }238        .buttonStyle(.plain)239        #if os(iOS)240        .hoverEffect(.highlight)241        #endif242        .accessibilityLabel(Text("\(label) : \(count)"))243    }244245    private func status(_ text: String, ok: Bool, neutral: Bool = false) -> some View {246        Label { Text(text).foregroundStyle(SPColor.text) } icon: { Image(systemName: neutral ? "minus.circle" : ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(neutral ? SPColor.text3 : ok ? SPColor.ok : SPColor.danger) }247            .font(SPFont.callout).frame(minHeight: 26)248    }249}250251/// Used space of a mailbox, with a meter when the quota is known.252struct StorageMeter: View {253    let title: String254    let used: Int255    let quota: Int?256    var body: some View {257        let fraction = quota.flatMap { $0 > 0 ? min(1, Double(used) / Double($0)) : nil }258        VStack(alignment: .leading, spacing: 4) {259            HStack {260                Text(title).font(SPFont.callout).foregroundStyle(SPColor.text).lineLimit(1).truncationMode(.middle)261                Spacer(minLength: SPSpacing.m)262                Text(quota.map { L("\(used.byteLabel) sur \($0.byteLabel)") } ?? used.byteLabel).font(SPFont.caption).foregroundStyle(SPColor.text3)263            }264            if let fraction {265                GeometryReader { g in266                    ZStack(alignment: .leading) {267                        Capsule().fill(SPColor.surface3)268                        Capsule().fill(fraction > 0.9 ? SPColor.danger : fraction > 0.75 ? SPColor.warn : SPColor.accent).frame(width: max(4, g.size.width * fraction))269                    }270                }271                .frame(height: 6)272            }273        }274        .padding(.vertical, 3)275        .accessibilityElement(children: .ignore)276        .accessibilityLabel(Text(title))277        .accessibilityValue(Text(fraction.map { L("\(Int(($0 * 100).rounded())) % utilisés, \(used.byteLabel)") } ?? used.byteLabel))278    }279}280281/// Show / hide and reorder the widgets. Saved in the synchronised preference `dashboard` (the other preferences are untouched).282struct DashboardCustomizer: View {283    let app: AppModel284    @Environment(\.dismiss) private var dismiss285286    var body: some View {287        @Bindable var next = app.next288        NavigationStack {289            List {290                Section {291                    ForEach(next.dashboardLayout.order) { widget in292                        Toggle(isOn: Binding(get: { !next.dashboardLayout.hidden.contains(widget) }, set: { on in if on { next.dashboardLayout.hidden.remove(widget) } else { next.dashboardLayout.hidden.insert(widget) } })) {293                            Label(widget.title, systemImage: widget.icon)294                        }295                    }296                    .onMove { from, to in next.dashboardLayout.order.move(fromOffsets: from, toOffset: to) }297                } footer: { Text("Faites glisser pour réordonner. La disposition est synchronisée entre vos appareils.") }298                Section { Button("Rétablir la disposition par défaut") { next.dashboardLayout.resetKnown() } }299            }300            .navigationTitle("Personnaliser")301            #if os(iOS)302            .navigationBarTitleDisplayMode(.inline)303            .environment(\.editMode, .constant(.active))304            #endif305            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }306        }307        #if os(macOS)308        .frame(width: 420, height: 520)309        #endif310        .spTheme(app.settings)311        .onDisappear { Task { await app.next.saveDashboardLayout() } }312    }313}314
Files main
Menu

Theme