SPB Git

Repository Public

SPMailWidgets.swift 18.1 KB 376 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Widgets/SPMailWidgets.swift3// Description: SP Mail's widgets (WidgetKit; iOS / iPadOS home and lock screen, macOS desktop and Notification Centre): « Boîte de4// réception » (unread per mailbox), « Récents » (latest conversations, each row opens its conversation), « Suivis » (reminders due), a5// lock-screen unread count and a « Nouveau message » control. They show the sealed snapshot the app writes after each sync, reduced to6// the notification privacy level, and nothing but a lock glyph while SP Mail is locked. Timelines are reloaded by the app, never polled.7import AppIntents8import SPMailCore9import SPMailSystem10import SwiftUI11import WidgetKit1213// MARK: - timeline1415struct MailEntry: TimelineEntry {16    let date: Date17    let content: WidgetContent18    /// The app has not written a snapshot for more than an hour: the numbers are shown as « last known ».19    var stale = false20    var dev = false21}2223struct MailTimeline: TimelineProvider {24    func placeholder(in context: Context) -> MailEntry { MailEntry(date: Date(), content: .content(Self.sample)) }2526    func getSnapshot(in context: Context, completion: @escaping (MailEntry) -> Void) {27        // the widget gallery shows sample data, never the person's mail28        completion(context.isPreview ? MailEntry(date: Date(), content: .content(Self.sample)) : Self.entries(now: Date()).first!)29    }30    func getTimeline(in context: Context, completion: @escaping (Timeline<MailEntry>) -> Void) {31        // every entry is computed now; the app reloads the timeline after each sync and on lock changes32        completion(Timeline(entries: Self.entries(now: Date()), policy: .never))33    }3435    /// Now, then the moment the app lock would engage (the lock is a function of time since the app was left), then the moment the36    /// snapshot becomes stale.37    static func entries(now: Date) -> [MailEntry] {38        let store = SharedStore.open()39        let state = store.state(), snapshot = store.snapshot(), dev = store.environment.dev40        func entry(_ at: Date) -> MailEntry {41            MailEntry(date: at, content: WidgetContent.resolve(state: state, snapshot: snapshot, now: at), stale: snapshot?.isStale(now: at) ?? false, dev: dev)42        }43        var dates = [now]44        if let lock = state?.lock, lock.enabled, !lock.locked, let left = lock.leftAt {45            let at = left.addingTimeInterval(Double(max(0, lock.afterMinutes)) * 60 + 1)46            if at > now { dates.append(at) }47        }48        if let snapshot, !snapshot.isStale(now: now) { dates.append(snapshot.generatedAt.addingTimeInterval(3601)) }49        return dates.sorted().map(entry)50    }5152    /// Placeholder and gallery content: invented, in the shape of real data.53    static var sample: WidgetSnapshot {54        let now = Date()55        func row(_ i: Int, _ name: String, _ subject: String, _ preview: String, unread: Bool) -> SearchResult? {56            SearchResult(json: ["mailbox_id": "sample", "email_id": .string("s\(i)"), "thread_id": .string("t\(i)"), "from": [["name": .string(name), "email": "exemple@spboucher.ai"]], "subject": .string(subject), "preview": .string(preview),57                                "received_at": .string(ISO8601DateFormatter().string(from: now.addingTimeInterval(Double(-1500 * (i + 1))))), "keywords": .object(unread ? [:] : ["$seen": true])])58        }59        let french = ExtConfig.isFrench60        let rows = [row(0, "Camille Roy", french ? "Ordre du jour de jeudi" : "Thursday’s agenda", french ? "Voici les points à couvrir…" : "Here are the points to cover…", unread: true),61                    row(1, "Marc Lavoie", french ? "Version révisée du rapport" : "Revised report", french ? "J’ai intégré vos commentaires." : "I included your comments.", unread: true),62                    row(2, "Bibliothèque", french ? "Votre réservation est prête" : "Your hold is ready", "", unread: false),63                    row(3, "Élise Fortin", french ? "Photos du week-end" : "Weekend photos", "", unread: false)].compactMap { $0 }64        return WidgetSnapshot(unread: [.init(mailboxId: "sample", address: "moi@spboucher.ai", unread: 4), .init(mailboxId: "sample2", address: "travail@spboucher.ai", unread: 2)], recent: rows, preview: .full, limit: 6, generatedAt: now)65    }66}6768// MARK: - shared pieces6970private func link(_ l: DeepLink, _ entry: MailEntry) -> URL { l.url(dev: entry.dev) }7172/// Signed out / locked: the same quiet card for every widget.73private struct StatusCard: View {74    let symbol: String75    let title: LocalizedStringKey76    @Environment(\.widgetFamily) private var family77    var body: some View {78        VStack(spacing: 6) {79            Image(systemName: symbol).font(.title2).foregroundStyle(.secondary)80            Text(title).font(.caption).foregroundStyle(.secondary).multilineTextAlignment(.center)81        }82        .frame(maxWidth: .infinity, maxHeight: .infinity)83    }84}8586private struct Header: View {87    let symbol: String88    let title: LocalizedStringKey89    var count: Int?90    @Environment(\.colorScheme) private var scheme91    var body: some View {92        HStack(spacing: 5) {93            Image(systemName: symbol).font(.caption.weight(.semibold)).foregroundStyle(ExtColor.accent(scheme))94            Text(title).font(.caption.weight(.semibold)).foregroundStyle(ExtColor.accent(scheme)).lineLimit(1)95            Spacer(minLength: 0)96            if let count, count > 0 { Text("\(count)").font(.caption.weight(.semibold).monospacedDigit()).foregroundStyle(.secondary) }97        }98    }99}100101private struct StaleNote: View {102    let entry: MailEntry103    var body: some View {104        if entry.stale { Text("Dernier état connu").font(.caption2).foregroundStyle(.tertiary) }105    }106}107108/// Wraps a widget body: placeholder states first, the content otherwise.109private struct Gate<Content: View>: View {110    let entry: MailEntry111    @ViewBuilder var content: (WidgetSnapshot) -> Content112    var body: some View {113        switch entry.content {114        case .signedOut: StatusCard(symbol: "envelope", title: "Ouvrez SP Mail pour vous connecter")115        case .locked: StatusCard(symbol: "lock.fill", title: "SP Mail est verrouillé")116        case .content(let snapshot): content(snapshot)117        }118    }119}120121// MARK: - « Boîte de réception »122123struct InboxWidgetView: View {124    let entry: MailEntry125    @Environment(\.widgetFamily) private var family126    @Environment(\.colorScheme) private var scheme127128    var body: some View {129        Gate(entry: entry) { s in130            if family == .systemSmall { small(s) } else { medium(s) }131        }132        .widgetURL(link(.inbox(mailboxId: nil), entry))133    }134135    private func small(_ s: WidgetSnapshot) -> some View {136        VStack(alignment: .leading, spacing: 2) {137            Header(symbol: "tray.fill", title: "Courrier")138            Spacer(minLength: 0)139            Text("\(s.totalUnread)").font(.system(size: 44, weight: .semibold, design: .rounded)).monospacedDigit().minimumScaleFactor(0.6).contentTransition(.numericText())140            Text(s.totalUnread == 1 ? "non lu" : "non lus").font(.caption).foregroundStyle(.secondary)141            StaleNote(entry: entry)142        }143        .frame(maxWidth: .infinity, alignment: .leading)144    }145146    private func medium(_ s: WidgetSnapshot) -> some View {147        HStack(alignment: .top, spacing: 14) {148            VStack(alignment: .leading, spacing: 2) {149                Header(symbol: "tray.fill", title: "Boîte de réception")150                Spacer(minLength: 0)151                Text("\(s.totalUnread)").font(.system(size: 44, weight: .semibold, design: .rounded)).monospacedDigit().minimumScaleFactor(0.6)152                Text(s.totalUnread == 1 ? "non lu" : "non lus").font(.caption).foregroundStyle(.secondary)153                StaleNote(entry: entry)154            }155            .frame(maxWidth: 120, alignment: .leading)156            VStack(alignment: .leading, spacing: 6) {157                ForEach(s.unread.prefix(3)) { box in158                    Link(destination: link(.inbox(mailboxId: box.mailboxId), entry)) {159                        HStack(spacing: 6) {160                            Text(box.address).font(.caption).lineLimit(1).truncationMode(.middle).privacySensitive()161                            Spacer(minLength: 4)162                            Text("\(box.unread)").font(.caption.weight(.semibold).monospacedDigit()).foregroundStyle(box.unread > 0 ? .primary : .secondary)163                        }164                    }165                }166                Spacer(minLength: 0)167                Button(intent: ComposeMessageIntent()) {168                    Label("Nouveau message", systemImage: "square.and.pencil").font(.caption.weight(.semibold)).frame(maxWidth: .infinity)169                }170                .buttonStyle(.borderedProminent).tint(ExtColor.accent(scheme)).controlSize(.small)171            }172            .frame(maxWidth: .infinity, alignment: .leading)173        }174    }175}176177struct InboxWidget: Widget {178    var body: some WidgetConfiguration {179        StaticConfiguration(kind: "ai.spboucher.spmail.widget.inbox", provider: MailTimeline()) { entry in180            InboxWidgetView(entry: entry).containerBackground(.fill.tertiary, for: .widget)181        }182        .configurationDisplayName("Boîte de réception")183        .description("Le nombre de messages non lus de vos boîtes de réception.")184        .supportedFamilies([.systemSmall, .systemMedium])185    }186}187188// MARK: - « Récents »189190struct RecentsWidgetView: View {191    let entry: MailEntry192    @Environment(\.widgetFamily) private var family193    @Environment(\.colorScheme) private var scheme194195    var body: some View {196        Gate(entry: entry) { s in197            VStack(alignment: .leading, spacing: family == .systemLarge ? 8 : 5) {198                Header(symbol: "envelope.fill", title: "Récents", count: s.totalUnread)199                if s.conversations.isEmpty {200                    Spacer(minLength: 0)201                    Text("Aucun message récent").font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity)202                    Spacer(minLength: 0)203                } else {204                    ForEach(s.conversations.prefix(family == .systemLarge ? 6 : 3)) { c in205                        Link(destination: link(.conversation(mailboxId: c.mailboxId, emailId: c.emailId, threadId: c.threadId), entry)) { row(c, large: family == .systemLarge) }206                    }207                    Spacer(minLength: 0)208                    StaleNote(entry: entry)209                }210            }211        }212        .widgetURL(link(.inbox(mailboxId: nil), entry))213    }214215    /// A conversation at the level the snapshot allows: sender and subject, sender only, or just « Nouveau message ».216    private func row(_ c: WidgetSnapshot.Conversation, large: Bool) -> some View {217        HStack(alignment: .firstTextBaseline, spacing: 6) {218            Circle().fill(c.unread ? ExtColor.accent(scheme) : .clear).frame(width: 6, height: 6).accessibilityHidden(true)219            VStack(alignment: .leading, spacing: 1) {220                HStack(spacing: 4) {221                    Group { if let sender = c.sender { Text(sender) } else { Text(c.unread ? "Nouveau message" : "Message") } }222                        .font(.caption.weight(c.unread ? .semibold : .regular)).lineLimit(1)223                    Spacer(minLength: 4)224                    Text(c.receivedAt, style: .time).font(.caption2).foregroundStyle(.secondary)225                }226                if let subject = c.subject { Text(subject.isEmpty ? String(localized: "(sans objet)") : subject).font(.caption2).foregroundStyle(.secondary).lineLimit(1) }227                if large, let preview = c.preview, !preview.isEmpty { Text(preview).font(.caption2).foregroundStyle(.tertiary).lineLimit(1) }228            }229        }230        .privacySensitive()231        .accessibilityElement(children: .combine)232    }233}234235struct RecentsWidget: Widget {236    var body: some WidgetConfiguration {237        StaticConfiguration(kind: "ai.spboucher.spmail.widget.recents", provider: MailTimeline()) { entry in238            RecentsWidgetView(entry: entry).containerBackground(.fill.tertiary, for: .widget)239        }240        .configurationDisplayName("Récents")241        .description("Les dernières conversations de vos boîtes de réception, au niveau de confidentialité choisi pour les notifications.")242        .supportedFamilies([.systemMedium, .systemLarge])243    }244}245246// MARK: - « Suivis »247248struct RemindersWidgetView: View {249    let entry: MailEntry250    @Environment(\.widgetFamily) private var family251252    var body: some View {253        Gate(entry: entry) { s in254            VStack(alignment: .leading, spacing: 5) {255                Header(symbol: "bell.fill", title: "Suivis", count: family == .systemSmall ? nil : s.remindersDue)256                if family == .systemSmall {257                    Spacer(minLength: 0)258                    Text("\(s.remindersDue)").font(.system(size: 44, weight: .semibold, design: .rounded)).monospacedDigit()259                    Text(s.remindersDue == 1 ? "rappel à traiter" : "rappels à traiter").font(.caption).foregroundStyle(.secondary)260                } else if s.reminders.isEmpty {261                    Spacer(minLength: 0)262                    Text(s.remindersDue == 0 ? "Aucun suivi en attente" : "Ouvrez SP Mail pour voir vos suivis").font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity)263                    Spacer(minLength: 0)264                } else {265                    ForEach(s.reminders.prefix(3)) { r in266                        Link(destination: link(.conversation(mailboxId: r.mailboxId, emailId: r.emailId, threadId: nil), entry)) {267                            HStack(alignment: .firstTextBaseline, spacing: 6) {268                                Image(systemName: "clock").font(.caption2).foregroundStyle(.secondary).accessibilityHidden(true)269                                VStack(alignment: .leading, spacing: 1) {270                                    Group { if let who = r.counterpart { Text(who) } else { Text("Rappel de suivi") } }.font(.caption.weight(.semibold)).lineLimit(1)271                                    if let subject = r.subject, !subject.isEmpty { Text(subject).font(.caption2).foregroundStyle(.secondary).lineLimit(1) }272                                }273                                Spacer(minLength: 4)274                                if let due = r.dueAt { Text(due, style: .relative).font(.caption2).foregroundStyle(.secondary).multilineTextAlignment(.trailing).frame(maxWidth: 70, alignment: .trailing) }275                            }276                            .privacySensitive()277                        }278                    }279                    Spacer(minLength: 0)280                }281                StaleNote(entry: entry)282            }283            .frame(maxWidth: .infinity, alignment: .leading)284        }285        .widgetURL(link(.reminders, entry))286    }287}288289struct RemindersWidget: Widget {290    var body: some WidgetConfiguration {291        StaticConfiguration(kind: "ai.spboucher.spmail.widget.reminders", provider: MailTimeline()) { entry in292            RemindersWidgetView(entry: entry).containerBackground(.fill.tertiary, for: .widget)293        }294        .configurationDisplayName("Suivis")295        .description("Les rappels de suivi arrivés à échéance.")296        .supportedFamilies([.systemSmall, .systemMedium])297    }298}299300// MARK: - lock screen (iOS / iPadOS)301302#if os(iOS)303struct UnreadAccessoryView: View {304    let entry: MailEntry305    @Environment(\.widgetFamily) private var family306307    private var count: Int? { if case .content(let s) = entry.content { s.totalUnread } else { nil } }308    private var locked: Bool { entry.content == .locked }309310    var body: some View {311        Group {312            switch family {313            case .accessoryCircular:314                ZStack {315                    AccessoryWidgetBackground()316                    VStack(spacing: 0) {317                        Image(systemName: locked ? "lock.fill" : "envelope.fill").font(.caption2)318                        if let count { Text("\(count)").font(.system(.title3, design: .rounded).weight(.semibold)).monospacedDigit().minimumScaleFactor(0.5) }319                    }320                }321            case .accessoryInline:322                if let count { Label(count == 1 ? "1 non lu" : "\(count) non lus", systemImage: "envelope.fill") } else { Label("SP Mail", systemImage: locked ? "lock.fill" : "envelope") }323            default:324                HStack(spacing: 6) {325                    Image(systemName: locked ? "lock.fill" : "envelope.fill")326                    VStack(alignment: .leading) {327                        Text("SP Mail").font(.headline).widgetAccentable()328                        if let count { Text(count == 0 ? "Aucun message non lu" : count == 1 ? "1 message non lu" : "\(count) messages non lus").font(.caption) }329                        else { Text(locked ? "Verrouillé" : "Non connecté").font(.caption) }330                    }331                    Spacer(minLength: 0)332                }333            }334        }335        .widgetURL(link(.inbox(mailboxId: nil), entry))336    }337}338339struct UnreadAccessoryWidget: Widget {340    var body: some WidgetConfiguration {341        StaticConfiguration(kind: "ai.spboucher.spmail.widget.unread", provider: MailTimeline()) { entry in342            UnreadAccessoryView(entry: entry).containerBackground(.clear, for: .widget)343        }344        .configurationDisplayName("Non lus")345        .description("Le nombre de messages non lus, sur l’écran verrouillé.")346        .supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])347    }348}349350/// Control Centre, the lock screen and the Action button: one tap to a new message.351struct ComposeControl: ControlWidget {352    var body: some ControlWidgetConfiguration {353        StaticControlConfiguration(kind: "ai.spboucher.spmail.control.compose") {354            ControlWidgetButton(action: ComposeMessageIntent()) { Label("Nouveau message", systemImage: "square.and.pencil") }355        }356        .displayName("Nouveau message")357        .description("Ouvre un nouveau message dans SP Mail.")358    }359}360#endif361362// MARK: - bundle363364@main365struct SPMailWidgetBundle: WidgetBundle {366    var body: some Widget {367        InboxWidget()368        RecentsWidget()369        RemindersWidget()370        #if os(iOS)371        UnreadAccessoryWidget()372        ComposeControl()373        #endif374    }375}376
Files main
Menu

Theme