SPB Git

Repository Public

MainViews.swift 21.8 KB 379 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/MainViews.swift3// Description: The mail interface of one window — three-column split view (translucent sidebar, list, reader with a trailing inspector on macOS),4// the sidebar (account switcher, unified section, folders with drop targets, quiet sync footer) and the per-window sheets.5import SPMailCore6import SwiftUI7import UniformTypeIdentifiers89struct MainView: View {10    @Bindable var scene: MailScene11    @State private var preferredColumn = NavigationSplitViewColumn.content12    @State private var columns = NavigationSplitViewVisibility.all13    @Namespace private var composeSpace14    #if os(macOS)15    @Environment(\.openWindow) private var openWindow16    @Environment(\.openSettings) private var openSettings17    #else18    @Environment(\.horizontalSizeClass) private var sizeClass19    #endif2021    private var app: AppModel { scene.app }22    /// iPhone, or an iPad window narrow enough to collapse to one column: the compose button floats within reach of the thumb.23    private var compactWindow: Bool {24        #if os(iOS)25        sizeClass == .compact26        #else27        false28        #endif29    }3031    private var sidebar: some View {32        SidebarView(scene: scene) { preferredColumn = scene.isWideScreen ? .detail : .content }33            #if os(macOS)34            .navigationSplitViewColumnWidth(min: 200, ideal: 232, max: 320)35            #else36            .navigationSplitViewColumnWidth(min: 260, ideal: 300, max: 360)37            #endif38    }3940    var body: some View {41        Group {42            if scene.isWideScreen {43                // the Command Center and the attachment gallery take the whole width beside the sidebar44                NavigationSplitView(columnVisibility: $columns, preferredCompactColumn: $preferredColumn) { sidebar } detail: {45                    if scene.selection == .attachments { AttachmentGalleryView(scene: scene) } else { DashboardView(scene: scene) }46                }47            } else {48                NavigationSplitView(columnVisibility: $columns, preferredCompactColumn: $preferredColumn) { sidebar } content: {49                    Group {50                        switch scene.selection {51                        case .outbox: OutboxView(scene: scene)52                        case .unified(let view): UnifiedListView(scene: scene, view: view, composeSpace: composeSpace, compactWindow: compactWindow) { preferredColumn = .detail }53                        case .scheduled: ScheduledView(scene: scene)54                        case .search, .label, .savedSearch: SearchView(scene: scene, composeSpace: composeSpace, compactWindow: compactWindow) { preferredColumn = .detail }55                        case .snoozed: SnoozedView(scene: scene) { preferredColumn = .detail }56                        case .followUps: FollowUpsView(scene: scene) { preferredColumn = .detail }57                        case .contacts: ContactListView(scene: scene) { preferredColumn = .detail }58                        default: MessageListView(scene: scene, composeSpace: composeSpace, compactWindow: compactWindow) { preferredColumn = .detail }59                        }60                    }61                    #if os(macOS)62                    .navigationSplitViewColumnWidth(min: 300, ideal: 372, max: 560)63                    #else64                    .navigationSplitViewColumnWidth(min: 320, ideal: 390, max: 480)65                    #endif66                } detail: {67                    if scene.selection == .contacts { ContactDetailView(scene: scene) } else { ReaderView(scene: scene) }68                }69            }70        }71        .navigationSplitViewStyle(.balanced)72        .nextPresenters(scene)73        .toastHost(app)74        .composeUndoHost(app)75        .overlay { if scene.showPalette { CommandPaletteOverlay(scene: scene) } }76        .onChange(of: scene.selection) { _, _ in scene.didSelectSidebar() }77        .onChange(of: scene.detailRequest) { _, _ in preferredColumn = .detail }78        .focusedSceneValue(scene)79        #if os(macOS)80        .onChange(of: scene.composeRequest) { _, id in81            if let id { openWindow(id: "compose", value: id); scene.composeRequest = nil }82        }83        .onChange(of: scene.studioRequest) { _, _ in openWindow(id: "studio") }84        #if DEBUG85        .task {86            // screenshot fixtures: a message window, the Settings window87            guard let wanted = AppConfig.screenshotScene, wanted == "message" || wanted == "settings" else { return }88            try? await Task.sleep(for: .seconds(wanted == "message" ? 14 : 2))89            if wanted == "message", let account = scene.currentAccount { openWindow(id: "message", value: MessageRef(account: account, emailId: "demo-0", conversation: true)) } else if wanted == "settings" { openSettings() }90        }91        #endif92        #else93        .sheet(item: Binding(get: { scene.composeRequest.flatMap { app.composers[$0] } }, set: { if $0 == nil { scene.composeRequest = nil } })) { composer in94            ComposeSheet(composer: composer, app: app, space: composeSpace) { scene.composeRequest = nil }95        }96        .modifier(ComposeSheetRestoration(scene: scene, app: app))97        .sheet(isPresented: $scene.showSettings) {98            NavigationStack { SettingsView(model: app).toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { scene.showSettings = false } } } }.spTheme(app.settings)99        }100        .fullScreenCover(isPresented: $scene.showStudio) { StudioRoot(studio: app.studio) { scene.showStudio = false } }101        .onChange(of: scene.studioRequest) { _, _ in scene.showStudio = true }102        #endif103        .onOpenURL { url in if url.scheme == "mailto" { Task { await scene.compose(.mailto(url)) } } }104    }105}106107#if os(iOS)108/// The composer on iOS / iPadOS: a sheet with detents (large by default, medium to glance at the message underneath).109struct ComposeSheet: View {110    let composer: ComposeModel111    let app: AppModel112    let space: Namespace.ID113    let onClose: () -> Void114    @State private var detent = PresentationDetent.large115116    var body: some View {117        NavigationStack {118            ComposeView(model: composer, onClose: onClose)119                .navigationTitle(composer.subject.isEmpty ? L("Nouveau message") : composer.subject)120                .navigationBarTitleDisplayMode(.inline)121        }122        .presentationDetents([.medium, .large], selection: $detent)123        .presentationSizing(.page) // iPad: a page-sized sheet — the form size leaves a few lines of text above the software keyboard124        .presentationDragIndicator(.visible)125        .presentationBackgroundInteraction(.enabled(upThrough: .medium))126        .interactiveDismissDisabled()127        .navigationTransition(.zoom(sourceID: "compose", in: space))128        .spTheme(app.settings)129    }130}131#endif132133// MARK: - sidebar134135/// The account switcher at the top of the sidebar: avatar, address, unread count; a menu when there are several mailboxes.136struct AccountSwitcher: View {137    let scene: MailScene138    private var app: AppModel { scene.app }139140    private func label(_ box: MeResponse.Box?) -> some View {141        HStack(spacing: SPSpacing.m) {142            AvatarView(name: box?.display_name, address: box?.address ?? "", size: 28)143            VStack(alignment: .leading, spacing: 0) {144                if let name = box?.display_name, !name.isEmpty { Text(name).font(SPFont.callout.weight(.semibold)).foregroundStyle(SPColor.text).lineLimit(1) }145                Text(box?.address ?? "").font(.caption).foregroundStyle(SPColor.text2).lineLimit(1).truncationMode(.middle)146            }147            Spacer(minLength: 2)148            if app.accounts.count > 1 { Image(systemName: "chevron.up.chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(SPColor.text3) }149        }150        .contentShape(Rectangle())151    }152153    var body: some View {154        if app.accounts.count > 1 {155            Menu {156                ForEach(app.accounts) { a in157                    let unread = app.inboxUnread[a.id] ?? 0158                    Button { Task { await scene.switchAccount(a.id) } } label: {159                        if a.id == scene.currentAccount { Label(unread > 0 ? "\(a.address) (\(unread))" : a.address, systemImage: "checkmark") } else { Text(unread > 0 ? "\(a.address) (\(unread))" : a.address) }160                    }161                }162            } label: { label(scene.currentBox) }163            .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)164            .accessibilityLabel(Text("Boîte"))165            .accessibilityValue(Text(scene.currentBox?.address ?? ""))166        } else { label(scene.currentBox).accessibilityElement(children: .combine) }167    }168}169170struct SidebarView: View {171    @Bindable var scene: MailScene172    var onPick: () -> Void173    @State private var newFolder = false174    @State private var folderName = ""175    @State private var renaming: Mailbox?176    @State private var deleting: Mailbox?177    @State private var dropTarget: String?178    @State private var deletingLabel: MailLabel?179    @State private var renamingSearch: SavedSearch?180    @State private var deletingSearch: SavedSearch?181    @Environment(\.spReduceTransparency) private var opaque182    @Environment(\.spMidnight) private var midnight183184    private var app: AppModel { scene.app }185    private func badge(_ m: Mailbox) -> Int { m.knownRole == .drafts ? m.totalEmails : (m.knownRole == .sent || m.knownRole == .trash ? 0 : m.unreadEmails) }186187    @ViewBuilder private func row(_ m: Mailbox) -> some View {188        let title = MailScene.title(of: m)189        pick(.mailbox(m.id)) { Label(title, systemImage: MailScene.icon(of: m)).badge(badge(m)) }190            .dropDestination(for: String.self) { items, _ in191                let ids = Set(items.flatMap(MailDrag.ids(from:)))192                guard !ids.isEmpty else { return false }193                Task { await scene.perform(.move(m.id), on: ids) }194                return true195            } isTargeted: { on in if on { dropTarget = m.id } else if dropTarget == m.id { dropTarget = nil } }196            // drop targets highlight with accent-soft and a 2 pt accent outline197            .listRowBackground(dropTarget == m.id ? RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).fill(SPColor.accentSoft)198                .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.accent, lineWidth: 2)).padding(.horizontal, 4) : nil)199            .accessibilityLabel(Text(badge(m) > 0 ? "\(title), \(badge(m)) non lus" : title))200    }201202    /// macOS: a selectable row. iOS / iPadOS: a button, so that touching the folder already open brings back its list.203    @ViewBuilder private func pick<V: View>(_ item: SidebarItem, @ViewBuilder label: () -> V) -> some View {204        #if os(iOS)205        Button { if scene.selection != item { scene.selection = item }; onPick() } label: { label().frame(maxWidth: .infinity, minHeight: 30, alignment: .leading).contentShape(Rectangle()) }206            .buttonStyle(.plain)207            .listRowBackground(scene.selection == item ? RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).fill(SPColor.accentSoft).padding(.horizontal, 4) : nil)208            .hoverEffect(.highlight)209            .accessibilityAddTraits(scene.selection == item ? .isSelected : [])210        #else211        label().tag(item)212        #endif213    }214215    @ViewBuilder private var list: some View {216        #if os(iOS)217        List { rows }.listStyle(.sidebar)218        #else219        List(selection: $scene.selection) { rows }.listStyle(.sidebar)220        #endif221    }222223    /// A label of the sidebar: colour dot, and a drop target that applies it to the dragged conversations (of any mailbox).224    @ViewBuilder private func labelRow(_ label: MailLabel) -> some View {225        let key = "label." + label.id226        pick(.label(label.id)) {227            Label { Text(label.name).lineLimit(1) } icon: { Image(systemName: "circle.fill").font(.system(size: 9)).foregroundStyle(LabelPalette.token(LabelPalette.index(forHex: label.color))) }228        }229        .dropDestination(for: String.self) { items, _ in230            guard !label.keyword.isEmpty else { return false }231            let ids = Set(items.flatMap(MailDrag.ids(from:))), remote = items.flatMap(MailDrag.remote(from:))232            guard !ids.isEmpty || !remote.isEmpty else { return false }233            Task {234                if !ids.isEmpty { await scene.perform(.keyword(label.keyword, true), on: ids) }235                if !remote.isEmpty { await scene.applyKeyword(label.keyword, true, to: remote) }236            }237            return true238        } isTargeted: { on in if on { dropTarget = key } else if dropTarget == key { dropTarget = nil } }239        .listRowBackground(dropTarget == key ? RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).fill(SPColor.accentSoft)240            .overlay(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.accent, lineWidth: 2)).padding(.horizontal, 4) : nil)241        .contextMenu {242            Button("Modifier…") { scene.next.labelEdit = LabelEditRequest(label: label) }243            Button("Supprimer le libellé…", role: .destructive) { deletingLabel = label }244        }245        .accessibilityLabel(Text("Libellé \(label.name)"))246    }247248    @ViewBuilder private func savedSearchRow(_ saved: SavedSearch) -> some View {249        pick(.savedSearch(saved.id)) { Label(saved.name, systemImage: saved.pinned ? "pin" : "sparkle.magnifyingglass") }250            .contextMenu {251                Button("Renommer…") { folderName = saved.name; renamingSearch = saved }252                Button(saved.pinned ? L("Désépingler") : L("Épingler en tête")) { Task { await app.next.updateSavedSearch(saved, SavedSearchContent(pinned: !saved.pinned)) } }253                Button("Supprimer la recherche…", role: .destructive) { deletingSearch = saved }254            }255            .accessibilityLabel(Text("Recherche enregistrée \(saved.name)"))256    }257258    @ViewBuilder private var rows: some View {259        let next = app.next260        Section {261            AccountSwitcher(scene: scene)262                #if os(macOS)263                .selectionDisabled()264                #endif265                .listRowSeparator(.hidden)266            if next.has(.dashboard) { pick(.dashboard) { Label("Centre de commande", systemImage: "square.grid.2x2") } }267            if next.has(.contacts) { pick(.contacts) { Label("Contacts", systemImage: "person.2") } }268            if next.has(.attachments) { pick(.attachments) { Label("Pièces jointes", systemImage: "paperclip") } }269        }270        Section("Toutes les boîtes") {271            pick(.unified(.inbox)) { Label("Toutes les boîtes", systemImage: "tray.2").badge(app.totalInboxUnread) }272            pick(.unified(.unread)) { Label("Non lus", systemImage: "envelope.badge") }273            pick(.unified(.flagged)) { Label("Avec drapeau", systemImage: "flag") }274            pick(.unified(.drafts)) { Label("Brouillons", systemImage: "doc") }275            pick(.unified(.sent)) { Label("Envoyés", systemImage: "paperplane") }276            pick(.scheduled) { Label("Programmés", systemImage: "clock.badge") }277            if next.has(.snooze) { pick(.snoozed) { Label("En veille", systemImage: "clock").badge(next.snoozes.count) } }278            if next.has(.reminders) { pick(.followUps) { Label("Suivis", systemImage: "bell").badge(next.reminders.filter { $0.status == .due }.count) } }279            Button { scene.studioRequest += 1 } label: { Label("Modèles", systemImage: "rectangle.3.group").frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }280                .buttonStyle(.plain).help("Studio de modèles (⇧⌘M)").accessibilityHint(Text("Ouvre le studio de modèles"))281        }282        Section("Courrier") {283            let system = scene.mailboxes.filter { $0.knownRole != nil }284            if let inbox = system.first(where: { $0.knownRole == .inbox }) { row(inbox) }285            pick(.unread) { Label("Non lus", systemImage: "envelope.badge").badge(scene.unreadCount) }286            pick(.flagged) { Label("Avec drapeau", systemImage: "flag").badge(scene.flaggedCount) }287            ForEach(system.filter { $0.knownRole != .inbox }) { row($0) }288            pick(.outbox) { Label("Boîte d’envoi", systemImage: "arrow.up.circle").badge(app.outboxAttention) }289        }290        if next.has(.savedSearches), !next.savedSearches.isEmpty {291            Section("Recherches") { ForEach(next.savedSearches) { savedSearchRow($0) } }292        }293        if next.has(.labels) {294            Section("Libellés") {295                ForEach(next.labels) { labelRow($0) }296                Button { scene.next.labelEdit = LabelEditRequest(label: nil) } label: { Label("Nouveau libellé…", systemImage: "plus").frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }297                    .buttonStyle(.plain).foregroundStyle(SPColor.text2)298            }299        }300        Section("Dossiers") {301            ForEach(scene.customMailboxes.filter { !$0.isSnoozedFolder }) { m in302                row(m).contextMenu {303                    Button("Renommer…") { folderName = m.name; renaming = m }304                    Button("Supprimer le dossier…", role: .destructive) { deleting = m }305                }306            }307            Button { folderName = ""; newFolder = true } label: { Label("Nouveau dossier…", systemImage: "folder.badge.plus").frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()) }308                .buttonStyle(.plain).foregroundStyle(SPColor.text2)309        }310    }311312    var body: some View {313        list314        // translucent by default; opaque when transparency is reduced, and true black in the midnight theme315        .scrollContentBackground(opaque || midnight ? .hidden : .automatic)316        .background { if opaque || midnight { (midnight ? SPColor.bg : SPColor.surface2).ignoresSafeArea() } }317        .navigationTitle("SP Mail")318        .onChange(of: scene.selection) { _, _ in onPick() }319        .onChange(of: scene.newFolderRequest) { _, _ in folderName = ""; newFolder = true }320        .safeAreaInset(edge: .bottom, spacing: 0) {321            if app.sync.display != .synced {322                HStack { SyncIndicator(status: app.sync) { Task { await scene.refresh() } }; Spacer(minLength: 0) }323                    .padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.m)324            }325        }326        #if os(iOS)327        .toolbar {328            ToolbarItem(placement: .topBarLeading) { Button { scene.showSettings = true } label: { Label("Réglages", systemImage: "gearshape") } }329        }330        #endif331        .alert("Nouveau dossier", isPresented: $newFolder) {332            TextField("Nom", text: $folderName)333            Button("Créer") { let n = folderName; Task { await scene.createFolder(n) } }.disabled(folderName.trimmingCharacters(in: .whitespaces).isEmpty)334            Button("Annuler", role: .cancel) {}335        }336        .alert("Renommer le dossier", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {337            TextField("Nom", text: $folderName)338            Button("Renommer") { if let m = renaming { let n = folderName; Task { await scene.renameFolder(m.id, to: n) } } }339            Button("Annuler", role: .cancel) {}340        }341        .confirmationDialog("Supprimer ce libellé ?", isPresented: Binding(get: { deletingLabel != nil }, set: { if !$0 { deletingLabel = nil } }), titleVisibility: .visible, presenting: deletingLabel) { label in342            Button("Supprimer", role: .destructive) { Task { if scene.selection == .label(label.id) { scene.selection = scene.mailbox(.inbox).map { .mailbox($0.id) } }; await app.next.deleteLabel(label) } }343            Button("Annuler", role: .cancel) {}344        } message: { _ in Text("Les messages qui le portent ne sont ni déplacés ni supprimés.") }345        .alert("Renommer la recherche", isPresented: Binding(get: { renamingSearch != nil }, set: { if !$0 { renamingSearch = nil } })) {346            TextField("Nom", text: $folderName)347            Button("Renommer") { if let saved = renamingSearch { let n = folderName.trimmingCharacters(in: .whitespaces); if !n.isEmpty { Task { await app.next.updateSavedSearch(saved, SavedSearchContent(name: n)) } } } }348            Button("Annuler", role: .cancel) {}349        }350        .confirmationDialog("Supprimer cette recherche enregistrée ?", isPresented: Binding(get: { deletingSearch != nil }, set: { if !$0 { deletingSearch = nil } }), titleVisibility: .visible, presenting: deletingSearch) { saved in351            Button("Supprimer", role: .destructive) { Task { if scene.selection == .savedSearch(saved.id) { scene.selection = scene.mailbox(.inbox).map { .mailbox($0.id) } }; await app.next.deleteSavedSearch(saved) } }352            Button("Annuler", role: .cancel) {}353        }354        .confirmationDialog("Supprimer ce dossier et tous ses messages ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {355            Button("Supprimer", role: .destructive) { if let m = deleting { Task { await scene.deleteFolder(m.id) } } }356            Button("Annuler", role: .cancel) {}357        }358    }359}360361/// Message ids travel between the list and the sidebar as a tagged string (drag and drop to folders).362enum MailDrag {363    static let prefix = "spmail-messages:"364    static func payload(_ ids: Set<String>) -> String { prefix + ids.sorted().joined(separator: ",") }365    static func ids(from s: String) -> [String] { s.hasPrefix(prefix) ? s.dropFirst(prefix.count).split(separator: ",").map(String.init) : [] }366}367368/// A row dragged out of a list: the tagged ids for a folder of the sidebar, and the original message as an `.eml` file for the Finder369/// and other apps (downloaded on demand).370struct MessageDragItem: Transferable {371    let payload: String372    let email: EmailSummary373    let export: @Sendable (EmailSummary) async throws -> URL374    static var transferRepresentation: some TransferRepresentation {375        ProxyRepresentation(exporting: \.payload)376        FileRepresentation(exportedContentType: .emailMessage) { item in SentTransferredFile(try await item.export(item.email)) }377    }378}379
Files main
Menu

Theme