Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocModel/ParagraphText.swift3// Description: Text operations on a paragraph. Every offset is a UTF-16 code unit offset; callers align offsets on composed character boundaries.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public extension String {10 var utf16Length: Int { utf16.count }1112 /// Substring by UTF-16 range, clamped to the string.13 func utf16Substring(_ range: Range<Int>) -> String {14 let ns = self as NSString15 let lo = max(0, min(ns.length, range.lowerBound)), hi = max(lo, min(ns.length, range.upperBound))16 return ns.substring(with: NSRange(location: lo, length: hi - lo))17 }1819 /// Moves `offset` to the nearest composed-character boundary at or before it, so an edit never splits a surrogate pair,20 /// an emoji sequence or a base letter and its combining marks.21 func composedBoundary(atOrBefore offset: Int) -> Int {22 let ns = self as NSString23 guard offset > 0, offset < ns.length else { return max(0, min(ns.length, offset)) }24 return ns.rangeOfComposedCharacterSequence(at: offset).location25 }2627 /// The composed-character boundary after `offset`.28 func composedBoundary(after offset: Int) -> Int {29 let ns = self as NSString30 guard offset < ns.length else { return ns.length }31 let r = ns.rangeOfComposedCharacterSequence(at: max(0, offset))32 return r.location + r.length33 }3435 /// The composed-character boundary before `offset`.36 func composedBoundary(before offset: Int) -> Int {37 let ns = self as NSString38 guard offset > 0 else { return 0 }39 return ns.rangeOfComposedCharacterSequence(at: min(ns.length, offset) - 1).location40 }41}4243public extension Paragraph {44 /// The paragraph text, inline objects appearing as U+FFFC. Includes text marked as deleted.45 var plainText: String { runs.count == 1 ? runs[0].text : runs.reduce(into: "") { $0 += $1.text } }4647 /// Text as it reads once every tracked change is accepted, with inline objects removed.48 var visibleText: String {49 runs.reduce(into: "") { acc, r in if !r.isDeleted && r.inline == nil { acc += r.text } }50 }5152 var length: Int { runs.reduce(0) { $0 + $1.length } }53 var isEmpty: Bool { runs.allSatisfy { $0.text.isEmpty } }5455 /// Index of the run containing `offset` and the offset inside it. At a run boundary the run BEFORE the offset is returned56 /// (typing continues the formatting on the left), except at offset 0.57 func runLocation(at offset: Int) -> (index: Int, local: Int)? {58 guard !runs.isEmpty else { return nil }59 var pos = 060 for (i, r) in runs.enumerated() {61 let len = r.length62 if offset <= pos + len { return (i, max(0, offset - pos)) }63 pos += len64 }65 return (runs.count - 1, runs[runs.count - 1].length)66 }6768 /// The run a character at `offset` belongs to (the run AFTER the boundary).69 func run(containing offset: Int) -> Run? {70 var pos = 071 for r in runs {72 let len = r.length73 if offset >= pos && offset < pos + len { return r }74 pos += len75 }76 return nil77 }7879 /// Formatting that newly typed text takes at `offset`: that of the text to its left (never an inline object's link or revision).80 func typingAttributes(at offset: Int) -> (props: CharProps, charStyle: String?, comments: [String]) {81 guard let loc = runLocation(at: offset) else { return (.none, nil, []) }82 let r = runs[loc.index]83 var p = r.props84 // A link does not extend to text typed right after it.85 if loc.local == r.length, offset == length || run(containing: offset)?.props.link != p.link { p.link = nil }86 let inside = loc.local > 0 && loc.local < r.length87 return (p, r.charStyle, inside ? r.comments : [])88 }8990 /// Makes `offset` a run boundary and returns the index of the run that starts there (runs.count when at the end).91 @discardableResult92 mutating func splitRun(at offset: Int) -> Int {93 var pos = 094 for i in runs.indices {95 let len = runs[i].length96 if offset == pos { return i }97 if offset < pos + len {98 let local = offset - pos99 var left = runs[i], right = runs[i]100 left.text = runs[i].text.utf16Substring(0..<local)101 right.text = runs[i].text.utf16Substring(local..<len)102 runs[i] = left103 runs.insert(right, at: i + 1)104 return i + 1105 }106 pos += len107 }108 return runs.count109 }110111 mutating func insert(_ run: Run, at offset: Int) {112 guard !run.text.isEmpty else { return }113 let i = splitRun(at: max(0, min(length, offset)))114 runs.insert(run, at: i)115 normalize()116 }117118 mutating func insert(_ newRuns: [Run], at offset: Int) {119 let i = splitRun(at: max(0, min(length, offset)))120 runs.insert(contentsOf: newRuns.filter { !$0.text.isEmpty }, at: i)121 normalize()122 }123124 /// Removes the text in `range` for good (no change tracking).125 mutating func delete(_ range: Range<Int>) {126 let lo = max(0, min(length, range.lowerBound)), hi = max(lo, min(length, range.upperBound))127 guard hi > lo else { return }128 let a = splitRun(at: lo)129 let b = splitRun(at: hi)130 runs.removeSubrange(a..<b)131 normalize()132 }133134 /// The runs covering `range` (copies; boundary runs are cut).135 func slice(_ range: Range<Int>) -> [Run] {136 var p = self137 let lo = max(0, min(length, range.lowerBound)), hi = max(lo, min(length, range.upperBound))138 let a = p.splitRun(at: lo)139 let b = p.splitRun(at: hi)140 return Array(p.runs[a..<b])141 }142143 /// Applies `transform` to every run inside `range`, splitting runs at the boundaries.144 mutating func transform(_ range: Range<Int>, _ transform: (inout Run) -> Void) {145 let lo = max(0, min(length, range.lowerBound)), hi = max(lo, min(length, range.upperBound))146 guard hi > lo else { return }147 let a = splitRun(at: lo)148 let b = splitRun(at: hi)149 for i in a..<b { transform(&runs[i]) }150 normalize()151 }152153 /// Drops empty runs and merges neighbours that share formatting.154 mutating func normalize() {155 guard runs.count > 0 else { return }156 var out: [Run] = []157 out.reserveCapacity(runs.count)158 for r in runs where !r.text.isEmpty {159 if let last = out.last, last.canMerge(with: r) {160 out[out.count - 1].text += r.text161 } else {162 out.append(r)163 }164 }165 runs = out166 }167168 /// Splits the paragraph at `offset`. The second half gets a new id and `nextStyle` when the split is at the very end.169 func split(at offset: Int, nextStyle: String? = nil) -> (Paragraph, Paragraph) {170 var first = self171 let i = first.splitRun(at: max(0, min(length, offset)))172 var second = self173 second.id = DocID.make()174 second.runs = Array(first.runs[i...])175 second.markRevision = markRevision176 first.runs = Array(first.runs[..<i])177 first.markRevision = nil178 first.normalize(); second.normalize()179 if second.runs.isEmpty, let ns = nextStyle, ns != style {180 second.style = ns181 second.props = .none182 // A heading followed by body text does not continue a list or page-break flag.183 second.list = nil184 }185 second.props.pageBreakBefore = nil186 return (first, second)187 }188189 /// Appends the content of `other` (joining two paragraphs). The receiver keeps its own paragraph formatting.190 mutating func append(contentsOf other: Paragraph) {191 runs.append(contentsOf: other.runs)192 markRevision = other.markRevision193 normalize()194 }195196 /// Offsets of the inline objects with their payload.197 var inlineObjects: [(offset: Int, inline: Inline)] {198 var out: [(Int, Inline)] = []199 var pos = 0200 for r in runs {201 if let i = r.inline { out.append((pos, i)) }202 pos += r.length203 }204 return out205 }206207 var hasTrackedChanges: Bool { markRevision != nil || runs.contains { $0.revision != nil || $0.formatRevision != nil } }208}209