SPB Git

Repository Public

BlockIds.swift 2.7 KB 65 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/BlockIds.swift3// Description: Block id assignment on the flattened model, equivalent to the server's ensureBlockIds (same node4//              types, same pre-order traversal, same rule for missing or duplicated ids).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NoteDocument {11    /// Assigns the missing or duplicated block ids; returns whether anything changed.12    mutating func assignBlockIds() -> Bool {13        var seen = Set<String>()14        var changed = false15        func claim(_ current: JSONValue?) -> String? {16            if let id = BlockID.usable(current), !seen.contains(id) { seen.insert(id); return nil }17            var id = BlockID.generate()18            while seen.contains(id) { id = BlockID.generate() }19            seen.insert(id)20            changed = true21            return id22        }23        func walk(_ n: PMNode) -> PMNode {24            var out = n25            if Schema.idTypes.contains(n.type), let id = claim(n.attrs?["id"]) {26                var a = n.attrs ?? [:]27                a["id"] = .string(id)28                out.attrs = a29            }30            if let kids = n.content, !kids.isEmpty { out.content = kids.map(walk) }31            return out32        }33        var open: [Int] = []34        for i in lines.indices {35            let path = lines[i].path36            var d = 037            while d < min(open.count, path.count), open[d] == path[d].key { d += 1 }38            for j in d..<path.count where Schema.idTypes.contains(path[j].type) {39                guard let id = claim(path[j].attrs["id"]) else { continue }40                var l = i41                while l < lines.count, lines[l].path.count > j, lines[l].path[j].key == path[j].key {42                    lines[l].path[j].attrs["id"] = .string(id)43                    l += 144                }45            }46            open = path.map(\.key)47            if Schema.idTypes.contains(lines[i].type), let id = claim(lines[i].attrs["id"]) { lines[i].attrs["id"] = .string(id) }48            switch lines[i].content {49            case .blockAtom(var n):50                if let kids = n.content, !kids.isEmpty {51                    n.content = kids.map(walk)52                    lines[i].content = .blockAtom(n)53                }54            case .inline(let runs):55                // Inline atoms are normally not id-bearing; an out-of-schema block nested in a text block still gets its id.56                lines[i].content = .inline(runs.map { run in57                    if case .atom(let n) = run { return .atom(walk(n)) }58                    return run59                })60            }61        }62        return changed63    }64}65
Files main
Menu

Theme