oficina / docs Public

Docs native S1b: pagination equivalence, large-document and line-request tests

- PaginationEquivalenceTests (spec §11): edits typed through the real
  text view and checked before their publication and after: typing before
  a break, an optimistic Return, a Backspace at a block's start, a block
  deleted, three blocks pasted, three blocks in one flush, typing in a
  list taller than a page, typing that moves a break and moves it back.
  Breaks, every line origin (0.5pt) and the frame height equal a fresh
  DocumentPageLayoutOracle run; without a window and in one at 100% and
  150%. The fixture puts a large heading and an image first on a page,
  and starts lines with inline code. Seen to fail with breaks kept by
  character index and with the break offset applied relatively.
- A break never goes inside a paragraph a Backspace merged (the oracle,
  measuring runs, puts one there; §7 Design 4 says it may not).
- PaginationLargeDocumentTests (§7 item 10): 200 pages in a window; after
  the idle chunks the live layout holds nothing at the end; ⌘↓ and typing
  there, the caret is against its glyph, no line crosses a separator and
  the pages are the oracle's; the same when the jump comes before the
  chunks finish; and after Pages off and on.
- The line-fragment gate, per key at 20 and 200 pages, paged and not:
  TextKit's requests to the live container, through the key's display,
  stay within the edited block's lines, the visible lines and 8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 51ed8b97eab70dba929c7dc45a020b68a6b1490c parent 6582618
3 files changed, +515 −0
  • native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift +320 −0
  • native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift +173 −0
  • native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift +22 −0
