Repository Public
1// SP Notes Core2// File: Sources/SPNotesDocument/NextNodes.swift3// Description: Text, Markdown and HTML of the 3.0 document nodes (SPEC §2), a line-by-line port of the server's4// src/lib/editor/next-nodes.ts and src/lib/export/next-nodes-html.ts so that both sides produce the same5// bytes; plus the attachment, page and reference ids those nodes point to.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011enum NextNodes {12 static let blockTypes = Schema.nextBlocks13 static func isNextBlock(_ type: String) -> Bool { blockTypes.contains(type) }1415 // MARK: JavaScript helpers of next-nodes.ts1617 /// `typeof v === "string" ? v : ""`.18 static func str(_ v: JSONValue?) -> String { v?.stringValue ?? "" }1920 /// `/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i`, lower-cased; nil otherwise.21 static func id(_ v: JSONValue?) -> String? {22 guard case .string(let s)? = v else { return nil }23 let u = Array(s.unicodeScalars)24 guard u.count == 36 else { return nil }25 for (i, c) in u.enumerated() {26 if i == 8 || i == 13 || i == 18 || i == 23 {27 if c != "-" { return nil }28 } else if !(("0"..."9").contains(c) || ("a"..."f").contains(c) || ("A"..."F").contains(c)) {29 return nil30 }31 }32 return s.lowercased()33 }3435 /// `str(v).replace(/\s*\n\s*/g, " ").trim()`: every run of white space holding a line feed becomes one space.36 static func oneLine(_ v: JSONValue?) -> String { oneLine(str(v)) }3738 static func oneLine(_ s: String) -> String {39 var out = String.UnicodeScalarView()40 var run = String.UnicodeScalarView()41 var runHasNewline = false42 func flush() {43 if runHasNewline { out.append(" ") } else { out.append(contentsOf: run) }44 run = String.UnicodeScalarView()45 runHasNewline = false46 }47 for u in s.unicodeScalars {48 if JS.isSpace(u) {49 run.append(u)50 if u == "\n" { runHasNewline = true }51 } else {52 if !run.isEmpty { flush() }53 out.append(u)54 }55 }56 if !run.isEmpty { flush() }57 return JS.trim(String(out))58 }5960 /// `n.attrs?.__href?.[id] || "/api/files/<id>"` (the link an export resolver substituted; never stored).61 static func fileURL(_ n: PMNode, _ attachmentId: String) -> String {62 let substituted = str(n.attrs?["__href"]?[attachmentId])63 return substituted.isEmpty ? "/api/files/\(attachmentId)" : substituted64 }6566 /// `cellText`: null → "", booleans → true / false, finite numbers as ECMAScript prints them, strings on one line.67 /// An array or an object (not a valid cell: the server refuses it) is printed as compact JSON with sorted keys.68 static func cellText(_ v: JSONValue?) -> String {69 guard let v else { return "" }70 switch v {71 case .null: return ""72 case .int(let i): return String(i)73 case .double(let d): return d.isFinite ? JS.string(.double(d)) : ""74 case .bool(let b): return b ? "true" : "false"75 case .string(let s): return oneLine(s)76 case .array, .object: return oneLine(v.canonicalString())77 }78 }7980 /// `[mm:ss]` without the brackets; minutes are not capped at 59; negative or invalid times read 00:00.81 static func timecode(_ t: JSONValue?) -> String {82 var seconds: Int64 = 083 switch t {84 case .int(let i)?: seconds = max(0, i)85 case .double(let d)?: seconds = d.isFinite && d > 0 ? Int64(min(d.rounded(.down), 9.0e15)) : 086 default: seconds = 087 }88 func pad(_ n: Int64) -> String { n < 10 ? "0\(n)" : String(n) }89 return "\(pad(seconds / 60)):\(pad(seconds % 60))"90 }9192 static func rows(_ n: PMNode) -> [[JSONValue]] { (n.attrs?["rows"]?.arrayValue ?? []).compactMap(\.arrayValue) }93 static func columns(_ n: PMNode) -> [String] { (n.attrs?["columns"]?.arrayValue ?? []).map { cellText($0) } }9495 /// `a && typeof a === "object"`: objects, and arrays (which then have none of the fields).96 static func objects(_ v: JSONValue?) -> [[String: JSONValue]] {97 (v?.arrayValue ?? []).compactMap { item in98 switch item {99 case .object(let o): return o100 case .array: return [:]101 default: return nil102 }103 }104 }105106 static func annotations(_ n: PMNode) -> [[String: JSONValue]] { objects(n.attrs?["annotations"]) }107108 static func transcript(_ n: PMNode) -> [(t: JSONValue?, text: String)] {109 objects(n.attrs?["transcript"]).compactMap { s in110 let text = oneLine(s["text"])111 return text.isEmpty ? nil : (s["t"], text)112 }113 }114115 /// `Math.max(1, Math.floor(Number(page)))` when finite, else 1 — as text.116 static func pageNumber(_ v: JSONValue?) -> String {117 let n = JS.number(v)118 guard n.isFinite else { return "1" }119 return JS.string(.double(max(1, n.rounded(.down))))120 }121122 static func annotationLine(_ a: [String: JSONValue]) -> String {123 ["p.\(pageNumber(a["page"]))", oneLine(a["text"]), oneLine(a["note"])].filter { !$0.isEmpty }.joined(separator: " — ")124 }125126 static func outputText(_ n: PMNode) -> String? {127 guard case .object(let o)? = n.attrs?["output"], case .string(let text)? = o["text"] else { return nil }128 return text129 }130131 static func label(_ prefix: String, _ title: JSONValue?) -> String {132 let t = oneLine(title)133 return t.isEmpty ? prefix : "\(prefix): \(t)"134 }135136 // MARK: Plain text137138 /// Plain text of a 3.0 node (search index, word count): the Markdown form without its syntax. Transcript and139 /// annotation text are included; identifiers and time codes are not. nil for any other node type.140 static func text(_ n: PMNode) -> String? {141 let a = n.attrs142 switch n.type {143 case NodeType.mermaid: return str(a?["code"])144 case NodeType.runCode: return [str(a?["code"]), outputText(n) ?? ""].filter { !$0.isEmpty }.joined(separator: "\n")145 case NodeType.chart:146 let lines = [oneLine(a?["title"]), columns(n).joined(separator: " ")] + rows(n).map { $0.map { cellText($0) }.joined(separator: " ") }147 return lines.map(JS.trim).filter { !$0.isEmpty }.joined(separator: "\n")148 case NodeType.drawing: return "Dessin"149 case NodeType.pdf: return ([label("PDF", a?["name"])] + annotations(n).map(annotationLine)).joined(separator: "\n")150 case NodeType.audio: return ([label("Audio", a?["title"])] + transcript(n).map(\.text)).joined(separator: "\n")151 case NodeType.queryView: return label("Vue", a?["title"])152 case NodeType.blockRef: return ""153 case NodeType.citation: return oneLine(a?["label"])154 case NodeType.bibliography:155 let t = oneLine(a?["title"])156 return t.isEmpty ? "Références" : t157 case NodeType.canvasLink: return "Canvas"158 default: return nil159 }160 }161162 // MARK: Markdown163164 static func mdCell(_ v: JSONValue?) -> String { cellText(v).replacingOccurrences(of: "|", with: "\\|") }165166 /// Markdown of a 3.0 node. Block nodes end with exactly one line feed; `citation` is inline and has none.167 /// nil for any other node type.168 static func markdown(_ n: PMNode) -> String? {169 let a = n.attrs170 switch n.type {171 case NodeType.mermaid: return "```mermaid\n\(str(a?["code"]))\n```\n"172 case NodeType.runCode:173 let out = outputText(n)174 return "```\(str(a?["language"]))\n\(str(a?["code"]))\n```\n" + (out.map { "\n```output\n\($0)\n```\n" } ?? "")175 case NodeType.chart:176 let title = oneLine(a?["title"]), cols = columns(n), rows = rows(n)177 if cols.isEmpty { return "\(title.isEmpty ? "[Graphique]" : title)\n" }178 let body = rows.map { r in "| \(cols.indices.map { mdCell($0 < r.count ? r[$0] : nil) }.joined(separator: " | ")) |\n" }.joined()179 let table = "| \(cols.map { mdCell(.string($0)) }.joined(separator: " | ")) |\n| \(cols.map { _ in "---" }.joined(separator: " | ")) |\n\(body)"180 return title.isEmpty ? table : "\(title)\n\n\(table)"181 case NodeType.drawing:182 guard let p = id(a?["preview"]) else { return "[Dessin]\n" }183 return "))\n"184 case NodeType.pdf:185 let name = label("PDF", a?["name"])186 let head = id(a?["attachmentId"]).map { "[\(name)](\(fileURL(n, $0)))" } ?? "[\(name)]"187 let notes = annotations(n).map { "> \(annotationLine($0))\n" }.joined()188 return "\(head)\n" + (notes.isEmpty ? "" : "\n\(notes)")189 case NodeType.audio:190 let name = label("Audio", a?["title"])191 let head = id(a?["attachmentId"]).map { "[\(name)](\(fileURL(n, $0)))" } ?? "[\(name)]"192 let lines = transcript(n).map { "[\(timecode($0.t))] \($0.text)\n" }.joined()193 return "\(head)\n" + (lines.isEmpty ? "" : "\n\(lines)")194 case NodeType.queryView: return "[\(label("Vue", a?["title"]))]\n"195 case NodeType.blockRef:196 let block = str(a?["blockId"])197 return "[[\(id(a?["pageId"]) ?? "")\(block.isEmpty ? "" : "#\(block)")]]\n"198 case NodeType.citation:199 let label = oneLine(a?["label"])200 return "[@\(label.isEmpty ? (id(a?["refId"]) ?? "?") : label)]"201 case NodeType.bibliography:202 let t = oneLine(a?["title"])203 return "## \(t.isEmpty ? "Références" : t)\n"204 case NodeType.canvasLink:205 guard let p = id(a?["pageId"]) else { return "[Canvas]\n" }206 return "[Canvas](/p/\(p))\n"207 default: return nil208 }209 }210211 // MARK: HTML (next-nodes-html.ts, without resolvers)212213 /// `one(v)`: a string on one line, "" for anything else.214 private static func one(_ v: JSONValue?) -> String { oneLine(v) }215216 private static func file(_ n: PMNode, _ v: JSONValue?) -> String? {217 guard let attachmentId = id(v) else { return nil }218 if let substituted = JS.nullish(n.attrs?["__href"]?[attachmentId]) { return JS.string(substituted) }219 return "/api/files/\(attachmentId)"220 }221222 /// `Math.max(1, Math.floor(Number(x.page)) || 1)` as text.223 private static func htmlPage(_ v: JSONValue?) -> String {224 let floor = JS.number(v).rounded(.down)225 return JS.string(.double(max(1, floor.isNaN || floor == 0 ? 1 : floor)))226 }227228 static func html(_ n: PMNode) -> String? {229 let a = n.attrs230 let esc = HTMLExport.esc231 let escape = HTMLExport.escape232 switch n.type {233 case NodeType.mermaid:234 let img = file(n, a?["preview"]).map { "<img src=\"\(escape($0))\" alt=\"Diagramme\">" } ?? ""235 return "<figure class=\"nx nx-mermaid\">\(img)<pre><code class=\"language-mermaid\">\(esc(a?["code"]))</code></pre></figure>"236 case NodeType.runCode:237 var out = ""238 if let text = outputText(n) {239 out = "<pre class=\"nx-output\(JS.truthy(a?["output"]?["error"]) ? " nx-error" : "")\"><code>\(escape(text))</code></pre>"240 }241 return "<div class=\"nx nx-runcode\"><pre><code class=\"language-\(esc(a?["language"]))\">\(esc(a?["code"]))</code></pre>\(out)</div>"242 case NodeType.chart:243 let cols = a?["columns"]?.arrayValue ?? [], rows = rows(n), title = one(a?["title"])244 var table = ""245 if !cols.isEmpty {246 let head = cols.map { "<th>\(escape(cellText($0)))</th>" }.joined()247 let body = rows.map { r in "<tr>\(cols.indices.map { "<td>\(escape(cellText($0 < r.count ? r[$0] : nil)))</td>" }.joined())</tr>" }.joined()248 table = "<table><tr>\(head)</tr>\(body)</table>"249 }250 return "<figure class=\"nx nx-chart\">\(title.isEmpty ? "" : "<figcaption>\(escape(title))</figcaption>")\(table)</figure>"251 case NodeType.drawing:252 guard let img = file(n, a?["preview"]) else { return "<p class=\"nx nx-drawing\">[Dessin]</p>" }253 return "<figure class=\"nx nx-drawing\"><img src=\"\(escape(img))\" alt=\"Dessin\"></figure>"254 case NodeType.pdf:255 let name = one(a?["name"]).isEmpty ? "PDF" : "PDF: \(one(a?["name"]))"256 let link = file(n, a?["attachmentId"]).map { "<a href=\"\(escape($0))\">\(escape(name))</a>" } ?? escape(name)257 let notes = annotations(n).map { x in258 "<li>\(escape(["p.\(htmlPage(x["page"]))", one(x["text"]), one(x["note"])].filter { !$0.isEmpty }.joined(separator: " — ")))</li>"259 }260 return "<div class=\"nx nx-pdf\"><p class=\"file\">📎 \(link)</p>\(notes.isEmpty ? "" : "<ul>\(notes.joined())</ul>")</div>"261 case NodeType.audio:262 let name = one(a?["title"]).isEmpty ? "Audio" : "Audio: \(one(a?["title"]))"263 let link = file(n, a?["attachmentId"]).map { "<a href=\"\(escape($0))\">\(escape(name))</a>" } ?? escape(name)264 let segments = transcript(n).map { "<p class=\"nx-seg\"><small>[\(timecode($0.t))]</small> \(escape($0.text))</p>" }.joined()265 return "<div class=\"nx nx-audio\"><p class=\"file\">🎙 \(link)</p>\(segments)</div>"266 case NodeType.queryView:267 return "<p class=\"nx nx-query\">[\(escape(one(a?["title"]).isEmpty ? "Vue" : "Vue: \(one(a?["title"]))"))]</p>"268 case NodeType.blockRef:269 guard let p = id(a?["pageId"]) else { return "<p class=\"nx nx-blockref\">Référence introuvable</p>" }270 let block = str(a?["blockId"])271 let href = "/p/\(p)" + (block.isEmpty ? "" : "#block-\(block)")272 return "<p class=\"nx nx-blockref\"><a href=\"\(escape(href))\">↗ \(escape(p))\(JS.truthy(a?["blockId"]) ? "#\(esc(a?["blockId"]))" : "")</a></p>"273 case NodeType.citation:274 let label = one(a?["label"]), locator = one(a?["locator"])275 let shown = label.isEmpty ? (a?["refId"]?.stringValue ?? "?") : label276 return "<span class=\"nx nx-citation\">[\(escape(shown))\(locator.isEmpty ? "" : ", \(escape(locator))")]</span>"277 case NodeType.bibliography:278 return "<h2 class=\"nx nx-bibliography\">\(escape(one(a?["title"]).isEmpty ? "Références" : one(a?["title"])))</h2>"279 case NodeType.canvasLink:280 guard let p = id(a?["pageId"]) else { return "<p class=\"nx nx-canvas\">[Canvas]</p>" }281 return "<p class=\"nx nx-canvas\"><a href=\"\(escape("/p/\(p)"))\">Canvas</a></p>"282 default: return nil283 }284 }285286 // MARK: References287288 /// Attachment ids a 3.0 node points to (`nodeAttachmentIds`).289 static func attachmentIds(_ n: PMNode) -> [String] {290 let a = n.attrs291 switch n.type {292 case NodeType.mermaid: return [id(a?["preview"])].compactMap { $0 }293 case NodeType.drawing: return [id(a?["ink"]), id(a?["preview"]), id(a?["pk"])].compactMap { $0 }294 case NodeType.pdf, NodeType.audio: return [id(a?["attachmentId"])].compactMap { $0 }295 default: return []296 }297 }298299 /// The page a `blockRef` or a `canvasLink` links to, with the anchor block when there is one (`nodePageRef`).300 static func pageRef(_ n: PMNode) -> (pageId: String, blockId: String?)? {301 guard n.type == NodeType.blockRef || n.type == NodeType.canvasLink, let p = id(n.attrs?["pageId"]) else { return nil }302 let block = n.type == NodeType.blockRef ? str(n.attrs?["blockId"]) : ""303 return (p, block.isEmpty ? nil : block)304 }305306 /// The reference a `citation` cites (`nodeRefId`).307 static func refId(_ n: PMNode) -> String? { n.type == NodeType.citation ? id(n.attrs?["refId"]) : nil }308}309