Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/VersionsTimeline.swift3// Description: The versions of a file as a timeline: who added each one and when, download, restore (which adds a version — history only grows), delete an old one, and compare any version with the current one: a line diff for text, Markdown, JSON and CSV; side by side for images and PDF; a plain statement of what differs for other formats.4import PDFKit5import SPDriveCore6import SPDriveNext7import SwiftUI89/// A line-based difference (longest common subsequence), for files of reasonable size.10enum LineDiff {11 enum Kind { case same, removed, added }12 struct Line: Identifiable { let id: Int; let kind: Kind; let text: String }13 static let maxLines = 400014 static func lines(_ a: String, _ b: String) -> [Line]? {15 let x = a.components(separatedBy: .newlines), y = b.components(separatedBy: .newlines)16 guard x.count <= maxLines, y.count <= maxLines else { return nil }17 var t = [[Int]](repeating: [Int](repeating: 0, count: y.count + 1), count: x.count + 1)18 if !x.isEmpty, !y.isEmpty { for i in stride(from: x.count - 1, through: 0, by: -1) { for j in stride(from: y.count - 1, through: 0, by: -1) { t[i][j] = x[i] == y[j] ? t[i + 1][j + 1] + 1 : max(t[i + 1][j], t[i][j + 1]) } } }19 var out: [Line] = [], i = 0, j = 0, n = 020 func add(_ k: Kind, _ s: String) { out.append(Line(id: n, kind: k, text: s)); n += 1 }21 while i < x.count, j < y.count {22 if x[i] == y[j] { add(.same, x[i]); i += 1; j += 1 }23 else if t[i + 1][j] >= t[i][j + 1] { add(.removed, x[i]); i += 1 }24 else { add(.added, y[j]); j += 1 }25 }26 while i < x.count { add(.removed, x[i]); i += 1 }27 while j < y.count { add(.added, y[j]); j += 1 }28 return out29 }30}3132struct VersionsTimeline: View {33 let model: AppModel34 let nav: Navigator35 let item: DriveItem36 @Environment(\.dismiss) private var dismiss37 @State private var list: Loadable<VersionList> = .loading38 @State private var compare: VersionInfo?39 @State private var busy = false40 @State private var note: String?41 @State private var confirmDelete: VersionInfo?4243 var body: some View {44 VStack(alignment: .leading, spacing: 0) {45 HStack(spacing: SPDTheme.Space.md) {46 ItemThumbnail(model: model, item: item, side: 30)47 VStack(alignment: .leading, spacing: 0) {48 Text("Versions de « \(item.name) »").font(SPDTheme.Typo.title).lineLimit(1).truncationMode(.middle)49 Text("Restaurer une version en crée une nouvelle : l’historique ne fait que grandir.").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary)50 }51 Spacer()52 Button("Terminé") { dismiss() }.keyboardShortcut(.cancelAction)53 }.padding(SPDTheme.Space.lg)54 Rectangle().fill(SPDTheme.hairline).frame(height: 1)55 HSplitView {56 timeline.frame(minWidth: 300, idealWidth: 330, maxWidth: 380)57 Group {58 if let v = compare, let current = list.value?.versions.first(where: \.current) { VersionCompare(model: model, item: item, old: v, current: current).id(v.id) }59 else { SPDEmptyState(symbol: "arrow.left.arrow.right", title: "Comparer", message: "Choisissez « Comparer » sur une version ancienne pour la voir à côté de la version actuelle.", width: 300) }60 }.frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity)61 }62 if let note { Label(note, systemImage: "exclamationmark.triangle").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.critical).padding(SPDTheme.Space.md) }63 }64 .frame(width: 940, height: 620).background(SPDTheme.surface)65 .task {66 await reload()67 #if SPD_DEV68 if UserDefaults.standard.bool(forKey: "spdCompare") { compare = list.value?.versions.first { !$0.current } } // visual checks69 #endif70 }71 .confirmationDialog("Supprimer la version \(confirmDelete?.seq ?? 0) ?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } })) {72 Button("Supprimer cette version", role: .destructive) { if let v = confirmDelete { Task { await delete(v) } } }73 Button("Annuler", role: .cancel) {}74 } message: { Text("Cette version sera effacée définitivement. Les autres versions et le fichier ne changent pas.") }75 .accessibilityIdentifier("versions-timeline")76 }77 @ViewBuilder private var timeline: some View {78 switch list {79 case .loading: ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)80 case .failed(let m): SPDEmptyState(symbol: "wifi.slash", title: "Historique indisponible", message: m, width: 260) { Button("Réessayer") { Task { await reload() } } }81 case .ready(let l):82 ScrollView {83 VStack(alignment: .leading, spacing: 0) {84 ForEach(Array(l.versions.enumerated()), id: \.element.id) { i, v in85 HStack(alignment: .top, spacing: SPDTheme.Space.md) {86 VStack(spacing: 0) {87 Circle().fill(v.current ? SPDTheme.brand : SPDTheme.surfaceRaised).overlay(Circle().strokeBorder(v.current ? SPDTheme.brand : SPDTheme.textTertiary, lineWidth: 1.5)).frame(width: 11, height: 11).padding(.top, 4)88 if i < l.versions.count - 1 { Rectangle().fill(SPDTheme.hairline).frame(width: 1.5).frame(maxHeight: .infinity) }89 }90 VStack(alignment: .leading, spacing: 3) {91 HStack(spacing: 6) { Text("Version \(v.seq)").font(SPDTheme.Typo.bodyStrong); if v.current { SPDPill(text: "Actuelle", tint: SPDTheme.brand) }; if compare?.id == v.id { SPDPill(text: "Comparée", symbol: "arrow.left.arrow.right") } }92 Text("\(Fmt.date(v.createdAt)) · \(Fmt.bytes(v.size))\(delta(v, l.versions))").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)93 Text(author(v) + ((v.note ?? "").isEmpty ? "" : " · \(note(v))")).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textTertiary)94 HStack(spacing: SPDTheme.Space.sm) {95 if !v.current { Button("Comparer") { compare = v }.accessibilityIdentifier("compare-\(v.seq)") ; Button("Restaurer") { Task { await restore(v) } }.disabled(busy) }96 Button { Task { if let d = try? await model.api?.fileDetails(item.id), let fv = d.versions.first(where: { $0.id == v.id }) { await model.download([item], version: fv) } } } label: { Image(systemName: "arrow.down.circle") }.help("Télécharger cette version").accessibilityLabel("Télécharger la version \(v.seq)")97 if !v.current { Button(role: .destructive) { confirmDelete = v } label: { Image(systemName: "trash") }.help("Supprimer cette version").accessibilityLabel("Supprimer la version \(v.seq)") }98 }.controlSize(.small).padding(.top, 2)99 }.padding(.bottom, SPDTheme.Space.lg)100 }101 }102 }.padding(SPDTheme.Space.lg)103 }104 }105 }106 private func author(_ v: VersionInfo) -> String { v.createdBy.map { $0.me == true ? "Par vous" : "Par \($0.displayName ?? "un membre")" } ?? "Reçue par un lien de dépôt" }107 private func note(_ v: VersionInfo) -> String {108 let n = v.note ?? ""109 if n.hasPrefix("restored from version "), let seq = Int(n.dropFirst("restored from version ".count)) { return "restauration de la version \(seq)" }110 return n111 }112 private func delta(_ v: VersionInfo, _ all: [VersionInfo]) -> String {113 guard let prev = all.first(where: { $0.seq == v.seq - 1 }) else { return "" }114 let d = v.size - prev.size115 return d == 0 ? (v.sha256 == prev.sha256 ? " · identique à la précédente" : " · même taille") : " · \(d > 0 ? "+" : "−")\(Fmt.bytes(abs(d)))"116 }117 private func reload() async {118 guard let next = model.next else { return }119 do { list = .ready(try await next.versions(of: item.id)); note = nil } catch { if list.value == nil { list = .failed(NextText.error(error)) } else { note = NextText.error(error) } }120 }121 private func restore(_ v: VersionInfo) async {122 guard let next = model.next else { return }123 busy = true; defer { busy = false }124 do { _ = try await next.restoreVersion(fileID: item.id, versionID: v.id); compare = nil; await model.syncNow(); await reload() } catch { note = NextText.error(error) }125 }126 private func delete(_ v: VersionInfo) async {127 do { try await model.api?.deleteVersion(fileID: item.id, versionID: v.id); if compare?.id == v.id { compare = nil }; await reload() } catch { note = DriveError.wrap(error).errorDescription }128 }129}130131/// An old version next to the current one.132struct VersionCompare: View {133 enum Mode { case text([LineDiff.Line]), images(NSImage, NSImage), pdf(PDFDocument, PDFDocument), statement(String) }134 let model: AppModel135 let item: DriveItem136 let old: VersionInfo137 let current: VersionInfo138 @State private var mode: Loadable<Mode> = .loading139 static let textExtensions: Set<String> = ["txt", "md", "markdown", "json", "csv", "tsv", "xml", "yaml", "yml", "html", "css", "js", "ts", "swift", "py", "sh", "log", "ini", "toml", "tex", "srt"]140 static let imageExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "heic", "tiff", "tif", "bmp", "webp"]141 static let maxBytes: Int64 = 40 * 1024 * 1024142143 var body: some View {144 VStack(alignment: .leading, spacing: 0) {145 HStack {146 Text("Version \(old.seq)").font(SPDTheme.Typo.bodyStrong); Text(Fmt.date(old.createdAt)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)147 Spacer(); Image(systemName: "arrow.right").foregroundStyle(SPDTheme.textTertiary); Spacer()148 Text("Version \(current.seq) (actuelle)").font(SPDTheme.Typo.bodyStrong); Text(Fmt.date(current.createdAt)).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)149 }.padding(SPDTheme.Space.md)150 Rectangle().fill(SPDTheme.hairline).frame(height: 1)151 switch mode {152 case .loading: ProgressView("Récupération des deux versions…").frame(maxWidth: .infinity, maxHeight: .infinity)153 case .failed(let m): SPDEmptyState(symbol: "exclamationmark.triangle", title: "Comparaison impossible", message: m, width: 320)154 case .ready(.statement(let s)): SPDEmptyState(symbol: "equal.circle", title: "Pas d’aperçu comparé", message: s, width: 340)155 case .ready(.text(let lines)):156 let added = lines.filter { $0.kind == .added }.count, removed = lines.filter { $0.kind == .removed }.count157 Text(added + removed == 0 ? "Aucune ligne ne diffère." : "\(added) ligne\(added > 1 ? "s" : "") ajoutée\(added > 1 ? "s" : ""), \(removed) retirée\(removed > 1 ? "s" : "")").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).padding(.horizontal, SPDTheme.Space.md).padding(.top, SPDTheme.Space.sm)158 .accessibilityIdentifier("diff-summary")159 ScrollView([.vertical, .horizontal]) {160 LazyVStack(alignment: .leading, spacing: 0) {161 ForEach(lines) { l in162 HStack(spacing: 6) {163 Text(l.kind == .added ? "+" : l.kind == .removed ? "−" : " ").frame(width: 12)164 Text(l.text.isEmpty ? " " : l.text).fixedSize(horizontal: true, vertical: false) // a line of a file is a line here: scroll sideways rather than wrap165 }166 .font(SPDTheme.Typo.mono).foregroundStyle(l.kind == .same ? SPDTheme.textSecondary : SPDTheme.textPrimary)167 .padding(.horizontal, SPDTheme.Space.sm).padding(.vertical, 1).frame(maxWidth: .infinity, alignment: .leading)168 .background(l.kind == .added ? SPDTheme.positive.opacity(0.14) : l.kind == .removed ? SPDTheme.critical.opacity(0.12) : .clear)169 .accessibilityLabel((l.kind == .added ? "Ajouté : " : l.kind == .removed ? "Retiré : " : "") + l.text)170 }171 }.padding(.vertical, SPDTheme.Space.sm).frame(minWidth: 480, maxWidth: .infinity, alignment: .leading)172 }.textSelection(.enabled).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)173 case .ready(.images(let a, let b)):174 HStack(spacing: SPDTheme.Space.md) { picture(a); picture(b) }.padding(SPDTheme.Space.md)175 case .ready(.pdf(let a, let b)):176 HStack(spacing: 1) { PDFPane(document: a); PDFPane(document: b) }177 }178 }179 .task { await load() }180 }181 private func picture(_ img: NSImage) -> some View {182 VStack(spacing: 4) {183 Image(nsImage: img).resizable().aspectRatio(contentMode: .fit).frame(maxWidth: .infinity, maxHeight: .infinity).background(SPDTheme.sunken, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.md))184 Text("\(Int(img.representations.first?.pixelsWide ?? Int(img.size.width))) × \(Int(img.representations.first?.pixelsHigh ?? Int(img.size.height))) px").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)185 }186 }187 private func load() async {188 guard let next = model.next else { return }189 let ext = item.fileExtension.lowercased()190 let facts = "Version \(old.seq) : \(Fmt.bytes(old.size)), empreinte \(old.sha256.prefix(12))…\nVersion \(current.seq) : \(Fmt.bytes(current.size)), empreinte \(current.sha256.prefix(12))…"191 if old.sha256 == current.sha256 { mode = .ready(.statement("Les deux versions ont exactement le même contenu (même empreinte SHA-256).")); return }192 let kind = VersionCompare.textExtensions.contains(ext) ? "text" : VersionCompare.imageExtensions.contains(ext) ? "image" : ext == "pdf" ? "pdf" : "other"193 guard kind != "other" else { mode = .ready(.statement("Ce format ne se compare pas visuellement. Les contenus diffèrent :\n\(facts)\nTéléchargez les deux versions pour les ouvrir dans leur application.")); return }194 guard max(old.size, current.size) <= VersionCompare.maxBytes else { mode = .ready(.statement("Versions trop volumineuses pour être comparées ici (plus de 40 Mo).\n\(facts)")); return }195 do {196 let dir = model.cacheDirectory.appendingPathComponent("versions/\(item.id)", isDirectory: true)197 func fetch(_ v: VersionInfo) async throws -> URL {198 let url = dir.appendingPathComponent("\(v.id).\(ext.isEmpty ? "bin" : ext)")199 if FileManager.default.fileExists(atPath: url.path) { return url }200 let sha = try await next.downloadVersion(fileID: item.id, versionID: v.id, to: url)201 guard sha == v.sha256 else { try? FileManager.default.removeItem(at: url); throw NextError.invalidResponse("empreinte différente") } // never show bytes that are not that version202 return url203 }204 let a = try await fetch(old), b = try await fetch(current)205 switch kind {206 case "text":207 guard let x = try? String(contentsOf: a, encoding: .utf8), let y = try? String(contentsOf: b, encoding: .utf8) else { mode = .ready(.statement("Ces versions ne sont pas du texte UTF-8 lisible.\n\(facts)")); return }208 if let lines = LineDiff.lines(x, y) { mode = .ready(.text(lines)) } else { mode = .ready(.statement("Fichier trop long pour une comparaison ligne à ligne (plus de \(LineDiff.maxLines) lignes).\n\(facts)")) }209 case "image":210 guard let x = NSImage(contentsOf: a), let y = NSImage(contentsOf: b) else { mode = .ready(.statement("Image illisible.\n\(facts)")); return }211 mode = .ready(.images(x, y))212 default:213 guard let x = PDFDocument(url: a), let y = PDFDocument(url: b) else { mode = .ready(.statement("PDF illisible ou protégé.\n\(facts)")); return }214 mode = .ready(.pdf(x, y))215 }216 } catch { mode = .failed(NextText.error(error)) }217 }218}219private struct PDFPane: NSViewRepresentable {220 let document: PDFDocument221 func makeNSView(context: Context) -> PDFView { let v = PDFView(); v.autoScales = true; v.displayMode = .singlePageContinuous; v.document = document; v.backgroundColor = .clear; return v }222 func updateNSView(_ v: PDFView, context: Context) { if v.document !== document { v.document = document } }223}224