SPB Git

Repository Public

NoteHistoryView.swift 14.6 KB 301 lines swift

1// SP Notes iOS2// File: Features/History/NoteHistoryView.swift3// Description: History of a note: the restore points kept on this device and, when online, the versions kept by the server4//              (conflict copies included, labelled as such). A version is shown read-only and can be restored or copied.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI10import UIKit1112/// Wording of the reasons stored with versions.13enum HistoryLabels {14    static func local(reason: String) -> String {15        switch reason {16        case "open": String(localized: "À l’ouverture de la note")17        case "autosave": String(localized: "Enregistrement automatique")18        case "before-restore": String(localized: "Avant une restauration")19        case "conflict-local": String(localized: "Ta version avant la résolution d’un conflit")20        default: reason21        }22    }2324    /// Server versions: copies set aside by a conflict have a negative number when they were never applied to the note.25    static func server(reason: String?, version: Int) -> String {26        let reason = reason ?? ""27        if reason.hasPrefix("conflict") {28            if version < 0 || reason.contains("not applied") { return String(localized: "Conflit · copie non appliquée (cet appareil)") }29            if reason.contains("other session") { return String(localized: "Conflit · copie d’une autre session") }30            return String(localized: "Copie de conflit")31        }32        if version < 0 { return String(localized: "Copie non appliquée") }33        switch reason {34        case "": return String(localized: "Version \(version)")35        case "restore", "restored": return String(localized: "Version \(version) · restauration")36        case "autosave", "edit": return String(localized: "Version \(version)")37        default: return String(localized: "Version \(version) · \(reason)")38        }39    }4041    static func isUnappliedCopy(reason: String?, version: Int) -> Bool { version < 0 || (reason ?? "").contains("not applied") }42}4344/// A version picked in the list.45enum HistoryEntry: Hashable {46    case local(id: String)47    case server(version: Int)48}4950struct NoteHistoryView: View {51    let noteId: String52    /// Saves the text being edited before the history is read or a version restored.53    var prepare: () async -> Void = {}5455    enum ServerState: Equatable {56        case loading57        case loaded([PageVersionSummary])58        case unavailable(String)59        case failed(String)60    }6162    @Environment(AppModel.self) private var app63    @Environment(\.dismiss) private var dismiss64    @State private var local: [LocalVersionInfo] = []65    @State private var server: ServerState = .loading66    @State private var loadedLocal = false6768    var body: some View {69        NavigationStack {70            List {71                Section {72                    if local.isEmpty && loadedLocal {73                        Text("Aucun point de restauration pour l’instant. Il s’en crée à l’ouverture de la note et pendant la rédaction.")74                            .font(.subheadline).foregroundStyle(Color.spTextSecondary)75                    }76                    ForEach(local) { version in77                        NavigationLink(value: HistoryEntry.local(id: version.id)) {78                            HistoryRow(title: HistoryLabels.local(reason: version.reason), date: version.createdAt, words: version.wordCount, noteTitle: version.title, flagged: false)79                        }80                        .accessibilityIdentifier("history-local-row")81                    }82                } header: { Text("Sur cet appareil") } footer: {83                    Text("Jusqu’à \(NotesStore.maxLocalVersionsPerPage) points de restauration par note, gardés sur l’appareil.")84                }85                Section {86                    switch server {87                    case .loading:88                        HStack(spacing: 10) { ProgressView(); Text("Chargement…").foregroundStyle(Color.spTextSecondary) }89                    case .unavailable(let message):90                        Label(message, systemImage: "icloud.slash").font(.subheadline).foregroundStyle(Color.spTextSecondary)91                    case .failed(let message):92                        VStack(alignment: .leading, spacing: 8) {93                            Label(message, systemImage: "exclamationmark.triangle").font(.subheadline).foregroundStyle(Color.spTextSecondary)94                            Button("Réessayer") { Task { await loadServer() } }95                        }96                    case .loaded(let versions):97                        if versions.isEmpty {98                            Text("Le serveur n’a pas encore de version antérieure de cette note.").font(.subheadline).foregroundStyle(Color.spTextSecondary)99                        }100                        ForEach(versions) { version in101                            NavigationLink(value: HistoryEntry.server(version: version.version)) {102                                HistoryRow(title: HistoryLabels.server(reason: version.reason, version: version.version), date: version.createdAt, words: version.wordCount,103                                           noteTitle: version.title, flagged: HistoryLabels.isUnappliedCopy(reason: version.reason, version: version.version))104                            }105                            .accessibilityIdentifier("history-server-row")106                        }107                    }108                } header: { Text("Sur le serveur") }109            }110            .listStyle(.insetGrouped)111            .scrollContentBackground(.hidden)112            .background(Color.spBackground)113            .navigationTitle("Historique")114            .navigationBarTitleDisplayMode(.inline)115            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("history-close") } }116            .navigationDestination(for: HistoryEntry.self) { entry in117                HistoryVersionView(noteId: noteId, entry: entry, prepare: prepare) { dismiss() }118            }119            .task {120                await prepare()121                await loadLocal()122                await loadServer()123            }124            .task(id: app.feed.any) { if loadedLocal { await loadLocal() } }125        }126        .accessibilityIdentifier("history-sheet")127    }128129    private func loadLocal() async {130        local = (try? await app.store.localVersions(pageId: noteId)) ?? []131        loadedLocal = true132    }133134    private func loadServer() async {135        guard app.session == .signedIn else { server = .unavailable(String(localized: "Connecte-toi pour voir les versions gardées par le serveur.")); return }136        guard app.network.isOnline else { server = .unavailable(String(localized: "Hors ligne : les versions du serveur ne sont pas disponibles.")); return }137        guard let page = try? await app.store.page(id: noteId), page.serverVersion > 0 else {138            server = .unavailable(String(localized: "Cette note n’a pas encore été synchronisée."))139            return140        }141        server = .loading142        do {143            server = .loaded(try await app.api.pageVersions(pageID: noteId))144        } catch let error as APIError {145            if error.isOffline { server = .unavailable(String(localized: "Hors ligne : les versions du serveur ne sont pas disponibles.")) }146            else if error.isUnauthenticated { server = .unavailable(String(localized: "Session terminée : connecte-toi pour voir les versions du serveur.")) }147            else { server = .failed(String(localized: "Les versions du serveur n’ont pas pu être chargées.")) }148        } catch {149            server = .failed(String(localized: "Les versions du serveur n’ont pas pu être chargées."))150        }151    }152}153154private struct HistoryRow: View {155    let title: String156    let date: Date157    let words: Int?158    let noteTitle: String159    let flagged: Bool160161    var body: some View {162        VStack(alignment: .leading, spacing: 3) {163            HStack(spacing: 6) {164                if flagged { Image(systemName: "exclamationmark.arrow.triangle.2.circlepath").foregroundStyle(Color.spWarning).accessibilityHidden(true) }165                Text(DocumentFacts.dateTime(date)).font(.body.weight(.medium)).foregroundStyle(Color.spText)166            }167            Text(title).font(.subheadline).foregroundStyle(flagged ? Color.spWarning : Color.spTextSecondary)168            Text([AppModel.displayTitle(noteTitle), words.map(DocumentFacts.words)].compactMap { $0 }.joined(separator: " · "))169                .font(.caption).foregroundStyle(Color.spMuted).lineLimit(1)170        }171        .padding(.vertical, 2)172        .accessibilityElement(children: .combine)173    }174}175176/// One version, read-only, with "Restaurer cette version" and "Copier le texte".177struct HistoryVersionView: View {178    let noteId: String179    let entry: HistoryEntry180    var prepare: () async -> Void181    var onRestored: () -> Void182183    struct Loaded: Equatable {184        var title: String185        var label: String186        var date: Date187        var content: Data188        var document: NoteDocument189        var words: Int190    }191    enum Phase: Equatable { case loading, loaded(Loaded), failed(String) }192193    @Environment(AppModel.self) private var app194    @State private var phase: Phase = .loading195    @State private var confirmsRestore = false196    @State private var isRestoring = false197    @State private var errorMessage: String?198    @State private var copied = false199200    var body: some View {201        Group {202            switch phase {203            case .loading:204                ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)205            case .failed(let message):206                EmptyStateView(symbol: "clock.badge.exclamationmark", title: "Version indisponible", message: LocalizedStringKey(message), actionTitle: "Réessayer") { Task { await load() } }207            case .loaded(let version):208                VStack(spacing: 0) {209                    VStack(alignment: .leading, spacing: 3) {210                        Text(AppModel.displayTitle(version.title)).font(.title3.weight(.bold)).foregroundStyle(Color.spText)211                        Text("\(DocumentFacts.dateTime(version.date)) · \(DocumentFacts.words(version.words))").font(.footnote).foregroundStyle(Color.spTextSecondary)212                        Text(version.label).font(.footnote).foregroundStyle(Color.spTextSecondary)213                    }214                    .frame(maxWidth: 760, alignment: .leading)215                    .frame(maxWidth: .infinity)216                    .padding(.horizontal, 18)217                    .padding(.vertical, 10)218                    Divider().overlay(Color.spBorder)219                    NativeDocumentView(document: version.document, identifier: "history-version-text")220                        .frame(maxWidth: 760)221                        .frame(maxWidth: .infinity)222                }223                .safeAreaInset(edge: .bottom, spacing: 0) { actions(version) }224            }225        }226        .background(Color.spBackground)227        .navigationTitle("Version")228        .navigationBarTitleDisplayMode(.inline)229        .task { await load() }230        .confirmationDialog("Restaurer cette version ?", isPresented: $confirmsRestore, titleVisibility: .visible) {231            Button("Restaurer") { Task { await restore() } }232            Button("Annuler", role: .cancel) {}233        } message: {234            Text("Le texte actuel est d’abord gardé comme point de restauration sur cet appareil, puis cette version devient la note et se synchronise.")235        }236        .alert("Restauration impossible", isPresented: Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })) {237            Button("OK", role: .cancel) {}238        } message: { Text(errorMessage ?? "") }239    }240241    private func actions(_ version: Loaded) -> some View {242        VStack(spacing: 10) {243            Button { confirmsRestore = true } label: {244                if isRestoring { ProgressView().tint(.white) } else { Text("Restaurer cette version") }245            }246            .buttonStyle(PrimaryButtonStyle())247            .disabled(isRestoring)248            .accessibilityIdentifier("history-restore")249            Button {250                UIPasteboard.general.string = version.document.plainText()251                copied = true252                Haptics.success()253            } label: { Label(copied ? "Texte copié" : "Copier le texte", systemImage: copied ? "checkmark" : "doc.on.doc").frame(maxWidth: .infinity, minHeight: 30) }254            .buttonStyle(.bordered)255            .accessibilityIdentifier("history-copy")256        }257        .padding(16)258        .frame(maxWidth: 760)259        .frame(maxWidth: .infinity)260        .background(.bar)261    }262263    private func load() async {264        phase = .loading265        do {266            switch entry {267            case .local(let id):268                guard let version = try await app.store.localVersion(id: id) else { phase = .failed(String(localized: "Ce point de restauration n’existe plus.")); return }269                let document = (try? NoteDocument(json: version.content)) ?? NoteDocument()270                phase = .loaded(Loaded(title: version.title, label: HistoryLabels.local(reason: version.reason), date: version.createdAt, content: version.content, document: document, words: version.wordCount))271            case .server(let number):272                let snapshot = try await app.api.pageVersion(pageID: noteId, version: number)273                let document = (try? NoteDocument(json: snapshot.content.data)) ?? NoteDocument()274                phase = .loaded(Loaded(title: snapshot.title, label: HistoryLabels.server(reason: snapshot.reason, version: snapshot.version), date: snapshot.createdAt,275                                       content: snapshot.content.data, document: document, words: snapshot.wordCount ?? document.wordCount))276            }277        } catch let error as APIError where error.isOffline {278            phase = .failed(String(localized: "Hors ligne : cette version est sur le serveur."))279        } catch {280            phase = .failed(String(localized: "Cette version n’a pas pu être chargée."))281        }282    }283284    private func restore() async {285        guard case .loaded(let version) = phase, !isRestoring else { return }286        isRestoring = true287        defer { isRestoring = false }288        await prepare()289        do {290            switch entry {291            case .local(let id): try await app.restoreLocalVersion(id)292            case .server: try await app.applyServerVersion(noteId: noteId, title: version.title, content: version.content)293            }294            Haptics.success()295            onRestored()296        } catch {297            errorMessage = error.localizedDescription298        }299    }300}301
Files main
Menu

Theme