Docs native S1a: render one block, and index blocks by the storage
Spec 2026-11-22 §7 Design 4 and 7. - NativeTextProjection.renderBlock draws one top-level block exactly as the whole render draws it among its neighbours. What it reads from outside the block is DocumentBlockSpacing.Context: first, last, whether it holds the document's first character, and the next paragraph's top margin (which collapses with its last). Inline code and list numbering never cross a block. The whole render is unchanged, and stays for open and as the tests' oracle. - .docsTopBlock is now set on iOS too (it was Mac-only): typed text inherits it, so the storage itself says which block a character is in. - DocumentBlockIndex: the .docsTopBlock runs, kept current per edit (runs before it stay, runs after it shift, the touched ones are read again). Provisional blocks (one id over two paragraphs after an optimistic Return; two ids in one after a Backspace) are runs like any other. - DocumentRenderReconciliation.apply(_:to:in:) reconciles one stretch, with the same text and attribute rules as the whole-storage one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+202
−12
native/apple/Sources/DocsKit/DocumentBlockIndex.swift+99 −0native/apple/Sources/DocsKit/DocumentBlockSpacing.swift+54 −0native/apple/Sources/DocsKit/DocumentPageLayout.swift+0 −1native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift+16 −6native/apple/Sources/DocsKit/NativeTextProjection.swift+33 −5
Intent
diff --git a/native/apple/Sources/DocsKit/DocumentBlockIndex.swift b/native/apple/Sources/DocsKit/DocumentBlockIndex.swift| new file mode 100644 |
| index 0000000..f0a885e |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocumentBlockIndex.swift |
| @@ -0,0 +1,99 @@ |
| +import Foundation |
| + |
| +/// Which characters of the text storage belong to which top-level block, |
| +/// read from the storage's own `.docsTopBlock` runs (spec 2026-11-22 §7 |
| +/// Design 4). Not from publications: text typed before any publication |
| +/// inherits its block's id, so the storage is right before the replica |
| +/// has answered. |
| +/// |
| +/// The runs tile the storage, in order. A run with a nil id is text that |
| +/// carries no block (typed into an empty document). A *provisional* block |
| +/// is one id spanning more than one paragraph: an optimistic Return, whose |
| +/// new paragraph keeps its block's id until a publication names it. A |
| +/// Backspace at a block's start gives the reverse, one paragraph holding |
| +/// two runs. Both are legal until the publication that resolves them. |
| +struct DocumentBlockIndex: Equatable { |
| + struct Run: Equatable { |
| + var id: String? |
| + var location: Int |
| + var length: Int |
| + var end: Int { location + length } |
| + var range: NSRange { NSRange(location: location, length: length) } |
| + } |
| + private(set) var runs: [Run] = [] |
| + |
| + /// The runs as the storage holds them now, read afresh. |
| + static func runs(in storage: NSAttributedString, range: NSRange? = nil) -> [Run] { |
| + let range = range ?? NSRange(location: 0, length: storage.length) |
| + var runs: [Run] = [] |
| + guard range.length > 0 else { return runs } |
| + storage.enumerateAttribute(.docsTopBlock, in: range) { value, found, _ in |
| + let id = value as? String |
| + if let last = runs.last, last.id == id, last.end == found.location { runs[runs.count - 1].length += found.length } |
| + else { runs.append(Run(id: id, location: found.location, length: found.length)) } |
| + } |
| + return runs |
| + } |
| + |
| + mutating func rebuild(from storage: NSAttributedString) { runs = Self.runs(in: storage) } |
| + |
| + /// After the storage processed an edit: `edited` is the range in the |
| + /// new text, `delta` the change in length. Runs before it stay, runs |
| + /// after it shift by `delta`, and the runs it touched (with their |
| + /// neighbours, so that runs of one id merge) are read again from the |
| + /// attribute. O(blocks) integer work, and a re-read of only the touched |
| + /// runs. |
| + mutating func processEditing(_ storage: NSAttributedString, edited: NSRange, delta: Int) { |
| + guard !runs.isEmpty, edited.location != NSNotFound else { rebuild(from: storage); return } |
| + let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta |
| + // The first run ending at or after the edit, and the last starting |
| + // at or before its end (in the old text): the touched ones, with |
| + // whichever runs merely touch it. |
| + var first = firstRun(endingAtOrAfter: oldStart) |
| + if first > 0 { first -= 1 } |
| + var last = first |
| + while last + 1 < runs.count, runs[last + 1].location <= oldEnd { last += 1 } |
| + if last + 1 < runs.count { last += 1 } |
| + let start = runs[first].location |
| + let end = runs[last].end + delta |
| + guard start >= 0, end <= storage.length, start <= end else { rebuild(from: storage); return } |
| + let fresh = Self.runs(in: storage, range: NSRange(location: start, length: end - start)) |
| + for index in (last + 1)..<runs.count { runs[index].location += delta } |
| + runs.replaceSubrange(first...last, with: fresh) |
| + // The re-read starts and ends on old run boundaries, so a seam can |
| + // only join equal ids that were apart before. |
| + let seams = [first + fresh.count, first] |
| + for seam in seams where seam > 0 && seam < runs.count { |
| + if runs[seam - 1].id == runs[seam].id, runs[seam - 1].end == runs[seam].location { |
| + runs[seam - 1].length += runs[seam].length |
| + runs.remove(at: seam) |
| + } |
| + } |
| + if runs.isEmpty, storage.length > 0 { rebuild(from: storage) } |
| + } |
| + |
| + private func firstRun(endingAtOrAfter location: Int) -> Int { |
| + var low = 0, high = runs.count - 1 |
| + while low < high { |
| + let middle = (low + high) / 2 |
| + if runs[middle].end < location { low = middle + 1 } else { high = middle } |
| + } |
| + return low |
| + } |
| + |
| + /// The runs holding any character from `first` to `last`, inclusive. |
| + func runs(holding first: Int, through last: Int) -> ArraySlice<Run> { |
| + guard !runs.isEmpty, last >= first else { return [] } |
| + var from = firstRun(endingAtOrAfter: first) |
| + if runs[from].end == first, from + 1 < runs.count { from += 1 } |
| + var to = from |
| + while to + 1 < runs.count, runs[to + 1].location <= last { to += 1 } |
| + return runs[from...to] |
| + } |
| + /// Run positions by block id, in storage order. |
| + func positions() -> [String: [Int]] { |
| + var found: [String: [Int]] = [:] |
| + for (index, run) in runs.enumerated() { if let id = run.id { found[id, default: []].append(index) } } |
| + return found |
| + } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift b/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift| index 819b99c..0ace4a0 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift |
| @@ -30,6 +30,60 @@ extension NSAttributedString.Key { static let docsFirstMargin = NSAttributedStri |
| output.addAttribute(.paragraphStyle, value: style, range: range) |
| } |
| } |
| + /// What one top-level block's spacing reads from outside it. |
| + struct Context: Equatable { |
| + /// First of the document: a heading's or quote's top margin is dropped. |
| + var first = false |
| + /// Last of the document: its bottom margin is dropped. |
| + var last = false |
| + /// It holds the document's first character (every block before it |
| + /// is an empty list or quote), so it carries `docsFirstMargin`. |
| + var leading = false |
| + /// The top margin of the next paragraph in the document, which |
| + /// collapses with this block's last; nil when there is none. |
| + var nextBefore: CGFloat? |
| + } |
| + /// The top margin of a block's first paragraph, or nil when it has |
| + /// none (an empty list or quote). Never first of the document. |
| + static func firstBefore(_ node: CRDTNode, first: Bool = false) -> CGFloat? { |
| + flatten(node, clearBefore: first).first?.before |
| + } |
| + /// Each block's context in `nodes`, as `apply(_:to:)` lays them out. |
| + static func contexts(_ nodes: [CRDTNode]) -> [Context] { |
| + var contexts = Array(repeating: Context(), count: nodes.count) |
| + var next: CGFloat? |
| + for index in nodes.indices.reversed() { |
| + contexts[index].first = index == 0 |
| + contexts[index].last = index == nodes.count - 1 |
| + contexts[index].nextBefore = next |
| + if let before = firstBefore(nodes[index], first: index == 0) { next = before } |
| + } |
| + for index in nodes.indices { |
| + contexts[index].leading = true |
| + if firstBefore(nodes[index]) != nil { break } |
| + } |
| + return contexts |
| + } |
| + /// `apply(_:to:)` for one block rendered on its own: the same margins, |
| + /// given what `context` says about its neighbours. |
| + static func apply(_ node: CRDTNode, context: Context, to output: NSMutableAttributedString) { |
| + let blocks = flatten(node, clearBefore: context.first, clearAfter: context.last) |
| + guard let first = blocks.first, output.length > 0 else { return } |
| + if context.leading { output.addAttribute(.docsFirstMargin, value: first.before, range: NSRange(location: 0, length: 1)) } |
| + var ranges: [String: NSRange] = [:] |
| + output.enumerateAttribute(.docsBlock, in: NSRange(location: 0, length: output.length)) { value, range, _ in |
| + guard let id = value as? String else { return } |
| + ranges[id] = ranges[id].map { NSUnionRange($0, range) } ?? range |
| + } |
| + for (index, block) in blocks.enumerated() { |
| + guard let range = ranges[block.id], let existing = output.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle, |
| + let style = existing.mutableCopy() as? NSMutableParagraphStyle else { continue } |
| + style.paragraphSpacingBefore = 0 |
| + let next = index + 1 < blocks.count ? blocks[index + 1].before : context.nextBefore |
| + style.paragraphSpacing = next.map { max(block.after, $0) } ?? block.after |
| + output.addAttribute(.paragraphStyle, value: style, range: range) |
| + } |
| + } |
| static func margins(_ node: CRDTNode) -> (CGFloat, CGFloat) { |
| let blocks = flatten(node) |
| return (blocks.first?.before ?? 0, blocks.last?.after ?? 0) |
diff --git a/native/apple/Sources/DocsKit/DocumentPageLayout.swift b/native/apple/Sources/DocsKit/DocumentPageLayout.swift| index 9ae7f8f..fd73d45 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentPageLayout.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentPageLayout.swift |
| @@ -2,7 +2,6 @@ |
| import AppKit |
| extension NSAttributedString.Key { |
| - static let docsTopBlock = NSAttributedString.Key("OficinaDocsTopBlock") |
| static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore") |
| static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter") |
| } |
diff --git a/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift| index 87e13aa..5db77d4 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift |
| @@ -9,22 +9,32 @@ import UIKit |
| /// Equal visible text can still carry a new CRDT node mapping after publication. |
| @MainActor enum DocumentRenderReconciliation { |
| static func apply(_ content: NSAttributedString, to storage: NSMutableAttributedString) { |
| + apply(content, to: storage, in: NSRange(location: 0, length: storage.length)) |
| + } |
| + /// The same, for one stretch of the storage: `range` becomes `content`. |
| + /// The text view's per-block drawing (DocumentSurface) reconciles only |
| + /// the characters of the blocks that changed. |
| + static func apply(_ content: NSAttributedString, to storage: NSMutableAttributedString, in range: NSRange) { |
| #if DOCS_PROBES |
| let probeStart = DocsProbes.now() |
| defer { DocsProbes.reconciles += 1; DocsProbes.reconcileMs += DocsProbes.ms(since: probeStart) } |
| #endif |
| - guard !storage.isEqual(to: content) else { return } |
| + let whole = range.location == 0 && range.length == storage.length |
| + if whole { guard !storage.isEqual(to: content) else { return } } |
| + else { guard !storage.attributedSubstring(from: range).isEqual(to: content) else { return } } |
| storage.beginEditing() |
| defer { storage.endEditing() } |
| - if let (range, replacement) = DocumentComposition.replacement(before: storage.string, after: content.string) { |
| - storage.replaceCharacters(in: range, with: replacement) |
| + let before = whole ? storage.string : (storage.string as NSString).substring(with: range) |
| + if let (changed, replacement) = DocumentComposition.replacement(before: before, after: content.string) { |
| + storage.replaceCharacters(in: NSRange(location: range.location + changed.location, length: changed.length), with: replacement) |
| } |
| - content.enumerateAttributes(in: NSRange(location: 0, length: content.length)) { attributes, range, _ in |
| + content.enumerateAttributes(in: NSRange(location: 0, length: content.length)) { attributes, found, _ in |
| + let target = NSRange(location: range.location + found.location, length: found.length) |
| var changed = false |
| - storage.enumerateAttributes(in: range) { current, _, stop in |
| + storage.enumerateAttributes(in: target) { current, _, stop in |
| if !NSDictionary(dictionary: current).isEqual(to: attributes) { changed = true; stop.pointee = true } |
| } |
| - if changed { storage.setAttributes(attributes, range: range) } |
| + if changed { storage.setAttributes(attributes, range: target) } |
| } |
| } |
diff --git a/native/apple/Sources/DocsKit/NativeTextProjection.swift b/native/apple/Sources/DocsKit/NativeTextProjection.swift| index 606b74a..fba64b7 100644 |
| --- a/native/apple/Sources/DocsKit/NativeTextProjection.swift |
| +++ b/native/apple/Sources/DocsKit/NativeTextProjection.swift |
| @@ -13,6 +13,11 @@ extension NSAttributedString.Key { |
| static let docsOffset = NSAttributedString.Key("OficinaDocsOffset") |
| static let docsQuoteBorders = NSAttributedString.Key("OficinaDocsQuoteBorders") |
| static let docsMarks = NSAttributedString.Key("OficinaDocsMarks") |
| + /// The id of the top-level block a character belongs to, on both |
| + /// platforms. Typed text inherits it, so the storage itself says which |
| + /// characters belong to which block before any publication arrives |
| + /// (DocumentBlockIndex; spec 2026-11-22 §7 Design 4). |
| + static let docsTopBlock = NSAttributedString.Key("OficinaDocsTopBlock") |
| } |
| @MainActor enum NativeTextProjection { |
| /// Sorted keys: a dictionary's keys come out in a different order from |
| @@ -32,16 +37,39 @@ extension NSAttributedString.Key { |
| for node in projection.children { |
| let start = output.length |
| append(node, to: output, depth: 0, lists: [], images: images) |
| - #if os(macOS) |
| - let margins = DocumentBlockSpacing.margins(node) |
| - output.addAttributes([.docsTopBlock: node.id, .docsMarginBefore: margins.0, .docsMarginAfter: margins.1], |
| - range: NSRange(location: start, length: output.length - start)) |
| - #endif |
| + markTopBlock(node, in: output, from: start) |
| } |
| DocumentBlockSpacing.apply(projection.children, to: output) |
| DocumentInlineCode.apply(to: output) |
| return output |
| } |
| + /// One top-level block, exactly as `render` draws it among its |
| + /// neighbours: `context` carries everything `render` reads from outside |
| + /// the block (whether it is first or last, whether it holds the |
| + /// document's first character, and the next block's top margin, which |
| + /// collapses with this block's bottom one). Inline code and list |
| + /// numbering never cross a block, so they are the block's own. |
| + static func renderBlock(_ node: CRDTNode, context: DocumentBlockSpacing.Context, images: [String: DocsPlatformImage] = [:]) -> NSAttributedString { |
| + #if DOCS_PROBES |
| + let probeStart = DocsProbes.now() |
| + defer { DocsProbes.blockRenders += 1; DocsProbes.blockRenderMs += DocsProbes.ms(since: probeStart) } |
| + #endif |
| + let output = NSMutableAttributedString(string: "") |
| + append(node, to: output, depth: 0, lists: [], images: images) |
| + markTopBlock(node, in: output, from: 0) |
| + DocumentBlockSpacing.apply(node, context: context, to: output) |
| + DocumentInlineCode.apply(to: output) |
| + return output |
| + } |
| + private static func markTopBlock(_ node: CRDTNode, in output: NSMutableAttributedString, from start: Int) { |
| + let range = NSRange(location: start, length: output.length - start) |
| + #if os(macOS) |
| + let margins = DocumentBlockSpacing.margins(node) |
| + output.addAttributes([.docsTopBlock: node.id, .docsMarginBefore: margins.0, .docsMarginAfter: margins.1], range: range) |
| + #else |
| + output.addAttribute(.docsTopBlock, value: node.id, range: range) |
| + #endif |
| + } |
| private static func append(_ node: CRDTNode, to output: NSMutableAttributedString, depth: Int, lists: [NSTextList], images: [String: DocsPlatformImage], containers: [DocsClipboardContainer] = []) { |
| if ["bullet_list", "ordered_list", "list_item", "blockquote"].contains(node.type) { |
| var nested = lists |