SPB Git

Repository Public

SettingsScreen.swift 13.9 KB 277 lines swift

1// SP Notes iOS2// File: Features/Settings/SettingsScreen.swift3// Description: Settings: account and sign-out, security (app lock, passkeys, sessions), synchronisation, storage, appearance4//              and the about page. Only real options: nothing here pretends to configure what the app does not do.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI1011struct SettingsScreen: View {12    @Environment(AppModel.self) private var app13    @Environment(\.dismiss) private var dismiss14    @AppStorage("appearance") private var appearanceRaw = Appearance.system.rawValue15    @State private var showsSignOutChoice = false16    @State private var confirmErase = false17    @State private var isSigningIn = false18    @State private var isSyncing = false19    @State private var signInFailure: SignInFailure?20    @State private var storage = StorageFigures()21    @State private var isFreeing = false22    @State private var freedMessage: String?23    @State private var lockUnavailable = false2425    var body: some View {26        NavigationStack {27            Form {28                accountSection29                securitySection30                syncSection31                TaskNotificationsSettingsSection() // 2.0 — Features/Settings/TaskNotificationsSettings.swift32                storageSection33                Section("Apparence") {34                    Picker("Thème", selection: $appearanceRaw) {35                        ForEach(Appearance.allCases) { Text($0.label).tag($0.rawValue) }36                    }37                    .pickerStyle(.segmented)38                    .accessibilityIdentifier("appearance")39                }40                Section {41                    NavigationLink { AboutScreen() } label: { Label("À propos de SP Notes", systemImage: "info.circle") }42                        .accessibilityIdentifier("about")43                }44            }45            .navigationTitle("Réglages")46            .navigationBarTitleDisplayMode(.inline)47            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("settings-done") } }48            .task(id: app.feed.any) { storage = await StorageFigures.measure(app) }49            .confirmationDialog("Se déconnecter", isPresented: $showsSignOutChoice, titleVisibility: .visible) {50                Button("Garder les notes sur cet appareil") { Task { await app.signOut(erase: false) } }51                Button("Effacer les données de cet appareil", role: .destructive) { confirmErase = true }52                Button("Annuler", role: .cancel) {}53            } message: {54                Text("Tu peux garder tes notes ici pour continuer hors ligne, ou tout effacer de cet appareil.")55            }56            .alert("Effacer les données de cet appareil ?", isPresented: $confirmErase) {57                Button("Effacer", role: .destructive) { Task { await app.signOut(erase: true); dismiss() } }58                Button("Annuler", role: .cancel) {}59            } message: {60                Text(EraseWarning.message(pending: app.syncStatus.pending))61            }62        }63    }6465    // MARK: account6667    private var accountSection: some View {68        Section {69            LabeledContent("Propriétaire") { Text(app.ownerName ?? String(localized: "Pas encore connu")) }70            LabeledContent("Serveur") { Text(app.configuration.api.baseURL.host ?? app.configuration.api.baseURL.absoluteString) }71            LabeledContent("Session") {72                Text(app.session == .signedIn ? "Connecté" : "Terminée").foregroundStyle(app.session == .signedIn ? Color.spSuccess : Color.spWarning)73            }74            if app.session == .signedIn {75                Button("Se déconnecter", role: .destructive) { showsSignOutChoice = true }.accessibilityIdentifier("sign-out")76            } else {77                Button {78                    Task {79                        isSigningIn = true; signInFailure = nil80                        defer { isSigningIn = false }81                        do { try await app.signIn() } catch { signInFailure = SignInFailure(error) }82                    }83                } label: {84                    HStack { Text("Se connecter avec une clé d’accès"); if isSigningIn { Spacer(); ProgressView() } }85                }86                .disabled(isSigningIn)87                Button("Effacer les données de cet appareil", role: .destructive) { confirmErase = true }88            }89        } header: { Text("Compte") } footer: {90            if let message = signInFailure?.message { Text(message) }91            else if app.session != .signedIn { Text("Tes notes restent utilisables sur cet appareil. Elles ne sont plus synchronisées tant que tu n’es pas reconnecté.") }92        }93    }9495    // MARK: security9697    private var securitySection: some View {98        Section {99            if app.lock.canProtect {100                Toggle(isOn: Binding(get: { app.lock.isEnabled }, set: { wanted in101                    if wanted { Task { if await !app.lock.enable() { lockUnavailable = !app.lock.canProtect } } } else { Task { _ = await app.lock.disable() } }102                })) { Label("Verrouiller l’app", systemImage: app.lock.biometrySymbol) }103                .accessibilityIdentifier("lock-toggle")104                if app.lock.isEnabled {105                    Picker("Verrouiller après", selection: Binding(get: { app.lock.gracePeriod }, set: { app.lock.gracePeriod = $0 })) {106                        Text("Immédiatement").tag(TimeInterval(0))107                        Text("1 minute").tag(TimeInterval(60))108                        Text("5 minutes").tag(TimeInterval(300))109                        Text("15 minutes").tag(TimeInterval(900))110                    }111                }112            } else {113                Label("Verrouillage indisponible : cet appareil n’a pas de code. Définis-en un dans Réglages pour protéger SP Notes.", systemImage: "lock.slash")114                    .font(.subheadline).foregroundStyle(Color.spTextSecondary)115            }116            NavigationLink { PasskeysScreen() } label: { Label("Clés d’accès", systemImage: "person.badge.key") }.accessibilityIdentifier("passkeys")117            NavigationLink { SessionsScreen() } label: { Label("Sessions ouvertes", systemImage: "desktopcomputer.and.arrow.down") }.accessibilityIdentifier("sessions")118        } header: { Text("Sécurité") } footer: {119            if app.lock.canProtect {120                Text("Le verrouillage utilise \(app.lock.biometryName) sur cet appareil. Rien de biométrique ne quitte l’appareil. Le contenu est masqué dans le sélecteur d’apps quand il est activé.")121            }122        }123    }124125    // MARK: sync126127    private var syncSection: some View {128        let presentation = app.syncPresentation129        return Section {130            LabeledContent("État") { Label(presentation.label, systemImage: presentation.symbol).labelStyle(.titleAndIcon) }131            LabeledContent("En attente d’envoi") { Text(app.syncStatus.pending, format: .number) }132            LabeledContent("Dernière réussite") {133                if let last = app.syncStatus.lastSuccess { Text(last, format: .relative(presentation: .named)) } else { Text("Jamais") }134            }135            Button {136                Task { isSyncing = true; await app.syncAndWait(); isSyncing = false }137            } label: {138                HStack { Text("Synchroniser maintenant"); if isSyncing { Spacer(); ProgressView() } }139            }140            .disabled(isSyncing || app.session != .signedIn || !app.network.isOnline)141        } header: { Text("Synchronisation") } footer: {142            Text(presentation.explanation + " " + String(localized: "La synchronisation se fait seule, sur Wi-Fi comme sur réseau cellulaire."))143        }144    }145146    // MARK: storage147148    private var storageSection: some View {149        Section {150            LabeledContent("Notes") { Text(storage.notes, format: .number) }151            LabeledContent("Base de données") { Text(storage.database.map { $0.formatted(.byteCount(style: .file)) } ?? "—") }152            LabeledContent("Pièces jointes") { Text(storage.attachments.formatted(.byteCount(style: .file))) }153            Button {154                Task {155                    isFreeing = true156                    let freed = await app.evictDownloadedAttachments()157                    storage = await StorageFigures.measure(app)158                    freedMessage = freed.count == 0159                        ? String(localized: "Rien à libérer : aucune pièce jointe téléchargée ne peut être retirée sans risque.")160                        : String(localized: "\(freed.count) fichier(s) retiré(s) de cet appareil, \(freed.bytes.formatted(.byteCount(style: .file))) libérés. Ils restent sur le serveur.")161                    isFreeing = false162                }163            } label: {164                HStack { Text("Libérer de l’espace"); if isFreeing { Spacer(); ProgressView() } }165            }166            .disabled(isFreeing)167            .accessibilityIdentifier("free-space")168        } header: { Text("Stockage") } footer: {169            Text(freedMessage ?? String(localized: "Retire de cet appareil les pièces jointes déjà envoyées au serveur ; elles seront retéléchargées à la demande. Les notes et les fichiers pas encore envoyés ne sont jamais touchés."))170        }171    }172}173174enum EraseWarning {175    /// What erasing the device would lose, said plainly.176    static func message(pending: Int) -> String {177        let base = String(localized: "Toutes les notes et pièces jointes seront retirées de cet appareil. Ce qui est déjà sur le serveur y reste.")178        guard pending > 0 else { return base }179        let lost = pending == 1180            ? String(localized: "Attention : 1 modification n’a pas encore été synchronisée et sera perdue définitivement.")181            : String(localized: "Attention : \(pending) modifications n’ont pas encore été synchronisées et seront perdues définitivement.")182        return lost + " " + base183    }184}185186struct StorageFigures: Equatable {187    var notes = 0188    var database: Int64?189    var attachments: Int64 = 0190191    @MainActor static func measure(_ app: AppModel) async -> StorageFigures {192        var figures = StorageFigures()193        figures.notes = (try? await app.store.pageCount()) ?? 0194        let files = app.files195        let directory = app.configuration.dataDirectory196        let inMemory = app.configuration.inMemoryStore197        let sizes: (Int64?, Int64) = await Task.detached(priority: .utility) {198            var database: Int64?199            if !inMemory {200                var total: Int64 = 0201                for name in ["notes.sqlite", "notes.sqlite-wal", "notes.sqlite-shm"] {202                    let path = directory.appendingPathComponent(name).path203                    total += ((try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? NSNumber)?.int64Value ?? 0204                }205                database = total206            }207            return (database, files.totalSize())208        }.value209        figures.database = sizes.0210        figures.attachments = sizes.1211        return figures212    }213}214215extension AppModel {216    /// Removes from the device the attachment files that are safely on the server (not kept offline, not waiting for upload).217    func evictDownloadedAttachments() async -> (count: Int, bytes: Int64) {218        var count = 0219        var bytes: Int64 = 0220        var attempted = Set<String>()221        while true {222            let candidates = ((try? await store.evictionCandidates(limit: 100)) ?? []).filter { !attempted.contains($0.id) }223            guard !candidates.isEmpty else { break }224            for record in candidates {225                attempted.insert(record.id)226                guard let path = record.localPath else { continue }227                do {228                    try await store.markAttachmentEvicted(id: record.id)229                    files.remove(relativePath: path)230                    count += 1231                    bytes += record.size232                } catch { continue }233            }234        }235        return (count, bytes)236    }237}238239// MARK: - About240241struct AboutScreen: View {242    private var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "—" }243    private var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—" }244245    var body: some View {246        Form {247            Section {248                VStack(spacing: 10) {249                    BrandMark(size: 72)250                    Text("SP Notes").font(.title2.bold()).foregroundStyle(Color.spText)251                }252                .frame(maxWidth: .infinity)253                .padding(.vertical, 8)254                .listRowBackground(Color.clear)255            }256            Section {257                LabeledContent("Version", value: version)258                LabeledContent("Build", value: build)259                Button {260                    if let url = URL(string: "https://note.spboucher.ai") { UIApplication.shared.open(url) }261                } label: {262                    HStack { Text("note.spboucher.ai"); Spacer(); Image(systemName: "arrow.up.right").font(.footnote).accessibilityHidden(true) }263                }264                .accessibilityHint("S’ouvre dans le navigateur")265                .accessibilityIdentifier("website")266            }267            Section("Confidentialité") {268                Text("Tes notes sont stockées sur cet appareil et sur le serveur MacLustr du propriétaire, avec lequel l’app communique en HTTPS. Elles ne sont pas chiffrées de bout en bout : le serveur peut les lire, c’est ce qui permet la recherche et la synchronisation entre tes appareils. Les fonctions d’IA envoient le texte que tu sélectionnes aux fournisseurs d’IA configurés sur le serveur. Le verrouillage par Face ID ou Touch ID est local à cet appareil.")269                    .font(.subheadline).foregroundStyle(Color.spTextSecondary)270                    .accessibilityIdentifier("privacy-text")271            }272        }273        .navigationTitle("À propos")274        .navigationBarTitleDisplayMode(.inline)275    }276}277
Files main
Menu

Theme