Repository Public
1// ORIX Docs2// File: App/Sources/Sheets/CompareSheet.swift3// Description: The compare sheet: chooses the other document and the direction, sets the options, runs the comparison off the4// main thread and opens the comparison window.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import UniformTypeIdentifiers11import DocModel12import DocContainer13import DocReview14import DocAutomation1516struct CompareSheet: View {17 let session: DocumentSession18 @State private var other: LoadedDocument?19 @State private var loading = false20 @State private var comparing = false21 @State private var problem: String?22 @State private var choosing = false23 /// The open document is the revised version (the usual case: compare against an earlier file).24 @State private var currentIsRevised = true25 @State private var detectMoves = true26 @State private var compareFormatting = true27 @State private var ignoreCase = false28 @State private var ignoreWhitespace = false2930 struct LoadedDocument {31 let name: String32 let document: DocumentModel33 let warnings: Int34 let words: Int35 }3637 init(session: DocumentSession) { self.session = session }3839 private var currentName: String {40 session.document?.displayName ?? (session.doc.meta.title.isEmpty ? String(localized: "Untitled") : session.doc.meta.title)41 }4243 static var importTypes: [UTType] {44 var types: [UTType] = []45 for format in DocumentConverter.importFormats {46 if let type = UTType(filenameExtension: format.fileExtension), !types.contains(type) { types.append(type) }47 }48 return types49 }5051 var body: some View {52 FileSheetFrame(symbol: "rectangle.split.2x1", title: "Compare Documents",53 subtitle: Text("Shows what differs between this document and another file. Neither is changed.")) {54 VStack(alignment: .leading, spacing: ORIX.Space.l) {55 VStack(alignment: .leading, spacing: ORIX.Space.s) {56 sectionTitle("Documents")57 VStack(spacing: 0) {58 documentRow(role: currentIsRevised ? "Revised" : "Original", symbol: "doc.text.fill", name: currentName,59 detail: Text("This document · \(session.statistics.words) words"))60 Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1)61 HStack(spacing: ORIX.Space.s) {62 if let other {63 documentRow(role: currentIsRevised ? "Original" : "Revised", symbol: "doc", name: other.name,64 detail: other.warnings > 0 ? Text("\(other.words) words · \(other.warnings) import notes") : Text("\(other.words) words"))65 } else {66 documentRow(role: currentIsRevised ? "Original" : "Revised", symbol: "doc.badge.plus", name: String(localized: "No file chosen"),67 detail: Text("Choose the file to compare with"))68 }69 if loading { ProgressView().controlSize(.small) }70 Button(other == nil ? "Choose…" : "Change…") { choosing = true }71 .buttonStyle(ORIXButtonStyle(prominent: false))72 .disabled(loading || comparing)73 .padding(.trailing, ORIX.Space.m)74 .accessibilityIdentifier("compare-choose")75 }76 }77 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface))78 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))79 Button { currentIsRevised.toggle() } label: { Label("Swap Original and Revised", systemImage: "arrow.up.arrow.down") }80 .buttonStyle(.plain).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.accent)81 .help("Insertions and deletions are reported from the original to the revised document.")82 .accessibilityIdentifier("compare-swap")83 }84 VStack(alignment: .leading, spacing: ORIX.Space.s) {85 sectionTitle("Options")86 Grid(alignment: .leading, horizontalSpacing: ORIX.Space.xl, verticalSpacing: ORIX.Space.s) {87 GridRow {88 Toggle("Detect moved paragraphs", isOn: $detectMoves).accessibilityIdentifier("compare-moves")89 Toggle("Ignore letter case", isOn: $ignoreCase).accessibilityIdentifier("compare-case")90 }91 GridRow {92 Toggle("Compare formatting and styles", isOn: $compareFormatting).accessibilityIdentifier("compare-formatting")93 Toggle("Ignore white space", isOn: $ignoreWhitespace).accessibilityIdentifier("compare-whitespace")94 }95 }96 .toggleStyle(.checkbox).controlSize(.small).font(ORIX.Font.label)97 }98 if let problem {99 Label(problem, systemImage: "exclamationmark.triangle.fill")100 .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.critical).fixedSize(horizontal: false, vertical: true)101 .accessibilityIdentifier("compare-error")102 }103 }104 .padding(ORIX.Space.xl)105 } footer: {106 if comparing {107 ProgressView().controlSize(.small)108 Text("Comparing…").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)109 }110 Spacer()111 Button("Cancel") { session.activeSheet = nil }112 .buttonStyle(ORIXButtonStyle(prominent: false)).keyboardShortcut(.cancelAction)113 .accessibilityIdentifier("compare-cancel")114 Button("Compare") { compare() }115 .buttonStyle(ORIXButtonStyle()).keyboardShortcut(.defaultAction)116 .disabled(other == nil || comparing).opacity(other == nil || comparing ? 0.45 : 1)117 .accessibilityIdentifier("compare-run")118 }119 .fileImporter(isPresented: $choosing, allowedContentTypes: CompareSheet.importTypes) { result in120 switch result {121 case .success(let url): load(url)122 case .failure(let error): problem = error.localizedDescription123 }124 }125 .onAppear {126 // Automated runs (`-ORIXCompareWith <file>`): load the file and compare at once.127 if other == nil, let path = UserDefaults.standard.string(forKey: "ORIXCompareWith") { load(URL(fileURLWithPath: path), thenCompare: true) }128 }129 .accessibilityIdentifier("compare-sheet")130 }131132 private func sectionTitle(_ title: LocalizedStringKey) -> some View {133 Text(title).font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary).accessibilityAddTraits(.isHeader)134 }135136 private func documentRow(role: LocalizedStringKey, symbol: String, name: String, detail: Text) -> some View {137 HStack(spacing: ORIX.Space.m) {138 Text(role).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)139 .frame(width: 58, alignment: .leading)140 Image(systemName: symbol).font(.system(size: 14)).foregroundStyle(ORIX.Palette.accent).frame(width: 18)141 VStack(alignment: .leading, spacing: 1) {142 Text(name).font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1).truncationMode(.middle)143 detail.font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)144 }145 Spacer(minLength: 0)146 }147 .padding(.horizontal, ORIX.Space.m).padding(.vertical, ORIX.Space.s)148 .accessibilityElement(children: .combine)149 }150151 private func load(_ url: URL, thenCompare: Bool = false) {152 loading = true153 problem = nil154 Task {155 let outcome: (result: ImportResult?, failure: String) = await Task.detached(priority: .userInitiated) {156 let scoped = url.startAccessingSecurityScopedResource()157 defer { if scoped { url.stopAccessingSecurityScopedResource() } }158 do { return (try DocumentConverter.importDocument(at: url), "") } catch { return (nil, "\(error)") }159 }.value160 loading = false161 if let result = outcome.result {162 other = LoadedDocument(name: url.lastPathComponent, document: result.document,163 warnings: result.warnings.filter { $0.severity != .info }.count, words: DocumentStatistics(result.document).words)164 if thenCompare { compare() }165 } else {166 problem = String(localized: "“\(url.lastPathComponent)” could not be read. \(outcome.failure)")167 }168 }169 }170171 private func compare() {172 guard let other, !comparing else { return }173 comparing = true174 problem = nil175 let current = session.doc, otherDocument = other.document176 let original = currentIsRevised ? otherDocument : current, revised = currentIsRevised ? current : otherDocument177 let originalName = currentIsRevised ? other.name : currentName, revisedName = currentIsRevised ? currentName : other.name178 let options = ComparisonOptions(author: session.author.isEmpty ? "ORIX Docs" : session.author, detectMoves: detectMoves,179 compareFormatting: compareFormatting, ignoreWhitespace: ignoreWhitespace, ignoreCase: ignoreCase)180 let target = session181 Task {182 let result = await Task.detached(priority: .userInitiated) {183 DocumentComparer.compare(original: original, revised: revised, options: options)184 }.value185 comparing = false186 target.activeSheet = nil187 ComparisonWindowController.present(ComparisonPayload(result: result, options: options, original: original, revised: revised,188 originalName: originalName, revisedName: revisedName))189 }190 }191}192