SPB Git

Repository Public

Inline.swift 6.8 KB 182 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/Inline.swift3// Description: Inline content helpers: runs to nodes and back, UTF-16 offsets, splitting, normalization and4//              mark-set arithmetic following ProseMirror's rules (rank order, exclusions).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// A position inside the document: a line and an inline offset (UTF-16 units; an atom counts as 1).11public struct InlinePosition: Sendable, Hashable {12    public var line: Int13    public var offset: Int1415    public init(line: Int, offset: Int) {16        self.line = line17        self.offset = offset18    }19}2021extension InlineRun {22    /// Length in inline units: UTF-16 code units of the text, 1 for an atom.23    public var length: Int {24        switch self {25        case .text(let s, _): return s.utf16.count26        case .atom: return 127        }28    }2930    /// The marks of the run (an atom's marks are those of its node).31    public var marks: [PMMark] {32        switch self {33        case .text(_, let m): return m34        case .atom(let n): return n.marks ?? []35        }36    }37}3839extension Line {40    /// The inline runs of a text line; empty for a block atom.41    public var runs: [InlineRun] {42        if case .inline(let r) = content { return r }43        return []44    }4546    /// Whether the line is a text block.47    public var isText: Bool {48        if case .inline = content { return true }49        return false50    }5152    /// Inline length of the line (UTF-16 units, atoms count 1); 0 for a block atom.53    public var inlineLength: Int { runs.reduce(0) { $0 + $1.length } }5455    /// The string an editor displays: text as is, a hard break as U+2028, any other atom as U+FFFC.56    /// Its UTF-16 length equals `inlineLength`.57    public var displayString: String {58        var s = ""59        for run in runs {60            switch run {61            case .text(let t, _): s += t62            case .atom(let n): s += n.type == NodeType.hardBreak ? "\u{2028}" : "\u{FFFC}"63            }64        }65        return s66    }67}6869enum InlineTools {70    /// Serializes runs: empty text runs are dropped, adjacent text runs with identical marks are merged.71    static func nodes(from runs: [InlineRun]) -> [PMNode] {72        var out: [PMNode] = []73        var lastIsRunText = false74        for run in runs {75            switch run {76            case .atom(let n):77                out.append(n)78                lastIsRunText = false79            case .text(let s, let marks):80                if s.isEmpty { continue }81                if lastIsRunText, let last = out.last, (last.marks ?? []) == marks {82                    out[out.count - 1].text = (last.text ?? "") + s83                } else {84                    out.append(.text(s, marks: marks))85                    lastIsRunText = true86                }87            }88        }89        return out90    }9192    /// Plain text as runs: line feeds become hard breaks.93    static func runs(plain text: String, marks: [PMMark] = []) -> [InlineRun] {94        var out: [InlineRun] = []95        for (n, part) in text.components(separatedBy: "\n").enumerated() {96            if n > 0 { out.append(.atom(.hardBreak())) }97            if !part.isEmpty { out.append(.text(part, marks: marks)) }98        }99        return out100    }101102    /// Drops empty text runs and merges adjacent text runs with identical marks.103    static func normalized(_ runs: [InlineRun]) -> [InlineRun] {104        var out: [InlineRun] = []105        for run in runs {106            if case .text(let s, let m) = run {107                if s.isEmpty { continue }108                if case .text(let ps, let pm)? = out.last, pm == m { out[out.count - 1] = .text(ps + s, marks: m); continue }109            }110            out.append(run)111        }112        return out113    }114115    static func length(_ runs: [InlineRun]) -> Int { runs.reduce(0) { $0 + $1.length } }116117    /// Splits a string at a UTF-16 offset, moved back to a scalar boundary when it falls inside a surrogate pair.118    static func splitText(_ s: String, at offset: Int) -> (String, String) {119        let u = s.utf16120        var idx = u.index(u.startIndex, offsetBy: max(0, min(offset, u.count)))121        while idx > u.startIndex, idx.samePosition(in: s.unicodeScalars) == nil { idx = u.index(before: idx) }122        return (String(s[..<idx]), String(s[idx...]))123    }124125    /// Splits runs at an inline offset (clamped).126    static func split(_ runs: [InlineRun], at offset: Int) -> (left: [InlineRun], right: [InlineRun]) {127        var left: [InlineRun] = [], right: [InlineRun] = []128        var pos = 0129        for run in runs {130            let len = run.length131            if pos + len <= offset { left.append(run) }132            else if pos >= offset { right.append(run) }133            else if case .text(let s, let m) = run {134                let (a, b) = splitText(s, at: offset - pos)135                if !a.isEmpty { left.append(.text(a, marks: m)) }136                if !b.isEmpty { right.append(.text(b, marks: m)) }137            }138            pos += len139        }140        return (left, right)141    }142143    /// Splits runs in three at a range (clamped).144    static func split(_ runs: [InlineRun], range: Range<Int>) -> (before: [InlineRun], inside: [InlineRun], after: [InlineRun]) {145        let total = length(runs)146        let lo = max(0, min(range.lowerBound, total)), hi = max(lo, min(range.upperBound, total))147        let (head, after) = split(runs, at: hi)148        let (before, inside) = split(head, at: lo)149        return (before, inside, after)150    }151152    /// Text of runs as the server's `nodeText` gives it (hard break → line feed, mention → @label, math → latex).153    static func plainText(_ runs: [InlineRun]) -> String {154        runs.map { run -> String in155            switch run {156            case .text(let s, _): return s157            case .atom(let n): return TextTools.nodeText(n)158            }159        }.joined()160    }161162    // MARK: Mark sets163164    /// ProseMirror's `Mark.addToSet`: rank order, a mark replaces one of its type, `code` excludes every other mark.165    static func adding(_ mark: PMMark, to set: [PMMark]) -> [PMMark] {166        if set.contains(mark) { return set }167        if mark.type != "code", set.contains(where: { $0.type == "code" }) { return set }168        var out = mark.type == "code" ? [] : set.filter { $0.type != mark.type }169        let rank = Schema.markRank(mark.type)170        out.insert(mark, at: out.firstIndex { Schema.markRank($0.type) > rank } ?? out.count)171        return out172    }173174    static func removing(_ type: String, from set: [PMMark]) -> [PMMark] { set.filter { $0.type != type } }175176    /// A mark set made valid for the schema: rank order, one mark per type, `code` alone.177    static func validMarks(_ marks: [PMMark]) -> [PMMark] {178        if let code = marks.first(where: { $0.type == "code" }) { return [code] }179        return marks.reduce(into: [PMMark]()) { $0 = adding($1, to: $0) }180    }181}182
Files main
Menu

Theme