Repository Public
1// SP Notes iOS2// File: Features/Conflicts/ConflictSheet.swift3// Description: Resolution of an edit conflict: the note on this device and the copy from the server, side by side on a wide4// screen or in two tabs on a phone, and three choices in plain words. Whatever the choice, both copies survive5// (server history and local restore points).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SwiftUI1112/// Wording of what can go wrong while a conflict is settled.13enum ConflictMessages {14 static func failure(_ error: Error, isOnline: Bool, session: SessionState) -> String {15 if session != .signedIn { return String(localized: "Connecte-toi pour régler ce conflit : la résolution se fait avec le serveur. Tes deux versions restent intactes.") }16 if let api = error as? APIError {17 if api.isConflict { return String(localized: "La note a encore changé sur le serveur pendant ton choix. La copie du serveur a été mise à jour : relis-la avant de choisir.") }18 if api.isOffline || !isOnline { return offline }19 if api.isUnauthenticated { return String(localized: "Session terminée : connecte-toi pour régler ce conflit. Tes deux versions restent intactes.") }20 if api.isRetryable { return String(localized: "Le serveur n’a pas répondu. Rien n’a été changé ; réessaie dans un instant.") }21 }22 return String(localized: "La résolution a échoué. Rien n’a été changé.")23 }2425 static var offline: String { String(localized: "Tu es hors ligne. Régler un conflit demande le serveur ; tes deux versions restent intactes en attendant.") }26}2728struct ConflictSheet: View {29 let noteId: String30 /// Saves the text being edited before the choice is sent.31 var prepare: () async -> Void = {}3233 enum Side: String, CaseIterable, Identifiable {34 case mine, server35 var id: String { rawValue }36 var title: String { self == .mine ? String(localized: "Cet appareil") : String(localized: "Serveur") }37 }3839 struct Copy: Equatable {40 var title: String41 var date: Date42 var document: NoteDocument43 var words: Int44 }4546 @Environment(AppModel.self) private var app47 @Environment(\.dismiss) private var dismiss48 @Environment(\.horizontalSizeClass) private var sizeClass49 @State private var mine: Copy?50 @State private var server: Copy?51 @State private var loaded = false52 @State private var side: Side = .mine53 @State private var working: ConflictResolution?54 @State private var message: String?55 @State private var pendingChoice: PendingChoice?5657 private struct PendingChoice: Identifiable {58 let choice: ConflictResolution59 var id: String { String(describing: choice) }60 }6162 var body: some View {63 NavigationStack {64 Group {65 if !loaded {66 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)67 } else if let mine, let server {68 VStack(spacing: 0) {69 if let message {70 Label(message, systemImage: "info.circle")71 .font(.footnote)72 .foregroundStyle(Color.spText)73 .padding(12)74 .frame(maxWidth: .infinity, alignment: .leading)75 .background(Color.spWarning.opacity(0.18))76 .accessibilityIdentifier("conflict-message")77 }78 if sizeClass == .regular {79 HStack(spacing: 0) {80 pane(.mine, mine)81 Divider().overlay(Color.spBorder)82 pane(.server, server)83 }84 } else {85 Picker("Version affichée", selection: $side) {86 ForEach(Side.allCases) { Text($0.title).tag($0) }87 }88 .pickerStyle(.segmented)89 .padding(.horizontal, 16)90 .padding(.vertical, 8)91 .accessibilityIdentifier("conflict-sides")92 pane(side, side == .mine ? mine : server)93 }94 }95 .safeAreaInset(edge: .bottom, spacing: 0) { choices }96 } else {97 EmptyStateView(symbol: "checkmark.circle", title: "Plus de conflit", message: "Cette note n’est plus en conflit.", actionTitle: "Fermer") { dismiss() }98 }99 }100 .background(Color.spBackground)101 .navigationTitle("Deux versions de cette note")102 .navigationBarTitleDisplayMode(.inline)103 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Plus tard") { dismiss() }.accessibilityIdentifier("conflict-later") } }104 .task {105 await prepare()106 await load()107 }108 .confirmationDialog(confirmTitle, isPresented: Binding(get: { pendingChoice != nil }, set: { if !$0 { pendingChoice = nil } }), titleVisibility: .visible, presenting: pendingChoice) { pending in109 Button(confirmButton(pending.choice)) { Task { await resolve(pending.choice) } }110 Button("Annuler", role: .cancel) {}111 } message: { pending in Text(explanation(pending.choice)) }112 }113 .accessibilityIdentifier("conflict-sheet")114 .interactiveDismissDisabled(working != nil)115 }116117 private func pane(_ side: Side, _ copy: Copy) -> some View {118 VStack(alignment: .leading, spacing: 0) {119 VStack(alignment: .leading, spacing: 2) {120 Label(side.title, systemImage: side == .mine ? "iphone" : "cloud").font(.caption.weight(.semibold)).foregroundStyle(Color.accentColor)121 Text(AppModel.displayTitle(copy.title)).font(.headline).foregroundStyle(Color.spText).lineLimit(2)122 Text(side == .mine123 ? String(localized: "Modifiée ici le \(DocumentFacts.dateTime(copy.date)) · \(DocumentFacts.words(copy.words))")124 : String(localized: "Modifiée ailleurs le \(DocumentFacts.dateTime(copy.date)) · \(DocumentFacts.words(copy.words))"))125 .font(.caption).foregroundStyle(Color.spTextSecondary)126 }127 .padding(.horizontal, 18)128 .padding(.vertical, 10)129 .frame(maxWidth: .infinity, alignment: .leading)130 Divider().overlay(Color.spBorder)131 NativeDocumentView(document: copy.document, identifier: side == .mine ? "conflict-mine-text" : "conflict-server-text")132 }133 .frame(maxWidth: .infinity, maxHeight: .infinity)134 }135136 private var choices: some View {137 VStack(spacing: 8) {138 Text("Quel que soit ton choix, aucune version n’est perdue : l’autre reste dans l’historique de la note (menu « … » › Historique).")139 .font(.footnote).foregroundStyle(Color.spTextSecondary)140 .frame(maxWidth: .infinity, alignment: .leading)141 choiceButton(.keepMine, title: "Garder ma version", detail: "Le texte de cet appareil remplace celui du serveur.", symbol: "iphone", identifier: "conflict-keep-mine")142 choiceButton(.keepTheirs, title: "Garder la version du serveur", detail: "Le texte du serveur remplace celui de cet appareil.", symbol: "cloud", identifier: "conflict-keep-server")143 choiceButton(.keepBoth, title: "Garder les deux", detail: "Le serveur reste la note ; ta version devient une note à part.", symbol: "doc.on.doc", identifier: "conflict-keep-both")144 }145 .padding(16)146 .frame(maxWidth: 760)147 .frame(maxWidth: .infinity)148 .background(.bar)149 .disabled(working != nil)150 }151152 private func choiceButton(_ choice: ConflictResolution, title: LocalizedStringKey, detail: LocalizedStringKey, symbol: String, identifier: String) -> some View {153 Button { pendingChoice = PendingChoice(choice: choice) } label: {154 HStack(spacing: 12) {155 Image(systemName: symbol).font(.body.weight(.medium)).foregroundStyle(Color.accentColor).frame(width: 26).accessibilityHidden(true)156 VStack(alignment: .leading, spacing: 1) {157 Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Color.spText)158 Text(detail).font(.caption).foregroundStyle(Color.spTextSecondary).multilineTextAlignment(.leading)159 }160 Spacer(minLength: 0)161 if isWorking(choice) { ProgressView() }162 }163 .padding(.horizontal, 12)164 .padding(.vertical, 8)165 .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)166 .background(Color.spSurface, in: RoundedRectangle(cornerRadius: 12, style: .continuous))167 .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Color.spBorder))168 .contentShape(RoundedRectangle(cornerRadius: 12, style: .continuous))169 }170 .buttonStyle(.plain)171 .accessibilityIdentifier(identifier)172 }173174 private func isWorking(_ choice: ConflictResolution) -> Bool {175 guard let working else { return false }176 return String(describing: working) == String(describing: choice)177 }178179 private var confirmTitle: String {180 switch pendingChoice?.choice {181 case .keepMine?: String(localized: "Garder ma version ?")182 case .keepTheirs?: String(localized: "Garder la version du serveur ?")183 case .keepBoth?: String(localized: "Garder les deux ?")184 case nil: ""185 }186 }187188 private func confirmButton(_ choice: ConflictResolution) -> String {189 switch choice {190 case .keepMine: String(localized: "Garder ma version")191 case .keepTheirs: String(localized: "Garder la version du serveur")192 case .keepBoth: String(localized: "Garder les deux")193 }194 }195196 private func explanation(_ choice: ConflictResolution) -> String {197 switch choice {198 case .keepMine: String(localized: "Ta version devient la note partout. La version du serveur reste dans l’historique du serveur.")199 case .keepTheirs: String(localized: "La version du serveur devient la note sur cet appareil. Ta version reste dans l’historique : « Sur cet appareil » et « Sur le serveur ».")200 case .keepBoth: String(localized: "La version du serveur reste cette note. Ta version est gardée dans une nouvelle note, que tu retrouveras dans la liste après la synchronisation.")201 }202 }203204 private func load() async {205 let conflict = try? await app.store.conflict(pageId: noteId)206 let page = try? await app.store.page(id: noteId)207 if let conflict, let page {208 let local = (try? NoteDocument(json: page.content)) ?? NoteDocument()209 let remote = (try? NoteDocument(json: conflict.server.content)) ?? NoteDocument()210 mine = Copy(title: page.title, date: page.localUpdatedAt, document: local, words: page.wordCount)211 server = Copy(title: conflict.server.title, date: conflict.server.updatedAt, document: remote, words: remote.wordCount)212 } else {213 mine = nil; server = nil214 }215 loaded = true216 }217218 private func resolve(_ choice: ConflictResolution) async {219 guard working == nil else { return }220 guard app.session == .signedIn else { message = ConflictMessages.failure(APIError.offline, isOnline: app.network.isOnline, session: app.session); return }221 guard app.network.isOnline else { message = ConflictMessages.offline; return }222 working = choice223 defer { working = nil }224 await prepare()225 do {226 _ = try await app.engine.resolveConflict(pageId: noteId, choice: choice)227 Haptics.success()228 dismiss()229 } catch {230 message = ConflictMessages.failure(error, isOnline: app.network.isOnline, session: app.session)231 Haptics.warning()232 // After a new 409 the engine recorded the newer server copy: show it.233 await load()234 if (error as? APIError)?.isConflict == true { side = .server }235 }236 }237}238239/// The banner shown in the note screen while the note is in conflict.240struct ConflictBanner: View {241 var action: () -> Void242 var body: some View {243 Button(action: action) {244 HStack(spacing: 10) {245 Image(systemName: "exclamationmark.arrow.triangle.2.circlepath").foregroundStyle(Color.spWarning).accessibilityHidden(true)246 VStack(alignment: .leading, spacing: 1) {247 Text("Cette note existe en deux versions").font(.subheadline.weight(.semibold)).foregroundStyle(Color.spText)248 Text("Compare-les et choisis laquelle garder.").font(.caption).foregroundStyle(Color.spTextSecondary)249 }250 Spacer(minLength: 0)251 Text("Comparer").font(.subheadline.weight(.semibold)).foregroundStyle(Color.accentColor)252 }253 .padding(.horizontal, 16)254 .padding(.vertical, 10)255 .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)256 .background(Color.spWarning.opacity(0.16))257 .contentShape(Rectangle())258 }259 .buttonStyle(.plain)260 .accessibilityIdentifier("conflict-banner")261 }262}263