Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/Position.swift3// Description: Addressing: stories (body, headers, footers, notes), paragraph paths, text positions, selections, and traversal helpers.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public enum HeaderFooterVariant: String, Codable, Sendable, CaseIterable { case `default`, first, even }1011/// An independently editable flow of blocks.12public enum StoryID: Hashable, Sendable, Codable {13 case body14 case header(section: Int, variant: HeaderFooterVariant)15 case footer(section: Int, variant: HeaderFooterVariant)16 case note(String)17}1819public struct CellPath: Hashable, Sendable, Codable, Comparable {20 public var row: Int21 /// Index into `TableRow.cells` (not the grid column).22 public var cell: Int23 public var paragraph: Int24 public init(row: Int, cell: Int, paragraph: Int = 0) { self.row = row; self.cell = cell; self.paragraph = paragraph }25 public static func < (a: CellPath, b: CellPath) -> Bool { (a.row, a.cell, a.paragraph) < (b.row, b.cell, b.paragraph) }26}2728/// Path to a paragraph (or to a whole block when `cell` is nil and the block is not a paragraph).29public struct ParaPath: Hashable, Sendable, Codable, Comparable {30 public var block: Int31 public var cell: CellPath?32 public init(block: Int, cell: CellPath? = nil) { self.block = block; self.cell = cell }33 public static func < (a: ParaPath, b: ParaPath) -> Bool {34 if a.block != b.block { return a.block < b.block }35 switch (a.cell, b.cell) {36 case let (x?, y?): return x < y37 case (nil, _?): return true38 default: return false39 }40 }41}4243/// A caret position. In a paragraph `offset` is a UTF-16 offset; on an atomic block or a whole table it is 0 (before) or 1 (after).44public struct Position: Hashable, Sendable, Codable, Comparable {45 public var path: ParaPath46 public var offset: Int47 public init(path: ParaPath, offset: Int) { self.path = path; self.offset = offset }48 public init(block: Int, offset: Int) { self.path = ParaPath(block: block); self.offset = offset }49 public static func < (a: Position, b: Position) -> Bool { a.path != b.path ? a.path < b.path : a.offset < b.offset }50}5152public struct Selection: Hashable, Sendable, Codable {53 public var story: StoryID54 public var anchor: Position55 public var head: Position56 public init(story: StoryID = .body, anchor: Position, head: Position) { self.story = story; self.anchor = anchor; self.head = head }57 public init(story: StoryID = .body, caret: Position) { self.story = story; self.anchor = caret; self.head = caret }58 public var isCaret: Bool { anchor == head }59 public var start: Position { min(anchor, head) }60 public var end: Position { max(anchor, head) }61 public static let documentStart = Selection(caret: Position(block: 0, offset: 0))62}6364public extension DocumentModel {65 /// Page setups of every section in order (the first one is `pageSetup`).66 var sectionSetups: [PageSetup] {67 [pageSetup] + body.compactMap { if case .sectionBreak(let s) = $0 { return s.setup } else { return nil } }68 }6970 /// Index of the section that contains body block `index`.71 func sectionIndex(ofBlock index: Int) -> Int {72 var s = 073 for (i, b) in body.enumerated() where i <= index { if case .sectionBreak = b { s += 1 } }74 return s75 }7677 /// Reads or replaces the page setup of section `index`.78 func setup(ofSection index: Int) -> PageSetup {79 let all = sectionSetups80 return all[max(0, min(all.count - 1, index))]81 }8283 mutating func setSetup(_ setup: PageSetup, ofSection index: Int) {84 if index <= 0 { pageSetup = setup; return }85 var s = 086 for i in body.indices {87 if case .sectionBreak(var br) = body[i] {88 s += 189 if s == index { br.setup = setup; body[i] = .sectionBreak(br); return }90 }91 }92 }9394 /// The blocks of a story. Header, footer and note stories only hold paragraphs.95 func blocks(in story: StoryID) -> [Block] {96 switch story {97 case .body: return body98 case .header(let s, let v): return headerFooter(setup(ofSection: s).header, v).map { .paragraph($0) }99 case .footer(let s, let v): return headerFooter(setup(ofSection: s).footer, v).map { .paragraph($0) }100 case .note(let id): return (notes[id]?.paragraphs ?? []).map { .paragraph($0) }101 }102 }103104 private func headerFooter(_ hf: HeaderFooter, _ v: HeaderFooterVariant) -> [Paragraph] {105 switch v { case .default: return hf.default; case .first: return hf.first; case .even: return hf.even }106 }107108 /// Replaces the blocks of a story. Non-paragraph blocks are dropped from header, footer and note stories.109 mutating func setBlocks(_ blocks: [Block], in story: StoryID) {110 func paras() -> [Paragraph] { blocks.compactMap(\.paragraph) }111 switch story {112 case .body:113 body = blocks.isEmpty ? [.paragraph(Paragraph())] : blocks114 case .header(let s, let v):115 var su = setup(ofSection: s)116 switch v { case .default: su.header.default = paras(); case .first: su.header.first = paras(); case .even: su.header.even = paras() }117 setSetup(su, ofSection: s)118 case .footer(let s, let v):119 var su = setup(ofSection: s)120 switch v { case .default: su.footer.default = paras(); case .first: su.footer.first = paras(); case .even: su.footer.even = paras() }121 setSetup(su, ofSection: s)122 case .note(let id):123 notes[id]?.paragraphs = paras()124 }125 }126127 /// Visits every paragraph of the body in reading order, table cells included.128 func forEachBodyParagraph(_ visit: (Paragraph, ParaPath) -> Void) {129 DocumentModel.forEachParagraph(in: body, visit)130 }131132 static func forEachParagraph(in blocks: [Block], _ visit: (Paragraph, ParaPath) -> Void) {133 for (bi, block) in blocks.enumerated() {134 switch block {135 case .paragraph(let p): visit(p, ParaPath(block: bi))136 case .table(let t):137 for (ri, row) in t.rows.enumerated() {138 for (ci, cell) in row.cells.enumerated() {139 for (pi, p) in cell.paragraphs.enumerated() { visit(p, ParaPath(block: bi, cell: CellPath(row: ri, cell: ci, paragraph: pi))) }140 }141 }142 default: break143 }144 }145 }146147 /// Visits every paragraph of the whole document (body, table cells, headers, footers, notes).148 func forEachParagraphEverywhere(_ visit: (Paragraph, StoryID, ParaPath) -> Void) {149 forEachBodyParagraph { visit($0, .body, $1) }150 for (si, su) in sectionSetups.enumerated() {151 for v in HeaderFooterVariant.allCases {152 for (i, p) in headerFooter(su.header, v).enumerated() { visit(p, .header(section: si, variant: v), ParaPath(block: i)) }153 for (i, p) in headerFooter(su.footer, v).enumerated() { visit(p, .footer(section: si, variant: v), ParaPath(block: i)) }154 }155 }156 for (id, n) in notes.sorted(by: { $0.key < $1.key }) {157 for (i, p) in n.paragraphs.enumerated() { visit(p, .note(id), ParaPath(block: i)) }158 }159 }160161 /// Rewrites every paragraph of the whole document in place.162 mutating func mutateEveryParagraph(_ f: (inout Paragraph) -> Void) {163 DocumentModel.mutateParagraphs(in: &body, f)164 func hf(_ h: inout HeaderFooter) {165 for i in h.default.indices { f(&h.default[i]) }166 for i in h.first.indices { f(&h.first[i]) }167 for i in h.even.indices { f(&h.even[i]) }168 }169 hf(&pageSetup.header); hf(&pageSetup.footer)170 for i in body.indices {171 if case .sectionBreak(var s) = body[i] { hf(&s.setup.header); hf(&s.setup.footer); body[i] = .sectionBreak(s) }172 }173 for k in notes.keys {174 for i in notes[k]!.paragraphs.indices { f(¬es[k]!.paragraphs[i]) }175 }176 }177178 static func mutateParagraphs(in blocks: inout [Block], _ f: (inout Paragraph) -> Void) {179 for bi in blocks.indices {180 switch blocks[bi] {181 case .paragraph(var p): f(&p); blocks[bi] = .paragraph(p)182 case .table(var t):183 for ri in t.rows.indices { for ci in t.rows[ri].cells.indices { for pi in t.rows[ri].cells[ci].paragraphs.indices { f(&t.rows[ri].cells[ci].paragraphs[pi]) } } }184 blocks[bi] = .table(t)185 default: break186 }187 }188 }189}190191public extension Array where Element == Block {192 /// The paragraph at `path`, if the path designates one.193 func paragraph(at path: ParaPath) -> Paragraph? {194 guard indices.contains(path.block) else { return nil }195 switch self[path.block] {196 case .paragraph(let p): return path.cell == nil ? p : nil197 case .table(let t):198 guard let c = path.cell, t.rows.indices.contains(c.row), t.rows[c.row].cells.indices.contains(c.cell),199 t.rows[c.row].cells[c.cell].paragraphs.indices.contains(c.paragraph) else { return nil }200 return t.rows[c.row].cells[c.cell].paragraphs[c.paragraph]201 default: return nil202 }203 }204205 /// Replaces the paragraph at `path`. Returns false when the path is invalid.206 @discardableResult207 mutating func setParagraph(_ p: Paragraph, at path: ParaPath) -> Bool {208 guard indices.contains(path.block) else { return false }209 switch self[path.block] {210 case .paragraph:211 guard path.cell == nil else { return false }212 self[path.block] = .paragraph(p)213 return true214 case .table(var t):215 guard let c = path.cell, t.rows.indices.contains(c.row), t.rows[c.row].cells.indices.contains(c.cell),216 t.rows[c.row].cells[c.cell].paragraphs.indices.contains(c.paragraph) else { return false }217 t.rows[c.row].cells[c.cell].paragraphs[c.paragraph] = p218 self[path.block] = .table(t)219 return true220 default: return false221 }222 }223224 /// Every paragraph path in reading order.225 var paragraphPaths: [ParaPath] {226 var out: [ParaPath] = []227 DocumentModel.forEachParagraph(in: self) { _, path in out.append(path) }228 return out229 }230}231232/// Counts shown in the status bar.233public struct DocumentStatistics: Hashable, Sendable {234 public var words = 0235 public var characters = 0236 public var charactersNoSpaces = 0237 public var paragraphs = 0238 public var tables = 0239 public var images = 0240 public var equations = 0241 public var footnotes = 0242243 public init() {}244245 public init(_ doc: DocumentModel) {246 self.init()247 doc.forEachBodyParagraph { p, _ in add(p) }248 for n in doc.notes.values { for p in n.paragraphs { add(p) } }249 tables = doc.body.reduce(0) { $0 + ($1.table == nil ? 0 : 1) }250 footnotes = doc.notes.count251 }252253 public init(text: String) {254 self.init()255 add(text: text)256 }257258 mutating func add(_ p: Paragraph) {259 let t = p.visibleText260 if !t.isEmpty { paragraphs += 1 }261 add(text: t)262 for r in p.runs where !r.isDeleted {263 switch r.inline {264 case .image: images += 1265 case .equation: equations += 1266 default: break267 }268 }269 }270271 mutating func add(text t: String) {272 characters += t.count273 var inWord = false274 for ch in t.unicodeScalars {275 let isSpace = CharacterSet.whitespacesAndNewlines.contains(ch)276 if !isSpace { charactersNoSpaces += 1 }277 let isWordChar = CharacterSet.alphanumerics.contains(ch) || ch == "'" || ch == "’" || ch == "-"278 if isWordChar && !inWord { if CharacterSet.alphanumerics.contains(ch) { words += 1; inWord = true } }279 else if !isWordChar { inWord = false }280 }281 }282}283