SPB Git

Repository Public

SyncIndicator.swift 12.7 KB 238 lines swift

1// SP Notes iOS2// File: Components/SyncIndicator.swift3// Description: The compact synchronisation state of the navigation bar and its detail sheet. The wording never claims more4//              than what happened: "Enregistré sur cet appareil" is not "Synchronisé".5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI1011/// What the indicator says, derived from the sync status, the network and the session (pure, tested).12struct SyncPresentation: Equatable {13    enum Kind: Equatable { case upToDate, syncing, offline, pending, conflict, error, sessionEnded }14    var kind: Kind15    var pending: Int16    var conflicts: Int17    /// 2.0: task operations the server refused for good (kept until retried or discarded).18    var rejected = 019    /// 2.0: queued actions written by a newer build, kept and not sent by this one.20    var unsupported = 021    /// 2.0: canvases whose two copies could not be merged automatically.22    var canvasConflicts = 02324    /// The 2.0 problems that need the user, said in one line each (empty when there are none).25    var attention: [String] {26        var lines: [String] = []27        if rejected > 0 { lines.append(rejected == 1 ? String(localized: "1 modification de tâche refusée par le serveur. Elle est conservée : ouvre Tâches pour réessayer ou l’abandonner.") : String(localized: "\(rejected) modifications de tâches refusées par le serveur. Elles sont conservées : ouvre Tâches pour réessayer ou les abandonner.")) }28        if canvasConflicts > 0 { lines.append(canvasConflicts == 1 ? String(localized: "1 canvas a changé à deux endroits. Les deux copies sont conservées.") : String(localized: "\(canvasConflicts) canvas ont changé à deux endroits. Les deux copies sont conservées.")) }29        if unsupported > 0 { lines.append(String(localized: "\(unsupported) action(s) en attente viennent d’une version plus récente de l’app. Elles sont conservées et partiront après la mise à jour.")) }30        return lines31    }3233    init(status: SyncStatus, isOnline: Bool, session: SessionState) {34        pending = status.pending35        conflicts = status.conflicts36        rejected = status.rejected37        unsupported = status.unsupported38        canvasConflicts = status.canvasConflicts39        if session != .signedIn || status.phase == .signedOut { kind = .sessionEnded }40        else if status.conflicts > 0 { kind = .conflict }41        else if !isOnline || status.phase == .offline { kind = .offline }42        else if status.phase == .syncing { kind = .syncing }43        else if case .failed = status.phase { kind = .error }44        else if status.rejected > 0 || status.canvasConflicts > 0 { kind = .conflict }45        else if status.pending > 0 { kind = .pending }46        else { kind = .upToDate }47    }4849    var label: String {50        switch kind {51        case .upToDate: return String(localized: "À jour")52        case .syncing: return String(localized: "Synchronisation…")53        case .offline: return String(localized: "Hors ligne")54        case .pending: return String(localized: "\(pending) en attente")55        case .conflict:56            if conflicts == 0 { return String(localized: "À vérifier") }57            return conflicts == 1 ? String(localized: "1 conflit") : String(localized: "\(conflicts) conflits")58        case .error: return String(localized: "Erreur de synchronisation")59        case .sessionEnded: return String(localized: "Session terminée")60        }61    }6263    /// One sentence saying where the notes are, honestly.64    var explanation: String {65        switch kind {66        case .upToDate: return String(localized: "Synchronisé : tes notes sont sur cet appareil et sur ton serveur.")67        case .syncing: return String(localized: "Synchronisation en cours avec ton serveur.")68        case .offline:69            return pending > 070                ? String(localized: "Enregistré sur cet appareil. \(pending) modification(s) partiront au retour du réseau.")71                : String(localized: "Hors ligne. Tes notes restent accessibles sur cet appareil.")72        case .pending: return String(localized: "Enregistré sur cet appareil. \(pending) modification(s) pas encore envoyée(s) au serveur.")73        case .conflict where conflicts == 0: return attention.first ?? ""74        case .conflict: return String(localized: "Une note a changé à deux endroits. Ta version est conservée sur cet appareil ; ouvre la note pour choisir.")75        case .error: return String(localized: "Enregistré sur cet appareil. Le dernier envoi au serveur a échoué ; une nouvelle tentative suivra.")76        case .sessionEnded: return String(localized: "Enregistré sur cet appareil seulement. Reconnecte-toi pour synchroniser.")77        }78    }7980    var symbol: String {81        switch kind {82        case .upToDate: return "checkmark.icloud"83        case .syncing: return "arrow.triangle.2.circlepath.icloud"84        case .offline: return "icloud.slash"85        case .pending: return "icloud.and.arrow.up"86        case .conflict: return "exclamationmark.triangle"87        case .error: return "exclamationmark.icloud"88        case .sessionEnded: return "person.crop.circle.badge.exclamationmark"89        }90    }9192    var tint: Color {93        switch kind {94        case .upToDate, .syncing: return .spTextSecondary95        case .offline, .pending: return .spMuted96        case .conflict, .sessionEnded: return .spWarning97        case .error: return .spDanger98        }99    }100}101102extension AppModel {103    var syncPresentation: SyncPresentation { SyncPresentation(status: syncStatus, isOnline: network.isOnline, session: session) }104}105106/// Navigation-bar button: the state as a symbol (and a count when something waits); opens the details.107struct SyncIndicator: View {108    @Environment(AppModel.self) private var app109    @Environment(ShellState.self) private var shell110111    var body: some View {112        let presentation = app.syncPresentation113        Button { shell.sheet = .syncDetails } label: {114            HStack(spacing: 4) {115                Image(systemName: presentation.symbol)116                    .symbolEffect(.pulse, isActive: presentation.kind == .syncing)117                if presentation.kind == .pending || (presentation.kind == .offline && presentation.pending > 0) {118                    Text(presentation.pending, format: .number).font(.footnote.weight(.semibold)).monospacedDigit()119                }120            }121            .foregroundStyle(presentation.tint)122            .frame(minWidth: 44, minHeight: 44)123            .contentShape(Rectangle())124        }125        .accessibilityLabel(Text("Synchronisation : \(presentation.label)"))126        .accessibilityIdentifier("sync-indicator")127    }128}129130/// The details behind the indicator.131struct SyncDetailsSheet: View {132    @Environment(AppModel.self) private var app133    @Environment(ShellState.self) private var shell134    @Environment(\.dismiss) private var dismiss135    @State private var conflicts: [ConflictRow] = []136    @State private var isSyncing = false137    @State private var signInFailure: SignInFailure?138139    struct ConflictRow: Identifiable { let id: String; var title: String; var detectedAt: Date }140141    var body: some View {142        let presentation = app.syncPresentation143        NavigationStack {144            List {145                Section {146                    HStack(alignment: .top, spacing: 14) {147                        Image(systemName: presentation.symbol).font(.title).foregroundStyle(presentation.tint).frame(width: 40)148                            .accessibilityHidden(true)149                        VStack(alignment: .leading, spacing: 4) {150                            Text(presentation.label).font(.headline).foregroundStyle(Color.spText)151                            Text(presentation.explanation).font(.subheadline).foregroundStyle(Color.spTextSecondary)152                            if case .failed(let reason) = app.syncStatus.phase {153                                Text(reason).font(.footnote).foregroundStyle(Color.spMuted)154                            }155                        }156                    }157                    .padding(.vertical, 4)158                    .accessibilityElement(children: .combine)159                }160                Section {161                    LabeledContent("Dernière synchronisation réussie") {162                        if let last = app.syncStatus.lastSuccess { Text(last, format: .relative(presentation: .named)) } else { Text("Jamais sur cet appareil") }163                    }164                    LabeledContent("En attente d’envoi") { Text(app.syncStatus.pending, format: .number) }165                    LabeledContent("Réseau") { Text(app.network.isOnline ? "En ligne" : "Hors ligne") }166                    if presentation.rejected > 0 { LabeledContent("Tâches refusées par le serveur") { Text(presentation.rejected, format: .number) }.accessibilityIdentifier("sync-rejected") }167                    if presentation.canvasConflicts > 0 { LabeledContent("Canvas en conflit") { Text(presentation.canvasConflicts, format: .number) } }168                    if presentation.unsupported > 0 { LabeledContent("Actions d’une version plus récente") { Text(presentation.unsupported, format: .number) } }169                } footer: {170                    if !presentation.attention.isEmpty { Text(presentation.attention.joined(separator: "\n")) }171                }172                if !conflicts.isEmpty {173                    Section("Conflits") {174                        ForEach(conflicts) { conflict in175                            Button {176                                dismiss()177                                shell.open(note: conflict.id)178                            } label: {179                                HStack {180                                    VStack(alignment: .leading, spacing: 2) {181                                        Text(conflict.title).foregroundStyle(Color.spText)182                                        Text("Détecté \(conflict.detectedAt.listLabel)").font(.footnote).foregroundStyle(Color.spTextSecondary)183                                    }184                                    Spacer()185                                    Image(systemName: "chevron.right").font(.footnote).foregroundStyle(Color.spMuted).accessibilityHidden(true)186                                }187                            }188                        }189                    }190                }191                Section {192                    if app.session == .signedIn {193                        Button {194                            Task { isSyncing = true; await app.syncAndWait(); isSyncing = false }195                        } label: {196                            HStack {197                                Label("Synchroniser maintenant", systemImage: "arrow.triangle.2.circlepath")198                                if isSyncing { Spacer(); ProgressView() }199                            }200                        }201                        .disabled(isSyncing || !app.network.isOnline)202                        .accessibilityIdentifier("sync-now")203                        if app.syncStatus.needsReauth {204                            Button {205                                Task { do { try await app.confirmPendingDeletions() } catch { signInFailure = SignInFailure(error) } }206                            } label: { Label("Confirmer les suppressions définitives", systemImage: "key") }207                            .disabled(!app.network.isOnline)208                        }209                    } else {210                        Button {211                            Task { do { try await app.signIn() } catch { signInFailure = SignInFailure(error) } }212                        } label: { Label("Se reconnecter avec une clé d’accès", systemImage: "person.badge.key") }213                    }214                } footer: {215                    if let message = signInFailure?.message { Text(message).foregroundStyle(Color.spDanger) }216                    else if needsReauthFooter { Text("Des suppressions définitives attendent ta confirmation avec ta clé d’accès.") }217                }218            }219            .navigationTitle("Synchronisation")220            .navigationBarTitleDisplayMode(.inline)221            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() } } }222            .task(id: app.feed.conflicts) { await loadConflicts() }223        }224        .presentationDetents([.medium, .large])225    }226227    private var needsReauthFooter: Bool { app.session == .signedIn && app.syncStatus.needsReauth }228229    private func loadConflicts() async {230        var rows: [ConflictRow] = []231        for record in (try? await app.store.conflicts()) ?? [] {232            let title = (try? await app.store.summary(id: record.pageId))?.title ?? record.server.title233            rows.append(ConflictRow(id: record.pageId, title: AppModel.displayTitle(title), detectedAt: record.detectedAt))234        }235        conflicts = rows236    }237}238
Files main
Menu

Theme