Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/DocumentCodec.swift3// Description: Lossless conversion between the flattened note document and the attributed text the editor works on (one paragraph per line, raw marks and nodes preserved).4import AppKit5import SPNotesDocument67/// Text storage conventions:8/// - every line ends with "\n", the last one included (the terminating newline carries the paragraph attributes, so an empty9/// last paragraph still has a style and still draws its bullet);10/// - a code block is one line whose text holds the line feeds: its paragraphs share one `ParaStyle` instance;11/// - a block atom is a paragraph made of one attachment character; an inline atom is one attachment character, except a12/// hard break which is U+2028 tagged with `.spInlineNode`.13@MainActor public struct DocumentCodec {14 public var theme: EditorTheme15 public weak var resources: AtomResources?16 public init(theme: EditorTheme, resources: AtomResources?) { self.theme = theme; self.resources = resources }1718 static let lineSeparator = "\u{2028}"19 static let attachmentCharacter = "\u{FFFC}"2021 // MARK: Document → text2223 public func attributedString(from doc: NoteDocument) -> NSMutableAttributedString {24 let out = NSMutableAttributedString()25 let lines = doc.lines.isEmpty ? [Line(path: [], type: "paragraph", attrs: [:], content: .inline([]))] : doc.lines26 for line in lines { out.append(attributed(line)) }27 Styler(theme: theme).style(out, in: NSRange(location: 0, length: out.length))28 return out29 }3031 /// One line, terminated, carrying its semantic attributes (not styled yet).32 public func attributed(_ line: Line) -> NSMutableAttributedString {33 let out = NSMutableAttributedString()34 switch line.content {35 case .blockAtom(let node):36 let style = ParaStyle(line: line, isAtom: true)37 out.append(NSAttributedString(attachment: AtomAttachment(node: node, isBlock: true, theme: theme, resources: resources)))38 out.append(NSAttributedString(string: "\n"))39 out.addAttributes([.spPara: style, .spMarks: MarkSet.none], range: NSRange(location: 0, length: out.length))40 case .inline(let runs):41 let style = ParaStyle(line: line, isAtom: false)42 for run in runs { out.append(attributed(run, code: style.isCode)) }43 out.append(NSAttributedString(string: "\n", attributes: [.spMarks: MarkSet.none]))44 out.addAttribute(.spPara, value: style, range: NSRange(location: 0, length: out.length))45 }46 return out47 }4849 public func attributed(_ run: InlineRun, code: Bool = false) -> NSAttributedString {50 switch run {51 case .text(let text, let marks):52 // a line feed inside a text node of an ordinary block would end the paragraph: it is shown as a soft line break53 let s = code ? text : text.replacingOccurrences(of: "\n", with: Self.lineSeparator)54 return NSAttributedString(string: s, attributes: [.spMarks: MarkSet(marks)])55 case .atom(let node):56 if node.type == "hardBreak" { return NSAttributedString(string: Self.lineSeparator, attributes: [.spInlineNode: NodeBox(node), .spMarks: MarkSet(node.marks ?? [])]) }57 let a = NSMutableAttributedString(attachment: AtomAttachment(node: node, isBlock: false, theme: theme, resources: resources))58 a.addAttribute(.spMarks, value: MarkSet(node.marks ?? []), range: NSRange(location: 0, length: a.length))59 return a60 }61 }6263 // MARK: Text → document6465 public static func document(from text: NSAttributedString) -> NoteDocument {66 NoteDocument(lines: lines(from: text, in: NSRange(location: 0, length: text.length)))67 }6869 /// Lines of the paragraphs intersecting `range` (whole paragraphs). Block ids met twice are kept on the first block only.70 public static func lines(from text: NSAttributedString, in range: NSRange, dedupeIDs: Bool = true) -> [Line] {71 let ns = text.string as NSString72 var lines: [Line] = []; var lastCode: ParaStyle?; var seen = Set<String>()73 var loc = range.location; let end = NSMaxRange(range)74 while loc < ns.length, loc < end || (range.length == 0 && loc == range.location) {75 let para = ns.paragraphRange(for: NSRange(location: loc, length: 0))76 var content = para; if content.length > 0, ns.character(at: NSMaxRange(content) - 1) == 0x0A { content.length -= 1 }77 let style = (text.attribute(.spPara, at: para.location, effectiveRange: nil) as? ParaStyle) ?? ParaStyle()78 defer { loc = NSMaxRange(para) }79 if style.isAtom {80 var extra: [InlineRun] = []; var found = false81 for run in runs(of: text, in: content, code: false) {82 if case .atom(let n) = run, !found, blockAtom(in: text, range: content)?.node == n { found = true; var l = style.line(.blockAtom(n)); l.attrs = dedupe(n.attrs ?? [:], &seen, dedupeIDs); lines.append(l) }83 else { extra.append(run) }84 }85 if !extra.isEmpty || !found { lines.append(Line(path: style.path, type: "paragraph", attrs: [:], content: .inline(extra))) }86 lastCode = nil; continue87 }88 let r = runs(of: text, in: content, code: style.isCode)89 if style.isCode, let prev = lastCode, prev === style, case .inline(var prior)? = lines.last?.content {90 prior.append(.text("\n", marks: [])); prior.append(contentsOf: r)91 lines[lines.count - 1].content = .inline(coalesce(prior, code: true))92 continue93 }94 // a block node that ended up inside a text paragraph (paste, drop) becomes its own line, after the text95 var inline: [InlineRun] = []; var strays: [PMNode] = []96 for run in r { if case .atom(let n) = run, isBlockAttachment(n, in: text, range: content) { strays.append(n) } else { inline.append(run) } }97 var l = style.line(.inline(style.isCode ? coalesce(inline, code: true) : inline)); l.attrs = dedupe(l.attrs, &seen, dedupeIDs); lines.append(l)98 for n in strays { lines.append(Line(path: style.path, type: n.type, attrs: [:], content: .blockAtom(n))) }99 lastCode = style.isCode ? style : nil100 }101 return lines102 }103104 private static func dedupe(_ attrs: [String: JSONValue], _ seen: inout Set<String>, _ on: Bool) -> [String: JSONValue] {105 guard on, case .string(let id)? = attrs["id"] else { return attrs }106 if seen.insert(id).inserted { return attrs }107 var a = attrs; a["id"] = nil; return a108 }109110 private static func blockAtom(in text: NSAttributedString, range: NSRange) -> AtomAttachment? {111 var hit: AtomAttachment?112 text.enumerateAttribute(.attachment, in: range) { v, _, stop in if let a = v as? AtomAttachment, a.isBlock { hit = a; stop.pointee = true } }113 return hit114 }115 private static func isBlockAttachment(_ node: PMNode, in text: NSAttributedString, range: NSRange) -> Bool {116 var hit = false117 text.enumerateAttribute(.attachment, in: range) { v, _, stop in if let a = v as? AtomAttachment, a.isBlock, a.node == node { hit = true; stop.pointee = true } }118 return hit119 }120121 /// Inline runs of a character range (no paragraph terminator inside, except in code).122 public static func runs(of text: NSAttributedString, in range: NSRange, code: Bool) -> [InlineRun] {123 guard range.length > 0 else { return [] }124 var out: [InlineRun] = []125 let ns = text.string as NSString126 text.enumerateAttributes(in: range) { attrs, r, _ in127 let marks = (attrs[.spMarks] as? MarkSet)?.marks ?? []128 if let a = attrs[.attachment] as? AtomAttachment { for _ in 0..<r.length { out.append(.atom(a.node)) }; return }129 if attrs[.attachment] != nil { return } // a foreign attachment (never created by the editor) has no document meaning130 if let box = attrs[.spInlineNode] as? NodeBox, ns.substring(with: r).allSatisfy({ $0 == "\u{2028}" }) { for _ in 0..<r.length { out.append(.atom(box.node)) }; return }131 var s = ns.substring(with: r)132 if !code { s = s.replacingOccurrences(of: lineSeparator, with: "\n") }133 s = s.replacingOccurrences(of: attachmentCharacter, with: "")134 if !s.isEmpty { out.append(.text(s, marks: code ? [] : marks)) }135 }136 return coalesce(out, code: code)137 }138139 static func coalesce(_ runs: [InlineRun], code: Bool) -> [InlineRun] {140 var out: [InlineRun] = []141 for r in runs {142 if case .text(let t, let m) = r, case .text(let pt, let pm)? = out.last, pm == m || code { out[out.count - 1] = .text(pt + t, marks: code ? [] : pm) }143 else if case .text(let t, _) = r, t.isEmpty { continue }144 else { out.append(r) }145 }146 return out147 }148149 /// Largest container key used by a document (new containers must be numbered above it).150 public static func maxKey(_ doc: NoteDocument) -> Int { doc.lines.flatMap(\.path).map(\.key).max() ?? 0 }151}152