Repository Public
1// SP Notes iOS2// File: Editor/AttributedCodec.swift3// Description: Lossless conversion between the document model (lines) and the attributed text held by the text storage.4// Model → storage when a note is opened or replaced; storage → model at every (debounced) save.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import SPNotesCore1011enum AttributedCodec {12 // MARK: model → storage1314 /// Builds the bare attributed string (model attributes only). `EditorStyler` adds fonts, paragraph styles and atom images afterwards.15 static func attributedString(from document: NoteDocument) -> NSMutableAttributedString {16 let out = NSMutableAttributedString()17 let lines = document.lines.isEmpty ? [Line(path: [], type: "paragraph", attrs: LineStyle.paragraphAttrs, content: .inline([]))] : document.lines18 for (index, line) in lines.enumerated() {19 var box = LineBox(LineStyle(line))20 let paragraph = NSMutableAttributedString()21 switch line.content {22 case .blockAtom(let node):23 box = LineBox(style(forBlockAtom: node, path: line.path))24 paragraph.append(NSAttributedString(attachment: AtomAttachment(node: node, isBlock: true)))25 case .inline(let runs):26 for run in runs { paragraph.append(attributed(run, isCode: line.type == "codeBlock")) }27 }28 _ = index29 // Every line, the last one included, ends with a newline: it carries the paragraph's identity even when the line is empty.30 paragraph.append(NSAttributedString(string: "\n"))31 paragraph.addAttribute(.spnLine, value: box, range: NSRange(location: 0, length: paragraph.length))32 out.append(paragraph)33 }34 return out35 }3637 private static func attributed(_ run: InlineRun, isCode: Bool) -> NSAttributedString {38 switch run {39 case .text(let text, let marks):40 // Inside a code block the model keeps real newlines in one line; in the storage they are soft breaks so the block stays one paragraph.41 _ = isCode42 let shown = text.replacingOccurrences(of: "\n", with: EditorCharacter.softBreak)43 return NSAttributedString(string: shown, attributes: marks.isEmpty ? [:] : [.spnMarks: MarksBox(marks)])44 case .atom(let node):45 if node.type == "hardBreak" && node.attrs == nil && node.marks == nil && node.extra.isEmpty {46 return NSAttributedString(string: EditorCharacter.softBreak)47 }48 return NSAttributedString(attachment: AtomAttachment(node: node, isBlock: false))49 }50 }5152 // MARK: storage → model5354 /// Reads the storage back into lines. The storage ends with the terminator of its last paragraph (see `attributedString(from:)`);55 /// a storage without it (never produced by the editor) is read the same way, its last characters forming the last line.56 static func document(from storage: NSAttributedString) -> NoteDocument {57 var lines: [Line] = []58 let string = storage.string as NSString59 var location = 060 let length = string.length61 var lastStyle: LineStyle?62 while location < length {63 let paragraphRange = string.paragraphRange(for: NSRange(location: location, length: 0))64 var contentRange = paragraphRange65 if contentRange.length > 0, string.character(at: NSMaxRange(contentRange) - 1) == EditorCharacter.newlineScalar { contentRange.length -= 1 }66 let style = (storage.attribute(.spnLine, at: paragraphRange.location, effectiveRange: nil) as? LineBox)?.style67 ?? lastStyle?.paragraphHere() ?? LineStyle(attrs: LineStyle.paragraphAttrs)68 lines.append(contentsOf: Self.lines(from: storage, contentRange: contentRange, style: style))69 lastStyle = style70 location = NSMaxRange(paragraphRange)71 }72 if lines.isEmpty { lines.append(emptyLine(LineStyle(attrs: LineStyle.paragraphAttrs))) }73 return NoteDocument(lines: lines)74 }7576 private static func emptyLine(_ style: LineStyle) -> Line {77 // A block-atom style without its attachment (the user deleted it) degrades to an empty paragraph at the same place.78 let textual = isTextual(style) ? style : style.paragraphHere()79 return Line(path: textual.path, type: textual.type, attrs: textual.attrs, content: .inline([]))80 }8182 /// Block atoms have a style whose type is the atom's node type; everything else holds inline content.83 static func isTextual(_ style: LineStyle) -> Bool { !blockAtomTypes.contains(style.type) && !style.attrs.keys.contains(atomMarkerKey) }84 static let blockAtomTypes: Set<String> = Set(["image", "fileBlock", "table", "blockMath", "horizontalRule", "youtube"]).union(NodeType.nextBlocks)85 /// Unknown block atoms are flagged in the (storage-only) style so they are recognised without a type list.86 static let atomMarkerKey = "\u{1}spnAtom"8788 /// One storage paragraph → one line, or several when a block atom shares the paragraph with text (after a paste or an unusual89 /// deletion): the atom then gets a line of its own and the text around it stays text. Nothing is ever dropped.90 private static func lines(from storage: NSAttributedString, contentRange: NSRange, style: LineStyle) -> [Line] {91 let textual = isTextual(style) ? style : style.paragraphHere()92 guard contentRange.length > 0 else { return [Line(path: textual.path, type: textual.type, attrs: textual.attrs, content: .inline([]))] }93 var out: [Line] = []94 var runs: [InlineRun] = []95 let isCode = textual.isCode96 let string = storage.string as NSString97 func flush(force: Bool) {98 if runs.isEmpty && !force { return }99 // Text split off around an atom is a plain paragraph for the pieces after the first (a heading does not repeat itself).100 let s = out.contains(where: { if case .inline = $0.content { return true } else { return false } }) ? textual.paragraphHere() : textual101 out.append(Line(path: s.path, type: s.type, attrs: s.attrs, content: .inline(runs)))102 runs = []103 }104 storage.enumerateAttributes(in: contentRange, options: []) { attributes, range, _ in105 if let atom = attributes[.attachment] as? AtomAttachment {106 if atom.isBlock {107 flush(force: false)108 for _ in 0..<range.length { out.append(Line(path: style.path, type: atom.node.type, attrs: atom.node.attrs ?? [:], content: .blockAtom(atom.node))) }109 } else {110 for _ in 0..<range.length { runs.append(.atom(atom.node)) }111 }112 return113 }114 if attributes[.attachment] != nil { return } // foreign attachment (system paste): not representable in the model115 let marks = isCode ? [] : ((attributes[.spnMarks] as? MarksBox)?.marks ?? [])116 let text = string.substring(with: range)117 if isCode {118 append(text: text.replacingOccurrences(of: EditorCharacter.softBreak, with: "\n"), marks: [], to: &runs)119 } else {120 // Soft breaks are hardBreak nodes; the text around them keeps its marks.121 var first = true122 for piece in text.components(separatedBy: EditorCharacter.softBreak) {123 if !first { runs.append(.atom(EditorNodeTypes.hardBreak)) }124 first = false125 append(text: piece.replacingOccurrences(of: EditorCharacter.attachment, with: ""), marks: marks, to: &runs)126 }127 }128 }129 flush(force: out.isEmpty)130 return out131 }132133 private static func append(text: String, marks: [PMMark], to runs: inout [InlineRun]) {134 guard !text.isEmpty else { return }135 if case .text(let previous, let previousMarks)? = runs.last, previousMarks == marks {136 runs[runs.count - 1] = .text(previous + text, marks: marks)137 } else {138 runs.append(.text(text, marks: marks))139 }140 }141142 // MARK: helpers shared with the editor143144 /// The style to give the paragraph that holds a block atom.145 static func style(forBlockAtom node: PMNode, path: [Container]) -> LineStyle {146 var attrs = node.attrs ?? [:]147 if !blockAtomTypes.contains(node.type) { attrs[atomMarkerKey] = .bool(true) }148 return LineStyle(path: path, type: node.type, attrs: attrs)149 }150}151