| 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 |