SPB Git

Repository Public

TableComparer.swift 11.9 KB 208 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocReview/TableComparer.swift3// Description: Table comparison: rows aligned first, then columns, then cell by cell; incompatible tables are reported as replaced.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import DocModel910extension ComparisonContext {11    /// One line of a row or column alignment: an index on each side (nil = absent on that side).12    private struct Slot { var a: Int?; var b: Int? }1314    /// A table is regular when every row has one single-column cell per grid column; only regular tables can gain or lose columns.15    private func isRegular(_ t: Table) -> Bool {16        t.rows.allSatisfy { $0.cells.count == t.columnCount && $0.cells.allSatisfy { $0.colSpan == 1 } }17    }1819    /// Aligns two key sequences: LCS, then gaps of equal size pair position by position, other gaps pair by `similar`.20    private func align(_ ka: [Int], _ kb: [Int], similar: (Int, Int) -> Double) -> [Slot] {21        var slots: [Slot] = []22        func gap(_ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int) {23            let n = a1 - a0, m = b1 - b024            if n == m { for k in 0..<n { slots.append(Slot(a: a0 + k, b: b0 + k)) }; return }25            var i = a0, j = b026            // Greedy in-order pairing; gaps inside a table are small.27            while i < a1 && j < b1 {28                var bestJ = -129                var best = 0.030                for c in j..<b1 { let s = similar(i, c); if s >= ComparisonTuning.modifiedSimilarity && s > best { best = s; bestJ = c } }31                if bestJ >= 0 {32                    while j < bestJ { slots.append(Slot(a: nil, b: j)); j += 1 }33                    slots.append(Slot(a: i, b: j)); i += 1; j += 134                } else { slots.append(Slot(a: i, b: nil)); i += 1 }35            }36            while i < a1 { slots.append(Slot(a: i, b: nil)); i += 1 }37            while j < b1 { slots.append(Slot(a: nil, b: j)); j += 1 }38        }39        var pa = 0, pb = 040        for (mi, mj) in SequenceDiff.lcs(ka, kb, anchors: false) {41            gap(pa, mi, pb, mj)42            slots.append(Slot(a: mi, b: mj))43            pa = mi + 1; pb = mj + 144        }45        gap(pa, ka.count, pb, kb.count)46        return slots47    }4849    private func rowBag(_ row: TableRow, side: Side) -> [Int] {50        var keys: [Int] = []51        for cell in row.cells { for p in cell.paragraphs { for t in tokens(p, side: side) where t.isContent { keys.append(t.key) } } }52        return keys.sorted()53    }5455    private func cellKey(_ c: TableCell, side: Side) -> String {56        c.paragraphs.map { paragraphKey($0, side: side) }.joined(separator: "\u{2029}")57    }5859    /// Returns one merged table, or two blocks (the original table as a deletion, the revised table as an insertion) when the60    /// tables cannot be compared cell by cell.61    func compareTables(_ a: Table, _ b: Table, _ i: Int, _ j: Int, scope: Scope) -> [Block] {62        if a == b { wordsEqual += words(of: b); return [.table(b)] }63        var tableScope = scope64        if scope.isBody { tableScope.isBody = false; tableScope.fixedOriginal = i; tableScope.fixedRevised = j }65        let prefix = scope.label.isEmpty ? "" : scope.label + ", "66        tableScope.label = ""6768        func replaced() -> [Block] {69            wordsDeleted += words(of: a); wordsInserted += words(of: b)70            var s = tableScope71            s.label = scope.label72            add(.structure, scope: s, original: i, revised: j, before: Excerpt.short(Excerpt.display(Block.table(a))), after: Excerpt.short(Excerpt.display(Block.table(b))),73                detail: "Table replaced (\(a.rows.count) × \(a.columnCount) → \(b.rows.count) × \(b.columnCount))")74            return [.table(marked(a, .deletion, fromOriginal: true)), .table(marked(b, .insertion, fromOriginal: false))]75        }7677        // Rows.78        let rowKeysA = a.rows.map { interner.id("R" + rowKey($0, side: .original)) }, rowKeysB = b.rows.map { interner.id("R" + rowKey($0, side: .revised)) }79        var bagsA = [[Int]?](repeating: nil, count: a.rows.count), bagsB = [[Int]?](repeating: nil, count: b.rows.count)80        var rows = align(rowKeysA, rowKeysB) { ra, rb in81            if bagsA[ra] == nil { bagsA[ra] = rowBag(a.rows[ra], side: .original) }82            if bagsB[rb] == nil { bagsB[rb] = rowBag(b.rows[rb], side: .revised) }83            return diceSimilarity(bagsA[ra]!, bagsB[rb]!)84        }85        let pairedRows = rows.filter { $0.a != nil && $0.b != nil }86        guard !pairedRows.isEmpty else { return replaced() }8788        // Columns.89        var columns: [Slot]? = nil       // nil = cells are compared by position90        if a.columnCount != b.columnCount {91            guard isRegular(a), isRegular(b) else { return replaced() }92            func signature(_ t: Table, _ c: Int, _ side: Side) -> [Int] {93                pairedRows.map { interner.id("C" + cellKey(t.rows[side == .original ? $0.a! : $0.b!].cells[c], side: side)) }94            }95            let sigA = (0..<a.columnCount).map { signature(a, $0, .original) }, sigB = (0..<b.columnCount).map { signature(b, $0, .revised) }96            let keyA = sigA.map { interner.id("S" + $0.map(String.init).joined(separator: ",")) }, keyB = sigB.map { interner.id("S" + $0.map(String.init).joined(separator: ",")) }97            let slots = align(keyA, keyB) { ca, cb in98                var same = 099                for k in 0..<pairedRows.count where sigA[ca][k] == sigB[cb][k] { same += 1 }100                return Double(same) / Double(max(1, pairedRows.count))101            }102            guard slots.contains(where: { $0.a != nil && $0.b != nil }) else { return replaced() }103            columns = slots104        } else {105            // Same grid: a row pair whose cell counts differ (different merges) cannot be compared cell by cell.106            var fixed: [Slot] = []107            for r in rows {108                if let ra = r.a, let rb = r.b, a.rows[ra].cells.count != b.rows[rb].cells.count {109                    fixed.append(Slot(a: ra, b: nil)); fixed.append(Slot(a: nil, b: rb))110                } else { fixed.append(r) }111            }112            rows = fixed113            guard rows.contains(where: { $0.a != nil && $0.b != nil }) else { return replaced() }114        }115116        var merged = b117        merged.rows = []118        if let columns {119            merged.columnWidths = columns.map { $0.b.map { b.columnWidths[$0] } ?? a.columnWidths[$0.a!] }120            for c in columns {121                if c.b == nil, let ca = c.a {122                    let head = a.rows.first.map { Excerpt.display($0.cells[ca].paragraphs.first ?? Paragraph()) } ?? ""123                    add(.structure, scope: tableScope, original: i, revised: j, before: Excerpt.short(head), detail: prefix + "Column deleted (column \(ca + 1))")124                } else if c.a == nil, let cb = c.b {125                    let head = b.rows.first.map { Excerpt.display($0.cells[cb].paragraphs.first ?? Paragraph()) } ?? ""126                    add(.structure, scope: tableScope, original: i, revised: j, after: Excerpt.short(head), detail: prefix + "Column inserted (column \(cb + 1))")127                }128            }129        }130131        func compareCells(_ x: TableCell, _ y: TableCell, row: Int, column: Int, _ formatNotes: inout [String]) -> TableCell {132            var out = y133            if x.paragraphs == y.paragraphs {134                for p in y.paragraphs { wordsEqual += Tokenizer.quickWordCount(p.visibleText) }135            } else {136                var s = tableScope137                s.label = prefix + "Table cell R\(row + 1)C\(column + 1)"138                s.forcePairSingles = true139                out.paragraphs = compareBlocks(x.paragraphs.map { .paragraph($0) }, y.paragraphs.map { .paragraph($0) }, scope: s).merged.compactMap(\.paragraph)140            }141            if options.compareFormatting {142                if x.shading != y.shading { formatNotes.append("Cell R\(row + 1)C\(column + 1) shading changed") }143                if x.vAlign != y.vAlign { formatNotes.append("Cell R\(row + 1)C\(column + 1) vertical alignment \(x.vAlign.rawValue) → \(y.vAlign.rawValue)") }144                if x.colSpan != y.colSpan || x.vMerge != y.vMerge { formatNotes.append("Cell R\(row + 1)C\(column + 1) merge changed") }145                if x.borderTop != y.borderTop || x.borderBottom != y.borderBottom || x.borderLeft != y.borderLeft || x.borderRight != y.borderRight {146                    formatNotes.append("Cell R\(row + 1)C\(column + 1) borders changed")147                }148                if x.formula != y.formula { formatNotes.append("Cell R\(row + 1)C\(column + 1) formula “\(x.formula ?? "")” → “\(y.formula ?? "")”") }149            }150            return out151        }152153        var formatNotes: [String] = []154        for r in rows {155            switch (r.a, r.b) {156            case let (ra?, rb?):157                let x = a.rows[ra], y = b.rows[rb]158                var row = y159                row.cells = []160                if let columns {161                    for c in columns {162                        switch (c.a, c.b) {163                        case let (ca?, cb?): row.cells.append(compareCells(x.cells[ca], y.cells[cb], row: rb, column: cb, &formatNotes))164                        case let (ca?, nil):165                            for p in x.cells[ca].paragraphs { wordsDeleted += Tokenizer.quickWordCount(p.visibleText) }166                            row.cells.append(marked(x.cells[ca], .deletion, fromOriginal: true))167                        case let (nil, cb?):168                            for p in y.cells[cb].paragraphs { wordsInserted += Tokenizer.quickWordCount(p.visibleText) }169                            row.cells.append(marked(y.cells[cb], .insertion, fromOriginal: false))170                        default: break171                        }172                    }173                } else {174                    for k in y.cells.indices { row.cells.append(compareCells(x.cells[k], y.cells[k], row: rb, column: k, &formatNotes)) }175                }176                if options.compareFormatting {177                    if x.isHeader != y.isHeader { formatNotes.append("Row \(rb + 1) \(y.isHeader ? "became a header row" : "is no longer a header row")") }178                    if x.minHeight != y.minHeight { formatNotes.append("Row \(rb + 1) height changed") }179                }180                merged.rows.append(row)181            case let (ra?, nil):182                let x = a.rows[ra]183                for c in x.cells { for p in c.paragraphs { wordsDeleted += Tokenizer.quickWordCount(p.visibleText) } }184                add(.structure, scope: tableScope, original: i, revised: j, before: Excerpt.short(Excerpt.display(x)), detail: prefix + "Row deleted (row \(ra + 1))")185                merged.rows.append(marked(x, .deletion, fromOriginal: true))186            case let (nil, rb?):187                let y = b.rows[rb]188                for c in y.cells { for p in c.paragraphs { wordsInserted += Tokenizer.quickWordCount(p.visibleText) } }189                add(.structure, scope: tableScope, original: i, revised: j, after: Excerpt.short(Excerpt.display(y)), detail: prefix + "Row inserted (row \(rb + 1))")190                merged.rows.append(marked(y, .insertion, fromOriginal: false))191            default: break192            }193        }194195        if options.compareFormatting {196            if a.style != b.style { formatNotes.insert("Table style \(a.style.name) → \(b.style.name)", at: 0) }197            if a.alignment != b.alignment { formatNotes.append("Table alignment \(a.alignment.rawValue) → \(b.alignment.rawValue)") }198            if columns == nil && a.columnWidths != b.columnWidths { formatNotes.append("Column widths changed") }199            if !formatNotes.isEmpty {200                var shown = Array(formatNotes.prefix(8))201                if formatNotes.count > 8 { shown.append("… \(formatNotes.count - 8) more") }202                add(.formatting, scope: tableScope, original: i, revised: j, detail: prefix + shown.joined(separator: "; "))203            }204        }205        return [.table(merged)]206    }207}208
Files main
Menu

Theme