Docs native S1b: incremental pagination on the Mac
Spec 2026-11-22 §7, "Incremental pagination". Before, every storage edit in the paged view copied the document, laid the copy out whole and set a break table keyed by character index, which invalidated all layout; then layout() laid out the whole live container (65 ms a key at 20 pages, about 700 ms at 200). - DocsPagination keeps a measurement layout manager on the live storage with a rectangular container as wide as the paper's text, so TextKit lays it out non-contiguously and shifts what follows an edit. It caches per block (a run of .docsTopBlock starting a paragraph) the advance, used bottom and margins; natural tops are prefix sums, so Return, deletes and pastes are splices. Edits re-measure only the blocks they touched; today's break algorithm runs over the cached numbers from the page holding the first edited block until a break lands where it was. - The full path runs at open (visible blocks first, then 50 a run-loop turn), on a width change, and when most blocks changed at once; a jump or scroll past the frontier measures up to it first. Zoom never runs it. - The break table is per block. The live container asks for a break's absolute top by the character its first line starts at and takes max(proposed, top), so a line proposed twice gets the same answer. Changes invalidate the live layout from the first block that moved, never textContainerChangedGeometry. - The frame height comes from the caches; layout() no longer lays out the whole container. The live layout is contiguous, to the visible bottom: TextKit does not lay out a non-rectangular container non-contiguously (§7 "Fallback"; recorded in the discussion). - Drawing the separators draws only those in the clip (NSTextView asks for its whole bounds; 200 page labels were drawn per frame). - Today's measurement moves to the test target as DocumentPageLayoutOracle.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+611
−88
native/apple/Sources/DocsKit/DocsLayoutManager.swift+1 −3native/apple/Sources/DocsKit/DocsPagedTextView.swift+85 −60native/apple/Sources/DocsKit/DocsPagination.swift+478 −0native/apple/Sources/DocsKit/DocsPaging.swift+8 −4native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift+7 −2native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift+12 −13native/apple/{Sources/DocsKit/DocumentPageLayout.swift => Tests/DocsKitTests/DocumentPageLayoutOracle.swift}+20 −6
diff --git a/native/apple/Sources/DocsKit/DocsLayoutManager.swift b/native/apple/Sources/DocsKit/DocsLayoutManager.swift| index 206380b..dec1121 100644 |
| --- a/native/apple/Sources/DocsKit/DocsLayoutManager.swift |
| +++ b/native/apple/Sources/DocsKit/DocsLayoutManager.swift |
| @@ -10,14 +10,12 @@ extension NSAttributedString.Key { |
| /// half-leading. TextKit's single paragraph multiplier cannot express that when |
| /// a line mixes font families or sizes. |
| @MainActor final class DocsLayoutManager: NSLayoutManager, @preconcurrency NSLayoutManagerDelegate { |
| - private(set) var storageRevision: UInt64 = 0 |
| override func processEditing(for textStorage: NSTextStorage, edited editMask: NSTextStorageEditActions, |
| range newCharRange: NSRange, changeInLength delta: Int, invalidatedRange invalidatedCharRange: NSRange) { |
| super.processEditing(for: textStorage, edited: editMask, range: newCharRange, |
| changeInLength: delta, invalidatedRange: invalidatedCharRange) |
| - storageRevision &+= 1 |
| for container in textContainers { |
| - (container.textView as? DocsPagedTextView)?.invalidatePagination() |
| + (container.textView as? DocsPagedTextView)?.storageEdited(edited: newCharRange, delta: delta) |
| } |
| } |
| override init() { super.init(); usesFontLeading = false; delegate = self } |
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift| index c652724..1cd4807 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| @@ -3,30 +3,41 @@ import Foundation |
| import AppKit |
| @MainActor class DocsPagedTextView: NSTextView { |
| - var paged = false { didSet { if oldValue != paged { needsLayout = true; needsDisplay = true } } } |
| - private var updatingGeometry = false |
| - private var updatingPagination = false |
| - private var separators: [CGFloat] = [] |
| - private var measuredRevision: UInt64? |
| - private var measuredWidth: CGFloat = 0 |
| - private var measuredPaged = false |
| - private var measuredContent: NSAttributedString? |
| - func invalidatePagination() { |
| - measuredRevision = nil |
| - // TextKit may ask for caret geometry before the next NSView layout. |
| - // Prepare the complete page plan now, on an independent layout stack. |
| - if !updatingGeometry { updatePagination() } |
| - needsLayout = true |
| + var paged = false { |
| + didSet { |
| + guard oldValue != paged else { return } |
| + pagination.paged = paged |
| + needsLayout = true; needsDisplay = true |
| + } |
| } |
| + private var updatingGeometry = false |
| + /// The page plan (spec §7, "Incremental pagination"): a measurement |
| + /// stack on this view's own storage, per-block caches, the break table |
| + /// the container reads, and the frame height. |
| + let pagination: DocsPagination |
| override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) { |
| let storage = NSTextStorage() |
| let manager = DocsLayoutManager() |
| manager.usesFontLeading = false |
| - let pages = DocsPageTextContainer(size: CGSize(width: max(320, frameRect.width), height: 1_000_000)) |
| + // Laid out where it is shown, never all of it (§7 items 6 and 8): |
| + // contiguously, to the visible bottom (§7 "Fallback"). TextKit does |
| + // not lay out a container that is not a simple rectangle |
| + // non-contiguously, so the Mac takes the fallback; background layout |
| + // would lay out the rest after every edit. |
| + manager.allowsNonContiguousLayout = false |
| + manager.backgroundLayoutEnabled = false |
| + let size = CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000) |
| + let pages = DocsPageTextContainer(size: size) |
| pages.lineFragmentPadding = 0 |
| + let geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false) |
| + pages.geometry = geometry |
| storage.addLayoutManager(manager) |
| manager.addTextContainer(pages) |
| + pagination = DocsPagination(storage: storage, live: manager, geometry: geometry) |
| super.init(frame: frameRect, textContainer: pages) |
| + pages.tops = pagination |
| + pagination.canDefer = { [weak self] in self?.window != nil } |
| + pagination.changed = { [weak self] in self?.paginationChanged() } |
| textContainerInset = .zero |
| // This view owns its paginated height; NSTextView auto-sizing uses a |
| // different used rect and briefly clips the current line during input. |
| @@ -41,6 +52,13 @@ import AppKit |
| // NSTextView's inferred origin moves during incremental layout and can put |
| // its native insertion indicator at a different origin from the glyphs. |
| override var textContainerOrigin: NSPoint { .zero } |
| + /// The live layout manager saw an edit (DocsLayoutManager): the units |
| + /// shift now; the measuring waits for this view's next layout, before |
| + /// anything is drawn. |
| + func storageEdited(edited: NSRange, delta: Int) { |
| + pagination.storageEdited(edited: edited, delta: delta) |
| + needsLayout = true |
| + } |
| override func didChangeText() { |
| // Size the document before AppKit scrolls the newly edited caret. |
| needsLayout = true |
| @@ -50,69 +68,63 @@ import AppKit |
| /// A fixed paper band: the desk (DocsDeskView) places and centres it, so |
| /// a width change or the inspector never changes the text's geometry. |
| private var viewportWidth: CGFloat { DocsDeskLayout.paperWidth } |
| - private func updatePagination() { |
| - guard !updatingPagination else { return } |
| - #if DOCS_PROBES |
| - let probeStart = DocsProbes.now() |
| - defer { DocsProbes.paginations += 1; DocsProbes.paginationMs += DocsProbes.ms(since: probeStart) } |
| - #endif |
| - updatingPagination = true |
| - defer { updatingPagination = false } |
| - guard let pages = textContainer as? DocsPageTextContainer, |
| - let manager = layoutManager as? DocsLayoutManager, let storage = textStorage else { return } |
| + /// The plan, up to date to the visible bottom (and `character`). |
| + func updatePagination(through character: Int? = nil) { |
| + guard let pages = textContainer as? DocsPageTextContainer else { return } |
| let width = viewportWidth |
| let size = CGSize(width: width, height: 1_000_000) |
| if pages.size != size { pages.size = size } |
| pages.geometry = DocsPageGeometry(viewportWidth: width, paged: false) |
| - let revision = manager.storageRevision |
| - guard measuredRevision != revision || measuredWidth != width || measuredPaged != paged else { return } |
| - let content = paged ? DocumentPageLayout.measurementContent(storage) : nil |
| - if measuredWidth == width, measuredPaged == paged, let content, measuredContent?.isEqual(to: content) == true { |
| - measuredRevision = revision |
| - return |
| - } |
| - var plan = DocumentPageLayout.Result() |
| - if let content { |
| - // Never clear the live container to measure unpaginated content: doing |
| - // so exposes a second set of caret/scroll coordinates during edits. |
| - let measurement = NSTextStorage(attributedString: content) |
| - let measurementManager = DocsLayoutManager() |
| - let measurementContainer = DocsPageTextContainer(size: size) |
| - measurementContainer.lineFragmentPadding = 0 |
| - measurementContainer.isMeasurement = true |
| - measurementContainer.geometry = pages.geometry |
| - measurement.addLayoutManager(measurementManager) |
| - measurementManager.addTextContainer(measurementContainer) |
| - measurementManager.ensureLayout(for: measurementContainer) |
| - plan = DocumentPageLayout.measure(storage: measurement, manager: measurementManager, container: measurementContainer) |
| - } |
| - if pages.blockStarts != plan.starts || separators != plan.separators { needsDisplay = true } |
| - pages.blockStarts = plan.starts |
| - separators = plan.separators |
| - measuredRevision = revision; measuredWidth = width; measuredPaged = paged |
| - measuredContent = content |
| + pagination.setGeometry(pages.geometry) |
| + pagination.update(visibleBottom: visibleRect.maxY, through: character) |
| + } |
| + /// An idle chunk or a jump moved lines or the height outside layout(). |
| + private func paginationChanged() { |
| + if !updatingGeometry { needsLayout = true } |
| + // Not plain setNeedsDisplay: NSTextView's lays the rect out at once. |
| + setNeedsDisplay(visibleRect, avoidAdditionalLayout: true) |
| } |
| override func layout() { |
| - guard !updatingGeometry, let pages = textContainer as? DocsPageTextContainer, |
| - let manager = layoutManager else { return } |
| + guard !updatingGeometry, let pages = textContainer as? DocsPageTextContainer else { return } |
| #if DOCS_PROBES |
| let probeStart = DocsProbes.now() |
| defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) } |
| #endif |
| updatingGeometry = true |
| defer { updatingGeometry = false } |
| - updatePagination() |
| // AppKit must only lay out the caret after final page coordinates exist. |
| + updatePagination() |
| super.layout() |
| - manager.ensureLayout(for: pages) |
| + // The height from the caches (§7 item 7), never from laying out the |
| + // last glyph; the caret's line is laid out by AppKit as it draws it. |
| let width = viewportWidth |
| - let bottom = manager.numberOfGlyphs > 0 |
| - ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin |
| - let height = pages.geometry.documentHeight(usedHeight: bottom) |
| + let height = pages.geometry.documentHeight(usedHeight: pagination.bottom) |
| if abs(frame.width - width) > 0.5 || abs(frame.height - height) > 0.5 { |
| setFrameSize(CGSize(width: width, height: height)) |
| } |
| } |
| + /// Scrolled or jumped past the measured frontier: measure to what is |
| + /// about to be drawn first (§7 item 3, "a jump past the frontier"). |
| + override func viewWillDraw() { |
| + if !updatingGeometry { |
| + updatingGeometry = true |
| + pagination.update(visibleBottom: visibleRect.maxY) |
| + updatingGeometry = false |
| + let height = (textContainer as? DocsPageTextContainer)?.geometry.documentHeight(usedHeight: pagination.bottom) ?? frame.height |
| + if abs(frame.height - height) > 0.5 { setFrameSize(CGSize(width: frame.width, height: height)) } |
| + } |
| + super.viewWillDraw() |
| + } |
| + override func scrollRangeToVisible(_ range: NSRange) { |
| + if !updatingGeometry, range.location != NSNotFound { |
| + updatingGeometry = true |
| + pagination.update(visibleBottom: visibleRect.maxY, through: NSMaxRange(range)) |
| + updatingGeometry = false |
| + let height = (textContainer as? DocsPageTextContainer)?.geometry.documentHeight(usedHeight: pagination.bottom) ?? frame.height |
| + if abs(frame.height - height) > 0.5 { setFrameSize(CGSize(width: frame.width, height: height)) } |
| + } |
| + super.scrollRangeToVisible(range) |
| + } |
| #if DOCS_PROBES |
| override func draw(_ dirtyRect: NSRect) { |
| let probeStart = DocsProbes.now() |
| @@ -131,7 +143,20 @@ import AppKit |
| NSColor.white.setFill() |
| CGRect(x: geometry.paperX, y: 0, width: geometry.paperWidth, height: bounds.height).fill() |
| if paged { |
| - for (index, y) in separators.enumerated() where y + 18 >= dirtyRect.minY && y <= dirtyRect.maxY { |
| + // NSTextView asks for its whole bounds and clips to what it |
| + // draws: only the separators in the clip are drawn (each label |
| + // is a string drawing; a 200-page document has 200 of them). |
| + let clip = NSGraphicsContext.current?.cgContext.boundingBoxOfClipPath ?? dirtyRect |
| + let shown = dirtyRect.intersection(clip) |
| + let separators = pagination.separators |
| + var low = 0, high = separators.count |
| + while low < high { |
| + let middle = (low + high) / 2 |
| + if separators[middle] + 18 < shown.minY { low = middle + 1 } else { high = middle } |
| + } |
| + for index in low..<separators.count { |
| + let y = separators[index] |
| + guard y <= shown.maxY else { break } |
| NSColor.windowBackgroundColor.setFill() |
| CGRect(x: geometry.paperX, y: y, width: geometry.paperWidth, height: 18).fill() |
| let label = String(localized: "docs.editor.page.number", bundle: DocsResources.bundle) |
diff --git a/native/apple/Sources/DocsKit/DocsPagination.swift b/native/apple/Sources/DocsKit/DocsPagination.swift| new file mode 100644 |
| index 0000000..4935eef |
| --- /dev/null |
| +++ b/native/apple/Sources/DocsKit/DocsPagination.swift |
| @@ -0,0 +1,478 @@ |
| +#if os(macOS) |
| +import AppKit |
| + |
| +extension NSAttributedString.Key { |
| + static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore") |
| + static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter") |
| +} |
| + |
| +/// The page breaks, for `DocsPageTextContainer.lineFragmentRect`: the |
| +/// absolute top of a block that starts a page, looked up by the character |
| +/// its first line starts at (nil for any other line). |
| +protocol DocsPageTops: AnyObject { |
| + /// Called by TextKit 1, which lays out on the main thread. |
| + nonisolated func top(at characterIndex: Int) -> CGFloat? |
| +} |
| + |
| +/// The measurement stack's container (§7 "Incremental pagination" 1): a |
| +/// rectangle as wide as the paper's text, so TextKit lays it out |
| +/// non-contiguously and shifts the lines after an edit instead of laying |
| +/// them out again (it does neither for a container that is not a simple |
| +/// rectangle, as the live one is not). It keeps the one rule of the live |
| +/// container that changes where a line wraps: a line starting with inline |
| +/// code is narrower by the code's padding. It never moves a line up or |
| +/// down; the live container's vertical rules (the top margin, the first |
| +/// block's margin, the breaks) are applied to the cached numbers instead. |
| +final class DocsMeasureTextContainer: NSTextContainer { |
| + override var isSimpleRectangularTextContainer: Bool { true } |
| + override func lineFragmentRect( |
| + forProposedRect proposedRect: CGRect, at characterIndex: Int, |
| + writingDirection baseWritingDirection: NSWritingDirection, |
| + remaining remainingRect: UnsafeMutablePointer<CGRect>? |
| + ) -> CGRect { |
| + #if DOCS_PROBES |
| + DocsProbes.measureLineRequests += 1 |
| + #endif |
| + var rect = super.lineFragmentRect(forProposedRect: proposedRect, at: characterIndex, writingDirection: baseWritingDirection, remaining: remainingRect) |
| + if let storage = layoutManager?.textStorage, characterIndex < storage.length { |
| + var range = NSRange() |
| + if let padding = storage.attribute(.docsCodeStart, at: characterIndex, effectiveRange: &range) as? CGFloat, |
| + range.location == characterIndex { |
| + rect.origin.x += padding |
| + rect.size.width = max(0, rect.width - padding) |
| + } |
| + } |
| + return rect |
| + } |
| +} |
| + |
| +/// Incremental pagination on the Mac (spec 2026-11-22 §7, "Incremental |
| +/// pagination"). Mirrors pages.mjs as `DocumentPageLayoutOracle` (today's |
| +/// measurement, now the tests' reference) does: top-level blocks are kept |
| +/// whole, and a separator goes before the next block whose bottom passes |
| +/// the 648pt text budget. Offsets are layout only; nothing is added to the |
| +/// document. |
| +/// |
| +/// - **A measurement stack on the same storage** (item 1): a second |
| +/// `DocsLayoutManager` with a rectangular container as wide as the paper's |
| +/// text (`DocsMeasureTextContainer`), attached to the live `NSTextStorage`. |
| +/// Its geometry is the natural one. It never draws, lays out |
| +/// non-contiguously, and edits reach it by themselves. |
| +/// - **Per-block caches** (item 2), one `Unit` per block run: its |
| +/// `advance` (first line's top to last line's bottom) and `usedBottom`, |
| +/// and its two margins. Natural tops are their prefix sums, so a Return, |
| +/// a deleted block or a paste is a splice. |
| +/// - **The full path** (item 3) measures every block: at open (the visible |
| +/// blocks at once, the rest in idle chunks of 50 a turn), on a width |
| +/// change, and when most blocks changed together. |
| +/// - **Per edit** (item 4) only the edited blocks are measured again; the |
| +/// break algorithm runs from the page holding the first of them until a |
| +/// break lands on the same block with the same `extra` as before. |
| +/// - **The break table** (item 5) is per block, and `top(at:)` gives the |
| +/// live container a break's absolute top, `topU + X`, which it takes as |
| +/// `max(proposed, top)`: idempotent however often TextKit proposes a line. |
| +/// - **Invalidation** (item 6) is from the first block whose top moved, and |
| +/// only the live layout manager's; the frame height (item 7) comes from |
| +/// the caches. |
| +/// |
| +/// A *unit* is a run of `.docsTopBlock` that starts a paragraph, with any |
| +/// run after it that does not (a Backspace at a block's start leaves one |
| +/// paragraph holding two runs until the publication merges them): a break |
| +/// can only go where a paragraph starts (§7 Design 4). A run of one id over |
| +/// several paragraphs (an optimistic Return, a list) is one unit. |
| +@MainActor final class DocsPagination: DocsPageTops { |
| + struct Unit { |
| + var id: String? |
| + var location: Int |
| + var length: Int |
| + var end: Int { location + length } |
| + var range: NSRange { NSRange(location: location, length: length) } |
| + /// Measured since its last edit. |
| + var measured = false |
| + /// From the first line's top to the last line fragment's bottom. |
| + var advance: CGFloat = 0 |
| + /// From the first line's top to the last line's used bottom. |
| + var usedBottom: CGFloat = 0 |
| + var before: CGFloat = 0 |
| + var after: CGFloat = 0 |
| + /// The page break before it: 0 for none. |
| + var extra: CGFloat = 0 |
| + /// The separator's distance above `top` (when `extra > 0`). |
| + var lift: CGFloat = 0 |
| + /// Its natural top, and where the live layout puts its first line |
| + /// (natural plus every `extra` at or before it). nil until known. |
| + var natural: CGFloat? |
| + var top: CGFloat? |
| + } |
| + |
| + /// The units, tiling the storage in order. |
| + private(set) var units: [Unit] = [] |
| + /// Every unit below it has been measured (until an edit marks one). |
| + private(set) var frontier = 0 |
| + private(set) var separators: [CGFloat] = [] |
| + /// The live layout's last line bottom, from the caches. |
| + private(set) var bottom: CGFloat = DocsPageGeometry.verticalMargin |
| + var paged = false { didSet { if oldValue != paged { markBreaks(from: 0) } } } |
| + |
| + let measurement = DocsLayoutManager() |
| + let container: DocsMeasureTextContainer |
| + private weak var storage: NSTextStorage? |
| + private weak var live: NSLayoutManager? |
| + /// The first and last unit whose breaks must be worked out again. |
| + private var breaksFrom: Int? |
| + private var breaksThrough = -1 |
| + private var full = true |
| + private var chunkScheduled = false |
| + /// Runs after a pass that moved lines or the height (the text view |
| + /// lays itself out again). |
| + var changed: (() -> Void)? |
| + /// Whether the measurement may continue in idle chunks (a window shows |
| + /// the text) or must finish at once (no window: tests, snapshots). |
| + var canDefer: () -> Bool = { false } |
| + |
| + static let chunk = 50 |
| + |
| + private(set) var geometry: DocsPageGeometry |
| + |
| + init(storage: NSTextStorage, live: NSLayoutManager, geometry: DocsPageGeometry) { |
| + self.storage = storage |
| + self.live = live |
| + self.geometry = geometry |
| + container = DocsMeasureTextContainer(size: CGSize(width: geometry.textWidth, height: 100_000_000)) |
| + container.lineFragmentPadding = 0 |
| + measurement.allowsNonContiguousLayout = true |
| + measurement.backgroundLayoutEnabled = false |
| + measurement.addTextContainer(container) |
| + storage.addLayoutManager(measurement) |
| + } |
| + |
| + /// The break table by block id: each break's `extra` (§7 item 5). |
| + var breaks: [String: CGFloat] { |
| + var breaks: [String: CGFloat] = [:] |
| + for unit in units where unit.extra > 0 { if let id = unit.id { breaks[id] = unit.extra } } |
| + return breaks |
| + } |
| + /// The breaks as the oracle states them: the live top of each break's |
| + /// block, by the character it starts at. |
| + var breakStarts: [Int: CGFloat] { |
| + var starts: [Int: CGFloat] = [:] |
| + for unit in units where unit.extra > 0 { if let top = unit.top { starts[unit.location] = top } } |
| + return starts |
| + } |
| + |
| + /// Whether every unit has been measured (the probe's flag for §7 item 10). |
| + var isComplete: Bool { frontier >= units.count && !units.contains { !$0.measured } } |
| + |
| + /// The paper's text width changed: everything is measured again. |
| + func setGeometry(_ geometry: DocsPageGeometry) { |
| + guard geometry != self.geometry else { return } |
| + self.geometry = geometry |
| + if container.size.width != geometry.textWidth { container.size = CGSize(width: geometry.textWidth, height: 100_000_000) } |
| + full = true |
| + } |
| + |
| + // MARK: - Edits |
| + |
| + /// The live layout manager saw an edit: `edited` is in the new text, |
| + /// `delta` the change in length. The units it touched (and their |
| + /// neighbours) are read again from the storage; the rest shift. Nothing |
| + /// is measured here: the measurement stack hears of the edit after this. |
| + func storageEdited(edited: NSRange, delta: Int) { |
| + // The full path reads every unit again anyway. |
| + guard !full else { return } |
| + guard let storage, !units.isEmpty, edited.location != NSNotFound else { full = true; return } |
| + let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta |
| + var first = firstUnit(endingAtOrAfter: oldStart) |
| + if first > 0 { first -= 1 } |
| + var last = first |
| + while last + 1 < units.count, units[last + 1].location <= oldEnd { last += 1 } |
| + if last + 1 < units.count { last += 1 } |
| + let start = units[first].location |
| + let end = units[last].end + delta |
| + guard start >= 0, end <= storage.length, start <= end else { full = true; return } |
| + var fresh = Self.units(in: storage, range: NSRange(location: start, length: end - start)) |
| + // Keep what is known of the units the edit left as they were (the |
| + // neighbours read again with it): same id, place and length, and |
| + // none of their characters in the edit. |
| + let old = units[first...last] |
| + var cursor = old.startIndex |
| + for index in fresh.indices { |
| + let unit = fresh[index] |
| + while cursor <= last { |
| + let candidate = old[cursor] |
| + let location = candidate.location >= oldEnd ? candidate.location + delta : candidate.location |
| + if location < unit.location { cursor += 1; continue } |
| + if location == unit.location, candidate.id == unit.id { |
| + // The same block where it was: its tops and break stay |
| + // until it is measured again (now, if the edit touched |
| + // it or its length changed). |
| + var kept = candidate |
| + kept.location = location |
| + kept.length = unit.length |
| + let untouched = candidate.end <= oldStart || candidate.location >= oldEnd |
| + if !untouched || candidate.length != unit.length || NSIntersectionRange(candidate.range, edited).length > 0 { kept.measured = false } |
| + fresh[index] = kept |
| + cursor += 1 |
| + } |
| + break |
| + } |
| + } |
| + for index in (last + 1)..<units.count { units[index].location += delta } |
| + units.replaceSubrange(first...last, with: fresh) |
| + let shift = fresh.count - (last - first + 1) |
| + if frontier > last { frontier += shift } else if frontier > first { frontier = first } |
| + if breaksThrough > last { breaksThrough += shift } |
| + markBreaks(from: first, through: first + max(0, fresh.count - 1) + (first + fresh.count < units.count ? 1 : 0)) |
| + } |
| + |
| + private func markBreaks(from first: Int, through last: Int? = nil) { |
| + breaksFrom = min(breaksFrom ?? first, first) |
| + breaksThrough = max(breaksThrough, last ?? units.count - 1) |
| + } |
| + |
| + /// The units in `range` of `storage`, which starts at a unit's start |
| + /// (or 0) and ends at one's end (or the storage's). |
| + static func units(in storage: NSTextStorage, range: NSRange) -> [Unit] { |
| + var units: [Unit] = [] |
| + guard range.length > 0 else { return units } |
| + let characters = storage.mutableString |
| + storage.enumerateAttribute(.docsTopBlock, in: range) { value, found, _ in |
| + let id = value as? String |
| + let startsParagraph = found.location == 0 || Self.isParagraphEnd(characters.character(at: found.location - 1)) |
| + if let last = units.last, !startsParagraph || (last.id == id && last.end == found.location) { |
| + units[units.count - 1].length += found.length |
| + } else { |
| + units.append(Unit(id: id, location: found.location, length: found.length)) |
| + } |
| + } |
| + return units |
| + } |
| + static func isParagraphEnd(_ character: unichar) -> Bool { character == 10 || character == 13 || character == 0x2029 } |
| + |
| + private func firstUnit(endingAtOrAfter location: Int) -> Int { |
| + var low = 0, high = units.count - 1 |
| + while low < high { |
| + let middle = (low + high) / 2 |
| + if units[middle].end < location { low = middle + 1 } else { high = middle } |
| + } |
| + return low |
| + } |
| + |
| + // MARK: - The live container's lookup |
| + |
| + nonisolated func top(at characterIndex: Int) -> CGFloat? { |
| + MainActor.assumeIsolated { liveTop(at: characterIndex) } |
| + } |
| + private func liveTop(at characterIndex: Int) -> CGFloat? { |
| + var low = 0, high = units.count - 1 |
| + while low <= high { |
| + let middle = (low + high) / 2 |
| + let location = units[middle].location |
| + if location == characterIndex { return units[middle].extra > 0 ? units[middle].top : nil } |
| + if location < characterIndex { low = middle + 1 } else { high = middle - 1 } |
| + } |
| + return nil |
| + } |
| + |
| + // MARK: - Passes |
| + |
| + /// Brings the caches and the break table up to date: re-measures the |
| + /// edited units, measures on to `visibleBottom` (live coordinates) or |
| + /// `character`, works out the breaks that may have moved, and |
| + /// invalidates the live layout from the first unit whose top moved. |
| + /// Cheap when nothing changed. |
| + func update(visibleBottom: CGFloat, through character: Int? = nil, chunk: Int = 0) { |
| + guard let storage else { return } |
| + if full { |
| + full = false |
| + units = Self.units(in: storage, range: NSRange(location: 0, length: storage.length)) |
| + frontier = 0 |
| + markBreaks(from: 0) |
| + } |
| + // Edited units below the frontier: measured again now, unless most |
| + // of the document changed (a font every block uses arrived), which |
| + // takes the full path's visible-first order instead. |
| + var stale = 0 |
| + var firstStale: Int? |
| + for index in 0..<min(frontier, units.count) where !units[index].measured { |
| + stale += 1 |
| + if firstStale == nil { firstStale = index } |
| + } |
| + if let firstStale, stale > Self.chunk, canDefer() { |
| + frontier = firstStale |
| + for index in firstStale..<units.count { units[index].measured = false } |
| + } |
| + let deferring = canDefer() |
| + let wantsMore = frontier < units.count && (!deferring || chunk > 0 || frontierTop() <= visibleBottom |
| + || units[frontier].location <= (character ?? -1)) |
| + guard breaksFrom != nil || stale > 0 || wantsMore else { return } |
| + #if DOCS_PROBES |
| + let probeStart = DocsProbes.now() |
| + defer { DocsProbes.paginations += 1; DocsProbes.paginationMs += DocsProbes.ms(since: probeStart) } |
| + #endif |
| + for index in 0..<min(frontier, units.count) where !units[index].measured { measure(index) } |
| + // The frontier: to what is shown (or asked for), the rest later. |
| + var running = frontierTop() |
| + let targetCharacter = character ?? -1 |
| + let firstNew = frontier |
| + while frontier < units.count { |
| + if deferring && frontier - firstNew >= chunk && running > visibleBottom && units[frontier].location > targetCharacter { break } |
| + measure(frontier) |
| + if frontier == 0 { running = units[0].natural ?? 0 } |
| + running += units[frontier].advance |
| + frontier += 1 |
| + } |
| + if frontier > firstNew { markBreaks(from: firstNew, through: frontier - 1) } |
| + finish() |
| + if frontier < units.count { scheduleChunk() } |
| + } |
| + |
| + /// Where the frontier's unit starts in the live layout, as far as the |
| + /// measured units say (breaks after the last pass not counted: a low |
| + /// estimate, so the frontier only ever goes further than needed). |
| + private func frontierTop() -> CGFloat { |
| + guard frontier > 0 else { return 0 } |
| + let previous = units[frontier - 1] |
| + return (previous.top ?? previous.natural ?? 0) + previous.advance |
| + } |
| + |
| + private func measure(_ index: Int) { |
| + guard let storage else { return } |
| + let unit = units[index] |
| + let glyphs = measurement.glyphRange(forCharacterRange: unit.range, actualCharacterRange: nil) |
| + var top = CGFloat.greatestFiniteMagnitude, rectBottom = -CGFloat.greatestFiniteMagnitude, usedBottom = -CGFloat.greatestFiniteMagnitude |
| + measurement.enumerateLineFragments(forGlyphRange: glyphs) { rect, used, _, _, _ in |
| + top = min(top, rect.minY); rectBottom = max(rectBottom, rect.maxY); usedBottom = max(usedBottom, used.maxY) |
| + } |
| + if top == .greatestFiniteMagnitude { |
| + units[index].advance = 0; units[index].usedBottom = 0 |
| + } else { |
| + units[index].advance = rectBottom - top |
| + units[index].usedBottom = usedBottom - top |
| + } |
| + if index == 0 { |
| + // The live container's two vertical rules for the first line: |
| + // the page's top margin, and the first block's own margin. |
| + let margin = storage.length > 0 ? storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat ?? 0 : 0 |
| + units[0].natural = DocsPageGeometry.verticalMargin + max(0, margin) |
| + } |
| + units[index].before = storage.attribute(.docsMarginBefore, at: unit.location, effectiveRange: nil) as? CGFloat ?? 0 |
| + units[index].after = storage.attribute(.docsMarginAfter, at: max(unit.location, unit.end - 1), effectiveRange: nil) as? CGFloat ?? 0 |
| + units[index].measured = true |
| + } |
| + |
| + /// The break algorithm from the page holding the first unit to work |
| + /// out, the prefix sums, the separators, the height, and the live |
| + /// layout's invalidation. |
| + private func finish() { |
| + let measured = min(frontier, units.count) |
| + if let from = breaksFrom, measured > 0 { |
| + breakPass(from: min(from, measured - 1), through: breaksThrough, limit: measured) |
| + } |
| + breaksFrom = nil; breaksThrough = -1 |
| + // Prefix sums: natural tops, the extras, the live tops. |
| + var natural = units.first?.natural ?? DocsPageGeometry.verticalMargin |
| + var added: CGFloat = 0 |
| + var firstMoved: Int? |
| + var separators: [CGFloat] = [] |
| + var measuredAdvance: CGFloat = 0, measuredLength = 0 |
| + for index in units.indices { |
| + let known = index < measured |
| + if known { |
| + units[index].natural = natural |
| + added += units[index].extra |
| + let top = natural + added |
| + if units[index].extra > 0 { separators.append(top - units[index].lift) } |
| + if firstMoved == nil, units[index].top.map({ abs($0 - top) > 0.001 }) ?? true { firstMoved = index } |
| + units[index].top = top |
| + measuredAdvance += units[index].advance; measuredLength += units[index].length |
| + } else if units[index].top != nil { |
| + // Beyond the frontier: no top until measured, so TextKit |
| + // flows these lines on from the last measured one. |
| + if firstMoved == nil { firstMoved = index } |
| + units[index].top = nil; units[index].natural = nil |
| + } |
| + if known { natural += units[index].advance } |
| + } |
| + var bottom = units.isEmpty ? DocsPageGeometry.verticalMargin : natural + added |
| + if measured < units.count, measuredLength > 0 { |
| + // Below the frontier, an estimate from the average measured advance. |
| + let remaining = units[measured...].reduce(0) { $0 + $1.length } |
| + bottom += measuredAdvance / CGFloat(measuredLength) * CGFloat(remaining) |
| + } |
| + let moved = separators != self.separators || abs(bottom - self.bottom) > 0.001 || firstMoved != nil |
| + self.separators = separators |
| + self.bottom = bottom |
| + if let firstMoved, let live, let storage, firstMoved < units.count { |
| + let location = units[firstMoved].location |
| + live.invalidateLayout(forCharacterRange: NSRange(location: location, length: storage.length - location), actualCharacterRange: nil) |
| + } |
| + if moved { changed?() } |
| + } |
| + |
| + /// Today's algorithm (DocumentPageLayoutOracle.measure) over the cached |
| + /// natural geometry, from the last break before `from` (whose page |
| + /// holds it), until a break past `through` lands where it was. |
| + private func breakPass(from: Int, through: Int, limit: Int) { |
| + guard paged else { |
| + for index in units.indices where units[index].extra != 0 { units[index].extra = 0; units[index].lift = 0 } |
| + return |
| + } |
| + // The page holding `from` starts at the last break before it. |
| + var start = from - 1 |
| + while start >= 0, units[start].extra == 0 { start -= 1 } |
| + var pageTop: CGFloat? |
| + var previousMargin: CGFloat = 0 |
| + var natural: CGFloat |
| + var index: Int |
| + if start >= 0, let top = units[start].natural { |
| + pageTop = top |
| + previousMargin = units[start].after |
| + natural = top + units[start].advance |
| + index = start + 1 |
| + } else { |
| + natural = units.first?.natural ?? DocsPageGeometry.verticalMargin |
| + index = 0 |
| + } |
| + while index < limit { |
| + let unit = units[index] |
| + var extra: CGFloat = 0, lift: CGFloat = 0 |
| + if unit.id != nil, unit.usedBottom > 0 { |
| + let top = natural, bottom = top + unit.usedBottom |
| + if let current = pageTop { |
| + if bottom - current > 648 { |
| + let collapsed = max(previousMargin, unit.before) |
| + extra = max(previousMargin, 12) + 18 + max(unit.before, 12) - collapsed |
| + lift = extra + collapsed - max(previousMargin, 12) |
| + pageTop = top |
| + } |
| + } else { pageTop = top } |
| + previousMargin = unit.after |
| + } |
| + let converged = index > through && extra > 0 && unit.extra == extra |
| + units[index].extra = extra |
| + units[index].lift = lift |
| + if converged { return } |
| + natural += unit.advance |
| + index += 1 |
| + } |
| + // Past the frontier nothing is known: no breaks there yet. |
| + for rest in limit..<units.count where units[rest].extra != 0 { units[rest].extra = 0; units[rest].lift = 0 } |
| + } |
| + |
| + private func scheduleChunk() { |
| + guard !chunkScheduled, canDefer() else { return } |
| + chunkScheduled = true |
| + let timer = Timer(timeInterval: 0, repeats: false) { [weak self] _ in |
| + MainActor.assumeIsolated { |
| + guard let self else { return } |
| + self.chunkScheduled = false |
| + guard self.frontier < self.units.count else { return } |
| + // One chunk past the frontier, then the next turn. |
| + self.update(visibleBottom: -.greatestFiniteMagnitude, chunk: Self.chunk) |
| + } |
| + } |
| + RunLoop.main.add(timer, forMode: .common) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/DocsKit/DocsPaging.swift b/native/apple/Sources/DocsKit/DocsPaging.swift| index 01d0250..a20c929 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPaging.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPaging.swift |
| @@ -57,9 +57,13 @@ struct DocsPageGeometry: Equatable, Sendable { |
| final class DocsPageTextContainer: NSTextContainer { |
| #if os(macOS) |
| - var blockStarts: [Int: CGFloat] = [:] { |
| - didSet { if oldValue != blockStarts { layoutManager?.textContainerChangedGeometry(self) } } |
| - } |
| + /// The Mac's page breaks (spec §7, "Incremental pagination" 5): the |
| + /// absolute top of a block that starts a page, looked up by the |
| + /// character its first line starts at, and taken as `max(proposed, |
| + /// top)`: TextKit proposing one line twice gets the same answer. Changes |
| + /// never call `textContainerChangedGeometry`: `DocsPagination` |
| + /// invalidates the live layout from the first block that moved. |
| + weak var tops: (any DocsPageTops)? |
| #endif |
| var geometry = DocsPageGeometry(viewportWidth: 612, paged: false) { |
| didSet { |
| @@ -80,7 +84,7 @@ final class DocsPageTextContainer: NSTextContainer { |
| remainingRect?.pointee = .zero |
| var rect = geometry.lineRect(proposedRect) |
| #if os(macOS) |
| - if let top = blockStarts[characterIndex] { rect.origin.y = max(rect.minY, top) } |
| + if let top = tops?.top(at: characterIndex) { rect.origin.y = max(rect.minY, top) } |
| #endif |
| if let storage = layoutManager?.textStorage, characterIndex < storage.length { |
| if characterIndex == 0, let margin = storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat { |
diff --git a/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift b/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift| index 7b14634..7307886 100644 |
| --- a/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift |
| @@ -103,8 +103,13 @@ import XCTest |
| container.lineFragmentPadding = 0 |
| storage.addLayoutManager(manager); manager.addTextContainer(container) |
| manager.ensureLayout(for: container) |
| - let pages = paged ? DocumentPageLayout.measure(storage: storage, manager: manager, container: container) : DocumentPageLayout.Result() |
| - container.blockStarts = pages.starts |
| + let pages = paged ? DocumentPageLayoutOracle.measure(storage: storage, manager: manager, container: container) : DocumentPageLayoutOracle.Result() |
| + let tops = OracleTops(pages.starts) |
| + container.tops = tops |
| + defer { withExtendedLifetime(tops) {} } |
| + // A lookup change never invalidates by itself (production's |
| + // DocsPagination invalidates from the first moved block). |
| + manager.textContainerChangedGeometry(container) |
| manager.ensureLayout(for: container) |
| var lines: [Line] = [] |
| var contentBottom: CGFloat = 72 |
diff --git a/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift b/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift| index 6a64cff..901dc37 100644 |
| --- a/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift |
| @@ -13,25 +13,24 @@ import XCTest |
| storage.setAttributedString(NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false))) |
| view.paged = true |
| view.layout() |
| - let container = try XCTUnwrap(view.textContainer as? DocsPageTextContainer) |
| - XCTAssertFalse(container.blockStarts.isEmpty) |
| - let initial = container.blockStarts |
| + XCTAssertFalse(view.pagination.breakStarts.isEmpty) |
| + let initial = view.pagination.breakStarts |
| let insertion = String(repeating: "Inserted text before the boundary. ", count: 20) |
| storage.replaceCharacters(in: NSRange(location: 0, length: 0), with: insertion) |
| - assertBlockStarts(container, storage) |
| + assertBlockStarts(view, storage) |
| view.layout() |
| - XCTAssertNotEqual(initial, container.blockStarts) |
| - assertBlockStarts(container, storage) |
| + XCTAssertNotEqual(initial, view.pagination.breakStarts) |
| + assertBlockStarts(view, storage) |
| view.setSelectedRange(NSRange(location: 0, length: 0)) |
| view.setMarkedText("日本語", selectedRange: NSRange(location: 3, length: 0), replacementRange: NSRange(location: 0, length: 0)) |
| - assertBlockStarts(container, storage) |
| + assertBlockStarts(view, storage) |
| view.layout() |
| - assertBlockStarts(container, storage) |
| + assertBlockStarts(view, storage) |
| view.unmarkText() |
| storage.replaceCharacters(in: NSRange(location: 0, length: 3 + insertion.utf16.count), with: "") |
| - assertBlockStarts(container, storage) |
| + assertBlockStarts(view, storage) |
| view.layout() |
| - XCTAssertEqual(container.blockStarts, initial) |
| + XCTAssertEqual(view.pagination.breakStarts, initial) |
| XCTAssertEqual(storage.string, nodes.map(\.plainText).joined(separator: "\n") + "\n") |
| } |
| @@ -46,7 +45,7 @@ import XCTest |
| view.layout() |
| let manager = try XCTUnwrap(view.layoutManager) |
| let container = try XCTUnwrap(view.textContainer as? DocsPageTextContainer) |
| - XCTAssertGreaterThanOrEqual(container.blockStarts.count, 2) |
| + XCTAssertGreaterThanOrEqual(view.pagination.breakStarts.count, 2) |
| let selected = storage.length - 3 |
| view.setSelectedRange(NSRange(location: selected, length: 0)) |
| func caretY() -> CGFloat { |
| @@ -102,8 +101,8 @@ import XCTest |
| } |
| } |
| - private func assertBlockStarts(_ container: DocsPageTextContainer, _ storage: NSTextStorage) { |
| - for location in container.blockStarts.keys { |
| + private func assertBlockStarts(_ view: DocsPagedTextView, _ storage: NSTextStorage) { |
| + for location in view.pagination.breakStarts.keys { |
| var range = NSRange() |
| XCTAssertNotNil(storage.attribute(.docsTopBlock, at: location, effectiveRange: &range)) |
| XCTAssertEqual(range.location, location, "A separator must never move into a paragraph") |
diff --git a/native/apple/Sources/DocsKit/DocumentPageLayout.swift b/native/apple/Tests/DocsKitTests/DocumentPageLayoutOracle.swift| similarity index 77% |
| rename from native/apple/Sources/DocsKit/DocumentPageLayout.swift |
| rename to native/apple/Tests/DocsKitTests/DocumentPageLayoutOracle.swift |
| index fd73d45..04c08f5 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentPageLayout.swift |
| +++ b/native/apple/Tests/DocsKitTests/DocumentPageLayoutOracle.swift |
| @@ -1,15 +1,18 @@ |
| #if os(macOS) |
| import AppKit |
| +@testable import DocsKit |
| -extension NSAttributedString.Key { |
| - static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore") |
| - static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter") |
| -} |
| - |
| +/// The tests' reference for the Mac's page breaks (spec 2026-11-22 §7, |
| +/// "Incremental pagination" 9): the measurement production ran on every |
| +/// edit before S1b, moved here verbatim. Production's `DocsPagination` |
| +/// must put breaks, line origins and the frame height where a fresh run of |
| +/// this puts them. It differs from production's full path by construction: |
| +/// a copy of the storage and a separate layout stack, laid out whole. |
| +/// |
| /// Mirrors pages.mjs: keep top-level blocks intact and put a visual separator |
| /// before the next block exceeding the 648pt text budget. All offsets are layout |
| /// only; an oversized paragraph/list is never split or rewritten to make a page. |
| -@MainActor enum DocumentPageLayout { |
| +@MainActor enum DocumentPageLayoutOracle { |
| struct Result { |
| var starts: [Int: CGFloat] = [:] |
| var separators: [CGFloat] = [] |
| @@ -61,3 +64,14 @@ extension NSAttributedString.Key { |
| } |
| } |
| #endif |
| + |
| +#if os(macOS) |
| +/// The oracle's breaks as a container's lookup, as production's |
| +/// `blockStarts` table read them before S1b: a top for the character a |
| +/// break's block starts at. |
| +final class OracleTops: DocsPageTops, Sendable { |
| + let starts: [Int: CGFloat] |
| + init(_ starts: [Int: CGFloat]) { self.starts = starts } |
| + nonisolated func top(at characterIndex: Int) -> CGFloat? { starts[characterIndex] } |
| +} |
| +#endif |