native: a peer's key above the screen restacks instead of laying out again
Fable on #180 (required 1). An edit above the screen (a peer typing on page 2 while you read page 150) marked the layout inexact from the edit to the end, and the next layout threw all of it away and laid it out again from the top: ~465 ms of main thread per peer key at 200 pages. TextKit 2 does not move the fragments below one that changed; until a walk from the top stacks them again it places the screen at an estimate, and UIKit scrolls to keep the estimate still. A walk over laid-out fragments lays out no line again. So now: - `editedFrom` means "restack below here", set by edits and rebuilt breaks, cleared by a walk through it; throwing layout away is only for a screen past what is laid out (a jump, the §7 fallback); - an edit above the screen is handled before UIKit lays the screen out (`restackEdits`): the edited paragraphs measured on their own (a run of holes at a time, never everything down to the screen), the breaks placed, and a walk through the screen; - the screen's first fragment is kept where it was on screen, so a peer's edit above moves nothing a person is reading (also when a line cascades page breaks down to the screen); - on a key, only breaks through the screen's end are rebuilt; those below wait for idle. p200h, a peer's keys on page 2 with the screen at the middle, through the surface's publication path: median 13.0 ms (8.5 ms of it the surface's publication), keys moving at most one break max 16.2 ms, 0 paragraphs laid out again (was ~465 ms each). A line that cascades breaks over 40 pages above the screen costs 30 ms once: each moved break rebuilds its paragraph's fragment (TextKit 2 stacks a fragment's new height only after laying it out again). Tests: PhonePaginationTests.testAPeersKeysAboveTheScreenLayOutOnlyTheirParagraph (20 pages, published peer keys above the screen: nothing laid out again from the top, the screen does not scroll or move, its lines where a whole layout puts them; it failed before with 113 paragraphs laid out again per key); PhoneLargeDocumentTests adds the p200h peer-key timing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+279
−59
native/apple/Sources/DocsKit/DocsPagedTextView.swift+74 −27native/apple/Sources/DocsKit/DocsPhonePages.swift+66 −30native/apple/Sources/DocsKit/DocsProbes.swift+5 −1native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift+52 −1native/apple/Tests/DocsKitTests/PhonePaginationTests.swift+82 −0
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift| index df113ce..ce6b2b0 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| @@ -343,8 +343,10 @@ import UIKit |
| defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) } |
| #endif |
| updateGeometry() |
| + let anchor = restackEdits() |
| super.layoutSubviews() |
| paginate() |
| + if let anchor { keep(anchor) } |
| tilePages() |
| if let header { |
| let frame = CGRect(x: 0, y: 0, width: bounds.width, height: headerHeight) |
| @@ -353,13 +355,53 @@ import UIKit |
| } |
| } |
| + /// An edit (a key, a peer's change) above the screen's end, before |
| + /// UIKit lays the screen out: its paragraphs measured, the breaks |
| + /// placed and rebuilt, and TextKit 2's fragments stacked again from the |
| + /// top through the screen. Otherwise TextKit 2 places the screen at an |
| + /// estimate and UIKit scrolls to keep it still, which then moves the |
| + /// screen once the fragments are stacked (Fable on #180). |
| + /// Returns the screen's first fragment and where it was on screen, when |
| + /// the edit is above the screen: the screen is kept where it was. |
| + private func restackEdits() -> (fragment: NSTextLayoutFragment, y: CGFloat)? { |
| + guard !paginating, let edited = pages.editedFrom, let layout = textLayoutManager, let content = layout.textContentManager, |
| + let viewport = layout.textViewportLayoutController.viewportRange else { return nil } |
| + let start = content.offset(from: content.documentRange.location, to: viewport.location) |
| + let end = min(textStorage.length, content.offset(from: content.documentRange.location, to: viewport.endLocation)) |
| + guard edited <= end, end <= pages.laidOutThrough else { return nil } |
| + // Where the screen's first fragment is drawn now, before anything |
| + // above it is stacked again. |
| + let anchor = edited < start ? layout.textLayoutFragment(for: viewport.location).map { ($0, $0.layoutFragmentFrame.minY - contentOffset.y) } : nil |
| + paginating = true |
| + defer { paginating = false } |
| + pages.rebuildIfStale() |
| + let last = (pages.paragraph(at: end) ?? 0) + 1 |
| + pages.measureHoles(through: last, in: layout) |
| + pages.settle() |
| + pages.applyChanges(through: last) |
| + pages.ensureLayout(through: end, in: layout) |
| + return anchor |
| + } |
| + |
| + /// The screen scrolled so `anchor`'s fragment is where it was on screen: |
| + /// an edit above (a peer's) moves nothing a person is reading. A |
| + /// fragment built again since (a break's) is not followed. |
| + private func keep(_ anchor: (fragment: NSTextLayoutFragment, y: CGFloat)) { |
| + guard let layout = textLayoutManager, anchor.fragment.textLayoutManager === layout, anchor.fragment.state == .layoutAvailable else { return } |
| + let offset = anchor.fragment.layoutFragmentFrame.minY - anchor.y |
| + guard abs(offset - contentOffset.y) > 0.25 else { return } |
| + contentOffset.y = offset |
| + } |
| + |
| /// The page breaks for what is on screen, before it is drawn: |
| - /// - everything from the top through the screen's end is laid out |
| - /// (TextKit 2 places a paragraph exactly only after a layout of all |
| - /// above it; after a jump this is the spec's fallback, once per jump, |
| - /// and otherwise there is nothing to do); |
| - /// - what is on screen and not measured is measured, the breaks placed, |
| - /// and any that moved built again, then laid out again with the screen. |
| + /// - a screen past what is laid out (a jump) is laid out from the top |
| + /// through its end (the spec's fallback, once per jump); |
| + /// - what is on screen (and the paragraph after it) and not measured is |
| + /// measured, a run at a time, so an edit far above is measured alone; |
| + /// - the breaks are placed and those that moved rebuilt; |
| + /// - TextKit 2's fragments are stacked again from the top through the |
| + /// screen's end if an edit or a rebuilt break is above it, and the |
| + /// screen laid out again. |
| /// The rest is measured while idle. |
| private func paginate() { |
| guard !paginating, let layout = textLayoutManager, let content = layout.textContentManager else { return } |
| @@ -372,33 +414,37 @@ import UIKit |
| guard let viewport = layout.textViewportLayoutController.viewportRange else { break } |
| let start = content.offset(from: content.documentRange.location, to: viewport.location) |
| let end = content.offset(from: content.documentRange.location, to: viewport.endLocation) |
| - // A screen that starts past what was laid out exactly (a jump, or |
| - // a break moved above it) was placed at an estimate: lay out up |
| - // to it, then draw it again. An edit on screen needs neither. |
| - let estimated = start > pages.exactThrough |
| - // TextKit 2 keeps a fragment it placed at an estimate as laid |
| - // out (the screen's, and some around it), and measuring one gives |
| - // a nonsense lead: everything past the exact layout is laid out |
| - // again, from the top. |
| - if estimated, let from = content.location(content.documentRange.location, offsetBy: pages.exactThrough), |
| - let span = NSTextRange(location: from, end: content.documentRange.endLocation) { |
| - layout.invalidateLayout(for: span) |
| - } |
| - pages.ensureLayout(through: end, in: layout) |
| - if estimated { layout.textViewportLayoutController.layoutViewport() } |
| - let last = pages.paragraph(at: end) ?? 0 |
| - if let hole = pages.firstUnmeasured, hole <= last + 1 { |
| - pages.measure(hole..<min(pages.paragraphs.count, last + 2), in: layout) |
| - } |
| + if let span = pages.relayout(forScreenAt: start) { relay(span, through: end, in: layout) } |
| + let last = (pages.paragraph(at: end) ?? 0) + 1 |
| + pages.measureHoles(through: last, in: layout) |
| pages.settle() |
| - guard pages.hasChanges else { break } |
| - pages.applyChanges() |
| - pages.ensureLayout(through: end, in: layout) |
| + // Breaks below the screen wait for idle. |
| + let changed = pages.hasChanges(through: last) |
| + pages.applyChanges(through: last) |
| + let walked = pages.ensureLayout(through: end, in: layout) |
| + guard changed || walked else { break } |
| layout.textViewportLayoutController.layoutViewport() |
| } |
| scheduleIdle() |
| } |
| + /// Everything from `span`'s start thrown away and laid out again from |
| + /// the top through the screen's end, `end`. TextKit 2 keeps a fragment |
| + /// it placed at an estimate as laid out: thrown away, the layout from |
| + /// the top places it after what is exact. |
| + private func relay(_ span: Range<Int>, through end: Int, in layout: NSTextLayoutManager) { |
| + guard let content = layout.textContentManager, |
| + let from = content.location(content.documentRange.location, offsetBy: span.lowerBound), |
| + let range = NSTextRange(location: from, end: content.documentRange.endLocation) else { return } |
| + #if DOCS_PROBES |
| + DocsProbes.relaidParagraphs += (pages.paragraph(at: end) ?? 0) - (pages.paragraph(at: span.lowerBound) ?? 0) + 1 |
| + #endif |
| + layout.invalidateLayout(for: range) |
| + pages.applyChanges() |
| + pages.ensureLayout(through: end, in: layout) |
| + layout.textViewportLayoutController.layoutViewport() |
| + } |
| + |
| /// The rest of the document, a chunk per turn, while nothing else runs. |
| private func scheduleIdle() { |
| guard idle == nil, pages.firstUnmeasured != nil || pages.settleFrom != nil else { return } |
| @@ -430,6 +476,7 @@ import UIKit |
| setNeedsLayout(); layoutIfNeeded() |
| } |
| + |
| /// Where the last page's paper ends, when paged: the content is at |
| /// least this tall, so its bottom margin and number scroll into view. |
| private var pageFoot: CGFloat = 0 |
diff --git a/native/apple/Sources/DocsKit/DocsPhonePages.swift b/native/apple/Sources/DocsKit/DocsPhonePages.swift| index 52066fc..5f6b607 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPhonePages.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPhonePages.swift |
| @@ -66,13 +66,16 @@ import UIKit |
| /// True while the pages ask TextKit 2 to build paragraphs again (an |
| /// attribute-only edit of nothing): those edits are not text changes. |
| private(set) var regenerating = false |
| - /// TextKit 2's layout is contiguous from the top, and so exact, through |
| - /// this character: a paragraph built again or a new width moves it back. |
| + /// TextKit 2's layout is contiguous from the top through this character. |
| private(set) var laidOutThrough = 0 |
| - func invalidateLayout(from offset: Int) { laidOutThrough = min(laidOutThrough, max(0, offset)) } |
| - /// The first character edited since the layout was last made exact from |
| - /// the top. An edit on screen is placed exactly by TextKit 2 itself, and |
| - /// so is what follows it as the screen moves on; a jump past it is not. |
| + /// The first character below which TextKit 2's laid-out fragments may |
| + /// sit away from where they belong, since an edit or a rebuilt break. |
| + /// TextKit 2 does not move the fragments below one that changed (and |
| + /// until it does, places a screen there at an estimate); it stacks them |
| + /// again on a walk from the top. A walk over what is laid out lays out |
| + /// no line again (an edit's own paragraph aside), so it costs |
| + /// milliseconds at 200 pages, where throwing the layout below an edit |
| + /// away and laying it out again cost half a second (Fable on #180). |
| private(set) var editedFrom: Int? |
| weak var storage: NSTextStorage? |
| /// Chunk size for the idle measurement. |
| @@ -153,9 +156,14 @@ import UIKit |
| let oldStart = edited.location, oldEnd = NSMaxRange(edited) - delta |
| guard let first = paragraph(at: oldStart), let last = paragraph(at: oldEnd) else { rebuild(); return } |
| let from = starts[first] |
| - editedFrom = min(editedFrom ?? from, from) |
| - let to = starts[last] + paragraphs[last].length + delta |
| + let oldTo = starts[last] + paragraphs[last].length |
| + let to = oldTo + delta |
| guard from <= to, to <= string.length else { rebuild(); return } |
| + // What is laid out moves with the text; below the edit it waits for |
| + // a walk from the top. |
| + func moved(_ offset: Int) -> Int { offset <= from ? offset : offset >= oldTo ? offset + delta : from } |
| + laidOutThrough = moved(laidOutThrough) |
| + editedFrom = min(editedFrom.map(moved) ?? from, from) |
| var replacement = Self.lengths(in: string, range: NSRange(location: from, length: to - from)).map { Paragraph(length: $0) } |
| if replacement.isEmpty { replacement = [Paragraph(length: 0)] } |
| // The old breaks and bottoms, kept where the paragraphs line up, so |
| @@ -176,8 +184,24 @@ import UIKit |
| /// The first paragraph not yet measured, if any. |
| var firstUnmeasured: Int? { paragraphs.firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil } } |
| + /// Measures every paragraph not measured through paragraph `index`, a |
| + /// run at a time: an edited paragraph above the screen is measured on |
| + /// its own, never with everything between it and the screen. |
| + func measureHoles(through index: Int, in layout: NSTextLayoutManager) { |
| + var at = firstUnmeasured |
| + while let hole = at, hole <= index { |
| + var end = hole + 1 |
| + while end < paragraphs.count, end <= index + 1, paragraphs[end].height == nil || paragraphs[end].head == nil || paragraphs[end].tail == nil { end += 1 } |
| + measure(hole..<end, in: layout) |
| + at = paragraphs[end...].firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil } |
| + if at == hole { break } |
| + } |
| + } |
| + |
| /// Lays out paragraphs `range` (and the one before, for the lead) and |
| - /// records what it measures. |
| + /// records what it measures. Its measures are its own (fragment-local), |
| + /// so a paragraph laid out already and laid out again on its own (an |
| + /// edited one) is measured where it is. |
| func measure(_ indices: Range<Int>, in layout: NSTextLayoutManager) { |
| guard let content = layout.textContentManager, !indices.isEmpty, paragraphs.indices.contains(indices.lowerBound) else { return } |
| let lower = max(0, indices.lowerBound - 1) |
| @@ -190,9 +214,10 @@ import UIKit |
| let made = DocsProbes.layoutFragments |
| defer { DocsProbes.measureFragments += DocsProbes.layoutFragments - made } |
| #endif |
| - // From the document's start: TextKit 2 places a range laid out on |
| - // its own at an estimate, and only a layout of everything above it |
| - // is exact. What is already laid out costs nothing here. |
| + // Past what is laid out, from the document's start: TextKit 2 places |
| + // a range laid out on its own at an estimate, and only a layout of |
| + // everything above it is exact. Within it, the walk below lays out |
| + // only what an edit invalidated, after the paragraph before it. |
| ensureLayout(through: last, in: layout) |
| layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in |
| let offset = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) |
| @@ -250,26 +275,28 @@ import UIKit |
| settleThrough = -1 |
| } |
| - /// Lays out everything from the document's start through character |
| - /// `offset`: TextKit 2's positions are exact only for a layout that is |
| - /// contiguous from the top (a range laid out on its own sits at an |
| - /// estimate). |
| - /// Where the layout is known to be exact through: up to the first edit |
| - /// since it was made so, and up to `laidOutThrough`. |
| - var exactThrough: Int { min(laidOutThrough, editedFrom ?? .max) } |
| + /// What a screen starting at `start` needs thrown away and laid out |
| + /// again from the top: past what is laid out (a jump), TextKit 2 placed |
| + /// it at an estimate, and keeps what it placed so as laid out. Nil when |
| + /// it is laid out. |
| + func relayout(forScreenAt start: Int) -> Range<Int>? { |
| + start > laidOutThrough ? laidOutThrough..<Int.max : nil |
| + } |
| /// Lays out from the document's top through character `offset`, when |
| - /// that is past what is known to be exact. TextKit 2 places a range laid |
| - /// out on its own at an estimate (and keeps it so): only a layout from |
| - /// the top is exact. What is laid out already costs only the walk. |
| - /// False when there was nothing to do. |
| + /// that is past what is laid out or below an edit. TextKit |
| + /// 2 places a range laid out on its own at an estimate (and keeps it |
| + /// so): only a layout from the top is exact. What is laid out already |
| + /// costs only the walk, which stacks it again. False when there was |
| + /// nothing to do. |
| @discardableResult func ensureLayout(through offset: Int, in layout: NSTextLayoutManager) -> Bool { |
| - guard offset > exactThrough, let content = layout.textContentManager, |
| + guard offset > laidOutThrough || (editedFrom.map { $0 < offset } ?? false), let content = layout.textContentManager, |
| let end = content.location(content.documentRange.location, offsetBy: offset) ?? Optional(content.documentRange.endLocation), |
| let range = NSTextRange(location: content.documentRange.location, end: end) else { return false } |
| layout.ensureLayout(for: range) |
| - laidOutThrough = offset |
| - editedFrom = nil |
| + // Restacked through `offset`; what is laid out below it is not. |
| + if let edited = editedFrom, edited < offset { editedFrom = offset < laidOutThrough ? offset : nil } |
| + laidOutThrough = max(laidOutThrough, offset) |
| return true |
| } |
| @@ -277,10 +304,14 @@ import UIKit |
| /// changed. Nothing is laid out here: whoever draws or measures lays out |
| /// from the top through what it needs (`ensureLayout(through:in:)`), |
| /// which places everything after a rebuilt paragraph from its new size. |
| - func applyChanges() { |
| + /// Only those through paragraph `limit` when given (a key: what is |
| + /// below the screen waits for idle, so a break cascading down the |
| + /// document costs what is above the screen's end). |
| + func applyChanges(through limit: Int = .max) { |
| guard !changed.isEmpty, let storage else { return } |
| - let indices = changed |
| - changed = IndexSet() |
| + let indices = limit == .max ? changed : changed.filteredIndexSet { $0 <= limit } |
| + guard !indices.isEmpty else { return } |
| + changed.subtract(indices) |
| #if DOCS_PROBES |
| DocsProbes.pageBreakChanges += indices.count |
| #endif |
| @@ -289,7 +320,8 @@ import UIKit |
| // makes a new fragment only for a new element, and builds one for a |
| // paragraph whose attributes were edited: an edit of nothing does it |
| // (invalidating the layout keeps the old fragment). |
| - if let first = indices.first(where: { $0 > 0 && $0 < paragraphs.count }) { invalidateLayout(from: starts[first - 1]) } |
| + // What follows them waits for a walk from the top. |
| + if let first = indices.first(where: { $0 > 0 && $0 < paragraphs.count }) { editedFrom = min(editedFrom ?? .max, starts[first - 1]) } |
| regenerating = true |
| storage.beginEditing() |
| for index in indices where index > 0 && index < paragraphs.count { |
| @@ -301,6 +333,7 @@ import UIKit |
| } |
| var hasChanges: Bool { !changed.isEmpty } |
| + func hasChanges(through limit: Int) -> Bool { changed.contains { $0 <= limit } } |
| /// Every measured paragraph is placed again (the pages' origin moved). |
| func restartSettling() { settleFrom = 0; settleThrough = paragraphs.count } |
| @@ -315,6 +348,9 @@ import UIKit |
| /// The layout fragment for the paragraph at `location`: one that is |
| /// taller by the next paragraph's break space, when the next starts a page. |
| + /// (A fragment's space cannot change where it is: TextKit 2 stacks what |
| + /// follows a fragment again only after laying it out again, so a break |
| + /// that moves builds its fragment again.) |
| func fragment(for location: Int, element: NSTextElement) -> NSTextLayoutFragment { |
| guard paged, let index = paragraph(at: location), starts[index] == location, index + 1 < paragraphs.count, |
| paragraphs[index + 1].extra > 0, let range = element.elementRange else { |
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift| index fbf934e..0019377 100644 |
| --- a/native/apple/Sources/DocsKit/DocsProbes.swift |
| +++ b/native/apple/Sources/DocsKit/DocsProbes.swift |
| @@ -52,6 +52,10 @@ public enum DocsProbes { |
| /// iOS: layout fragments made while DocsPhonePages measured. |
| nonisolated(unsafe) public static var measureFragments = 0 |
| nonisolated(unsafe) public static var breakParagraphs = 0 |
| + /// iOS: paragraphs whose layout was thrown away to lay them out again |
| + /// from the top (DocsPagedTextView.paginate, a screen placed at an |
| + /// estimate: spec §7 Fallback). |
| + nonisolated(unsafe) public static var relaidParagraphs = 0 |
| nonisolated(unsafe) public static var measureLineRequests = 0 |
| /// Mac pagination passes, and their main-thread time. |
| nonisolated(unsafe) public static var paginations = 0 |
| @@ -77,7 +81,7 @@ public enum DocsProbes { |
| reconciles = 0; reconcileMs = 0; viewUpdates = 0; viewUpdateMs = 0 |
| hostBodies = 0; attributedTextAssignments = 0; publications = 0; publicationMs = 0 |
| workspaceBodies = 0; inspectorBodies = 0 |
| - lineRequests = 0; layoutFragments = 0; pageBreakChanges = 0; measureFragments = 0; breakParagraphs = 0; measureLineRequests = 0; paginations = 0; paginationMs = 0; paginationRedraws = 0 |
| + lineRequests = 0; layoutFragments = 0; pageBreakChanges = 0; measureFragments = 0; breakParagraphs = 0; relaidParagraphs = 0; measureLineRequests = 0; paginations = 0; paginationMs = 0; paginationRedraws = 0 |
| textLayouts = 0; textLayoutMs = 0; draws = 0; drawMs = 0 |
| toolbarRefreshes = 0; toolbarRefreshMs = 0; commands = 0; commandMs = 0 |
| } |
diff --git a/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift| index 89fccc4..bb741d0 100644 |
| --- a/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift |
| @@ -102,6 +102,51 @@ import XCTest |
| XCTAssertLessThanOrEqual(sorted[sorted.count / 2], 8, "per key ≤ 8 ms median") |
| XCTAssertLessThanOrEqual(newLineKeys.max() ?? 0, 16.7, "no stall over 16.7 ms on a key that changes a line count") |
| + // A peer's keys on page 2 while the screen is at the middle (Fable on |
| + // #180), through the surface's publication path as a peer's change |
| + // arrives, every fourth adding a line: main-thread time from the |
| + // publication to the screen laid out. Nothing on screen moves. |
| + // As a session would be by then: the rest measured while idle. |
| + let idleDeadline = Date().addingTimeInterval(20) |
| + while (text.pages.firstUnmeasured != nil || text.pages.settleFrom != nil || text.pages.hasChanges) && Date() < idleDeadline { |
| + try await Task.sleep(for: .milliseconds(20)) |
| + } |
| + text.layoutIfNeeded() |
| + var nodes = SurfaceFixture.pages(Self.pages) |
| + let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" }) |
| + var peerKeys: [Double] = [], peerLineKeys: [Double] = [], cascades: [(ms: Double, breaks: Int)] = [], plain: [Double] = [] |
| + var publications: [Double] = [] |
| + let relaid = DocsProbes.relaidParagraphs |
| + for index in 0..<20 { |
| + let typed = index % 4 == 3 ? wrap : "x" |
| + nodes[peer].children?[0].runs?[0].insert += typed |
| + let next = SurfaceFixture.projection(nodes) |
| + let anchor = layout.textViewportLayoutController.viewportRange.map { content.offset(from: content.documentRange.location, to: $0.location) } ?? 0 |
| + func screenY(_ at: Int) -> CGFloat { |
| + (content.location(content.documentRange.location, offsetBy: at).flatMap { layout.textLayoutFragment(for: $0)?.layoutFragmentFrame.minY } ?? 0) - text.contentOffset.y |
| + } |
| + let anchorY = screenY(anchor), breaks = DocsProbes.pageBreakChanges, published = DocsProbes.publicationMs |
| + start = .now |
| + surface.apply(DocumentSurface.Publication(generation: 1, projection: next, revision: UInt64(2 + index), dirty: ["p1-2"])) |
| + text.layoutIfNeeded() |
| + let elapsed = Self.ms(start) |
| + XCTAssertEqual(screenY(anchor + typed.utf16.count), anchorY, accuracy: 0.5, "peer key \(index): nothing on screen moved") |
| + peerKeys.append(elapsed) |
| + publications.append(DocsProbes.publicationMs - published) |
| + if typed == wrap { peerLineKeys.append(elapsed) } |
| + let moved = DocsProbes.pageBreakChanges - breaks |
| + if moved > 1 { cascades.append((elapsed, moved)) } else { plain.append(elapsed) } |
| + try await Task.sleep(for: .milliseconds(5)) |
| + } |
| + let peerSorted = peerKeys.sorted() |
| + print(String(format: "PHONE LARGE textkit2: a peer's keys on page 2, screen at the middle: median %.2f ms (publication median %.2f ms), max %.2f ms; adding a line max %.2f ms; %d paragraphs laid out again", |
| + peerSorted[peerSorted.count / 2], publications.sorted()[publications.count / 2], peerSorted.last ?? 0, peerLineKeys.max() ?? 0, DocsProbes.relaidParagraphs - relaid)) |
| + print("PHONE LARGE textkit2: peer keys moving at most one break, max \(String(format: "%.2f", plain.max() ?? 0)) ms; cascading breaks above the screen: \(cascades.map { String(format: "%.2f ms (%d breaks)", $0.ms, $0.breaks) })") |
| + XCTAssertTrue(surface.content.string.contains(nodes[peer].plainText), "the peer's keys arrived") |
| + XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "nothing laid out again from the top") |
| + XCTAssertLessThanOrEqual(peerSorted[peerSorted.count / 2], 16.7, "a peer's key ≤ 16.7 ms median") |
| + XCTAssertLessThanOrEqual(plain.max() ?? 0, 16.7, "no peer key over 16.7 ms that moves at most one break") |
| + |
| // A fresh view for the jump, laid out no further than its first screen. |
| let jumper = DocsTextView(frame: window.bounds) |
| jumper.paged = true |
| @@ -120,7 +165,13 @@ import XCTest |
| jumper.scrollRangeToVisible(jumper.selectedRange) |
| jumper.layoutIfNeeded() |
| let jump = Self.ms(start), jumpFragments = DocsProbes.layoutFragments - fragments |
| - let breaks = jumper.pages.paragraphs.indices.filter { jumper.pages.paragraphs[$0].extra > 0 } |
| + // Breaks through the screen's end: those below it are built while |
| + // idle, before the screen gets to them. |
| + let screenEnd = jumper.textLayoutManager.flatMap { layout in |
| + layout.textViewportLayoutController.viewportRange.flatMap { range in |
| + layout.textContentManager.map { $0.offset(from: $0.documentRange.location, to: range.endLocation) } } } ?? jumper.textStorage.length |
| + let lastShown = (jumper.pages.paragraph(at: screenEnd) ?? 0) + 1 |
| + let breaks = jumper.pages.paragraphs.indices.filter { jumper.pages.paragraphs[$0].extra > 0 && $0 <= lastShown } |
| // Every break laid out where it was placed. |
| if let layout = jumper.textLayoutManager, let content = layout.textContentManager { |
| var off = 0, worst: CGFloat = 0 |
diff --git a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift| index d63ba7d..f2acab6 100644 |
| --- a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift |
| @@ -49,6 +49,88 @@ import XCTest |
| try edit(NSRange(location: 15000, length: 108), "", "deleting them again") |
| } |
| + /// A peer's keys far above the screen (Fable on #180): through the |
| + /// surface's publication path, as a peer's change arrives. A key that |
| + /// leaves its paragraph's lines as they were lays out that paragraph |
| + /// and nothing else; one that adds a line moves the text only as far |
| + /// as the next page break, which takes it up. Either way the screen |
| + /// stays where a whole layout puts it, its breaks where they were |
| + /// placed, and nothing on it moves. |
| + func testAPeersKeysAboveTheScreenLayOutOnlyTheirParagraph() throws { |
| + DocsFonts.register() |
| + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) |
| + window.makeKeyAndVisible() |
| + defer { window.isHidden = true } |
| + let state = SurfaceState(width: 402) |
| + let text = state.text |
| + text.frame = window.bounds |
| + text.paged = true |
| + window.addSubview(text) |
| + defer { text.removeFromSuperview() } |
| + state.markPendingOnEdit = false |
| + var nodes = SurfaceFixture.pages(20) |
| + state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) |
| + text.layoutIfNeeded() |
| + text.paginateEverything() |
| + text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height - text.bounds.height * 2), animated: false) |
| + text.layoutIfNeeded() |
| + let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" }) |
| + let wrap = String(repeating: "Words to wrap the line. ", count: 3) |
| + for (what, typed) in [("a peer's key", "x"), ("a peer's key that adds a line", wrap), ("a peer's key", "y")] { |
| + let shown = Self.screen(text) |
| + nodes[peer].children?[0].runs?[0].insert += typed |
| + let relaid = DocsProbes.relaidParagraphs |
| + let offset = text.contentOffset.y |
| + state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p1-2"]) |
| + text.layoutIfNeeded() |
| + XCTAssertEqual(text.contentOffset.y, offset, "\(what): the screen does not scroll") |
| + XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "\(what): nothing laid out again from the top down to the screen") |
| + XCTAssertTrue(state.string.contains(typed), what) |
| + // Nothing on screen moved (the text there is the same text). |
| + let after = Self.screen(text) |
| + XCTAssertEqual(after.map(\.rect.minY), shown.map(\.rect.minY), "\(what): nothing on screen moved") |
| + try checkScreen(text, what) |
| + } |
| + } |
| + |
| + /// The screen's lines, by where they are drawn. |
| + private static func screen(_ text: DocsTextView) -> [(range: NSRange, rect: CGRect)] { |
| + PhoneLargeDocumentTests.lines(in: text, near: text.contentOffset.y, height: text.bounds.height).filter { $0.range.length > 0 } |
| + } |
| + |
| + /// The screen's lines where a fresh view of the same text, laid out |
| + /// whole, puts them, and its breaks where they were placed. |
| + private func checkScreen(_ text: DocsTextView, _ when: String) throws { |
| + let layout = try XCTUnwrap(text.textLayoutManager) |
| + let content = try XCTUnwrap(layout.textContentManager) |
| + let shown = Self.screen(text) |
| + XCTAssertGreaterThan(shown.count, 10, when) |
| + let whole = DocsTextView(frame: text.frame) |
| + whole.paged = true |
| + text.superview?.addSubview(whole) |
| + defer { whole.removeFromSuperview() } |
| + whole.attributedText = text.attributedText |
| + whole.layoutIfNeeded() |
| + whole.paginateEverything() |
| + let reference = Dictionary(PhoneLargeDocumentTests.lines(in: whole, near: 0, height: .greatestFiniteMagnitude) |
| + .map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a }) |
| + var differ = 0 |
| + for line in shown { |
| + guard let other = reference[line.range.location] else { differ += 1; continue } |
| + if abs(other.minY - line.rect.minY) > 0.5 { differ += 1 } |
| + } |
| + XCTAssertEqual(differ, 0, "\(when): lines on screen away from where a whole layout puts them") |
| + guard let first = shown.first?.range.location, let last = shown.last?.range.location, |
| + let from = text.pages.paragraph(at: first), let to = text.pages.paragraph(at: last) else { return } |
| + for index in from...to where text.pages.paragraphs[index].extra > 0 { |
| + guard let location = content.location(content.documentRange.location, offsetBy: text.pages.range(of: index).location), |
| + let fragment = layout.textLayoutFragment(for: location), |
| + let placed = text.pages.paragraphs[index].bottom.map({ $0 - (text.pages.paragraphs[index].height ?? 0) }) else { continue } |
| + let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0) |
| + XCTAssertEqual(top, placed, accuracy: 0.5, "\(when): a break on screen laid out where it was placed") |
| + } |
| + } |
| + |
| /// A one-line document scrolls to its page's foot (its bottom margin and |
| /// page number), not only to its text's end. |
| func testAShortDocumentScrollsToItsPagesFoot() throws { |