Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReview/DocumentComparer.swift3// Description: Entry point of the comparison engine: compares two documents and builds the change list, the block alignment4// and the merged document with tracked changes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011/// Two-level document comparison.12///13/// 1. **Blocks.** Each body block gets a content fingerprint (normalised text, inline objects replaced by their payload; formatting14/// excluded). The two fingerprint sequences are aligned by LCS: blocks that occur once on each side are pinned first (patience),15/// linear-space Myers fills in between. Unmatched blocks of a gap are paired when their word bags are similar enough16/// (`ComparisonTuning.modifiedSimilarity`), so an edited paragraph is "modified" rather than deleted and inserted.17/// 2. **Tokens.** A modified pair is diffed token by token (words, punctuation, white space, inline objects).18///19/// Pending tracked changes of the inputs are compared as if accepted (deleted runs ignored).20public enum DocumentComparer {21 public static func compare(original: DocumentModel, revised: DocumentModel, options: ComparisonOptions = .init()) -> ComparisonResult {22 let a = original.flattenedForComparison, b = revised.flattenedForComparison23 let ctx = ComparisonContext(options: options, original: a, revised: b)24 ctx.registerParagraphIDs(of: b.body)25 b.forEachParagraphEverywhere { p, story, _ in if story != .body { _ = ctx.uniqueID(p.id) } }2627 // Body.28 let body = ctx.compareBlocks(a.body, b.body, scope: Scope(isBody: true))29 var merged = b30 merged.body = body.merged.isEmpty ? [.paragraph(Paragraph())] : body.merged3132 // Page setup, headers and footers, section by section.33 let setupsA = a.sectionSetups, setupsB = b.sectionSetups34 let breaksA = a.body.indices.filter { if case .sectionBreak = a.body[$0] { return true } else { return false } }35 let breaksB = b.body.indices.filter { if case .sectionBreak = b.body[$0] { return true } else { return false } }36 for s in 0..<min(setupsA.count, setupsB.count) {37 let x = setupsA[s], y = setupsB[s]38 guard x != y else { continue }39 let blockA = s == 0 ? nil : breaksA[s - 1], blockB = s == 0 ? nil : breaksB[s - 1]40 if options.compareFormatting {41 let notes = FormatDescription.setup(x, y)42 if !notes.isEmpty {43 var scope = Scope(label: "Section \(s + 1) page setup")44 scope.fixedOriginal = blockA; scope.fixedRevised = blockB45 ctx.add(.structure, scope: scope, original: nil, revised: nil, detail: notes.joined(separator: "; "))46 }47 }48 for variant in HeaderFooterVariant.allCases {49 for isHeader in [true, false] {50 let story: StoryID = isHeader ? .header(section: s, variant: variant) : .footer(section: s, variant: variant)51 let pa = a.blocks(in: story), pb = b.blocks(in: story)52 guard pa != pb else { continue }53 var label = "\(isHeader ? "Header" : "Footer"), section \(s + 1)"54 if variant != .default { label += " (\(variant == .first ? "first page" : "even pages"))" }55 var scope = Scope(story: story, label: label)56 scope.fixedOriginal = blockA; scope.fixedRevised = blockB57 let res = ctx.compareBlocks(pa, pb, scope: scope)58 merged.setBlocks(res.merged, in: story)59 }60 }61 }6263 // Notes present under the same id on both sides that no paragraph diff has visited (formatting-only differences).64 for id in b.notes.keys.sorted() where !ctx.comparedNotes.contains(id) && a.notes[id] != nil && a.notes[id]!.paragraphs != b.notes[id]!.paragraphs {65 if ctx.noteKey(id, side: .original) == ctx.noteKey(id, side: .revised) || isReferenced(id, in: a) {66 ctx.compareNotes(id, id, hostOriginal: nil, hostRevised: nil, scope: Scope())67 }68 }6970 // Style definitions.71 if options.compareFormatting {72 for sb in b.styles.styles {73 guard let sa = a.styles.style(sb.id), sa != sb else { continue }74 var notes: [String] = []75 let pa = a.styles.styleProps(sa.id), pb = b.styles.styleProps(sb.id)76 if sa.kind == .paragraph {77 notes += FormatDescription.character(ResolvedChar(pa.char), ResolvedChar(pb.char))78 notes += FormatDescription.paragraph(ResolvedPara(pa.para), ResolvedPara(pb.para))79 } else {80 var ca = CharProps.none, cb = CharProps.none81 for s in a.styles.chain(sa.id) { ca.apply(s.char) }82 for s in b.styles.chain(sb.id) { cb.apply(s.char) }83 notes += FormatDescription.character(ResolvedChar(ca), ResolvedChar(cb))84 }85 if sa.name != sb.name { notes.append("renamed “\(sa.name)” → “\(sb.name)”") }86 if sa.basedOn != sb.basedOn { notes.append("based on \(sa.basedOn ?? "nothing") → \(sb.basedOn ?? "nothing")") }87 if sa.numbered != sb.numbered { notes.append(sb.numbered ? "numbering turned on" : "numbering turned off") }88 guard !notes.isEmpty else { continue }89 var scope = Scope(label: "Style definition \(sb.id)")90 scope.fixedOriginal = nil; scope.fixedRevised = nil91 ctx.add(.style, scope: scope, original: nil, revised: nil, before: sa.name, after: sb.name, detail: notes.joined(separator: "; "))92 }93 }9495 merged.notes = ctx.mergedNotes96 merged.assets = ctx.mergedAssets97 for s in ctx.extraStyles { merged.styles.upsert(s) }98 merged.lists.append(contentsOf: ctx.extraLists)99 merged.bibliography.append(contentsOf: ctx.extraBib)100101 var counts: [DocumentChange.Kind: Int] = [:]102 for c in ctx.changes { counts[c.kind, default: 0] += 1 }103 let common = ctx.wordsEqual + ctx.wordsMoved104 let wordsA = common + ctx.wordsDeleted, wordsB = common + ctx.wordsInserted105 let summary = ComparisonSummary(counts: counts, wordsInserted: ctx.wordsInserted, wordsDeleted: ctx.wordsDeleted, wordsMoved: ctx.wordsMoved,106 wordsOriginal: wordsA, wordsRevised: wordsB, blocksOriginal: a.body.count, blocksRevised: b.body.count,107 similarity: wordsA + wordsB == 0 ? 1 : 2 * Double(common) / Double(wordsA + wordsB))108 return ComparisonResult(changes: ctx.changes, rows: body.rows, merged: merged, summary: summary)109 }110111 /// Word-level diff of two paragraphs as runs with insertion/deletion revisions (and `FormatRevision`s on unchanged text whose112 /// formatting differs). The runs read as `b` once the changes are accepted and as `a` once they are rejected.113 public static func inlineDiff(_ a: Paragraph, _ b: Paragraph, options: ComparisonOptions) -> [Run] {114 let ctx = ComparisonContext(options: options, original: nil, revised: nil)115 return ctx.diff(a.flattenedForComparison, b.flattenedForComparison).runs116 }117118 private static func isReferenced(_ noteID: String, in doc: DocumentModel) -> Bool {119 var found = false120 doc.forEachParagraphEverywhere { p, _, _ in121 if found { return }122 for r in p.runs { if case .note(let ref)? = r.inline, ref.id == noteID { found = true; return } }123 }124 return found125 }126}127