SPB Git

Repository Public

SettingsView.swift 19.1 KB 299 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/SettingsView.swift3// Description: Settings — account, connected devices (remote revoke), passkeys, signatures per identity, appearance (theme, density, reading, swipe gestures),4// privacy, security (app lock) — and optional Spotlight indexing.5import SPMailCore6import SwiftUI78struct SettingsView: View {9    @Bindable var model: AppModel10    @State private var tab = SettingsView.initialTab1112    /// The pane shown first (a DEBUG launch argument picks another one for design captures).13    private static var initialTab: Int {14        #if DEBUG15        return UserDefaults.standard.integer(forKey: "spmSettingsTab")16        #else17        return 018        #endif19    }2021    var body: some View {22        #if os(macOS)23        TabView(selection: $tab) {24            AccountSettings(model: model).tabItem { Label("Comptes", systemImage: "person.crop.circle") }.tag(0)25            SignatureSettings(model: model).tabItem { Label("Signatures", systemImage: "signature") }.tag(1)26            ComposeSettingsPane(app: model).tabItem { Label("Rédaction", systemImage: "square.and.pencil") }.tag(9)27            AppearanceSettings(model: model).tabItem { Label("Apparence", systemImage: "paintbrush") }.tag(2)28            PrivacySettings(model: model).tabItem { Label("Confidentialité", systemImage: "hand.raised") }.tag(3)29            SecuritySettings(model: model).tabItem { Label("Sécurité", systemImage: "lock") }.tag(4)30            // SP Mail Next panes31            IntelligenceSettings(model: model).tabItem { Label("Intelligence", systemImage: "sparkles") }.tag(5)32            VacationSettings(model: model).tabItem { Label("Absence", systemImage: "airplane") }.tag(6)33            RulesSettings(model: model).tabItem { Label("Règles", systemImage: "line.3.horizontal.decrease.circle") }.tag(7)34            StorageSettings(model: model).tabItem { Label("Stockage", systemImage: "internaldrive") }.tag(8)35            NotificationSettings(model: model).tabItem { Label("Notifications", systemImage: "bell.badge") }.tag(10)36        }37        .frame(width: 760, height: 580)38        #else39        List {40            NavigationLink { AccountSettings(model: model).navigationTitle("Comptes et appareils") } label: { Label("Comptes et appareils", systemImage: "person.crop.circle") }41            NavigationLink { SignatureSettings(model: model).navigationTitle("Signatures") } label: { Label("Signatures", systemImage: "signature") }42            NavigationLink { ComposeSettings(app: model).navigationTitle("Rédaction") } label: { Label("Rédaction", systemImage: "square.and.pencil") }43            NavigationLink { AppearanceSettings(model: model).navigationTitle("Apparence") } label: { Label("Apparence", systemImage: "paintbrush") }44            NavigationLink { PrivacySettings(model: model).navigationTitle("Confidentialité") } label: { Label("Confidentialité", systemImage: "hand.raised") }45            NavigationLink { SecuritySettings(model: model).navigationTitle("Sécurité") } label: { Label("Sécurité", systemImage: "lock") }46            // SP Mail Next panes47            Section {48                NavigationLink { IntelligenceSettings(model: model).navigationTitle("Intelligence") } label: { Label("Intelligence", systemImage: "sparkles") }49                NavigationLink { VacationSettings(model: model).navigationTitle("Réponse automatique") } label: { Label("Réponse automatique", systemImage: "airplane") }50                NavigationLink { RulesSettings(model: model).navigationTitle("Filtres et règles") } label: { Label("Filtres et règles", systemImage: "line.3.horizontal.decrease.circle") }51                NavigationLink { StorageSettings(model: model).navigationTitle("Stockage") } label: { Label("Stockage", systemImage: "internaldrive") }52            }53            NavigationLink { NotificationSettings(model: model).navigationTitle("Notifications") } label: { Label("Notifications", systemImage: "bell.badge") }54        }55        .navigationTitle("Réglages")56        #endif57    }58}5960struct AccountSettings: View {61    @Bindable var model: AppModel62    @State private var sessions: [DeviceSession] = []63    @State private var passkeys: [PasskeyInfo] = []64    @State private var error: String?65    @State private var confirmSignOut = false66    @State private var revoking: DeviceSession?6768    var body: some View {69        Form {70            Section("Compte") {71                if let me = model.me {72                    LabeledContent("Utilisateur", value: "\(me.user.display_name) (\(me.user.handle))")73                    ForEach(model.accounts) { a in LabeledContent(a.display_name?.isEmpty == false ? a.display_name! : L("Boîte"), value: a.address) }74                    LabeledContent("Serveur", value: model.api.baseURL.host ?? "")75                }76                Button("Se déconnecter…", role: .destructive) { confirmSignOut = true }77            }78            Section {79                Link(destination: AppConfig.adminURL) { Label("Administration (web)", systemImage: "arrow.up.forward.app") }80                    .accessibilityHint(Text("Ouvre l’administration dans le navigateur"))81            } footer: {82                Text("Adresses et alias, clés d’API, approbations, webhooks et explorateur d’API se gèrent dans le navigateur.")83            }84            Section("Appareils connectés") {85                ForEach(sessions) { s in86                    HStack {87                        Image(systemName: s.kind == "native" ? "laptopcomputer.and.iphone" : "globe").foregroundStyle(.secondary)88                        VStack(alignment: .leading) {89                            Text(s.device_name?.isEmpty == false ? s.device_name! : (s.kind == "native" ? L("App") : L("Navigateur"))) + Text(s.current ? L(" — cet appareil") : "").foregroundStyle(.secondary)90                            Text([s.platform, s.ip, s.lastSeenAt.map { L("vu ") + $0.formatted(date: .abbreviated, time: .shortened) }].compactMap { $0 }.joined(separator: " · ")).font(.footnote).foregroundStyle(.secondary)91                        }92                        Spacer()93                        if !s.current { Button("Révoquer", role: .destructive) { revoking = s } }94                    }95                }96                if sessions.isEmpty { Text("Liste indisponible hors ligne").foregroundStyle(.secondary) }97            }98            Section("Clés d’accès") {99                ForEach(passkeys) { p in100                    LabeledContent(p.label ?? "Passkey", value: [p.backed_up == true ? L("synchronisée") : L("cet appareil seulement"), ISO8601DateFormatter().date(from: p.created_at ?? "").map { $0.formatted(date: .abbreviated, time: .omitted) }].compactMap { $0 }.joined(separator: " · "))101                }102                Button("Ajouter une clé d’accès sur cet appareil") {103                    Task {104                        do { try await model.addPasskey(label: AppConfig.clientInfo.deviceName); await load() } catch { self.error = model.describe(error) }105                    }106                }107            }108            Section("Notifications poussées") {109                LabeledContent("Jeton APNs", value: model.pushStatus)110                Text("Le serveur n’envoie pas encore de notifications poussées. Les nouveaux messages sont signalés quand l’app est ouverte ou lors d’une actualisation en arrière-plan.").font(.footnote).foregroundStyle(.secondary)111            }112            if let error { Section { Text(error).foregroundStyle(.red) } }113        }114        .formStyle(.grouped)115        .task { await load() }116        .confirmationDialog("Se déconnecter de cet appareil ?", isPresented: $confirmSignOut, titleVisibility: .visible) {117            Button("Se déconnecter et effacer le cache local", role: .destructive) { Task { await model.signOut() } }118            Button("Annuler", role: .cancel) {}119        } message: { Text("La session est révoquée sur le serveur. Les messages restent sur le serveur ; les brouillons non synchronisés de cet appareil sont effacés.") }120        .confirmationDialog("Révoquer cet appareil ?", isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }), titleVisibility: .visible, presenting: revoking) { s in121            Button("Révoquer", role: .destructive) { Task { do { try await model.api.revokeSession(id: s.id); await load() } catch { self.error = model.describe(error) } } }122            Button("Annuler", role: .cancel) {}123        } message: { _ in Text("Cet appareil devra se reconnecter avec une clé d’accès.") }124    }125126    private func load() async {127        do {128            sessions = try await model.api.sessions()129            passkeys = try await model.api.passkeys()130            error = nil131        } catch let e as APIError where e.isOffline { sessions = []; passkeys = [] } catch { self.error = model.describe(error) }132    }133}134135struct SignatureSettings: View {136    @Bindable var model: AppModel137    @State private var account = ""138    @State private var identities: [Identity] = []139    @State private var status = ""140141    var body: some View {142        Form {143            if model.accounts.count > 1 {144                Picker("Boîte", selection: $account) { ForEach(model.accounts) { Text($0.address).tag($0.id) } }145            }146            ForEach($identities) { $identity in147                Section(identity.email) {148                    TextField("Nom affiché", text: $identity.name)149                    VStack(alignment: .leading) {150                        Text("Signature").font(.subheadline).foregroundStyle(.secondary)151                        TextEditor(text: $identity.textSignature).frame(minHeight: 90).font(.body).accessibilityLabel(Text("Signature de \(identity.email)"))152                    }153                    Button("Enregistrer") { Task { await save(identity) } }154                }155            }156            if identities.isEmpty { Text("Identités indisponibles hors ligne").foregroundStyle(.secondary) }157            if !status.isEmpty { Text(status).foregroundStyle(.secondary) }158        }159        .formStyle(.grouped)160        .task { account = model.currentAccount ?? ""; await load() }161        .onChange(of: account) { _, _ in Task { await load() } }162    }163164    private func load() async { identities = (try? await model.engines[account]?.identities(refresh: model.isOnline)) ?? [] }165    private func save(_ identity: Identity) async {166        var i = identity167        i.htmlSignature = i.textSignature.isEmpty ? "" : HTMLText.html(fromPlain: i.textSignature)168        do { try await model.engines[account]?.updateIdentity(i); status = L("Signature enregistrée sur le serveur") } catch { status = model.describe(error) ?? "" }169    }170}171172struct AppearanceSettings: View {173    @Bindable var model: AppModel174    var body: some View {175        @Bindable var s = model.settings176        Form {177            Section("Thème") {178                Picker("Thème", selection: $s.theme) { ForEach(SPTheme.allCases) { Text($0.title).tag($0) } }179                    #if os(iOS)180                    .pickerStyle(.segmented)181                    #endif182                Text("« Minuit » est un thème sombre à fond noir véritable, pour les écrans OLED et la lecture de nuit.").font(.footnote).foregroundStyle(.secondary)183                Toggle("Réduire la transparence", isOn: $s.reduceTransparency)184                Text("Les barres et panneaux deviennent opaques. Le réglage du système « Réduire la transparence » est toujours respecté.").font(.footnote).foregroundStyle(.secondary)185            }186            Section("Liste des messages") {187                Picker("Densité", selection: $s.density) { ForEach(Density.allCases) { Text($0.title).tag($0) } }188                Picker("Lignes d’aperçu", selection: $s.previewLines) { Text("Aucune").tag(0); Text("1").tag(1); Text("2").tag(2) }189                Toggle("Afficher les avatars", isOn: $s.showAvatars)190                Toggle("Regrouper par conversation", isOn: $s.threaded).onChange(of: s.threaded) { _, _ in Task { for scene in model.scenes { await scene.reloadThreads() } } }191                ConversationRow(data: .sample, style: RowStyle(s)).padding(.horizontal, SPSpacing.m)192                    .background(SPColor.bg, in: RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))193                    .accessibilityHidden(true)194            }195            Section("Lecture") {196                Picker("Police de lecture", selection: $s.readingFont) { ForEach(ReadingFont.allCases) { Text($0.title).tag($0) } }197                Stepper("Taille du texte des messages : \(s.bodyFontSize)", value: $s.bodyFontSize, in: 12...24)198                #if os(iOS)199                Text("La taille suit aussi le réglage « Taille du texte » du système.").font(.footnote).foregroundStyle(.secondary)200                #endif201                Toggle("Lecture sombre des messages", isOn: $s.darkReading)202                Text("Dans les thèmes sombres, le contenu HTML d’un message reste sur une feuille blanche, comme son auteur l’a conçu. Activez cette option pour l’afficher sur fond sombre ; chaque message garde un bouton pour basculer.").font(.footnote).foregroundStyle(.secondary)203                Toggle("Marquer comme lu à l’ouverture", isOn: $s.markReadOnOpen)204            }205            #if os(iOS)206            Section {207                swipePicker("Balayage vers la droite — 1", $s.swipeLeading, 0)208                swipePicker("Balayage vers la droite — 2", $s.swipeLeading, 1)209                swipePicker("Balayage vers la gauche — 1", $s.swipeTrailing, 0)210                swipePicker("Balayage vers la gauche — 2", $s.swipeTrailing, 1)211                swipePicker("Balayage vers la gauche — 3", $s.swipeTrailing, 2)212                Button("Rétablir les gestes par défaut") { s.swipeLeading = AppSettings.defaultSwipeLeading; s.swipeTrailing = AppSettings.defaultSwipeTrailing }213            } header: { Text("Gestes de balayage") } footer: { Text("Un balayage complet déclenche la première action de son côté.") }214            #else215            Section("Barre des menus") {216                Toggle("Afficher SP Mail dans la barre des menus", isOn: $s.showMenuBarExtra)217            }218            #endif219        }.formStyle(.grouped)220    }221222    #if os(iOS)223    /// One swipe slot; « Aucune » shortens the list of actions of that side.224    private func swipePicker(_ title: LocalizedStringKey, _ list: Binding<[SwipeAction]>, _ index: Int) -> some View {225        Picker(title, selection: Binding(get: { list.wrappedValue.indices.contains(index) ? list.wrappedValue[index] : .none }, set: { new in226            var v = list.wrappedValue227            while v.count <= index { v.append(.none) }228            v[index] = new229            // « none » in the middle would leave a hole: keep the chosen actions, in order, without duplicates230            var seen = Set<SwipeAction>()231            list.wrappedValue = v.filter { $0 != .none && seen.insert($0).inserted }232        })) { ForEach(SwipeAction.allCases) { Label($0.title, systemImage: $0.icon).tag($0) } }233    }234    #endif235}236237extension ConversationRowData {238    /// The sample row of the Appearance pane.239    @MainActor static var sample: ConversationRowData {240        var d = ConversationRowData(row: ThreadSummary(email: EmailSummary(id: "sample", threadId: "sample", mailboxIds: [], keywords: [], receivedAt: Date(),241                                                                         from: [EmailAddress(name: "Camille Tremblay", email: "camille@example.org")],242                                                                         subject: L("Compte rendu de la réunion"), hasAttachment: true,243                                                                         preview: L("Bonjour, voici le compte rendu et les prochaines étapes. La version finale suivra demain.")), count: 3, unreadCount: 1, anyFlagged: true), showRecipients: false)244        d.labels = [4]245        return d246    }247}248249struct PrivacySettings: View {250    @Bindable var model: AppModel251    var body: some View {252        @Bindable var s = model.settings253        Form {254            Section("Images distantes") {255                Text("Les images distantes ne sont jamais chargées automatiquement. « Afficher les images » les fait venir par le serveur SP Mail, message par message : l’expéditeur ne voit ni votre adresse IP ni votre appareil.").font(.callout).foregroundStyle(.secondary)256            }257            Section("Notifications") {258                Toggle("Signaler les nouveaux messages", isOn: $s.notificationsEnabled)259                Toggle("Suspendre les notifications", isOn: $s.notificationsPaused).disabled(!s.notificationsEnabled)260                Toggle("Masquer l’expéditeur et l’objet dans les notifications", isOn: $s.hideNotificationContent)261                Text("Quand SP Mail est verrouillé, les notifications ne montrent jamais l’expéditeur ni l’objet.").font(.footnote).foregroundStyle(.secondary)262            }263            #if os(iOS)264            Section("Sélecteur d’apps") {265                Toggle("Masquer le contenu dans le sélecteur d’apps", isOn: $s.hideInAppSwitcher)266                Text("Le contenu est aussi masqué dès que le verrouillage de l’app est activé.").font(.footnote).foregroundStyle(.secondary)267            }268            #endif269            Section("Spotlight") {270                Toggle("Indexer les objets et les expéditeurs dans Spotlight", isOn: $s.spotlightEnabled).onChange(of: s.spotlightEnabled) { _, on in if !on { Spotlight.removeAll() } }271                Text("Désactivé par défaut. Le contenu des messages n’est jamais indexé.").font(.footnote).foregroundStyle(.secondary)272            }273            Section("Stockage local") {274                Text("Le contenu et les aperçus des messages, les brouillons et les pièces jointes en attente sont chiffrés sur cet appareil (AES-GCM, clé dans le trousseau). Les objets, adresses et dates servent à la recherche hors ligne et restent dans le conteneur protégé de l’app.").font(.callout).foregroundStyle(.secondary)275            }276        }.formStyle(.grouped)277    }278}279280struct SecuritySettings: View {281    @Bindable var model: AppModel282    var body: some View {283        @Bindable var s = model.settings284        Form {285            Section("Verrouillage de l’app") {286                Toggle("Exiger \(AppLock.biometryName) pour ouvrir SP Mail", isOn: $s.lockEnabled).disabled(!AppLock.isAvailable)287                Picker("Verrouiller après", selection: $s.lockAfterMinutes) {288                    Text("Dès la sortie de l’app").tag(0); Text("1 minute").tag(1); Text("5 minutes").tag(5); Text("15 minutes").tag(15); Text("1 heure").tag(60)289                }.disabled(!s.lockEnabled)290                Button("Verrouiller maintenant") { model.lockIfNeeded(force: true) }.disabled(!s.lockEnabled)291                if !AppLock.isAvailable { Text("Aucune méthode d’authentification n’est configurée sur cet appareil.").font(.footnote).foregroundStyle(.secondary) }292            }293            Section("Session") {294                Text("Le jeton de cet appareil est conservé dans le trousseau (jamais dans les préférences ni les journaux). Il peut être révoqué depuis un autre appareil dans « Appareils connectés ».").font(.callout).foregroundStyle(.secondary)295            }296        }.formStyle(.grouped)297    }298}299
Files main
Menu

Theme