diff --git a/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift b/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift
new file mode 100644
index 0000000..ece0cdc
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift
@@ -0,0 +1,320 @@
+#if os(macOS)
+import AppKit
+import XCTest
+@testable import DocsKit
+
+/// Pagination equivalence (spec 2026-11-22 §11; §7 "Incremental
+/// pagination" 9): edits typed through the real text view, each checked
+/// before its publication arrives and after. Production's break table,
+/// every live line-fragment origin (within 0.5pt) and the frame height must
+/// equal a fresh run of `DocumentPageLayoutOracle`, today's measurement
+/// before S1b, over the same storage.
+///
+/// The fixture puts a large heading and an image as the first line after a
+/// break, and holds a list taller than a page.
+@MainActor final class PaginationEquivalenceTests: XCTestCase {
+ static func ledger(_ line: Int) -> String { "Ledger, line \(line): water drawn and paid for, and the books kept." }
+ static let picture = "data:image/png;base64,picture"
+
+ /// 38 one-line paragraphs fill the first page, so the large heading is
+ /// the first line of page 2; 30 more and an image make the image the
+ /// first line of page 3; then a list of 70 items (taller than a page)
+ /// and more paragraphs.
+ static func fixture() -> [CRDTNode] {
+ var nodes = (1...38).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) }
+ nodes.append(SurfaceFixture.heading("h1", "Expansion through the early twentieth century", level: 1))
+ nodes += (39...68).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) }
+ nodes.append(CRDTNode(id: "img", type: "paragraph", children: [CRDTNode(id: "imgi", type: "image", attrs: ["src": picture, "alt": "The second reservoir"])]))
+ nodes += (69...84).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) }
+ // Inline code starting lines (its padding narrows the line) and a
+ // code block.
+ nodes.append(CRDTNode(id: "code1", type: "paragraph", children: [CRDTNode(id: "code1t", type: "text", runs: [
+ CRDTRun(insert: "reservoir.capacity", marks: ["code": .object([:])]),
+ CRDTRun(insert: " is what the engineer wrote, and the council read it twice before the vote that followed it."),
+ ])]))
+ nodes.append(CRDTNode(id: "code2", type: "code_block", children: [CRDTNode(id: "code2t", type: "text", runs: [
+ CRDTRun(insert: "reservoir.capacity = 1_200_000 # gallons, measured at the spillway in the spring of 1887\nfilter = .slowSand"),
+ ])]))
+ nodes.append(SurfaceFixture.list("list", "bullet_list", (1...70).map { "Item \($0) of a list longer than a page" }))
+ nodes += (85...130).map { SurfaceFixture.paragraph("a\($0)", ledger($0) + ($0 % 3 == 0 ? " " + String(repeating: "More words that wrap the line. ", count: 3) : "")) }
+ return nodes
+ }
+ static var images: [String: DocsPlatformImage] { [picture: NSImage(size: NSSize(width: 320, height: 180))] }
+
+ struct Plan {
+ var starts: [Int: CGFloat]
+ var separators: [CGFloat]
+ var lines: [Int: CGPoint]
+ var height: CGFloat
+ }
+
+ /// Today's measurement (`DocumentPageLayoutOracle`, a copy and its own
+ /// stack, laid out whole), and the live layout it gave: a copy of the
+ /// storage laid out with its breaks, as the container read them.
+ static func oracle(_ storage: NSAttributedString) -> Plan {
+ let size = CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000)
+ let geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false)
+ func stack(_ text: NSAttributedString) -> (NSTextStorage, DocsLayoutManager, DocsPageTextContainer) {
+ let storage = NSTextStorage(attributedString: text)
+ let manager = DocsLayoutManager()
+ let container = DocsPageTextContainer(size: size)
+ container.lineFragmentPadding = 0
+ container.geometry = geometry
+ container.isMeasurement = true
+ storage.addLayoutManager(manager)
+ manager.addTextContainer(container)
+ return (storage, manager, container)
+ }
+ let (measured, measurementManager, measurementContainer) = stack(DocumentPageLayoutOracle.measurementContent(storage))
+ measurementManager.ensureLayout(for: measurementContainer)
+ let result = DocumentPageLayoutOracle.measure(storage: measured, manager: measurementManager, container: measurementContainer)
+ let (copy, manager, container) = stack(storage)
+ let tops = OracleTops(result.starts)
+ container.tops = tops
+ manager.ensureLayout(for: container)
+ let lines = Self.lines(manager)
+ let bottom = manager.numberOfGlyphs > 0 ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin
+ withExtendedLifetime((tops, copy, measured)) {}
+ return Plan(starts: result.starts, separators: result.separators, lines: lines, height: geometry.documentHeight(usedHeight: bottom))
+ }
+
+ static func lines(_ manager: NSLayoutManager) -> [Int: CGPoint] {
+ var lines: [Int: CGPoint] = [:]
+ manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { rect, _, _, glyphs, _ in
+ lines[manager.characterIndexForGlyph(at: glyphs.location)] = rect.origin
+ }
+ return lines
+ }
+
+ /// What the text view does: its own pass, then (as anything drawing or
+ /// asking would) the live layout, here all of it.
+ static func production(_ view: DocsPagedTextView) -> Plan {
+ view.needsLayout = true
+ view.layoutSubtreeIfNeeded()
+ view.pagination.update(visibleBottom: .greatestFiniteMagnitude)
+ view.layout()
+ let manager = view.layoutManager!
+ manager.ensureLayout(for: view.textContainer!)
+ return Plan(starts: view.pagination.breakStarts, separators: view.pagination.separators, lines: lines(manager), height: view.frame.height)
+ }
+
+ func assertEquivalent(_ view: DocsPagedTextView, _ message: String, file: StaticString = #filePath, line: UInt = #line) {
+ let storage = view.textStorage!
+ // Lines TextKit lays out lazily, before anything forces the whole
+ // container: the caret's, as typing lays it out.
+ let caret = view.selectedRange().location
+ view.layout()
+ if storage.length > 0 {
+ let manager = view.layoutManager!
+ let glyph = manager.glyphIndexForCharacter(at: min(caret, storage.length - 1))
+ let lazy = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
+ let expected = Self.oracle(storage)
+ var range = NSRange()
+ _ = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &range)
+ let start = manager.characterIndexForGlyph(at: range.location)
+ if let oracleLine = expected.lines[start] {
+ XCTAssertEqual(lazy.minY, oracleLine.y, accuracy: 0.5, "the caret's line, laid out on its own: \(message)", file: file, line: line)
+ }
+ }
+ let expected = Self.oracle(storage)
+ let actual = Self.production(view)
+ XCTAssertEqual(Set(actual.starts.keys), Set(expected.starts.keys), "break blocks: \(message)", file: file, line: line)
+ for (location, top) in expected.starts {
+ if let mine = actual.starts[location] { XCTAssertEqual(mine, top, accuracy: 0.5, "break top at \(location): \(message)", file: file, line: line) }
+ }
+ XCTAssertEqual(actual.separators.count, expected.separators.count, "separators: \(message)", file: file, line: line)
+ for (mine, theirs) in zip(actual.separators, expected.separators) {
+ XCTAssertEqual(mine, theirs, accuracy: 0.5, "separator: \(message)", file: file, line: line)
+ }
+ XCTAssertEqual(Set(actual.lines.keys), Set(expected.lines.keys), "line starts: \(message)", file: file, line: line)
+ var worst: (Int, CGFloat) = (0, 0)
+ for (start, origin) in expected.lines {
+ guard let mine = actual.lines[start] else { continue }
+ let difference = max(abs(mine.y - origin.y), abs(mine.x - origin.x))
+ if difference > worst.1 { worst = (start, difference) }
+ }
+ XCTAssertLessThanOrEqual(worst.1, 0.5, "line origin at character \(worst.0): \(message)", file: file, line: line)
+ XCTAssertEqual(actual.height, expected.height, accuracy: 0.5, "frame height: \(message)", file: file, line: line)
+ }
+
+ // MARK: - The edits
+
+ @MainActor final class Document {
+ let state: SurfaceState
+ var nodes: [CRDTNode]
+ var fresh = 0
+ var view: DocsTextView { state.text }
+ init(_ nodes: [CRDTNode], window: Bool, magnification: CGFloat) {
+ state = SurfaceState(width: DocsDeskLayout.paperWidth)
+ self.nodes = nodes
+ state.text.paged = true
+ state.surface.imagesChanged(PaginationEquivalenceTests.images)
+ if window {
+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800))
+ scroll.hasVerticalScroller = true
+ scroll.allowsMagnification = true
+ scroll.documentView = DocsDeskView(page: state.text)
+ scroll.magnification = magnification
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = scroll
+ self.window = window
+ }
+ state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
+ }
+ var window: NSWindow?
+ func close() { window?.contentView = nil; window?.close() }
+
+ func location(of id: String) -> NSRange {
+ var found = NSRange(location: NSNotFound, length: 0)
+ let storage = view.textStorage!
+ storage.enumerateAttribute(.docsTopBlock, in: NSRange(location: 0, length: storage.length)) { value, range, stop in
+ if value as? String == id { found = found.location == NSNotFound ? range : NSUnionRange(found, range) }
+ }
+ return found
+ }
+ func index(of id: String) -> Int { nodes.firstIndex { $0.id == id }! }
+ func text(of id: String) -> String { nodes[index(of: id)].plainText }
+ func setText(_ id: String, _ text: String) {
+ let node = nodes[index(of: id)]
+ nodes[index(of: id)] = node.type == "heading"
+ ? SurfaceFixture.heading(id, text, level: Int(node.attrs?["level"] ?? "1") ?? 1)
+ : SurfaceFixture.paragraph(id, text)
+ }
+ /// The caret at `offset` into block `id`'s text, then typed.
+ func type(_ characters: String, in id: String, at offset: Int? = nil) {
+ let block = location(of: id)
+ let at = block.location + (offset ?? (block.length - 1))
+ view.setSelectedRange(NSRange(location: at, length: 0))
+ for character in characters {
+ if character == "\n" { view.insertNewline(nil) } else { view.insertText(String(character), replacementRange: view.selectedRange()) }
+ }
+ }
+ func publish(_ dirty: Set<String>?) {
+ state.pending = false
+ state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: dirty)
+ }
+ }
+
+ func testProductionPaginationEqualsTheOracle() throws {
+ DocsFonts.register()
+ for (window, magnification) in [(false, 4.0 / 3.0), (true, 4.0 / 3.0), (true, 2.0)] {
+ let label = window ? "zoom \(Int(magnification * 75))%" : "no window"
+ let document = Document(Self.fixture(), window: window, magnification: magnification)
+ defer { document.close() }
+ let view = document.view
+ assertEquivalent(view, "\(label): open")
+ let starts = Self.production(view).starts
+ // The fixture's point: a heading and an image start pages.
+ XCTAssertNotNil(starts[document.location(of: "h1").location], "\(label): the large heading starts page 2")
+ XCTAssertNotNil(starts[document.location(of: "img").location], "\(label): the image starts page 3")
+
+ // Typing before a break.
+ document.type(" Typed here", in: "a30")
+ assertEquivalent(view, "\(label): typed before a break")
+ document.setText("a30", Self.ledger(30) + " Typed here")
+ document.publish(["a30"])
+ assertEquivalent(view, "\(label): typed, published")
+
+ // An optimistic Return, then its publication.
+ let a31 = document.text(of: "a31")
+ document.type("\n", in: "a31", at: 10)
+ assertEquivalent(view, "\(label): Return, provisional block")
+ document.setText("a31", String(a31.prefix(10)))
+ document.nodes.insert(SurfaceFixture.paragraph("r1", String(a31.dropFirst(10))), at: document.index(of: "a31") + 1)
+ document.publish(["a31", "r1"])
+ assertEquivalent(view, "\(label): Return, published")
+
+ // Backspace at that block's start: one paragraph, two runs.
+ let r1 = document.location(of: "r1")
+ view.setSelectedRange(NSRange(location: r1.location, length: 0))
+ view.deleteBackward(nil)
+ assertEquivalent(view, "\(label): Backspace at a block's start")
+ document.nodes.remove(at: document.index(of: "r1"))
+ document.setText("a31", a31)
+ document.publish(["a31", "r1"])
+ assertEquivalent(view, "\(label): Backspace, published")
+
+ // A block deleted whole.
+ let a35 = document.location(of: "a35")
+ view.setSelectedRange(a35)
+ view.deleteBackward(nil)
+ assertEquivalent(view, "\(label): a block deleted")
+ document.nodes.remove(at: document.index(of: "a35"))
+ document.publish(["a35", "a34", "a36"])
+ assertEquivalent(view, "\(label): delete, published")
+
+ // A paste of three blocks, as DocsTextView.paste puts them in.
+ let pasted = (1...3).map { SurfaceFixture.paragraph("p\($0)", "Pasted paragraph \($0), long enough to matter to a page.") }
+ let at = document.location(of: "a20").location
+ let rendered = NativeTextProjection.render(SurfaceFixture.projection(pasted))
+ view.setSelectedRange(NSRange(location: at, length: 0))
+ XCTAssertTrue(document.state.surface.clipboardEdit(blocks: [], range: NSRange(location: at, length: 0), replacement: rendered.string))
+ view.textStorage!.replaceCharacters(in: NSRange(location: at, length: 0), with: rendered)
+ view.didChangeText()
+ assertEquivalent(view, "\(label): three blocks pasted")
+ document.nodes.insert(contentsOf: pasted, at: document.index(of: "a20"))
+ document.publish(["p1", "p2", "p3", "a19", "a20"])
+ assertEquivalent(view, "\(label): paste, published")
+
+ // Several blocks changed in one flush (a peer's).
+ for id in ["a5", "a50", "a100"] { document.setText(id, document.text(of: id) + " A peer's longer note that wraps the line onto another one.") }
+ document.publish(["a5", "a50", "a100"])
+ assertEquivalent(view, "\(label): three blocks in one flush")
+
+ // Typing inside a block taller than a page.
+ let list = document.location(of: "list")
+ view.setSelectedRange(NSRange(location: list.location + 200, length: 0))
+ view.insertText(" typed in the long list", replacementRange: view.selectedRange())
+ assertEquivalent(view, "\(label): typed inside a block taller than a page")
+
+ // Typing that moves a break forward, then back.
+ let before = Self.production(view).starts
+ let lastOnPage = document.nodes[document.index(of: "h1") - 1].id
+ let longer = " and more, enough words to need a second line of the paragraph."
+ document.type(longer, in: lastOnPage)
+ assertEquivalent(view, "\(label): a break moved")
+ XCTAssertNotEqual(Self.production(view).starts, before, "\(label): the typing moved a break")
+ let block = document.location(of: lastOnPage)
+ view.setSelectedRange(NSRange(location: NSMaxRange(block) - 1 - longer.utf16.count, length: longer.utf16.count))
+ view.deleteBackward(nil)
+ assertEquivalent(view, "\(label): the break moved back")
+ XCTAssertEqual(Set(Self.production(view).starts.keys), Set(before.keys), "\(label): the break is back")
+ }
+ }
+
+ /// A break goes only where a block's run starts a paragraph (§7
+ /// Design 4): after a Backspace at a block's start, the second run of
+ /// the merged paragraph is never a break, and no separator falls inside
+ /// a paragraph. (The oracle, measuring runs, could put one there.)
+ func testNoBreakInsideAMergedParagraph() throws {
+ DocsFonts.register()
+ var nodes = (1...37).map { SurfaceFixture.paragraph("a\($0)", Self.ledger($0)) }
+ nodes.append(SurfaceFixture.paragraph("x", "The paragraph a Backspace joins to the next."))
+ nodes.append(SurfaceFixture.paragraph("y", String(repeating: "The next one, long enough to cross the page's end. ", count: 6)))
+ nodes += (40...60).map { SurfaceFixture.paragraph("a\($0)", Self.ledger($0)) }
+ let document = Document(nodes, window: false, magnification: 1)
+ let view = document.view
+ _ = Self.production(view)
+ let y = document.location(of: "y")
+ view.setSelectedRange(NSRange(location: y.location, length: 0))
+ view.deleteBackward(nil)
+ let plan = Self.production(view)
+ let storage = view.textStorage!
+ // The case this is about: measuring runs, the oracle breaks before
+ // the second run, inside the paragraph.
+ let merged = document.location(of: "y").location
+ XCTAssertNotNil(Self.oracle(storage).starts[merged], "the fixture puts the oracle's break inside the merged paragraph")
+ XCTAssertNil(plan.starts[merged])
+ for location in plan.starts.keys {
+ XCTAssertTrue(location == 0 || storage.mutableString.character(at: location - 1) == 10, "a break at \(location) is inside a paragraph")
+ }
+ let manager = view.layoutManager!
+ manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { _, used, _, _, _ in
+ for separator in plan.separators {
+ XCTAssertFalse(used.minY < separator + 18 && used.maxY > separator, "a line straddles the separator at \(separator)")
+ }
+ }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift b/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift
new file mode 100644
index 0000000..3aaadad
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/PaginationLargeDocumentTests.swift
@@ -0,0 +1,173 @@
+#if os(macOS)
+import AppKit
+import XCTest
+@testable import DocsKit
+
+/// The Mac's large-document checks and the line-fragment gate (spec
+/// 2026-11-22 §7 "Incremental pagination" 10, "Measurement and targets";
+/// §11 "Large documents", "Line-fragment requests"), on a 200-page
+/// document built here the way fixtures/generate-large-doc.mjs builds one:
+/// five paragraphs with bold and italic runs a page, a heading every second
+/// page and a list every fifth.
+@MainActor final class PaginationLargeDocumentTests: XCTestCase {
+ static func pages(_ count: Int) -> [CRDTNode] { SurfaceFixture.pages(count) }
+
+ /// The document in a window, as the app shows it: the desk in a scroll
+ /// view at the default magnification, Pages on.
+ @MainActor final class Window {
+ let state = SurfaceState(width: DocsDeskLayout.paperWidth)
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
+ let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800))
+ var view: DocsTextView { state.text }
+ init(_ nodes: [CRDTNode], paged: Bool = true) {
+ window.isReleasedWhenClosed = false
+ scroll.hasVerticalScroller = true
+ scroll.allowsMagnification = true
+ scroll.documentView = DocsDeskView(page: state.text)
+ scroll.magnification = 4.0 / 3.0
+ window.contentView = scroll
+ window.orderFront(nil)
+ state.text.paged = paged
+ state.markPendingOnEdit = false
+ state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
+ window.displayIfNeeded()
+ }
+ func close() { window.contentView = nil; window.close() }
+ }
+
+ private func until(_ what: String, seconds: Double = 30, _ condition: () -> Bool) async throws {
+ let deadline = ContinuousClock.now + .seconds(seconds)
+ while !condition() {
+ guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ }
+
+ /// The caret against its glyph, no line across a separator, and the
+ /// page numbers the oracle gives.
+ private func assertEndChecks(_ document: Window, _ message: String, caretShown: Bool = true, file: StaticString = #filePath, line: UInt = #line) {
+ let view = document.view
+ let manager = view.layoutManager!
+ let storage = view.textStorage!
+ document.window.displayIfNeeded()
+ let caret = view.selectedRange().location
+ let glyph = manager.glyphIndexForCharacter(at: min(caret, storage.length - 1))
+ let caretLine = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
+ // As the smoke test checks it: where the text view puts the caret
+ // (its insertion point rect) against the line its glyph is on.
+ let caretRect = manager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: view.textContainer!)
+ XCTAssertEqual(caretRect.minY, caretLine.minY, accuracy: 1, "caret against glyph: \(message)", file: file, line: line)
+ if caretShown { XCTAssertTrue(view.visibleRect.intersects(caretLine), "the caret's line is shown: \(message)", file: file, line: line) }
+ // The lines laid out near the end: none across a separator.
+ let separators = view.pagination.separators
+ let shown = manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!)
+ manager.enumerateLineFragments(forGlyphRange: shown) { _, used, _, _, _ in
+ for separator in separators where used.minY < separator + 18 && used.maxY > separator {
+ XCTFail("a line (\(used)) straddles the separator at \(separator): \(message)", file: file, line: line)
+ }
+ }
+ // Page numbers: the separators above the caret, against the oracle.
+ let oracle = PaginationEquivalenceTests.oracle(storage)
+ XCTAssertEqual(separators.count, oracle.separators.count, "pages: \(message)", file: file, line: line)
+ XCTAssertEqual(separators.filter { $0 < caretLine.minY }.count, oracle.separators.filter { $0 < caretLine.minY }.count, "the caret's page: \(message)", file: file, line: line)
+ var range = NSRange()
+ _ = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &range)
+ if let oracleLine = oracle.lines[manager.characterIndexForGlyph(at: range.location)] {
+ XCTAssertEqual(caretLine.minY, oracleLine.y, accuracy: 0.5, "the caret's line where a whole layout puts it: \(message)", file: file, line: line)
+ }
+ }
+
+ /// §7 item 10: open, let the idle chunks finish (the live layout still
+ /// holds nothing past the first screen), ⌘↓ to the end and type.
+ func testLargeDocumentAfterMeasuringCompletes() async throws {
+ DocsFonts.register()
+ let document = Window(Self.pages(200))
+ defer { document.close() }
+ let view = document.view
+ let manager = view.layoutManager!
+ XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks")
+ try await until("the idle chunks complete") { view.pagination.isComplete }
+ let last = manager.numberOfGlyphs - 1
+ XCTAssertNil(manager.textContainer(forGlyphAt: last, effectiveRange: nil, withoutAdditionalLayout: true),
+ "the live layout manager holds no layout at the end")
+ view.moveToEndOfDocument(nil)
+ view.insertText("Typed at the end", replacementRange: view.selectedRange())
+ assertEndChecks(document, "after the idle chunks")
+ // Pages off and on (§7's bound on the toggle: ≤ 250 ms at p200h,
+ // indicative; printed, not held).
+ for paged in [false, true] {
+ let start = ContinuousClock.now
+ #if DOCS_PROBES
+ let pagination = DocsProbes.paginationMs, lines = DocsProbes.lineRequests
+ #endif
+ view.paged = paged
+ view.layoutSubtreeIfNeeded()
+ let laidOut = start.duration(to: .now)
+ document.window.displayIfNeeded()
+ #if DOCS_PROBES
+ print("PAGES TOGGLE p200 to paged=\(paged): \(start.duration(to: .now)) (layout \(laidOut), pagination \(DocsProbes.paginationMs - pagination) ms, \(DocsProbes.lineRequests - lines) line requests)")
+ #endif
+ }
+ // Toggling keeps the scroll offset, not the caret, in view (as before).
+ assertEndChecks(document, "after Pages off and on", caretShown: false)
+ }
+
+ /// The second variant: the jump comes at open, before the idle chunks
+ /// complete; its contiguous measurement makes the same checks pass.
+ func testLargeDocumentJumpBeforeMeasuringCompletes() async throws {
+ DocsFonts.register()
+ let document = Window(Self.pages(200))
+ defer { document.close() }
+ let view = document.view
+ XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks")
+ view.moveToEndOfDocument(nil)
+ view.insertText("Typed at the end", replacementRange: view.selectedRange())
+ assertEndChecks(document, "jumped before the idle chunks")
+ }
+
+ #if DOCS_PROBES
+ /// §7's line-fragment gate, per key at p20 and p200: TextKit's requests
+ /// to the live container (counted inside `lineFragmentRect`, so its own
+ /// re-layout counts) stay within the edited block's lines, the visible
+ /// lines and 8, through the key's display. Pages on and off.
+ func testLineFragmentRequestsPerKey() async throws {
+ DocsFonts.register()
+ for pages in [20, 200] {
+ for paged in [true, false] {
+ let document = Window(Self.pages(pages), paged: paged)
+ defer { document.close() }
+ let view = document.view
+ try await until("measured") { view.pagination.isComplete }
+ let manager = view.layoutManager!
+ let storage = view.textStorage!
+ // The end of a block in the middle of the document, on screen.
+ var block = NSRange()
+ _ = storage.attribute(.docsTopBlock, at: storage.length / 2, longestEffectiveRange: &block, in: NSRange(location: 0, length: storage.length))
+ view.setSelectedRange(NSRange(location: NSMaxRange(block) - 1, length: 0))
+ view.scrollRangeToVisible(view.selectedRange())
+ document.window.displayIfNeeded()
+ try await Task.sleep(for: .milliseconds(50))
+ var worst: (requests: Int, bound: Int) = (-1, 0)
+ var counts: [Int] = []
+ for index in 0..<40 {
+ let before = DocsProbes.lineRequests
+ view.insertText(index % 9 == 8 ? " " : "x", replacementRange: view.selectedRange())
+ document.window.displayIfNeeded()
+ let requests = DocsProbes.lineRequests - before
+ counts.append(requests)
+ var unit = NSRange()
+ _ = storage.attribute(.docsTopBlock, at: max(0, view.selectedRange().location - 1), longestEffectiveRange: &unit, in: NSRange(location: 0, length: storage.length))
+ var blockLines = 0, visibleLines = 0
+ manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forCharacterRange: unit, actualCharacterRange: nil)) { _, _, _, _, _ in blockLines += 1 }
+ manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!)) { _, _, _, _, _ in visibleLines += 1 }
+ let bound = blockLines + visibleLines + 8
+ if worst.requests < 0 || requests - bound > worst.requests - worst.bound { worst = (requests, bound) }
+ XCTAssertLessThanOrEqual(requests, bound, "p\(pages) paged=\(paged) key \(index): \(requests) line requests, bound \(bound)")
+ }
+ print("LINE REQUESTS p\(pages) paged=\(paged) per key: \(counts.map(String.init).joined(separator: " ")); closest to the bound: \(worst.requests) against \(worst.bound)")
+ }
+ }
+ }
+ #endif
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
index e0e7cc0..2cda7cc 100644
--- a/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
+++ b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
@@ -51,6 +51,28 @@ import UIKit
}
enum SurfaceFixture {
+ /// A long document the way fixtures/generate-large-doc.mjs builds one:
+ /// five paragraphs with bold and italic runs a page, a heading every
+ /// second page and a list every fifth.
+ static func pages(_ count: Int) -> [CRDTNode] {
+ var nodes: [CRDTNode] = []
+ let words = "water reservoir council minutes engineer filtration mains survey creek dam pumps cistern records town summer fever population".split(separator: " ")
+ for page in 0..<count {
+ if page % 2 == 0 { nodes.append(SurfaceFixture.heading("h\(page)", "Section \(page / 2 + 1): the works in year \(1880 + page)", level: 2)) }
+ for paragraph in 0..<5 {
+ var runs: [CRDTRun] = []
+ for sentence in 0..<6 {
+ let text = (0..<16).map { String(words[(page * 31 + paragraph * 7 + sentence * 3 + $0) % words.count]) }.joined(separator: " ") + ". "
+ let marks: [String: JSONValue]? = sentence == 2 ? ["strong": .object([:])] : sentence == 4 ? ["em": .object([:])] : nil
+ runs.append(CRDTRun(insert: text, marks: marks))
+ }
+ nodes.append(CRDTNode(id: "p\(page)-\(paragraph)", type: "paragraph", children: [CRDTNode(id: "p\(page)-\(paragraph)t", type: "text", runs: runs)]))
+ }
+ if page % 5 == 4 { nodes.append(SurfaceFixture.list("l\(page)", "bullet_list", (1...4).map { "Item \($0) on page \(page + 1)" })) }
+ }
+ return nodes
+ }
+
static func paragraph(_ id: String, _ text: String, marks: [String: JSONValue]? = nil, attrs: [String: String]? = nil) -> CRDTNode {
CRDTNode(id: id, type: "paragraph", attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])])
}