SPB Git

Repository Public

DocumentScan.swift 5.4 KB 128 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocAudit/DocumentScan.swift3// Description: Shared traversal helpers of the auditor and the research assistant: paragraph references, visible text with4//              stable offsets, heading levels, word enumeration.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel1011/// A paragraph with its address.12struct ParagraphRef {13    var story: StoryID14    var path: ParaPath15    var paragraph: Paragraph16}1718enum Scan {19    /// Every paragraph of the document in a deterministic order: body (cells included), headers and footers by section, notes by id.20    static func paragraphs(of doc: DocumentModel) -> [ParagraphRef] {21        var out: [ParagraphRef] = []22        doc.forEachParagraphEverywhere { p, story, path in out.append(ParagraphRef(story: story, path: path, paragraph: p)) }23        return out24    }2526    /// The paragraph text with the same UTF-16 offsets as `plainText`, in which text marked as deleted is blanked out27    /// (replaced by U+FFFC) so it can neither match a search nor count as content.28    static func maskedText(_ p: Paragraph) -> String {29        guard p.runs.contains(where: \.isDeleted) else { return p.plainText }30        var out = ""31        for r in p.runs {32            if r.isDeleted { out += String(repeating: objectReplacementCharacter, count: r.length) } else { out += r.text }33        }34        return out35    }3637    /// Trimmed visible text, shortened for display.38    static func excerpt(_ p: Paragraph, limit: Int = 110) -> String {39        short(p.visibleText.replacingOccurrences(of: lineSeparatorCharacter, with: " ").trimmingCharacters(in: .whitespacesAndNewlines), limit: limit)40    }4142    static func short(_ s: String, limit: Int = 110) -> String {43        guard s.count > limit else { return s }44        return String(s.prefix(limit)).trimmingCharacters(in: .whitespaces) + "…"45    }4647    /// A window of `text` around `range` (UTF-16), cut on composed-character boundaries, inline objects shown as spaces.48    static func context(_ text: String, around range: Range<Int>, radius: Int) -> String {49        let ns = text as NSString50        let lo = text.composedBoundary(atOrBefore: max(0, range.lowerBound - radius))51        let hi = text.composedBoundary(atOrBefore: min(ns.length, range.upperBound + radius))52        var s = ns.substring(with: NSRange(location: lo, length: max(0, hi - lo)))53        s = s.replacingOccurrences(of: objectReplacementCharacter, with: " ").replacingOccurrences(of: lineSeparatorCharacter, with: " ")54        return (lo > 0 ? "…" : "") + s.trimmingCharacters(in: .whitespacesAndNewlines) + (hi < ns.length ? "…" : "")55    }5657    static func wordCount(_ s: String) -> Int {58        var n = 059        var inWord = false60        for u in s.unicodeScalars {61            let w = u.properties.isAlphabetic || u.properties.numericType != nil62            if w && !inWord { n += 1 }63            inWord = w || (inWord && (u == "'" || u == "’" || u == "-" || u.properties.generalCategory == .nonspacingMark))64        }65        return n66    }6768    /// Word ranges (UTF-16) of a string, by the Unicode word-break rules.69    static func wordRanges(_ text: NSString, in range: NSRange? = nil) -> [NSRange] {70        var out: [NSRange] = []71        text.enumerateSubstrings(in: range ?? NSRange(location: 0, length: text.length), options: [.byWords, .substringNotRequired]) { _, r, _, _ in72            if r.length > 0 { out.append(r) }73        }74        return out75    }7677    static func sentenceRanges(_ text: NSString) -> [NSRange] {78        var out: [NSRange] = []79        text.enumerateSubstrings(in: NSRange(location: 0, length: text.length), options: [.bySentences, .substringNotRequired]) { _, r, _, _ in80            if r.length > 0 { out.append(r) }81        }82        return out83    }8485    /// Lower-case, diacritics removed, white space collapsed: the form used to compare headings and words.86    static func folded(_ s: String) -> String {87        s.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil)88            .split(whereSeparator: { $0.isWhitespace }).joined(separator: " ")89    }90}9192/// Outline levels of the paragraph styles of a document, cached.93struct HeadingLevels {94    private let styles: StyleSheet95    private var cache: [String: Int] = [:]96    init(_ doc: DocumentModel) { styles = doc.styles }9798    /// 1…9 for a heading, 0 for anything else.99    mutating func level(_ p: Paragraph) -> Int {100        let l: Int101        if let direct = p.props.outlineLevel { l = direct } else if let c = cache[p.style] { l = c } else {102            let v = styles.styleProps(p.style).para.outlineLevel ?? 0103            cache[p.style] = v104            l = v105        }106        return (1...9).contains(l) ? l : 0107    }108}109110extension StoryID {111    /// A sortable, printable key.112    var sortKey: String {113        switch self {114        case .body: return "0"115        case .header(let s, let v): return "1.\(String(format: "%05d", s)).\(HeaderFooterVariant.allCases.firstIndex(of: v) ?? 0)"116        case .footer(let s, let v): return "2.\(String(format: "%05d", s)).\(HeaderFooterVariant.allCases.firstIndex(of: v) ?? 0)"117        case .note(let id): return "3.\(id)"118        }119    }120}121122extension ParaPath {123    var sortKey: String {124        let c = cell.map { String(format: ".%05d.%05d.%05d", $0.row, $0.cell, $0.paragraph) } ?? ""125        return String(format: "%07d", block) + c126    }127}128
Files main
Menu

Theme