SPB Git

Repository Public

Schema.swift 16.6 KB 314 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/Schema.swift3// Description: The web editor's schema as the native core needs it: node and mark names, node classes, default4//              attributes of new nodes, block ids, and factories for new nodes, lines and containers.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// Node type names of the web schema.11public enum NodeType {12    public static let doc = "doc"13    public static let text = "text"14    public static let paragraph = "paragraph"15    public static let heading = "heading"16    public static let codeBlock = "codeBlock"17    public static let footnote = "footnote"18    public static let detailsSummary = "detailsSummary"19    public static let bulletList = "bulletList"20    public static let orderedList = "orderedList"21    public static let taskList = "taskList"22    public static let listItem = "listItem"23    public static let taskItem = "taskItem"24    public static let blockquote = "blockquote"25    public static let callout = "callout"26    public static let aiBlock = "aiBlock"27    public static let details = "details"28    public static let detailsContent = "detailsContent"29    public static let table = "table"30    public static let tableRow = "tableRow"31    public static let tableHeader = "tableHeader"32    public static let tableCell = "tableCell"33    public static let image = "image"34    public static let fileBlock = "fileBlock"35    public static let blockMath = "blockMath"36    public static let horizontalRule = "horizontalRule"37    public static let youtube = "youtube"38    public static let hardBreak = "hardBreak"39    public static let mention = "mention"40    public static let inlineMath = "inlineMath"41    public static let footnoteRef = "footnoteRef"42    // 3.0 (SPEC §2): block-level leaf atoms keeping all their data in attrs, and one inline atom.43    public static let mermaid = "mermaid"44    public static let drawing = "drawing"45    public static let chart = "chart"46    public static let queryView = "queryView"47    public static let bibliography = "bibliography"48    public static let pdf = "pdf"49    public static let blockRef = "blockRef"50    public static let runCode = "runCode"51    public static let audio = "audio"52    public static let canvasLink = "canvasLink"53    /// Inline atom.54    public static let citation = "citation"5556    /// The ten block atoms added in 3.0, in the server's order (`NEXT_BLOCK_TYPES`).57    public static let nextBlocks = [mermaid, drawing, chart, queryView, bibliography, pdf, blockRef, runCode, audio, canvasLink]58    /// The node types that carry a block `id` (the server's `ID_TYPES`): an editor that creates blocks itself gives an id59    /// to exactly these, as `ensureBlockIds()` does.60    public static let blockIdTypes: Set<String> = Set([paragraph, heading, blockquote, codeBlock, bulletList, orderedList, taskList, table, callout, details,61                                                       aiBlock, blockMath, image, fileBlock, listItem, taskItem]).union(nextBlocks)62}6364/// The marks the commands can toggle. `link` is handled by `setLink` / `removeLink`.65public enum MarkKind: String, Sendable, Hashable, CaseIterable {66    case bold, italic, underline, strike, code, highlight, `subscript`, superscript67}6869/// The three list kinds.70public enum ListKind: String, Sendable, Hashable, CaseIterable {71    case bullet, ordered, task7273    /// Node type of the list (`bulletList`, `orderedList`, `taskList`).74    public var listType: String {75        switch self {76        case .bullet: return NodeType.bulletList77        case .ordered: return NodeType.orderedList78        case .task: return NodeType.taskList79        }80    }8182    /// Node type of its items (`listItem` or `taskItem`).83    public var itemType: String { self == .task ? NodeType.taskItem : NodeType.listItem }8485    public init?(listType: String) {86        switch listType {87        case NodeType.bulletList: self = .bullet88        case NodeType.orderedList: self = .ordered89        case NodeType.taskList: self = .task90        default: return nil91        }92    }93}9495/// The types a text line can be set to.96public enum LineKind: Sendable, Hashable {97    case paragraph98    /// Level 1 to 3 (clamped).99    case heading(level: Int)100    /// `language` nil means the schema default, `plaintext`.101    case codeBlock(language: String?)102}103104enum Schema {105    static let textBlocks: Set<String> = [NodeType.paragraph, NodeType.heading, NodeType.codeBlock, NodeType.footnote, NodeType.detailsSummary]106    static let nextBlocks = Set(NodeType.nextBlocks)107    static let blockAtoms: Set<String> = Set([NodeType.table, NodeType.image, NodeType.fileBlock, NodeType.blockMath, NodeType.horizontalRule, NodeType.youtube]).union(nextBlocks)108    static let containers: Set<String> = [NodeType.bulletList, NodeType.orderedList, NodeType.taskList, NodeType.listItem, NodeType.taskItem,109                                          NodeType.blockquote, NodeType.callout, NodeType.aiBlock, NodeType.details, NodeType.detailsContent]110    static let inlineTypes: Set<String> = [NodeType.text, NodeType.hardBreak, NodeType.mention, NodeType.inlineMath, NodeType.footnoteRef, NodeType.citation, "math"]111    /// Same list as the server's `ID_TYPES` (3.0: list items and the new block atoms take an id too).112    static let idTypes: Set<String> = NodeType.blockIdTypes113    /// The `block` group of the schema.114    static let blockGroup: Set<String> = Set([NodeType.paragraph, NodeType.blockquote, NodeType.bulletList, NodeType.heading, NodeType.horizontalRule,115                                              NodeType.orderedList, NodeType.taskList, NodeType.table, NodeType.image, NodeType.youtube, NodeType.details,116                                              NodeType.codeBlock, NodeType.blockMath, NodeType.callout, NodeType.aiBlock, NodeType.fileBlock, NodeType.footnote]).union(nextBlocks)117    /// The `inline` group of the schema.118    static let inlineGroup: Set<String> = [NodeType.text, NodeType.mention, NodeType.hardBreak, NodeType.inlineMath, NodeType.footnoteRef, NodeType.citation]119    static let lists: Set<String> = [NodeType.bulletList, NodeType.orderedList, NodeType.taskList]120    static let items: Set<String> = [NodeType.listItem, NodeType.taskItem]121    /// Containers whose content is `block+` and that a block can be lifted out of.122    static let wrappers: Set<String> = [NodeType.blockquote, NodeType.callout, NodeType.aiBlock]123    /// Containers accepting any block at any position (`block+`).124    static let blockParents: Set<String> = [NodeType.blockquote, NodeType.callout, NodeType.aiBlock, NodeType.detailsContent]125    /// Marks in schema order (ProseMirror keeps the marks of a node sorted by this rank).126    static let markOrder = ["link", "bold", "code", "italic", "strike", "underline", "highlight", "subscript", "superscript"]127    static func markRank(_ type: String) -> Int { markOrder.firstIndex(of: type) ?? markOrder.count }128129    /// Default attributes of each node type, as the web editor serializes them.130    static let nodeDefaults: [String: [String: JSONValue]] = [131        NodeType.paragraph: ["textAlign": .null, "id": .null],132        NodeType.heading: ["textAlign": .null, "id": .null, "level": 1],133        NodeType.codeBlock: ["id": .null, "language": "plaintext"],134        NodeType.footnote: ["id": .null],135        NodeType.blockquote: ["id": .null],136        NodeType.bulletList: ["id": .null],137        NodeType.orderedList: ["id": .null, "start": 1, "type": .null],138        NodeType.taskList: ["id": .null],139        NodeType.listItem: ["id": .null],140        NodeType.taskItem: ["checked": false, "id": .null, "due": .null, "priority": .null, "taskId": .null],141        NodeType.table: ["id": .null],142        NodeType.tableHeader: ["colspan": 1, "rowspan": 1, "colwidth": .null, "align": .null],143        NodeType.tableCell: ["colspan": 1, "rowspan": 1, "colwidth": .null, "align": .null],144        NodeType.image: ["id": .null, "src": .null, "alt": .null, "title": .null, "width": .null, "height": .null],145        NodeType.youtube: ["src": .null, "start": 0, "width": 640, "height": 480],146        NodeType.details: ["id": .null, "open": false],147        NodeType.blockMath: ["id": .null, "latex": ""],148        NodeType.inlineMath: ["latex": ""],149        NodeType.callout: ["id": .null, "kind": "note", "icon": "💡"],150        NodeType.aiBlock: ["id": .null, "model": .null, "prompt": .null, "at": .null, "sources": .null, "action": .null],151        NodeType.fileBlock: ["id": .null, "src": .null, "name": "file", "size": 0, "mime": "", "attachmentId": .null],152        NodeType.footnoteRef: ["id": .null],153        NodeType.mention: ["id": .null, "label": .null, "mentionSuggestionChar": "@"],154        // 3.0 nodes (SPEC §2 table).155        NodeType.mermaid: ["id": .null, "code": "", "preview": .null, "previewHash": .null],156        NodeType.drawing: ["id": .null, "ink": .null, "preview": .null, "pk": .null, "width": 0, "height": 0, "background": "none"],157        NodeType.chart: ["id": .null, "kind": "bar", "title": "", "columns": [], "rows": [], "x": .null, "y": [], "source": .null],158        NodeType.queryView: ["id": .null, "source": "tasks", "databaseId": .null, "viewId": .null, "filter": [:], "layout": "list", "limit": 25, "title": ""],159        NodeType.citation: ["refId": .null, "locator": "", "label": ""],160        NodeType.bibliography: ["id": .null, "style": "apa", "title": "Références"],161        NodeType.pdf: ["id": .null, "attachmentId": .null, "name": "", "page": 1, "annotations": []],162        NodeType.blockRef: ["id": .null, "pageId": .null, "blockId": .null, "mode": "embed"],163        NodeType.runCode: ["id": .null, "language": "javascript", "code": "", "output": .null],164        NodeType.audio: ["id": .null, "attachmentId": .null, "duration": 0, "title": "", "recordedAt": .null, "transcript": [],165                         "transcriptStatus": "none", "transcriptEngine": .null, "summary": .null],166        NodeType.canvasLink: ["id": .null, "pageId": .null],167    ]168    /// Attributes added in 3.0 to nodes that existed before: a document written by a 2.x editor does not have them,169    /// so the strict validator accepts their absence.170    static let optionalAttrs: [String: Set<String>] = [171        NodeType.listItem: ["id"],172        NodeType.taskItem: ["id", "due", "priority", "taskId"],173        NodeType.aiBlock: ["sources", "action"],174    ]175    static let linkDefaults: [String: JSONValue] = ["href": .null, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": .null, "title": .null]176177    /// Attributes of a new node of `type`: schema defaults, a fresh block id when the type takes one, then `overrides`.178    static func attrs(_ type: String, _ overrides: [String: JSONValue] = [:]) -> [String: JSONValue] {179        var a = nodeDefaults[type] ?? [:]180        if idTypes.contains(type) { a["id"] = .string(BlockID.generate()) }181        for (k, v) in overrides { a[k] = v }182        return a183    }184}185186/// Block ids: 10 characters of the nanoid alphabet, like the server.187public enum BlockID {188    static let alphabet = Array("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")189190    /// A new random id.191    public static func generate() -> String {192        var rng = SystemRandomNumberGenerator()193        return String((0..<10).map { _ in alphabet[Int(rng.next() & 63)] })194    }195196    /// Whether `value` is a usable id (a non-empty string), as the server checks it.197    static func usable(_ value: JSONValue?) -> String? {198        if case .string(let s)? = value, !s.isEmpty { return s }199        return nil200    }201}202203// MARK: - Factories204205extension PMMark {206    /// A mark without attributes.207    public static func mark(_ kind: MarkKind) -> PMMark { PMMark(type: kind.rawValue) }208209    /// A link mark with the web editor's default attributes.210    public static func link(href: String, title: String? = nil) -> PMMark {211        var a = Schema.linkDefaults212        a["href"] = .string(href)213        if let title { a["title"] = .string(title) }214        return PMMark(type: "link", attrs: a)215    }216}217218extension PMNode {219    /// A text node; `marks` empty means no `marks` key.220    public static func text(_ text: String, marks: [PMMark] = []) -> PMNode {221        PMNode(type: NodeType.text, text: text, marks: marks.isEmpty ? nil : marks)222    }223224    /// A paragraph with a fresh id holding plain text; line feeds become hard breaks.225    public static func paragraph(_ text: String = "") -> PMNode {226        let kids = InlineTools.nodes(from: InlineTools.runs(plain: text))227        return PMNode(type: NodeType.paragraph, attrs: Schema.attrs(NodeType.paragraph), content: kids.isEmpty ? nil : kids)228    }229230    /// An image block.231    public static func image(src: String, alt: String? = nil, title: String? = nil) -> PMNode {232        PMNode(type: NodeType.image, attrs: Schema.attrs(NodeType.image, [233            "src": .string(src), "alt": alt.map(JSONValue.string) ?? .null, "title": title.map(JSONValue.string) ?? .null,234        ]))235    }236237    /// A file attachment block.238    public static func fileBlock(src: String, name: String, size: Int, mime: String, attachmentId: String?) -> PMNode {239        PMNode(type: NodeType.fileBlock, attrs: Schema.attrs(NodeType.fileBlock, [240            "src": .string(src), "name": .string(name), "size": .int(Int64(size)), "mime": .string(mime),241            "attachmentId": attachmentId.map(JSONValue.string) ?? .null,242        ]))243    }244245    /// A horizontal rule.246    public static func horizontalRule() -> PMNode { PMNode(type: NodeType.horizontalRule) }247248    /// A block of display math.249    public static func blockMath(latex: String) -> PMNode {250        PMNode(type: NodeType.blockMath, attrs: Schema.attrs(NodeType.blockMath, ["latex": .string(latex)]))251    }252253    /// An empty table of `rows` × `cols` (at least 1 × 1); the first row is made of header cells when `withHeaderRow`.254    public static func table(rows: Int, cols: Int, withHeaderRow: Bool) -> PMNode {255        let r = max(1, rows), c = max(1, cols)256        let body = (0..<r).map { row in257            PMNode(type: NodeType.tableRow, content: (0..<c).map { _ in tableCell(header: withHeaderRow && row == 0) })258        }259        return PMNode(type: NodeType.table, attrs: Schema.attrs(NodeType.table), content: body)260    }261262    /// A table cell holding one paragraph of plain text.263    static func tableCell(header: Bool, text: String = "") -> PMNode {264        let type = header ? NodeType.tableHeader : NodeType.tableCell265        return PMNode(type: type, attrs: Schema.attrs(type), content: [.paragraph(text)])266    }267268    /// A mention of a page.269    public static func mention(id: String, label: String) -> PMNode {270        PMNode(type: NodeType.mention, attrs: Schema.attrs(NodeType.mention, ["id": .string(id), "label": .string(label)]))271    }272273    /// A hard line break.274    public static func hardBreak() -> PMNode { PMNode(type: NodeType.hardBreak) }275    /// The inline call of a footnote; `id` is the footnote's label ("1", "2"…), shared with its `footnote` block.276    public static func footnoteRef(id: String) -> PMNode { PMNode(type: NodeType.footnoteRef, attrs: ["id": .string(id)]) }277278    /// Inline math.279    public static func inlineMath(latex: String) -> PMNode {280        PMNode(type: NodeType.inlineMath, attrs: ["latex": .string(latex)])281    }282}283284extension Line {285    /// A paragraph line with the schema defaults and a fresh id.286    public static func paragraph(_ runs: [InlineRun] = [], path: [Container] = []) -> Line {287        Line(path: path, type: NodeType.paragraph, attrs: Schema.attrs(NodeType.paragraph), content: .inline(runs))288    }289290    /// A paragraph line of plain text.291    public static func paragraph(text: String, path: [Container] = []) -> Line {292        paragraph(InlineTools.runs(plain: text), path: path)293    }294295    /// A heading line (level clamped to 1…3).296    public static func heading(level: Int, _ runs: [InlineRun] = [], path: [Container] = []) -> Line {297        Line(path: path, type: NodeType.heading,298             attrs: Schema.attrs(NodeType.heading, ["level": .int(Int64(min(3, max(1, level))))]), content: .inline(runs))299    }300301    /// A code block line; the text may contain line feeds.302    public static func codeBlock(language: String? = nil, text: String = "", path: [Container] = []) -> Line {303        Line(path: path, type: NodeType.codeBlock, attrs: Schema.attrs(NodeType.codeBlock, ["language": .string(language ?? "plaintext")]),304             content: .inline(text.isEmpty ? [] : [.text(text, marks: [])]))305    }306}307308extension NoteDocument {309    /// A new container frame of a schema type with default attributes, a fresh key and (when the type takes one) a fresh id.310    public mutating func makeContainer(_ type: String, attrs overrides: [String: JSONValue] = [:]) -> Container {311        Container(key: newContainerKey(), type: type, attrs: Schema.attrs(type, overrides))312    }313}314
Files main
Menu

Theme