SPB Git

Repository Public

Commands.swift 29.6 KB 642 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/Commands.swift3// Description: Block-level editing commands on the flattened model (line types, lists, indentation, quotes, callouts,4//              tasks, Enter, Backspace, block atoms). Each leaves a document valid for the web schema.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Structure helpers1112extension NoteDocument {13    func clamp(_ range: Range<Int>) -> Range<Int> {14        let lo = max(0, min(range.lowerBound, lines.count))15        return lo..<max(lo, min(range.upperBound, lines.count))16    }1718    /// The contiguous lines belonging to the same container node as line `i` at `depth`.19    func groupRange(of i: Int, depth: Int) -> Range<Int> {20        let key = lines[i].path[depth].key21        var a = i, b = i + 122        while a > 0, lines[a - 1].path.count > depth, lines[a - 1].path[depth].key == key { a -= 1 }23        while b < lines.count, lines[b].path.count > depth, lines[b].path[depth].key == key { b += 1 }24        return a..<b25    }2627    func firstLine(withContainer key: Int) -> (line: Int, depth: Int)? {28        for (i, line) in lines.enumerated() {29            if let d = line.path.firstIndex(where: { $0.key == key }) { return (i, d) }30        }31        return nil32    }3334    func samePathKeys(_ a: [Container], _ b: [Container]) -> Bool {35        a.count == b.count && zip(a, b).allSatisfy { $0.key == $1.key }36    }3738    /// Index in `path` of the innermost list item frame (preceded by its list frame).39    func innermostItemDepth(_ path: [Container]) -> Int? {40        var e = path.count - 141        while e >= 1 {42            if Schema.items.contains(path[e].type), Schema.lists.contains(path[e - 1].type) { return e }43            e -= 144        }45        return nil46    }4748    /// Whether the line sits directly in a list item (its innermost container is the item).49    func isDirectlyInItem(_ path: [Container]) -> Bool {50        path.count >= 2 && Schema.items.contains(path[path.count - 1].type) && Schema.lists.contains(path[path.count - 2].type)51    }5253    /// Whether removing the line (and the containers it is alone in) keeps the document valid.54    func canRemoveLine(_ i: Int) -> Bool {55        guard lines.count > 1 else { return false }56        var d = lines[i].path.count57        while d > 0, groupRange(of: i, depth: d - 1) == i..<(i + 1) { d -= 1 }58        guard d > 0 else { return true }59        let parent = lines[i].path[d - 1]60        if parent.type == NodeType.details { return false }61        if Schema.items.contains(parent.type), groupRange(of: i, depth: d - 1).lowerBound == i { return false }62        return true63    }6465    /// Applies `body` to every copy of the container frame `key` (a frame is repeated on each line of its group).66    public mutating func updateContainer(key: Int, _ body: (inout Container) -> Void) {67        for i in lines.indices {68            for d in lines[i].path.indices where lines[i].path[d].key == key { body(&lines[i].path[d]) }69        }70    }7172    /// Gives a new key (and a new block id) to a container whose lines are no longer contiguous: such groups already73    /// serialize as separate nodes, this makes the model say so. Commands call it; editors may after manual edits.74    public mutating func normalizeContainerKeys() {75        var open: [Int] = []76        var seen = Set<Int>()77        for i in lines.indices {78            var d = 079            while d < min(open.count, lines[i].path.count), open[d] == lines[i].path[d].key { d += 1 }80            var j = d81            while j < lines[i].path.count {82                let key = lines[i].path[j].key83                if seen.contains(key) {84                    let newKey = newContainerKey()85                    let prefix = lines[i].path[..<j].map(\.key)86                    let newId: JSONValue? = Schema.idTypes.contains(lines[i].path[j].type) ? .string(BlockID.generate()) : nil87                    var l = i88                    while l < lines.count, lines[l].path.count > j, lines[l].path[j].key == key,89                          lines[l].path[..<j].map(\.key) == prefix {90                        lines[l].path[j].key = newKey91                        if let newId { lines[l].path[j].attrs["id"] = newId }92                        l += 193                    }94                    seen.insert(newKey)95                } else {96                    seen.insert(key)97                }98                j += 199            }100            open = lines[i].path.map(\.key)101        }102    }103104    /// Inserts lines coming from elsewhere (paste, another document): their container keys are remapped to fresh105    /// ones. The caller chooses paths that are valid at the insertion point.106    public mutating func insert(lines newLines: [Line], at index: Int) {107        var map: [Int: Int] = [:]108        var copy = newLines109        for i in copy.indices {110            for d in copy[i].path.indices {111                let old = copy[i].path[d].key112                if map[old] == nil { map[old] = newContainerKey() }113                copy[i].path[d].key = map[old]!114            }115        }116        lines.insert(contentsOf: copy, at: max(0, min(index, lines.count)))117        normalizeContainerKeys()118    }119}120121// MARK: - Queries122123extension NoteDocument {124    /// Kind of the innermost list containing the line, nil outside a list.125    public func listKind(at line: Int) -> ListKind? {126        guard lines.indices.contains(line), let e = innermostItemDepth(lines[line].path) else { return nil }127        return ListKind(listType: lines[line].path[e - 1].type)128    }129130    /// Number of lists the line is nested in.131    public func listDepth(at line: Int) -> Int {132        guard lines.indices.contains(line) else { return 0 }133        return lines[line].path.filter { Schema.lists.contains($0.type) }.count134    }135136    /// Whether the line is the first paragraph of a list item (the one drawn with the bullet, number or checkbox).137    public func isListItemHead(at line: Int) -> Bool {138        guard lines.indices.contains(line), isDirectlyInItem(lines[line].path) else { return false }139        return groupRange(of: line, depth: lines[line].path.count - 1).lowerBound == line140    }141142    /// Checked state of the innermost task item containing the line; nil outside a task item.143    public func isTaskChecked(at line: Int) -> Bool? {144        guard lines.indices.contains(line), let item = lines[line].path.last(where: { $0.type == NodeType.taskItem }) else { return nil }145        return JS.truthy(item.attrs["checked"])146    }147148    /// Ordinal of the line's item in its ordered list (honours `start`); nil outside an ordered list.149    public func listItemNumber(at line: Int) -> Int? {150        guard lines.indices.contains(line), let e = innermostItemDepth(lines[line].path),151              lines[line].path[e - 1].type == NodeType.orderedList else { return nil }152        let start = groupRange(of: line, depth: e - 1).lowerBound153        var count = 0154        var last: Int?155        for l in start...line where lines[l].path[e].key != last {156            count += 1157            last = lines[l].path[e].key158        }159        return (lines[line].path[e - 1].attrs["start"]?.intValue ?? 1) + count - 1160    }161}162163// MARK: - Line type164165extension NoteDocument {166    /// Sets the type of the paragraph / heading / code block lines of the range. The first paragraph of a list item167    /// is left as it is (the schema requires a paragraph there).168    @discardableResult169    public mutating func setLineType(_ kind: LineKind, at range: Range<Int>) -> Bool {170        var changed = false171        for i in clamp(range) {172            guard lines[i].isText, [NodeType.paragraph, NodeType.heading, NodeType.codeBlock].contains(lines[i].type) else { continue }173            if kind != .paragraph, isListItemHead(at: i) { continue }174            if retype(i, to: kind) { changed = true }175        }176        return changed177    }178179    mutating func retype(_ i: Int, to kind: LineKind) -> Bool {180        let before = lines[i]181        var line = before182        let wasCode = line.type == NodeType.codeBlock183        var attrs = line.attrs184        let textAlign = wasCode ? JSONValue.null : (attrs["textAlign"] ?? .null)185        attrs["level"] = nil186        attrs["language"] = nil187        attrs["textAlign"] = nil188        if BlockID.usable(attrs["id"]) == nil { attrs["id"] = .string(BlockID.generate()) }189        switch kind {190        case .paragraph:191            line.type = NodeType.paragraph192            attrs["textAlign"] = textAlign193        case .heading(let level):194            line.type = NodeType.heading195            attrs["textAlign"] = textAlign196            attrs["level"] = .int(Int64(min(3, max(1, level))))197        case .codeBlock(let language):198            line.type = NodeType.codeBlock199            attrs["language"] = .string(language ?? (before.attrs["language"]?.stringValue ?? "plaintext"))200        }201        line.attrs = attrs202        let isCode = line.type == NodeType.codeBlock203        if isCode, !wasCode {204            let text = InlineTools.plainText(line.runs)205            line.content = .inline(text.isEmpty ? [] : [.text(text, marks: [])])206            line.preserved.marks = nil207        } else if wasCode, !isCode {208            line.content = .inline(InlineTools.runs(plain: InlineTools.plainText(line.runs)))209        }210        lines[i] = line211        return line != before212    }213}214215// MARK: - Lists216217extension NoteDocument {218    private func convertedList(_ c: Container, to kind: ListKind) -> Container {219        var c = c220        c.type = kind.listType221        if kind == .ordered {222            if c.attrs["start"] == nil { c.attrs["start"] = 1 }223            if c.attrs["type"] == nil { c.attrs["type"] = .null }224        } else {225            c.attrs["start"] = nil226            c.attrs["type"] = nil227        }228        if c.attrs["id"] == nil { c.attrs["id"] = .string(BlockID.generate()) }229        return c230    }231232    private func convertedItem(_ c: Container, to itemType: String) -> Container {233        guard c.type != itemType else { return c }234        var c = c235        c.type = itemType236        // The item keeps its block id; what only a task has (state, due date, priority, linked task) comes or goes.237        for (key, value) in Schema.nodeDefaults[NodeType.taskItem] ?? [:] where key != "id" {238            if itemType == NodeType.taskItem { c.attrs[key] = value } else { c.attrs.removeValue(forKey: key) }239        }240        return c241    }242243    private mutating func convertList(key: Int, to kind: ListKind) {244        var itemIds: [Int: String] = [:]245        for i in lines.indices {246            guard let d = lines[i].path.firstIndex(where: { $0.key == key }) else { continue }247            lines[i].path[d] = convertedList(lines[i].path[d], to: kind)248            if lines[i].path.count > d + 1, Schema.items.contains(lines[i].path[d + 1].type) {249                var item = convertedItem(lines[i].path[d + 1], to: kind.itemType)250                // An item written by a 2.x editor has no block id yet: one id per item, shared by all its lines.251                if BlockID.usable(item.attrs["id"]) == nil {252                    if itemIds[item.key] == nil { itemIds[item.key] = BlockID.generate() }253                    item.attrs["id"] = .string(itemIds[item.key]!)254                }255                lines[i].path[d + 1] = item256            }257        }258    }259260    /// Removes the item and its list around the lines of the item (they become children of the list's parent).261    private mutating func liftItemOutOfList(itemKey: Int) {262        guard let (f, e) = firstLine(withContainer: itemKey), e >= 1 else { return }263        for l in groupRange(of: f, depth: e) { lines[l].path.removeSubrange((e - 1)...e) }264    }265266    private func siblingList(at i: Int, prefix: [Container], type: String) -> Container? {267        let d = prefix.count268        guard lines.indices.contains(i), lines[i].path.count > d, samePathKeys(Array(lines[i].path[..<d]), prefix),269              lines[i].path[d].type == type else { return nil }270        return lines[i].path[d]271    }272273    /// Toggles a list kind on the lines: wraps paragraphs and headings that are outside a list (one item per line,274    /// joining an adjacent list of the same kind), converts lists of another kind, or — when every line is already275    /// in a list of that kind — lifts the items out of their list.276    @discardableResult277    public mutating func toggleList(_ kind: ListKind, at range: Range<Int>) -> Bool {278        var inList: [Int] = [], plain: [Int] = []279        for i in clamp(range) {280            if isDirectlyInItem(lines[i].path) { inList.append(i) }281            else if lines[i].isText, lines[i].type == NodeType.paragraph || lines[i].type == NodeType.heading { plain.append(i) }282        }283        guard !(inList.isEmpty && plain.isEmpty) else { return false }284        func listFrame(_ i: Int) -> Container { lines[i].path[lines[i].path.count - 2] }285        if plain.isEmpty, inList.allSatisfy({ listFrame($0).type == kind.listType }) {286            var keys: [Int] = []287            for i in inList where !keys.contains(lines[i].path.last!.key) { keys.append(lines[i].path.last!.key) }288            for k in keys { liftItemOutOfList(itemKey: k) }289        } else {290            var keys: [Int] = []291            for i in inList where listFrame(i).type != kind.listType && !keys.contains(listFrame(i).key) { keys.append(listFrame(i).key) }292            for k in keys { convertList(key: k, to: kind) }293            var n = 0294            while n < plain.count {295                var m = n296                while m + 1 < plain.count, plain[m + 1] == plain[m] + 1, samePathKeys(lines[plain[m + 1]].path, lines[plain[n]].path) { m += 1 }297                let a = plain[n], b = plain[m]298                let prefix = lines[a].path299                let list = siblingList(at: a - 1, prefix: prefix, type: kind.listType)300                    ?? siblingList(at: b + 1, prefix: prefix, type: kind.listType)301                    ?? makeContainer(kind.listType)302                if let next = siblingList(at: b + 1, prefix: prefix, type: kind.listType), next.key != list.key {303                    for l in groupRange(of: b + 1, depth: prefix.count) { lines[l].path[prefix.count] = list }304                }305                for l in a...b {306                    if lines[l].type == NodeType.heading { _ = retype(l, to: .paragraph) }307                    lines[l].path = prefix + [list, makeContainer(kind.itemType)]308                }309                n = m + 1310            }311        }312        normalizeContainerKeys()313        return true314    }315316    /// The innermost items of the lines, in order, without the items nested in another selected item.317    private func selectedItems(_ range: Range<Int>) -> [Int] {318        var keys: [Int] = []319        var ancestors: [Int: [Int]] = [:]320        for i in clamp(range) {321            guard let e = innermostItemDepth(lines[i].path) else { continue }322            let key = lines[i].path[e].key323            if !keys.contains(key) {324                keys.append(key)325                ancestors[key] = lines[i].path[..<e].map(\.key)326            }327        }328        return keys.filter { key in !(ancestors[key] ?? []).contains(where: keys.contains) }329    }330331    /// Nests each selected list item inside the previous item of its list (Tab). False when no item could move.332    @discardableResult333    public mutating func indentListItems(at range: Range<Int>) -> Bool {334        var changed = false335        for key in selectedItems(range) where sinkItem(key) { changed = true }336        if changed { normalizeContainerKeys() }337        return changed338    }339340    private mutating func sinkItem(_ key: Int) -> Bool {341        guard let (f, e) = firstLine(withContainer: key), e >= 1, f > 0 else { return false }342        let list = lines[f].path[e - 1]343        let prev = lines[f - 1]344        guard prev.path.count > e, prev.path[e - 1].key == list.key, Schema.items.contains(prev.path[e].type) else { return false }345        let prevItem = prev.path[e]346        let nested: Container347        if prev.path.count > e + 2, prev.path[e + 1].type == list.type, Schema.items.contains(prev.path[e + 2].type) {348            nested = prev.path[e + 1]349        } else {350            var attrs: [String: JSONValue] = [:]351            if list.type == NodeType.orderedList, let t = list.attrs["type"] { attrs["type"] = t }352            nested = makeContainer(list.type, attrs: attrs)353        }354        for l in groupRange(of: f, depth: e) { lines[l].path.replaceSubrange(e...e, with: [prevItem, nested, lines[l].path[e]]) }355        return true356    }357358    /// Moves each selected list item one level out (Shift-Tab). A nested item becomes the next sibling of its parent359    /// item and takes what followed it in the parent as its own children; a first-level item leaves the list.360    @discardableResult361    public mutating func outdentListItems(at range: Range<Int>) -> Bool {362        var changed = false363        for key in selectedItems(range) where liftItem(key) { changed = true }364        if changed { normalizeContainerKeys() }365        return changed366    }367368    mutating func liftItem(_ key: Int) -> Bool {369        guard let (f, e) = firstLine(withContainer: key), e >= 1 else { return false }370        let path = lines[f].path371        let g = groupRange(of: f, depth: e)372        guard e >= 3, Schema.items.contains(path[e - 2].type), Schema.lists.contains(path[e - 3].type) else {373            liftItemOutOfList(itemKey: key)374            return true375        }376        let outerItem = path[e - 2]377        let newItem = convertedItem(path[e], to: outerItem.type)378        for l in g { lines[l].path.replaceSubrange((e - 2)...e, with: [newItem]) }379        var l = g.upperBound380        while l < lines.count, lines[l].path.count > e - 2, lines[l].path[e - 2].key == outerItem.key {381            lines[l].path[e - 2] = newItem382            l += 1383        }384        return true385    }386387    /// Checks or unchecks the innermost task item containing the line.388    @discardableResult389    public mutating func setTaskChecked(_ checked: Bool, at line: Int) -> Bool {390        guard lines.indices.contains(line), let item = lines[line].path.last(where: { $0.type == NodeType.taskItem }),391              item.attrs["checked"] != .bool(checked) else { return false }392        updateContainer(key: item.key) { $0.attrs["checked"] = .bool(checked) }393        return true394    }395}396397// MARK: - Quotes and callouts398399extension NoteDocument {400    /// Wraps the blocks covering the lines in a blockquote, or lifts them out when every line is already quoted.401    @discardableResult402    public mutating func toggleBlockquote(at range: Range<Int>) -> Bool {403        toggleWrapper(NodeType.blockquote, attrs: [:], at: range)404    }405406    /// Wraps the blocks covering the lines in a callout; lifts them out when every line is already in a callout of407    /// that kind; re-types the callouts when they are of another kind.408    @discardableResult409    public mutating func toggleCallout(kind: String, icon: String, at range: Range<Int>) -> Bool {410        let r = clamp(range)411        let frames = r.map { lines[$0].path.last { $0.type == NodeType.callout } }412        if !r.isEmpty, frames.allSatisfy({ $0 != nil }), frames.contains(where: { $0!.attrs["kind"] != .string(kind) }) {413            for key in Set(frames.map { $0!.key }) {414                updateContainer(key: key) { $0.attrs["kind"] = .string(kind); $0.attrs["icon"] = .string(icon) }415            }416            return true417        }418        return toggleWrapper(NodeType.callout, attrs: ["kind": .string(kind), "icon": .string(icon)], at: range)419    }420421    private mutating func toggleWrapper(_ type: String, attrs: [String: JSONValue], at range: Range<Int>) -> Bool {422        let r = clamp(range)423        guard !r.isEmpty else { return false }424        if r.allSatisfy({ i in lines[i].path.contains { $0.type == type } }) {425            for i in r {426                guard let j = lines[i].path.lastIndex(where: { $0.type == type }) else { continue }427                let g = lines[i].path.count > j + 1 ? groupRange(of: i, depth: j + 1) : i..<(i + 1)428                for l in g { lines[l].path.remove(at: j) }429            }430            normalizeContainerKeys()431            return true432        }433        var c = lines[r.lowerBound].path.count434        for i in r {435            var d = 0436            while d < min(c, lines[i].path.count), lines[i].path[d].key == lines[r.lowerBound].path[d].key { d += 1 }437            c = d438        }439        var a = r.lowerBound, b = r.upperBound - 1440        while true {441            if lines[a].path.count > c { a = groupRange(of: a, depth: c).lowerBound }442            if lines[b].path.count > c { b = groupRange(of: b, depth: c).upperBound - 1 }443            if c == 0 { break }444            let parent = lines[a].path[c - 1]445            if Schema.blockParents.contains(parent.type) { break }446            if Schema.items.contains(parent.type), a > groupRange(of: a, depth: c - 1).lowerBound { break }447            c -= 1448        }449        let frame = makeContainer(type, attrs: attrs)450        for l in a...b { lines[l].path.insert(frame, at: c) }451        return true452    }453}454455// MARK: - Enter, Backspace456457extension NoteDocument {458    /// Enter at an inline offset of a line. Returns where the caret goes.459    @discardableResult460    public mutating func splitLine(at index: Int, offset: Int) -> InlinePosition {461        guard lines.indices.contains(index) else { return InlinePosition(line: max(0, min(index, lines.count - 1)), offset: 0) }462        let line = lines[index]463        guard case .inline(let runs) = line.content else {464            let at = insertionPoint(after: index)465            lines.insert(.paragraph(path: at.path), at: at.index)466            return InlinePosition(line: at.index, offset: 0)467        }468        let length = InlineTools.length(runs)469        let offset = max(0, min(offset, length))470        if line.type == NodeType.codeBlock {471            let (l, r) = InlineTools.split(runs, at: offset)472            lines[index].content = .inline(InlineTools.normalized(l + [.text("\n", marks: [])] + r))473            return InlinePosition(line: index, offset: InlineTools.length(l) + 1)474        }475        if line.type == NodeType.detailsSummary { return InlinePosition(line: index, offset: offset) }476        let (left, right) = InlineTools.split(runs, at: offset)477        var newAttrs: [String: JSONValue] = ["textAlign": line.attrs["textAlign"] ?? .null]478        if isListItemHead(at: index), let item = line.path.last {479            let depth = line.path.count - 1480            let alone = groupRange(of: index, depth: depth).count == 1481            if length == 0, alone {482                _ = liftItem(item.key)483                normalizeContainerKeys()484                return InlinePosition(line: index, offset: 0)485            }486            var newItem = item487            newItem.key = newContainerKey()488            // A new item is a new block (and, in a task list, a new unchecked task that is not the linked one).489            newItem.attrs["id"] = .string(BlockID.generate())490            if newItem.type == NodeType.taskItem {491                newItem.attrs["checked"] = false492                for key in ["due", "priority", "taskId"] where newItem.attrs[key] != nil { newItem.attrs[key] = .null }493            }494            lines[index].content = .inline(left)495            var l = index + 1496            while l < lines.count, lines[l].path.count > depth, lines[l].path[depth].key == item.key {497                lines[l].path[depth] = newItem498                l += 1499            }500            let newLine = Line(path: Array(line.path.dropLast()) + [newItem], type: NodeType.paragraph,501                               attrs: Schema.attrs(NodeType.paragraph, newAttrs), content: .inline(right))502            lines.insert(newLine, at: index + 1)503            return InlinePosition(line: index + 1, offset: 0)504        }505        if length == 0, line.type == NodeType.paragraph, let last = line.path.last, Schema.wrappers.contains(last.type) {506            lines[index].path.removeLast()507            normalizeContainerKeys()508            return InlinePosition(line: index, offset: 0)509        }510        var newType = NodeType.paragraph511        if line.type == NodeType.heading, offset < length {512            newType = NodeType.heading513            newAttrs["level"] = line.attrs["level"] ?? 1514        }515        lines[index].content = .inline(left)516        lines.insert(Line(path: line.path, type: newType, attrs: Schema.attrs(newType, newAttrs), content: .inline(right)), at: index + 1)517        return InlinePosition(line: index + 1, offset: 0)518    }519520    /// Backspace at the start of a line. First lifts the line out of its list item or quote; otherwise appends it to521    /// the previous text line. Returns the caret, or nil when nothing was done.522    @discardableResult523    public mutating func mergeWithPrevious(at index: Int) -> InlinePosition? {524        guard lines.indices.contains(index) else { return nil }525        let line = lines[index]526        if let last = line.path.last {527            if isListItemHead(at: index) {528                _ = liftItem(last.key)529                normalizeContainerKeys()530                return InlinePosition(line: index, offset: 0)531            }532            if Schema.wrappers.contains(last.type), groupRange(of: index, depth: line.path.count - 1).lowerBound == index {533                lines[index].path.removeLast()534                normalizeContainerKeys()535                return InlinePosition(line: index, offset: 0)536            }537        }538        guard index > 0, case .inline(let cur) = line.content, line.type != NodeType.detailsSummary, canRemoveLine(index) else { return nil }539        let prev = lines[index - 1]540        switch prev.content {541        case .blockAtom:542            guard InlineTools.length(cur) == 0 else { return nil }543            lines.remove(at: index)544            normalizeContainerKeys()545            return InlinePosition(line: index - 1, offset: 0)546        case .inline(let prevRuns):547            guard prev.type != NodeType.detailsSummary else { return nil }548            let caret = InlineTools.length(prevRuns)549            let appended: [InlineRun]550            if prev.type == NodeType.codeBlock {551                let text = InlineTools.plainText(cur)552                appended = text.isEmpty ? [] : [.text(text, marks: [])]553            } else if line.type == NodeType.codeBlock {554                appended = InlineTools.runs(plain: InlineTools.plainText(cur))555            } else {556                appended = cur557            }558            lines[index - 1].content = .inline(InlineTools.normalized(prevRuns + appended))559            lines.remove(at: index)560            normalizeContainerKeys()561            return InlinePosition(line: index - 1, offset: caret)562        }563    }564}565566// MARK: - Block atoms567568extension NoteDocument {569    /// Where a new sibling block goes after line `i`, and its path.570    func insertionPoint(after i: Int) -> (index: Int, path: [Container]) {571        let path = lines[i].path572        guard let last = path.last, last.type == NodeType.details else { return (i + 1, path) }573        // After a details summary: first child of the details content, or after the whole details.574        let d = path.count575        if i + 1 < lines.count, lines[i + 1].path.count > d, lines[i + 1].path[d - 1].key == last.key,576           lines[i + 1].path[d].type == NodeType.detailsContent {577            return (i + 1, Array(lines[i + 1].path[...d]))578        }579        return (groupRange(of: i, depth: d - 1).upperBound, Array(path.dropLast()))580    }581582    /// Inserts a block atom (image, file, rule, block math, table…) as a new line after `line` (nil: at the top).583    /// Returns the index of the new line.584    @discardableResult585    public mutating func insertBlockAtom(_ node: PMNode, after line: Int?) -> Int {586        guard let line, !lines.isEmpty else {587            lines.insert(Line(blockAtom: node), at: 0)588            return 0589        }590        let at = insertionPoint(after: max(0, min(line, lines.count - 1)))591        lines.insert(Line(blockAtom: node, path: at.path), at: at.index)592        return at.index593    }594595    /// Replaces the node of a block atom line (e.g. an edited table). The line keeps its block id.596    @discardableResult597    public mutating func replaceBlockAtom(at line: Int, with node: PMNode) -> Bool {598        guard lines.indices.contains(line), case .blockAtom(let old) = lines[line].content else { return false }599        let before = lines[line]600        var attrs = node.attrs ?? [:]601        if Schema.idTypes.contains(node.type), let id = BlockID.usable(before.attrs["id"]) { attrs["id"] = .string(id) }602        var stored = node603        stored.attrs = attrs.isEmpty ? node.attrs : attrs604        lines[line].type = node.type605        lines[line].attrs = attrs606        lines[line].content = .blockAtom(stored)607        return lines[line] != before || old != stored608    }609610    /// Removes a line when the document stays valid without it (not the first paragraph of a list item that has611    /// other content, not a details summary). The last line of the document is replaced by an empty paragraph.612    @discardableResult613    public mutating func deleteLine(at line: Int) -> Bool {614        guard lines.indices.contains(line) else { return false }615        if lines.count == 1 {616            lines = [.paragraph()]617            return true618        }619        guard canRemoveLine(line) else { return false }620        lines.remove(at: line)621        normalizeContainerKeys()622        return true623    }624}625626// MARK: - Footnotes (builders shared by the editors)627628extension Line {629    /// A top-level `footnote` block labelled `id`.630    public static func footnote(id: String, _ runs: [InlineRun] = []) -> Line {631        Line(path: [], type: NodeType.footnote, attrs: ["id": .string(id)], content: .inline(runs))632    }633}634635extension NoteDocument {636    /// The label of the next footnote: one more than the highest numeric label in use (as the editors number them).637    public func nextFootnoteLabel() -> String {638        let used = lines.filter { $0.type == NodeType.footnote }.compactMap { $0.attrs["id"]?.stringValue }.compactMap { Int($0) }639        return String((used.max() ?? 0) + 1)640    }641}642
Files main
Menu

Theme