SPB Git

Repository Public

ConflictSheet.swift 9.1 KB 140 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Transfers/ConflictSheet.swift3// Description: Settling a version conflict: this Mac's version and the server's side by side (dates, sizes, pictures, Quick Look), and three explicit choices — keep both, keep mine as a new version, keep the server's. Whatever is set aside stays recoverable; nothing is ever overwritten silently.4import SPDriveCore5import SPDriveSync6import SwiftUI78struct ConflictSheet: View {9    let model: AppModel10    let nav: Navigator11    let conflict: SyncConflict12    @Environment(\.dismiss) private var dismiss13    @State private var mine: DriveItem?14    @State private var server: DriveItem?15    @State private var loaded = false16    @State private var busy: AppModel.ConflictDecision?17    @State private var note: String?1819    var body: some View {20        VStack(alignment: .leading, spacing: 0) {21            VStack(alignment: .leading, spacing: SPDTheme.Space.xs) {22                Label("Conflit de versions", systemImage: "exclamationmark.triangle.fill").font(SPDTheme.Typo.caption.weight(.semibold)).foregroundStyle(SPDTheme.warning).textCase(.uppercase)23                Text("Deux versions de « \(conflict.itemName) »").font(SPDTheme.Typo.title).lineLimit(2)24                Text("Ce fichier a été modifié sur ce Mac pendant qu’un autre appareil le modifiait aussi. SP Drive a gardé les deux : choisissez laquelle doit porter le nom d’origine.")25                    .font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).fixedSize(horizontal: false, vertical: true)26            }27            .padding([.horizontal, .top], SPDTheme.Space.xl).padding(.bottom, SPDTheme.Space.lg)28            HStack(alignment: .top, spacing: SPDTheme.Space.lg) {29                side("Sur ce Mac", "laptopcomputer", mine, other: server, missing: "La copie de ce Mac n’existe plus sur SP Drive.", id: "conflict-mine")30                side("Sur le serveur", "server.rack", server, other: mine, missing: "Le fichier d’origine n’existe plus sur SP Drive.", id: "conflict-server")31            }32            .padding(.horizontal, SPDTheme.Space.xl)33            if let mine, let server, mine.sha256 == server.sha256, !mine.sha256.isEmpty {34                Label("Les deux versions ont exactement le même contenu (même empreinte SHA-256).", systemImage: "equal.circle").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).padding(.horizontal, SPDTheme.Space.xl).padding(.top, SPDTheme.Space.md)35            }36            if let note { Label(note, systemImage: "exclamationmark.circle").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.critical).padding(.horizontal, SPDTheme.Space.xl).padding(.top, SPDTheme.Space.md) }37            Spacer(minLength: SPDTheme.Space.lg)38            Rectangle().fill(SPDTheme.hairline).frame(height: 1)39            HStack(alignment: .top, spacing: SPDTheme.Space.md) {40                choice(.keepBoth, "Garder les deux", "Les deux fichiers restent côte à côte dans le dossier.", prominent: false, enabled: true)41                choice(.mineAsVersion, "Garder la mienne", "Elle devient la nouvelle version du fichier ; celle du serveur reste dans l’historique des versions.", prominent: true, enabled: mine != nil)42                choice(.server, "Garder celle du serveur", "La copie de ce Mac va à la corbeille de SP Drive, d’où elle reste récupérable.", prominent: false, enabled: server != nil)43            }44            .padding(SPDTheme.Space.lg)45            .disabled(busy != nil || !loaded)46            HStack {47                Text("Rien n’est jamais remplacé en silence : si le fichier change encore pendant votre choix, SP Drive s’arrête et vous le dit.").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textTertiary)48                Spacer()49                Button("Plus tard") { dismiss() }.keyboardShortcut(.cancelAction)50            }51            .padding(.horizontal, SPDTheme.Space.lg).padding(.bottom, SPDTheme.Space.lg)52        }53        .frame(width: 720, height: 640)54        .background(SPDTheme.surface)55        .task { await load() }56        .accessibilityIdentifier("conflict-sheet")57    }5859    private func side(_ title: String, _ symbol: String, _ item: DriveItem?, other: DriveItem?, missing: String, id: String) -> some View {60        VStack(alignment: .leading, spacing: SPDTheme.Space.md) {61            HStack {62                Label(title, systemImage: symbol).spdEyebrow()63                Spacer()64                if let item, let other, item.contentAt > other.contentAt { SPDPill(text: "Plus récente", symbol: "clock", tint: SPDTheme.brand) }65            }66            if let item {67                ConflictPreview(model: model, item: item)68                Text(item.name).font(SPDTheme.Typo.bodyStrong).lineLimit(2).truncationMode(.middle)69                VStack(alignment: .leading, spacing: 4) {70                    fact("Modifié", Fmt.date(item.contentAt))71                    fact("Taille", Fmt.bytes(item.size) + (other.map { o in o.size == item.size ? "" : " (\(item.size > o.size ? "+" : "−")\(Fmt.bytes(abs(item.size - o.size))))" } ?? ""))72                    fact("Version", "v\(item.versionSeq)")73                    fact("Empreinte", String(item.sha256.prefix(12)) + "…")74                }75                Button("Coup d’œil", systemImage: "eye") { Task { if let url = try? await model.localCopy(of: item, inContainer: true) { QuickLookCoordinator.shared.onKey = nil; QuickLookCoordinator.shared.show(url: url, itemID: "conflict-\(item.id)") } } }.controlSize(.small)76            } else if loaded {77                Label(missing, systemImage: "questionmark.folder").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary).frame(maxWidth: .infinity, minHeight: 200, alignment: .center)78            } else { ProgressView().frame(maxWidth: .infinity, minHeight: 200) }79        }80        .frame(maxWidth: .infinity, alignment: .leading)81        .spdCard()82        .accessibilityElement(children: .contain).accessibilityIdentifier(id)83    }84    private func fact(_ label: String, _ value: String) -> some View {85        HStack(alignment: .firstTextBaseline) { Text(label).foregroundStyle(SPDTheme.textSecondary).frame(width: 70, alignment: .leading); Text(value).monospacedDigit().textSelection(.enabled) }.font(SPDTheme.Typo.callout)86    }87    private func choice(_ d: AppModel.ConflictDecision, _ title: String, _ caption: String, prominent: Bool, enabled: Bool) -> some View {88        VStack(alignment: .leading, spacing: SPDTheme.Space.xs) {89            Group {90                if prominent { Button { settle(d) } label: { label(d, title) }.buttonStyle(.borderedProminent) }91                else { Button { settle(d) } label: { label(d, title) }.buttonStyle(.bordered) }92            }93            .controlSize(.large).disabled(!enabled)94            Text(caption).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).fixedSize(horizontal: false, vertical: true)95        }96        .frame(maxWidth: .infinity, alignment: .leading)97    }98    private func label(_ d: AppModel.ConflictDecision, _ title: String) -> some View {99        HStack { if busy == d { ProgressView().controlSize(.small) }; Text(title) }.frame(maxWidth: .infinity)100    }101    private func settle(_ d: AppModel.ConflictDecision) {102        busy = d; note = nil103        Task {104            let ok = await model.resolve(conflict, d)105            busy = nil106            if ok { dismiss() } else { note = "Le choix n’a pas pu être appliqué. Les deux versions sont toujours là."; await load() }107        }108    }109    /// Both sides as the server describes them now (the mirror when it cannot be reached).110    private func load() async {111        func fetch(_ id: String?) async -> DriveItem? {112            guard let id else { return nil }113            if let api = model.api, let fresh = try? await api.item(id, kind: .file) { return fresh.isTrashed ? nil : fresh }114            return model.item(id).flatMap { $0.isTrashed ? nil : $0 }115        }116        mine = await fetch(conflict.copyID); server = await fetch(conflict.itemID); loaded = true117    }118}119120/// A picture of one side: the server's thumbnail, or a Quick Look thumbnail of a verified copy fetched for the comparison (files up to 30 MB).121private struct ConflictPreview: View {122    let model: AppModel123    let item: DriveItem124    @State private var image: NSImage?125    var body: some View {126        ZStack {127            RoundedRectangle(cornerRadius: SPDTheme.Radius.md, style: .continuous).fill(SPDTheme.sunken)128            if let image { Image(nsImage: image).resizable().aspectRatio(contentMode: .fit).clipShape(RoundedRectangle(cornerRadius: SPDTheme.Radius.sm, style: .continuous)).padding(SPDTheme.Space.sm).spdElevation(.e1) }129            else { ItemIcon(item: item, size: 72) }130        }131        .frame(height: 140).frame(maxWidth: .infinity)132        .task(id: ThumbnailStore.key(item)) {133            if let img = await model.thumbnails.image(for: item) { image = img; return }134            guard item.size <= 30 * 1024 * 1024, let url = try? await model.localCopy(of: item, inContainer: true) else { return }135            image = await model.thumbnails.local(item, url: url, side: 320)136        }137        .accessibilityHidden(true)138    }139}140
Files main
Menu

Theme