Repository Public
1// SP Drive iOS2// File: Features/Conflicts/ConflictSheet.swift3// Description: Resolution of a version conflict, side by side: this device's version and the Drive's (date, size, preview when one can4// be shown), then three explicit choices — keep both, keep mine as a new version, keep the server's. Nothing is decided5// without the user, and the only choice that discards something asks again.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import QuickLook10import SwiftUI1112struct ConflictSheet: View {13 @Environment(AppModel.self) private var model14 @Environment(\.dismiss) private var dismiss15 @Environment(\.dynamicTypeSize) private var typeSize16 @Environment(\.horizontalSizeClass) private var sizeClass17 let conflict: ConflictRecord18 @State private var sides: ConflictSides?19 @State private var loading = true20 @State private var busy = false21 @State private var confirmDiscard = false22 @State private var previewURL: URL?23 @State private var localThumb: UIImage?24 @State private var serverThumb: UIImage?25 @State private var fetchingServerCopy = false2627 private var deleted: Bool { conflict.reason == .remoteDeleted }2829 var body: some View {30 NavigationStack {31 ScrollView {32 VStack(alignment: .leading, spacing: SPDTheme.Space.lg) {33 VStack(alignment: .leading, spacing: 6) {34 Text(conflict.name).font(SPDTheme.Typo.title).fixedSize(horizontal: false, vertical: true)35 Text(deleted ? "Tu as modifié ce fichier sur cet appareil pendant qu’il était supprimé sur le Drive. Tes modifications sont intactes."36 : "Ce fichier a été modifié sur cet appareil et ailleurs en même temps. Rien n’a été écrasé : les deux versions existent encore.")37 .font(SPDTheme.Typo.body).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)38 }39 if loading { ProgressView().frame(maxWidth: .infinity).padding() }40 else {41 let stacked = typeSize.isAccessibilitySize || sizeClass == .compact && typeSize >= .xxLarge42 let layout = stacked ? AnyLayout(VStackLayout(spacing: SPDTheme.Space.md)) : AnyLayout(HStackLayout(alignment: .top, spacing: SPDTheme.Space.md))43 layout {44 localCard45 serverCard46 }47 if sides?.serverReachable == false {48 Label("Le Drive est injoignable : la version du serveur affichée est la dernière connue de cet appareil. Les choix seront possibles au retour du réseau.", systemImage: "wifi.slash")49 .font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.Palette.warning).fixedSize(horizontal: false, vertical: true)50 }51 choices52 }53 }54 .padding(SPDTheme.Space.lg)55 }56 .background(SPDTheme.Palette.surface)57 .navigationTitle("Conflit de versions")58 .navigationBarTitleDisplayMode(.inline)59 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Plus tard") { dismiss() }.disabled(busy).accessibilityIdentifier("conflict.later") } }60 .quickLookPreview($previewURL)61 .confirmationDialog("Abandonner tes modifications ?", isPresented: $confirmDiscard, titleVisibility: .visible) {62 Button(deleted ? "Abandonner mes modifications" : "Abandonner ma version", role: .destructive) { resolve(.keepServer) }.accessibilityIdentifier("conflict.confirmDiscard")63 Button("Annuler", role: .cancel) {}64 } message: {65 Text("Les modifications faites sur cet appareil n’ont jamais été envoyées : elles seront effacées et ne pourront pas être récupérées.")66 }67 }68 .presentationDetents([.large])69 .interactiveDismissDisabled(busy)70 .task { await load() }71 .accessibilityIdentifier("conflictSheet")72 }7374 // MARK: The two versions7576 private var localCard: some View {77 versionCard(title: "Ma version", subtitle: "Sur cet appareil", symbol: "iphone", tint: SPDTheme.Palette.brand, thumb: localThumb,78 size: sides?.local?.size, date: sides?.local?.modifiedAt, extra: nil, id: "conflict.local",79 preview: sides?.local.map { local in { previewURL = local.url } })80 }8182 private var serverCard: some View {83 Group {84 if let server = sides?.server {85 versionCard(title: "Version du Drive", subtitle: "Sur le serveur", symbol: "icloud", tint: .teal, thumb: serverThumb,86 size: server.size, date: server.modifiedAt, extra: String(localized: "Version \(server.versionSeq)"), id: "conflict.server",87 preview: sides?.serverReachable == true ? { Task { await previewServer(server.item) } } : nil)88 } else {89 VStack(alignment: .leading, spacing: SPDTheme.Space.sm) {90 Label("Version du Drive", systemImage: "icloud.slash").font(SPDTheme.Typo.headline)91 Text("Supprimé sur le Drive").font(SPDTheme.Typo.body).foregroundStyle(.secondary)92 Text("Il n’y a plus de version sur le serveur.").font(SPDTheme.Typo.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)93 }94 .padding(SPDTheme.Space.md).frame(maxWidth: .infinity, alignment: .leading).spdCard()95 .accessibilityElement(children: .combine).accessibilityIdentifier("conflict.server")96 }97 }98 }99100 private func versionCard(title: LocalizedStringKey, subtitle: LocalizedStringKey, symbol: String, tint: Color, thumb: UIImage?, size: Int64?, date: Date?, extra: String?, id: String, preview: (() -> Void)?) -> some View {101 VStack(alignment: .leading, spacing: SPDTheme.Space.sm) {102 Label(title, systemImage: symbol).font(SPDTheme.Typo.headline).foregroundStyle(tint).accessibilityIdentifier(id)103 Color.clear.aspectRatio(4 / 3, contentMode: .fit)104 .overlay {105 if let thumb { Image(uiImage: thumb).resizable().scaledToFill() }106 else { ZStack { tint.opacity(0.1); Image(systemName: FileKind(extension: (conflict.name as NSString).pathExtension.lowercased()).symbol).font(.largeTitle).foregroundStyle(tint) } }107 }108 .clipShape(RoundedRectangle(cornerRadius: SPDTheme.Radius.md, style: .continuous))109 .accessibilityHidden(true)110 VStack(alignment: .leading, spacing: 2) {111 Text(subtitle).font(SPDTheme.Typo.caption).foregroundStyle(.secondary)112 Text(date.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? "—").font(SPDTheme.Typo.callout.weight(.medium)).fixedSize(horizontal: false, vertical: true)113 Text([size.map(\.byteString), extra].compactMap { $0 }.joined(separator: " · ")).font(SPDTheme.Typo.caption).foregroundStyle(.secondary).monospacedDigit()114 }115 .accessibilityElement(children: .combine)116 .accessibilityIdentifier("\(id).facts")117 if let preview {118 Button(action: preview) { Label("Aperçu", systemImage: "eye").frame(maxWidth: .infinity) }119 .buttonStyle(.bordered).disabled(fetchingServerCopy).accessibilityIdentifier("\(id).preview")120 }121 }122 .padding(SPDTheme.Space.md)123 .frame(maxWidth: .infinity, alignment: .leading)124 .spdCard()125 }126127 // MARK: Choices128129 private var choices: some View {130 VStack(alignment: .leading, spacing: SPDTheme.Space.md) {131 Text("Que veux-tu garder ?").font(SPDTheme.Typo.headline)132 if deleted {133 choice("Renvoyer comme nouveau fichier", "arrow.up.doc", note: "Ta version retourne sur le Drive comme un nouveau fichier.", prominent: true, id: "conflict.keepMine") { resolve(.keepMine) }134 choice("Abandonner mes modifications", "trash", note: "Le fichier reste supprimé ; ta copie locale est effacée.", destructive: true, id: "conflict.keepServer") { confirmDiscard = true }135 } else {136 choice("Garder les deux", "doc.on.doc", note: "Ta version devient un fichier à part, à côté de l’original, qui prend la version du Drive.", prominent: true, id: "conflict.keepBoth") { resolve(.keepBoth) }137 choice("Garder la mienne comme nouvelle version", "iphone", note: "Elle devient la version courante ; celle du Drive reste dans l’historique du fichier et peut être restaurée.", id: "conflict.keepMine") { resolve(.keepMine) }138 choice("Garder celle du Drive", "icloud", note: "Tes modifications faites ici sont abandonnées (confirmation demandée).", destructive: true, id: "conflict.keepServer") { confirmDiscard = true }139 }140 }141 .disabled(busy || sides?.serverReachable == false)142 }143144 private func choice(_ title: LocalizedStringKey, _ symbol: String, note: LocalizedStringKey, prominent: Bool = false, destructive: Bool = false, id: String, action: @escaping () -> Void) -> some View {145 VStack(alignment: .leading, spacing: 3) {146 Group {147 if prominent { Button(action: action) { Label(title, systemImage: symbol).frame(maxWidth: .infinity, minHeight: 30, alignment: .leading) }.buttonStyle(.borderedProminent) }148 else { Button(role: destructive ? .destructive : nil, action: action) { Label(title, systemImage: symbol).frame(maxWidth: .infinity, minHeight: 30, alignment: .leading) }.buttonStyle(.bordered) }149 }150 .accessibilityIdentifier(id)151 .accessibilityHint(Text(note))152 Text(note).font(SPDTheme.Typo.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)153 }154 }155156 // MARK: Work157158 private func load() async {159 sides = await model.engine.conflictSides(conflict.id)160 loading = false161 guard let sides else { dismiss(); return } // resolved elsewhere meanwhile162 let kind = FileKind(extension: (conflict.name as NSString).pathExtension.lowercased())163 if let local = sides.local {164 let url = local.url165 localThumb = await Task.detached { kind == .pdf ? ThumbnailLoader.pdfThumbnail(url) : kind == .image ? ThumbnailLoader.downsample(url) : nil }.value166 }167 if let server = sides.server, sides.serverReachable, server.item.hasThumbnail,168 let request = try? await model.api.thumbnailRequest(fileID: server.item.id), let data = try? await model.api.fetchSmall(request) {169 serverThumb = UIImage(data: data)170 }171 }172173 /// The Drive's version is fetched into a scratch file and verified; this device's edited copy is not touched.174 private func previewServer(_ item: DriveItem) async {175 fetchingServerCopy = true176 defer { fetchingServerCopy = false }177 await model.perform {178 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("SPDrive-conflict-\(item.id)-\(item.versionSeq)", isDirectory: true)179 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)180 let stem = (item.name as NSString).deletingPathExtension, ext = (item.name as NSString).pathExtension181 let url = dir.appendingPathComponent(LocalFiles.safeName("\(stem) (Drive)" + (ext.isEmpty ? "" : ".\(ext)")))182 if !IntegrityVerifier.verify(url, sha256: item.sha256) {183 try? FileManager.default.removeItem(at: url)184 try await DirectTransfer.download(item: item, api: model.api, to: url)185 }186 previewURL = url187 }188 }189190 private func resolve(_ choice: ConflictChoice) {191 busy = true192 let success: String193 switch (conflict.reason, choice) {194 case (.bothModified, .keepBoth): success = String(localized: "Les deux versions sont conservées")195 case (.bothModified, .keepMine): success = String(localized: "Ta version sera envoyée comme nouvelle version")196 case (.remoteDeleted, .keepBoth), (.remoteDeleted, .keepMine): success = String(localized: "Renvoyé comme nouveau fichier")197 case (.bothModified, .keepServer): success = String(localized: "Version du Drive conservée")198 case (.remoteDeleted, .keepServer): success = String(localized: "Modifications abandonnées")199 }200 Task {201 await model.perform(success: success) {202 try await model.engine.resolve(conflict.id, choice: choice, deviceName: AppConfiguration.deviceName)203 Haptics.success()204 dismiss()205 }206 busy = false207 }208 }209}210