SPB Git

Repository Public

Numbering.swift 10.7 KB 225 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/Numbering.swift3// Description: One pass over the document that resolves list labels, heading numbers, caption sequences, note numbers, citation order,4//              the outline and cross-reference targets. Everything that displays a number reads it from here.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public struct OutlineEntry: Hashable, Sendable, Identifiable {11    public var id: String12    public var level: Int13    public var text: String14    /// Hierarchical number ("2.1") when the heading style is numbered.15    public var number: String?16    public var blockIndex: Int17}1819public struct CaptionInfo: Hashable, Sendable {20    /// Sequence name: "Figure", "Table", "Equation" …21    public var label: String22    public var number: Int23    /// Full caption text as displayed ("Figure 2: Yield curve").24    public var text: String25    public var blockIndex: Int26}2728/// Formats citations and the bibliography. Implemented by the DocReferences module; the model only defines the contract.29public protocol CitationFormatting: Sendable {30    /// Inline text of a citation, e.g. "(Smith, 2020, p. 4)" or "[3]".31    func citationText(_ citation: Citation, document: DocumentModel, numbering: Numbering) -> String32    /// The formatted entries of the works cited in the document, in the order the style prescribes.33    func bibliographyParagraphs(document: DocumentModel, numbering: Numbering) -> [Paragraph]34}3536public struct Numbering: Sendable {37    /// Paragraph id → list label ("1.", "a)", "•").38    public private(set) var listLabels: [String: String] = [:]39    /// Paragraph id → heading number ("2.1").40    public private(set) var headingNumbers: [String: String] = [:]41    /// Paragraph id → values of its sequence fields, in order of appearance.42    public private(set) var sequences: [String: [Int]] = [:]43    /// Note id → number (footnotes and endnotes are numbered separately).44    public private(set) var noteNumbers: [String: Int] = [:]45    public private(set) var footnoteOrder: [String] = []46    public private(set) var endnoteOrder: [String] = []47    /// Citation key → rank of first citation (1-based).48    public private(set) var citationOrder: [String: Int] = [:]49    public private(set) var citedKeys: [String] = []50    public private(set) var outline: [OutlineEntry] = []51    /// Paragraph id → caption information (paragraphs that contain a sequence field).52    public private(set) var captions: [String: CaptionInfo] = [:]53    /// Bookmark name → id of the paragraph that holds it.54    public private(set) var bookmarks: [String: String] = [:]55    /// Paragraph id → text (headings and captions only), for text cross-references.56    public private(set) var targetText: [String: String] = [:]5758    public init() {}5960    public init(_ doc: DocumentModel) {61        var listCounters: [String: [Int]] = [:]62        var headingCounters = Array(repeating: 0, count: 10)63        var seqCounters: [String: Int] = [:]64        var styleCache: [String: (level: Int, numbered: Bool)] = [:]6566        func styleInfo(_ id: String) -> (level: Int, numbered: Bool) {67            if let c = styleCache[id] { return c }68            let info = (doc.styles.styleProps(id).para.outlineLevel ?? 0, doc.styles.isNumberedHeading(id))69            styleCache[id] = info70            return info71        }7273        func visit(_ p: Paragraph, blockIndex: Int, inBody: Bool) {74            // Lists75            if let li = p.list, let def = doc.list(li.listID), !def.levels.isEmpty {76                let lvl = max(0, min(def.levels.count - 1, li.level))77                var counters = listCounters[li.listID] ?? Array(repeating: 0, count: def.levels.count)78                counters[lvl] = counters[lvl] == 0 ? def.levels[lvl].start : counters[lvl] + 179                for deeper in (lvl + 1)..<counters.count { counters[deeper] = 0 }80                listCounters[li.listID] = counters81                let level = def.levels[lvl]82                if level.format == .bullet {83                    listLabels[p.id] = level.pattern84                } else {85                    var label = level.pattern86                    for k in stride(from: def.levels.count, through: 1, by: -1) {87                        let value = counters[k - 1] == 0 ? def.levels[k - 1].start : counters[k - 1]88                        label = label.replacingOccurrences(of: "%\(k)", with: def.levels[k - 1].format.string(value))89                    }90                    listLabels[p.id] = label91                }92            }93            // Headings94            let info = styleInfo(p.style)95            let level = p.props.outlineLevel ?? info.level96            if inBody, level >= 1, level <= 9 {97                var number: String?98                if info.numbered {99                    headingCounters[level] += 1100                    for deeper in (level + 1)..<headingCounters.count { headingCounters[deeper] = 0 }101                    number = (1...level).map { String(max(1, headingCounters[$0])) }.joined(separator: ".")102                    headingNumbers[p.id] = number103                }104                let text = p.visibleText.trimmingCharacters(in: .whitespacesAndNewlines)105                if !text.isEmpty { outline.append(OutlineEntry(id: p.id, level: level, text: text, number: number, blockIndex: blockIndex)) }106                targetText[p.id] = text107            }108            // Inline objects109            var seqValues: [Int] = []110            var firstSeq: (String, Int)?111            for r in p.runs where !r.isDeleted {112                guard let inline = r.inline else { continue }113                switch inline {114                case .field(.sequence(let name)):115                    let v = (seqCounters[name] ?? 0) + 1116                    seqCounters[name] = v117                    seqValues.append(v)118                    if firstSeq == nil { firstSeq = (name, v) }119                case .note(let ref):120                    guard noteNumbers[ref.id] == nil else { break }121                    if ref.kind == .footnote { footnoteOrder.append(ref.id); noteNumbers[ref.id] = footnoteOrder.count }122                    else { endnoteOrder.append(ref.id); noteNumbers[ref.id] = endnoteOrder.count }123                case .citation(let c):124                    for item in c.items where citationOrder[item.key] == nil {125                        citedKeys.append(item.key)126                        citationOrder[item.key] = citedKeys.count127                    }128                case .bookmark(let name):129                    bookmarks[name] = p.id130                default: break131                }132            }133            if !seqValues.isEmpty { sequences[p.id] = seqValues }134            if let (name, v) = firstSeq {135                captions[p.id] = CaptionInfo(label: name, number: v, text: "", blockIndex: blockIndex)136            }137        }138139        for (bi, block) in doc.body.enumerated() {140            switch block {141            case .paragraph(let p): visit(p, blockIndex: bi, inBody: true)142            case .table(let t):143                for row in t.rows { for cell in row.cells { for p in cell.paragraphs { visit(p, blockIndex: bi, inBody: false) } } }144            default: break145            }146        }147        // Notes are visited after the body so citations inside them rank after body citations of the same page order.148        for id in footnoteOrder + endnoteOrder {149            for p in doc.notes[id]?.paragraphs ?? [] { visit(p, blockIndex: -1, inBody: false) }150        }151        // Caption display text needs the final sequence values.152        for (bi, block) in doc.body.enumerated() {153            guard case .paragraph(let p) = block, var info = captions[p.id] else { continue }154            info.text = displayText(of: p, document: doc).trimmingCharacters(in: .whitespacesAndNewlines)155            info.blockIndex = bi156            captions[p.id] = info157            targetText[p.id] = info.text158        }159    }160161    /// The paragraph text with page-independent fields replaced by their value (sequences, note marks, title, author, date).162    public func displayText(of p: Paragraph, document doc: DocumentModel) -> String {163        var out = ""164        var seqIndex = 0165        for r in p.runs where !r.isDeleted {166            guard let inline = r.inline else { out += r.text; continue }167            switch inline {168            case .field(.sequence):169                let values = sequences[p.id] ?? []170                out += seqIndex < values.count ? String(values[seqIndex]) : "?"171                seqIndex += 1172            case .field(let f): out += staticFieldText(f, document: doc) ?? ""173            case .equation(let e): out += e.latex174            case .crossRef(let ref): out += crossRefText(ref, pageOf: { _ in nil })175            default: break176            }177        }178        return out179    }180181    /// Value of the fields that do not depend on pagination; nil for page-dependent fields.182    public func staticFieldText(_ field: Field, document doc: DocumentModel, now: Date = Date()) -> String? {183        switch field {184        case .title: return doc.meta.title185        case .author: return doc.meta.author186        case .date(let format):187            let f = DateFormatter()188            f.locale = Locale(identifier: doc.meta.language)189            f.dateFormat = format190            return f.string(from: now)191        case .pageNumber, .pageCount, .headingText, .sequence: return nil192        }193    }194195    public func noteMark(_ ref: NoteRef) -> String {196        let n = noteNumbers[ref.id] ?? 0197        return ref.kind == .footnote ? String(n) : NumberFormat.lowerRoman.string(n)198    }199200    /// True when the target of a cross-reference exists.201    public func targetExists(_ target: String) -> Bool {202        targetText[target] != nil || captions[target] != nil || bookmarks[target] != nil203    }204205    /// Displayed text of a cross-reference. `pageOf` maps a paragraph id to its formatted page number once layout is known.206    /// A missing target renders as "??" (and is reported by the auditor).207    public func crossRefText(_ ref: CrossRef, pageOf: (String) -> String?) -> String {208        let target = bookmarks[ref.target] ?? ref.target209        guard targetExists(ref.target) || targetExists(target) else { return "??" }210        switch ref.display {211        case .page:212            return pageOf(target) ?? "?"213        case .text:214            return targetText[target] ?? "??"215        case .number:216            if let c = captions[target] { return String(c.number) }217            return headingNumbers[target] ?? targetText[target] ?? "??"218        case .labelAndNumber:219            if let c = captions[target] { return c.label == "Equation" ? "(\(c.number))" : "\(c.label) \(c.number)" }220            if let n = headingNumbers[target] { return "Section \(n)" }221            return targetText[target] ?? "??"222        }223    }224}225
Files main
Menu

Theme