| 1 | import Foundation |
| 2 | #if os(macOS) |
| 3 | import AppKit |
| 4 | private typealias PlatformFont = NSFont |
| 5 | #else |
| 6 | import UIKit |
| 7 | private typealias PlatformFont = UIFont |
| 8 | #endif |
| 9 | |
| 10 | extension NSAttributedString.Key { |
| 11 | static let docsNode = NSAttributedString.Key("OficinaDocsNode") |
| 12 | static let docsBlock = NSAttributedString.Key("OficinaDocsBlock") |
| 13 | static let docsOffset = NSAttributedString.Key("OficinaDocsOffset") |
| 14 | static let docsQuoteBorders = NSAttributedString.Key("OficinaDocsQuoteBorders") |
| 15 | static let docsMarks = NSAttributedString.Key("OficinaDocsMarks") |
| 16 | /// The id of the top-level block a character belongs to, on both |
| 17 | /// platforms. Typed text inherits it, so the storage itself says which |
| 18 | /// characters belong to which block before any publication arrives |
| 19 | /// (DocumentBlockIndex; spec 2026-11-22 §7 Design 4). |
| 20 | static let docsTopBlock = NSAttributedString.Key("OficinaDocsTopBlock") |
| 21 | } |
| 22 | @MainActor enum NativeTextProjection { |
| 23 | /// Sorted keys: a dictionary's keys come out in a different order from |
| 24 | /// one encoding to the next, and two renders of one projection must |
| 25 | /// carry the same bytes (DocumentRenderReconciliation.isEquivalent). |
| 26 | private static let encoder: JSONEncoder = { |
| 27 | let encoder = JSONEncoder() |
| 28 | encoder.outputFormatting = .sortedKeys |
| 29 | return encoder |
| 30 | }() |
| 31 | static func render(_ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:]) -> NSAttributedString { |
| 32 | #if DOCS_PROBES |
| 33 | let probeStart = DocsProbes.now() |
| 34 | defer { DocsProbes.wholeRenders += 1; DocsProbes.wholeRenderMs += DocsProbes.ms(since: probeStart) } |
| 35 | #endif |
| 36 | let output = NSMutableAttributedString(string: "") |
| 37 | for node in projection.children { |
| 38 | let start = output.length |
| 39 | append(node, to: output, depth: 0, lists: [], images: images) |
| 40 | markTopBlock(node, in: output, from: start) |
| 41 | } |
| 42 | DocumentBlockSpacing.apply(projection.children, to: output) |
| 43 | DocumentInlineCode.apply(to: output) |
| 44 | return output |
| 45 | } |
| 46 | /// One top-level block, exactly as `render` draws it among its |
| 47 | /// neighbours: `context` carries everything `render` reads from outside |
| 48 | /// the block (whether it is first or last, whether it holds the |
| 49 | /// document's first character, and the next block's top margin, which |
| 50 | /// collapses with this block's bottom one). Inline code and list |
| 51 | /// numbering never cross a block, so they are the block's own. |
| 52 | static func renderBlock(_ node: CRDTNode, context: DocumentBlockSpacing.Context, images: [String: DocsPlatformImage] = [:]) -> NSAttributedString { |
| 53 | #if DOCS_PROBES |
| 54 | let probeStart = DocsProbes.now() |
| 55 | defer { DocsProbes.blockRenders += 1; DocsProbes.blockRenderMs += DocsProbes.ms(since: probeStart) } |
| 56 | #endif |
| 57 | let output = NSMutableAttributedString(string: "") |
| 58 | append(node, to: output, depth: 0, lists: [], images: images) |
| 59 | markTopBlock(node, in: output, from: 0) |
| 60 | DocumentBlockSpacing.apply(node, context: context, to: output) |
| 61 | DocumentInlineCode.apply(to: output) |
| 62 | return output |
| 63 | } |
| 64 | private static func markTopBlock(_ node: CRDTNode, in output: NSMutableAttributedString, from start: Int) { |
| 65 | let range = NSRange(location: start, length: output.length - start) |
| 66 | #if os(macOS) |
| 67 | let margins = DocumentBlockSpacing.margins(node) |
| 68 | output.addAttributes([.docsTopBlock: node.id, .docsMarginBefore: margins.0, .docsMarginAfter: margins.1], range: range) |
| 69 | #else |
| 70 | output.addAttribute(.docsTopBlock, value: node.id, range: range) |
| 71 | #endif |
| 72 | } |
| 73 | private static func append(_ node: CRDTNode, to output: NSMutableAttributedString, depth: Int, lists: [NSTextList], images: [String: DocsPlatformImage], containers: [DocsClipboardContainer] = []) { |
| 74 | if ["bullet_list", "ordered_list", "list_item", "blockquote"].contains(node.type) { |
| 75 | var nested = lists |
| 76 | if node.type == "bullet_list" { nested.append(NSTextList(markerFormat: .disc, options: 0)) } |
| 77 | if node.type == "ordered_list" { |
| 78 | let list = NSTextList(markerFormat: .decimal, options: 0) |
| 79 | if let order = Int(node.attrs?["order"] ?? ""), (Int(Int32.min)...Int(Int32.max)).contains(order) { list.startingItemNumber = order } |
| 80 | nested.append(list) |
| 81 | } |
| 82 | let ancestry = containers + [DocsClipboardContainer(id: node.id, type: node.type, attrs: node.attrs)] |
| 83 | for child in node.children ?? [] { append(child, to: output, depth: depth + (node.type == "list_item" || node.type == "blockquote" ? 1 : 0), lists: nested, images: images, containers: ancestry) } |
| 84 | return |
| 85 | } |
| 86 | let start = output.length |
| 87 | let style = NSMutableParagraphStyle() |
| 88 | style.paragraphSpacing = 0 |
| 89 | style.textLists = lists |
| 90 | let indent = max(0, min(8, Int(node.attrs?["indent"] ?? "0") ?? 0)) |
| 91 | style.headIndent = containers.reduce(CGFloat(indent * 36)) { offset, container in |
| 92 | offset + (container.type == "list_item" ? 16.8 : container.type == "blockquote" ? 14.25 : 0) |
| 93 | } |
| 94 | style.firstLineHeadIndent = style.headIndent |
| 95 | switch node.attrs?["align"] { case "center": style.alignment = .center; case "right": style.alignment = .right; default: style.alignment = .left } |
| 96 | let heading = node.type == "heading" ? max(1, min(6, Int(node.attrs?["level"] ?? "1") ?? 1)) : 0 |
| 97 | #if os(macOS) |
| 98 | style.headerLevel = heading |
| 99 | #endif |
| 100 | let base = baseSize(heading: heading) |
| 101 | let leading: CGFloat = heading > 0 ? 1.3 : 1.4 |
| 102 | let inheritedMarks = inherited(heading: heading, quoted: containers.contains(where: { $0.type == "blockquote" }), code: node.type == "code_block") |
| 103 | let baseFont = font(marks: inheritedMarks, size: base, heading: heading > 0) |
| 104 | #if os(macOS) |
| 105 | let naturalHeight = NSLayoutManager().defaultLineHeight(for: baseFont) |
| 106 | #else |
| 107 | let naturalHeight = baseFont.lineHeight |
| 108 | #endif |
| 109 | style.lineHeightMultiple = base * leading / naturalHeight |
| 110 | style.minimumLineHeight = base * leading |
| 111 | if heading > 0 { |
| 112 | style.paragraphSpacingBefore = base * 1.5 |
| 113 | style.paragraphSpacing = base * 0.5 |
| 114 | } |
| 115 | var baseAttributes: [NSAttributedString.Key: Any] = [.paragraphStyle: style, .font: baseFont, .docsBlock: node.id, .docsBlockType: node.type, .docsHeading: heading] |
| 116 | #if os(macOS) |
| 117 | baseAttributes[.docsBaseFont] = baseFont |
| 118 | baseAttributes[.docsLeading] = leading |
| 119 | #endif |
| 120 | var quoteBorders: [CGFloat] = [] |
| 121 | var containerIndent: CGFloat = 0 |
| 122 | for container in containers { |
| 123 | if container.type == "blockquote" { quoteBorders.append(containerIndent); containerIndent += 14.25 } |
| 124 | if container.type == "list_item" { containerIndent += 16.8 } |
| 125 | } |
| 126 | if !quoteBorders.isEmpty { |
| 127 | baseAttributes[.docsQuoteBorders] = quoteBorders |
| 128 | #if os(macOS) |
| 129 | baseAttributes[.foregroundColor] = NSColor(white: 74.0 / 255, alpha: 1) |
| 130 | #else |
| 131 | baseAttributes[.foregroundColor] = UIColor(white: 74.0 / 255, alpha: 1) |
| 132 | #endif |
| 133 | } |
| 134 | baseAttributes[.docsBlockAttributes] = try? encoder.encode(node.attrs ?? [:]) |
| 135 | baseAttributes[.docsClipboardContainers] = try? encoder.encode(containers) |
| 136 | if node.type == "horizontal_rule" { |
| 137 | let rule = NSMutableAttributedString(attributedString: DocsAttachments.rule(width: 468)) |
| 138 | rule.addAttributes(baseAttributes, range: NSRange(location: 0, length: rule.length)) |
| 139 | output.append(rule); output.append(NSAttributedString(string: "\n", attributes: baseAttributes)); return |
| 140 | } |
| 141 | for child in node.children ?? [] { |
| 142 | if child.type == "text" { |
| 143 | var offset = 0 |
| 144 | for run in child.runs ?? [] { |
| 145 | var attributes = baseAttributes |
| 146 | let marks = run.marks ?? [:] |
| 147 | var visualMarks = inheritedMarks.merging(marks, uniquingKeysWith: { _, authored in authored }) |
| 148 | if node.type == "code_block" { visualMarks["code"] = .object([:]) } |
| 149 | attributes[.font] = font(marks: visualMarks, size: base, heading: heading > 0) |
| 150 | attributes[.docsNode] = child.id |
| 151 | attributes[.docsOffset] = offset |
| 152 | attributes[.docsMarks] = try? encoder.encode(marks) |
| 153 | if case .object(let link)? = marks["link"], case .string(let href)? = link["href"], let url = URL(string: href), ["https", "http", "mailto"].contains(url.scheme ?? "") { attributes[.link] = url } |
| 154 | output.append(NSAttributedString(string: run.insert, attributes: attributes)) |
| 155 | offset += run.insert.utf16.count |
| 156 | } |
| 157 | } else if child.type == "hard_break" { output.append(NSAttributedString(string: "\u{2028}", attributes: baseAttributes)) } |
| 158 | else if child.type == "image" { let image = NSMutableAttributedString(attributedString: DocsAttachments.image(images[child.attrs?["src"] ?? ""], alt: child.attrs?["alt"] ?? "", maxWidth: 468)) |
| 159 | image.addAttributes(baseAttributes.merging([.docsNode: child.id], uniquingKeysWith: { _, new in new }), range: NSRange(location: 0, length: image.length)) |
| 160 | if let attrs = try? encoder.encode(child.attrs ?? [:]) { image.addAttribute(.docsImageAttributes, value: attrs, range: NSRange(location: 0, length: image.length)) } |
| 161 | output.append(image) } |
| 162 | else { append(child, to: output, depth: depth, lists: lists, images: images, containers: containers) } |
| 163 | } |
| 164 | var ending = baseAttributes |
| 165 | if output.length == start { ending[.docsNode] = node.id; ending[.docsOffset] = 0 } |
| 166 | output.append(NSAttributedString(string: "\n", attributes: ending)) |
| 167 | } |
| 168 | private static func font(marks: [String: JSONValue], size: CGFloat, heading: Bool) -> PlatformFont { |
| 169 | DocsFonts.font(marks: marks, size: size, heading: heading) |
| 170 | } |
| 171 | private static func baseSize(heading: Int) -> CGFloat { |
| 172 | heading == 1 ? 19.2 : heading == 2 ? 15.6 : heading == 3 ? 13.2 : 12 |
| 173 | } |
| 174 | /// The marks a block lends its text: italic for quotes and small |
| 175 | /// headings, code for a code block. |
| 176 | private static func inherited(heading: Int, quoted: Bool, code: Bool) -> [String: JSONValue] { |
| 177 | var marks: [String: JSONValue] = [:] |
| 178 | if heading >= 4 || quoted { marks["em"] = .object([:]) } |
| 179 | if code { marks["code"] = .object([:]) } |
| 180 | return marks |
| 181 | } |
| 182 | /// The face text typed at a collapsed caret will be in, given the marks |
| 183 | /// it will carry. A font picked at the caret is only typing marks until |
| 184 | /// the first character, so the text view's typing attributes take this |
| 185 | /// face: IME marked text is then drawn in the face it commits in, not in |
| 186 | /// its neighbour's first. |
| 187 | static func typingFont(in content: NSAttributedString, at location: Int, marks: [String: JSONValue]) -> DocsPlatformFont? { |
| 188 | guard content.length > 0 else { return nil } |
| 189 | let attributes = content.attributes(at: min(max(0, location), content.length - 1), effectiveRange: nil) |
| 190 | let heading = attributes[.docsHeading] as? Int ?? 0 |
| 191 | let visual = inherited(heading: heading, quoted: attributes[.docsQuoteBorders] != nil, code: attributes[.docsBlockType] as? String == "code_block") |
| 192 | .merging(marks, uniquingKeysWith: { _, typed in typed }) |
| 193 | return font(marks: visual, size: baseSize(heading: heading), heading: heading > 0) |
| 194 | } |
| 195 | } |
| 196 | |