SPB Git

Repository Public

EditorReview.swift 18.4 KB 378 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/EditorReview.swift3// Description: Review operations: listing, accepting and rejecting tracked changes; comments; find and replace.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct TrackedChange: Identifiable, Hashable, Sendable {10    public enum Kind: String, Sendable { case insertion, deletion, formatting, paragraphInserted, paragraphDeleted }11    /// Unique in the list (revision id + paragraph).12    public var id: String13    /// Id shared by every run of the same edit; pass it to `resolveChanges`.14    public var revisionID: String15    public var kind: Kind16    public var author: String17    public var date: Date18    /// The affected text (or a description for paragraph marks and formatting).19    public var text: String20    public var story: StoryID21    public var path: ParaPath22    public var range: Range<Int>23}2425public extension DocumentModel {26    /// Every tracked change in reading order (body, then headers and footers, then notes).27    func trackedChanges() -> [TrackedChange] {28        var out: [TrackedChange] = []29        forEachParagraphEverywhere { p, story, path in30            var pos = 031            var i = 032            while i < p.runs.count {33                let r = p.runs[i]34                if let rev = r.revision {35                    var text = r.inline == nil ? r.text : "[object]"36                    var end = pos + r.length37                    var j = i + 138                    while j < p.runs.count, p.runs[j].revision?.id == rev.id {39                        text += p.runs[j].inline == nil ? p.runs[j].text : "[object]"40                        end += p.runs[j].length41                        j += 142                    }43                    out.append(TrackedChange(id: "\(rev.id)@\(p.id)@\(pos)", revisionID: rev.id, kind: rev.kind == .insertion ? .insertion : .deletion,44                                             author: rev.author, date: rev.date, text: text, story: story, path: path, range: pos..<end))45                    pos = end46                    i = j47                    continue48                }49                if let f = r.formatRevision {50                    out.append(TrackedChange(id: "\(f.id)@\(p.id)@\(pos)", revisionID: f.id, kind: .formatting, author: f.author, date: f.date,51                                             text: r.text, story: story, path: path, range: pos..<(pos + r.length)))52                }53                pos += r.length54                i += 155            }56            if let m = p.markRevision {57                out.append(TrackedChange(id: "\(m.id)@\(p.id)@mark", revisionID: m.id, kind: m.kind == .insertion ? .paragraphInserted : .paragraphDeleted,58                                         author: m.author, date: m.date, text: "¶", story: story, path: path, range: p.length..<p.length))59            }60        }61        return out62    }6364    var hasTrackedChanges: Bool {65        var found = false66        forEachParagraphEverywhere { p, _, _ in if !found, p.hasTrackedChanges { found = true } }67        return found68    }6970    /// Accepts (or rejects) tracked changes everywhere. `ids` limits the operation to those revision ids; nil means all.71    mutating func resolveChanges(accept: Bool, ids: Set<String>? = nil) {72        func selected(_ id: String) -> Bool { ids?.contains(id) ?? true }7374        /// Resolves the runs of one paragraph. Returns true when the paragraph must be joined with the next one.75        func resolve(_ p: inout Paragraph) -> Bool {76            var runs: [Run] = []77            runs.reserveCapacity(p.runs.count)78            for var r in p.runs {79                if let rev = r.revision, selected(rev.id) {80                    let keep = (rev.kind == .insertion) == accept81                    if !keep { continue }82                    r.revision = nil83                }84                if let f = r.formatRevision, selected(f.id) {85                    if !accept { r.props = f.previous; r.charStyle = f.previousCharStyle }86                    r.formatRevision = nil87                }88                runs.append(r)89            }90            p.runs = runs91            p.normalize()92            if let m = p.markRevision, selected(m.id) {93                p.markRevision = nil94                return (m.kind == .deletion) == accept   // accepted deletion or rejected insertion of the paragraph break95            }96            return false97        }9899        func resolveParagraphs(_ paras: inout [Paragraph]) {100            var i = 0101            while i < paras.count {102                var p = paras[i]103                var join = resolve(&p)104                // A resolved paragraph break joins this paragraph with the next one; that one's own mark decides whether to keep joining.105                while join, i + 1 < paras.count {106                    var next = paras[i + 1]107                    join = resolve(&next)108                    if p.isEmpty && !next.isEmpty { p = next } else { p.runs.append(contentsOf: next.runs); p.normalize() }109                    paras.remove(at: i + 1)110                }111                paras[i] = p112                i += 1113            }114        }115116        func resolveBlocks(_ blocks: inout [Block]) {117            // Paragraph runs are handled in maximal sequences of adjacent paragraphs so joins stay inside them.118            var out: [Block] = []119            var pending: [Paragraph] = []120            func flush() {121                guard !pending.isEmpty else { return }122                resolveParagraphs(&pending)123                out.append(contentsOf: pending.map { .paragraph($0) })124                pending = []125            }126            for b in blocks {127                switch b {128                case .paragraph(let p): pending.append(p)129                case .table(var t):130                    flush()131                    // A row (or column) whose every paragraph carried a rejected insertion or an accepted deletion goes away with them.132                    func wholly(_ cell: TableCell) -> Bool {133                        !cell.paragraphs.isEmpty && cell.paragraphs.allSatisfy { p in134                            guard let m = p.markRevision, selected(m.id), (m.kind == .deletion) == accept else { return false }135                            return p.runs.allSatisfy { r in r.revision.map { selected($0.id) && ($0.kind == .deletion) == accept } ?? false }136                        }137                    }138                    let doomedRows = t.rows.indices.filter { r in t.rows[r].cells.allSatisfy { $0.vMerge == .continue || wholly($0) } && t.rows[r].cells.contains(where: wholly) }139                    var doomedColumns: [Int] = []140                    if doomedRows.isEmpty, t.rows.allSatisfy({ $0.cells.count == t.columnCount }) {141                        doomedColumns = (0..<t.columnCount).filter { c in t.rows.allSatisfy { wholly($0.cells[c]) } }142                    }143                    for r in doomedRows.reversed() { t.rows.remove(at: r) }144                    for c in doomedColumns.reversed() where t.columnCount > 1 {145                        for r in t.rows.indices { t.rows[r].cells.remove(at: c) }146                        t.columnWidths.remove(at: c)147                    }148                    for r in t.rows.indices { for c in t.rows[r].cells.indices {149                        resolveParagraphs(&t.rows[r].cells[c].paragraphs)150                        if t.rows[r].cells[c].paragraphs.isEmpty { t.rows[r].cells[c].paragraphs = [Paragraph(style: StyleID.tableText)] }151                    } }152                    if !t.rows.isEmpty { out.append(.table(t)) }153                default:154                    flush()155                    out.append(b)156                }157            }158            flush()159            blocks = out.isEmpty ? [.paragraph(Paragraph())] : out160        }161162        resolveBlocks(&body)163        func hf(_ h: inout HeaderFooter) { resolveParagraphs(&h.default); resolveParagraphs(&h.first); resolveParagraphs(&h.even) }164        hf(&pageSetup.header); hf(&pageSetup.footer)165        for i in body.indices {166            if case .sectionBreak(var s) = body[i] { hf(&s.setup.header); hf(&s.setup.footer); body[i] = .sectionBreak(s) }167        }168        for k in notes.keys { resolveParagraphs(&notes[k]!.paragraphs) }169    }170}171172public extension DocumentEditor {173    mutating func resolveChanges(accept: Bool, ids: Set<String>? = nil) {174        doc.resolveChanges(accept: accept, ids: ids)175        pruneOrphans()176        sanitizeDocument()177    }178179    /// Selects the next (or previous) tracked change relative to the selection. Returns it, or nil when the document has none.180    @discardableResult181    mutating func selectAdjacentChange(forward: Bool) -> TrackedChange? {182        let all = doc.trackedChanges().filter { $0.story == selection.story }183        let pool = all.isEmpty ? doc.trackedChanges() : all184        guard !pool.isEmpty else { return nil }185        let here = forward ? selection.end : selection.start186        let pick: TrackedChange187        if forward {188            pick = pool.first { Position(path: $0.path, offset: $0.range.lowerBound) >= here && !(selection.start == Position(path: $0.path, offset: $0.range.lowerBound) && selection.end == Position(path: $0.path, offset: $0.range.upperBound)) } ?? pool[0]189        } else {190            pick = pool.last { Position(path: $0.path, offset: $0.range.upperBound) <= here && Position(path: $0.path, offset: $0.range.lowerBound) < selection.start } ?? pool[pool.count - 1]191        }192        selection = Selection(story: pick.story, anchor: Position(path: pick.path, offset: pick.range.lowerBound), head: Position(path: pick.path, offset: pick.range.upperBound))193        return pick194    }195196    // MARK: Comments197198    /// Anchors a new comment on the selection (on the word around the caret when nothing is selected). Returns its id.199    @discardableResult200    mutating func addComment(_ text: String) -> String? {201        var b = blocks202        if selection.isCaret, let p = b.paragraph(at: selection.head.path) {203            let r = p.plainText.wordRange(at: max(0, selection.head.offset - (selection.head.offset == p.length ? 1 : 0)))204            guard !r.isEmpty else { return nil }205            selection = Selection(story: selection.story, anchor: Position(path: selection.head.path, offset: r.lowerBound), head: Position(path: selection.head.path, offset: r.upperBound))206        }207        let comment = Comment(author: author, date: now(), text: text)208        var anchored = false209        for (path, range) in selectedParagraphs() where !range.isEmpty {210            guard var p = b.paragraph(at: path) else { continue }211            p.transform(range) { $0.comments.append(comment.id) }212            b.setParagraph(p, at: path)213            anchored = true214        }215        guard anchored else { return nil }216        blocks = b217        doc.comments.append(comment)218        return comment.id219    }220221    mutating func removeComment(_ id: String) {222        doc.mutateEveryParagraph { p in223            guard p.runs.contains(where: { $0.comments.contains(id) }) else { return }224            for i in p.runs.indices { p.runs[i].comments.removeAll { $0 == id } }225            p.normalize()226        }227        doc.comments.removeAll { $0.id == id }228    }229230    mutating func replyToComment(_ id: String, text: String) {231        guard let i = doc.comments.firstIndex(where: { $0.id == id }) else { return }232        doc.comments[i].replies.append(CommentReply(author: author, date: now(), text: text))233    }234235    mutating func setComment(_ id: String, resolved: Bool) {236        guard let i = doc.comments.firstIndex(where: { $0.id == id }) else { return }237        doc.comments[i].resolved = resolved238    }239240    mutating func editComment(_ id: String, text: String) {241        guard let i = doc.comments.firstIndex(where: { $0.id == id }) else { return }242        doc.comments[i].text = text243    }244}245246public extension DocumentModel {247    /// Where a comment is anchored (first paragraph of its range) and the commented text.248    func commentAnchor(_ id: String) -> (story: StoryID, path: ParaPath, range: Range<Int>, text: String)? {249        var result: (StoryID, ParaPath, Range<Int>, String)?250        forEachParagraphEverywhere { p, story, path in251            guard result == nil else { return }252            var pos = 0, lo: Int?, hi = 0, text = ""253            for r in p.runs {254                if r.comments.contains(id) { if lo == nil { lo = pos }; hi = pos + r.length; text += r.inline == nil ? r.text : "" }255                pos += r.length256            }257            if let lo { result = (story, path, lo..<hi, text) }258        }259        return result.map { (story: $0.0, path: $0.1, range: $0.2, text: $0.3) }260    }261262    /// Comments in the order of their anchors in the document.263    func commentsInDocumentOrder() -> [Comment] {264        var order: [String: Int] = [:]265        var n = 0266        forEachParagraphEverywhere { p, _, _ in267            for r in p.runs { for c in r.comments where order[c] == nil { order[c] = n; n += 1 } }268        }269        return comments.sorted { (order[$0.id] ?? Int.max) < (order[$1.id] ?? Int.max) }270    }271}272273// MARK: - Find and replace274275public struct FindOptions: Hashable, Sendable {276    public var caseSensitive = false277    public var wholeWord = false278    public var regularExpression = false279    /// "resume" matches "résumé" when false.280    public var diacriticSensitive = false281    public init(caseSensitive: Bool = false, wholeWord: Bool = false, regularExpression: Bool = false, diacriticSensitive: Bool = false) {282        self.caseSensitive = caseSensitive; self.wholeWord = wholeWord; self.regularExpression = regularExpression; self.diacriticSensitive = diacriticSensitive283    }284}285286public struct TextMatch: Hashable, Sendable, Identifiable {287    public var story: StoryID288    public var path: ParaPath289    public var range: Range<Int>290    /// The paragraph text around the match, for result lists.291    public var context: String292    public var id: String { "\(story)-\(path)-\(range.lowerBound)" }293    public init(story: StoryID, path: ParaPath, range: Range<Int>, context: String = "") { self.story = story; self.path = path; self.range = range; self.context = context }294}295296public extension DocumentModel {297    /// Ranges of `query` inside one string (UTF-16).298    static func ranges(of query: String, in text: String, options: FindOptions) -> [Range<Int>] {299        guard !query.isEmpty else { return [] }300        let ns = text as NSString301        var out: [Range<Int>] = []302        if options.regularExpression {303            guard let re = try? NSRegularExpression(pattern: query, options: options.caseSensitive ? [] : [.caseInsensitive]) else { return [] }304            for m in re.matches(in: text, range: NSRange(location: 0, length: ns.length)) where m.range.length > 0 {305                out.append(m.range.location..<(m.range.location + m.range.length))306            }307            return out308        }309        var opts: NSString.CompareOptions = []310        if !options.caseSensitive { opts.insert(.caseInsensitive) }311        if !options.diacriticSensitive { opts.insert(.diacriticInsensitive) }312        var search = NSRange(location: 0, length: ns.length)313        func isWord(_ i: Int) -> Bool {314            guard i >= 0, i < ns.length, let s = UnicodeScalar(ns.character(at: i)) else { return false }315            return CharacterSet.alphanumerics.contains(s)316        }317        while search.length > 0 {318            let r = ns.range(of: query, options: opts, range: search)319            guard r.location != NSNotFound, r.length > 0 else { break }320            if !options.wholeWord || (!isWord(r.location - 1) && !isWord(r.location + r.length)) {321                out.append(r.location..<(r.location + r.length))322            }323            let next = r.location + max(1, r.length)324            search = NSRange(location: next, length: max(0, ns.length - next))325        }326        return out327    }328329    /// Every occurrence of `query` in the document: body, tables, headers, footers and notes.330    func findAll(_ query: String, options: FindOptions = FindOptions()) -> [TextMatch] {331        var out: [TextMatch] = []332        forEachParagraphEverywhere { p, story, path in333            let text = p.plainText334            for r in DocumentModel.ranges(of: query, in: text, options: options) {335                let lo = max(0, r.lowerBound - 30), hi = min(text.utf16Length, r.upperBound + 40)336                let ctx = text.utf16Substring(text.composedBoundary(atOrBefore: lo)..<text.composedBoundary(atOrBefore: hi)).replacingOccurrences(of: objectReplacementCharacter, with: " ")337                out.append(TextMatch(story: story, path: path, range: r, context: ctx))338            }339        }340        return out341    }342}343344public extension DocumentEditor {345    /// Replaces one match (honours change tracking). The formatting of the replaced text is kept.346    mutating func replace(_ match: TextMatch, with replacement: String) {347        selection = Selection(story: match.story, anchor: Position(path: match.path, offset: match.range.lowerBound), head: Position(path: match.path, offset: match.range.lowerBound))348        guard let p = blocks.paragraph(at: match.path), match.range.upperBound <= p.length else { return }349        // Type with the formatting of the first replaced character.350        let r = p.run(containing: match.range.lowerBound)351        selection.head = Position(path: match.path, offset: match.range.upperBound)352        typingOverride = r?.props353        deleteSelection(caretAtEnd: true)354        if !replacement.isEmpty { insertRuns([Run(replacement, props: r?.props ?? .none, charStyle: r?.charStyle)]) }355        typingOverride = nil356    }357358    /// Replaces every occurrence. Returns the number of replacements. With regular expressions, `$1` templates are expanded.359    @discardableResult360    mutating func replaceAll(_ query: String, with replacement: String, options: FindOptions = FindOptions()) -> Int {361        let saved = selection362        let matches = doc.findAll(query, options: options)363        // Back to front so earlier offsets stay valid.364        for m in matches.reversed() {365            var text = replacement366            if options.regularExpression, let re = try? NSRegularExpression(pattern: query, options: options.caseSensitive ? [] : [.caseInsensitive]),367               let p = doc.blocks(in: m.story).paragraph(at: m.path) {368                let source = p.plainText.utf16Substring(m.range)369                text = re.stringByReplacingMatches(in: source, range: NSRange(location: 0, length: source.utf16Length), withTemplate: replacement)370            }371            replace(m, with: text)372        }373        selection = saved374        sanitizeSelection()375        return matches.count376    }377}378
Files main
Menu

Theme