native: keep the screen on the caret or its middle when a peer edits above
Fable's delta review on #180, F1 and F4. F1's tests found the anchor wrong where no page break takes up a peer's added line: unpaged, the screen scrolled 16.7pt the wrong way; paged on the screen's top page, it did not scroll and the caret moved up a line. The anchor was the fragment at the viewport's start, which TextKit 2 lays out above the screen as overscan: it could be the edited paragraph itself, or a fragment rebuilt since. The anchor is now a character, taken at the end of every layout: the caret's when the caret is on screen, otherwise the one at the screen's middle (F4), with where its line is on screen. Edits before it move it with the text; after an edit above the screen's top, the screen scrolls so its line is back where it was. Tests: PhonePaginationTests.testAPeersLineAboveTheScreenUnpaged and testAPeersLineOnTheScreensTopPage (both failed before). A peer's line added above the screen, published as the replica publishes it (a new generation, the selection mapped past the insert): the screen scrolls by that line, the caret stays where it was on screen, and the screen, a screen above and the screen again all match a whole layout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+138
−23
native/apple/Sources/DocsKit/DocsPagedTextView.swift+65 −22native/apple/Tests/DocsKitTests/PhonePaginationTests.swift+73 −1
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift| index 93f0d61..d940666 100644 |
| --- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| +++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift |
| @@ -334,25 +334,85 @@ import UIKit |
| /// The text storage changed (DocumentSurface's storage delegate). |
| func storageEdited(_ edited: NSRange, delta: Int) { |
| pages.edited(edited, delta: delta) |
| + if !pages.regenerating { |
| + if edited.location < screenTop { editedAboveScreen = true } |
| + // The anchor moves with the text. |
| + if var kept = anchor, edited.location < kept.offset { |
| + let oldEnd = NSMaxRange(edited) - delta |
| + kept.offset = kept.offset >= oldEnd ? kept.offset + delta : NSMaxRange(edited) |
| + anchor = kept |
| + } |
| + } |
| setNeedsLayout() |
| } |
| + /// What the screen is kept on when an edit lands above it (a peer's): |
| + /// the caret's character when the caret is on screen, else the one at |
| + /// the screen's middle, and where its line was on screen (Fable's delta |
| + /// review, F4). Taken at the end of every layout. |
| + private var anchor: (offset: Int, y: CGFloat)? |
| + /// The first character on screen at the last layout. |
| + private var screenTop = 0 |
| + private var editedAboveScreen = false |
| + |
| + private func recordAnchor() { |
| + let top = contentOffset.y + adjustedContentInset.top |
| + let bottom = contentOffset.y + bounds.height - adjustedContentInset.bottom |
| + screenTop = character(atY: top) ?? 0 |
| + var at: Int? |
| + if isFirstResponder, let caret = lineTop(at: selectedRange.location), caret >= top, caret < bottom { at = selectedRange.location } |
| + if at == nil { at = character(atY: (top + bottom) / 2) } |
| + anchor = at.flatMap { offset in lineTop(at: offset).map { (offset, $0 - contentOffset.y) } } |
| + } |
| + |
| + /// The screen scrolled so the anchor's line is where it was on screen: |
| + /// an edit above (a peer's) moves nothing a person is reading. |
| + private func keepAnchor() { |
| + defer { editedAboveScreen = false } |
| + guard editedAboveScreen, let kept = anchor, let y = lineTop(at: kept.offset) else { return } |
| + let offset = y - kept.y |
| + guard abs(offset - contentOffset.y) > 0.25 else { return } |
| + contentOffset.y = offset |
| + } |
| + |
| + /// The top of the line holding character `offset`, in the text view. |
| + private func lineTop(at offset: Int) -> CGFloat? { |
| + guard let layout = textLayoutManager, let content = layout.textContentManager, textStorage.length > 0 else { return nil } |
| + let at = min(max(0, offset), textStorage.length - 1) |
| + guard let location = content.location(content.documentRange.location, offsetBy: at), |
| + let fragment = layout.textLayoutFragment(for: location) else { return nil } |
| + let inner = at - content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) |
| + let line = fragment.textLineFragments.first { NSLocationInRange(inner, $0.characterRange) } ?? fragment.textLineFragments.last |
| + return fragment.layoutFragmentFrame.minY + (line?.typographicBounds.minY ?? 0) + textContainerInset.top |
| + } |
| + |
| + /// The first character of the line at `y` in the text view. |
| + private func character(atY y: CGFloat) -> Int? { |
| + guard let layout = textLayoutManager, let content = layout.textContentManager, |
| + let fragment = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, y - textContainerInset.top))) else { return nil } |
| + let base = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) |
| + let inner = y - textContainerInset.top - fragment.layoutFragmentFrame.minY |
| + let line = fragment.textLineFragments.first { $0.typographicBounds.maxY > inner } ?? fragment.textLineFragments.last |
| + return base + (line?.characterRange.location ?? 0) |
| + } |
| + |
| override func layoutSubviews() { |
| #if DOCS_PROBES |
| let probeStart = DocsProbes.now() |
| defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) } |
| #endif |
| updateGeometry() |
| - let anchor = restackEdits() |
| + restackEdits() |
| super.layoutSubviews() |
| paginate() |
| - if let anchor { keep(anchor) } |
| + keepAnchor() |
| tilePages() |
| if let header { |
| let frame = CGRect(x: 0, y: 0, width: bounds.width, height: headerHeight) |
| if header.view.frame != frame { header.view.frame = frame } |
| reportScroll() |
| } |
| + recordAnchor() |
| } |
| /// An edit (a key, a peer's change) above the screen's end, before |
| @@ -361,17 +421,11 @@ import UIKit |
| /// 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)? { |
| + private func restackEdits() { |
| 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 viewport = layout.textViewportLayoutController.viewportRange else { return } |
| 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 |
| + guard edited <= end, end <= pages.laidOutThrough else { return } |
| paginating = true |
| defer { paginating = false } |
| pages.rebuildIfStale() |
| @@ -380,17 +434,6 @@ import UIKit |
| pages.settle() |
| applyBreaks(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: |
diff --git a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift| index 07156a4..9c06de3 100644 |
| --- a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift |
| @@ -93,6 +93,78 @@ import XCTest |
| } |
| } |
| + /// A peer's added line above the screen where no page break takes it |
| + /// up (Fable's delta review, F1): unpaged, and paged on the screen's top |
| + /// page. Everything on screen moves down a line, so the screen scrolls |
| + /// by that line and nothing on it moves; it is where a whole layout puts |
| + /// it, and so is a screen above it and the screen again. |
| + func testAPeersLineAboveTheScreenUnpaged() async throws { try await peerLineAbove(paged: false) } |
| + func testAPeersLineOnTheScreensTopPage() async throws { try await peerLineAbove(paged: true) } |
| + |
| + private func peerLineAbove(paged: Bool) async 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 = paged |
| + window.addSubview(text) |
| + defer { text.removeFromSuperview() } |
| + state.markPendingOnEdit = false |
| + var nodes = SurfaceFixture.pages(20) |
| + // The peer's paragraph, marked: the fixture's paragraphs repeat. |
| + let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p9-1" }) |
| + let original = nodes[peer].children?[0].runs?[0].insert ?? "" |
| + nodes[peer].children?[0].runs?[0].insert = "The peer's paragraph. " + original |
| + state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) |
| + text.layoutIfNeeded() |
| + text.paginateEverything() |
| + let layout = try XCTUnwrap(text.textLayoutManager), content = try XCTUnwrap(layout.textContentManager) |
| + // With the next paragraph on its page. |
| + let found = (text.textStorage.string as NSString).range(of: "The peer's paragraph. ") |
| + XCTAssertNotEqual(found.location, NSNotFound) |
| + let index = try XCTUnwrap(text.pages.paragraph(at: found.location)) |
| + XCTAssertEqual(text.pages.paragraphs[index + 1].extra, 0, "the next paragraph is on its page") |
| + func frame(_ at: Int) throws -> CGRect { |
| + let location = try XCTUnwrap(content.location(content.documentRange.location, offsetBy: text.pages.range(of: at).location)) |
| + return try XCTUnwrap(layout.textLayoutFragment(for: location)).layoutFragmentFrame |
| + } |
| + // The screen starts at the next paragraph, the caret in it. |
| + let next = try frame(index + 1) |
| + text.setContentOffset(CGPoint(x: 0, y: next.minY + text.textContainerInset.top - text.adjustedContentInset.top + 2), animated: false) |
| + text.layoutIfNeeded() |
| + XCTAssertTrue(text.becomeFirstResponder()) |
| + text.selectedRange = NSRange(location: text.pages.range(of: index + 1).location + 5, length: 0) |
| + text.delegate?.textViewDidChangeSelection?(text) |
| + text.layoutIfNeeded() |
| + try checkScreen(text, "before the line") |
| + let before = try frame(index).height, offset = text.contentOffset.y |
| + let caret = text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - offset |
| + let words = " A peer's words, enough of them to wrap onto a new line." |
| + nodes[peer].children?[0].runs?[0].insert += words |
| + // As the replica publishes a peer's change: a new generation, the |
| + // selection mapped past what was inserted above it. |
| + state.allowed = 2 |
| + state.selection = NSRange(location: text.selectedRange.location + words.utf16.count, length: 0) |
| + state.publish(SurfaceFixture.projection(nodes), generation: 2, dirty: ["p9-1"]) |
| + text.layoutIfNeeded() |
| + let line = try frame(index).height - before |
| + XCTAssertGreaterThan(line, 10, "the peer added a line") |
| + XCTAssertEqual(text.contentOffset.y - offset, line, accuracy: 0.5, "the screen scrolls by the line") |
| + XCTAssertEqual(text.caretRect(for: try XCTUnwrap(text.selectedTextRange).start).minY - text.contentOffset.y, caret, accuracy: 0.5, |
| + "the caret stays where it was on screen") |
| + try checkScreen(text, "after the line") |
| + let here = text.contentOffset.y |
| + text.setContentOffset(CGPoint(x: 0, y: here - text.bounds.height), animated: false) |
| + text.layoutIfNeeded() |
| + try checkScreen(text, "a screen up") |
| + text.setContentOffset(CGPoint(x: 0, y: here), animated: false) |
| + text.layoutIfNeeded() |
| + try checkScreen(text, "and down again") |
| + } |
| + |
| /// Marked text (Fable on #180, required 2): composing in the paragraph |
| /// that carries a page break's space, growing it by a line, moves the |
| /// break, but its fragment is not built again (an attribute edit of the |
| @@ -163,7 +235,7 @@ import XCTest |
| let shown = Self.screen(text) |
| XCTAssertGreaterThan(shown.count, 10, when) |
| let whole = DocsTextView(frame: text.frame) |
| - whole.paged = true |
| + whole.paged = text.paged |
| text.superview?.addSubview(whole) |
| defer { whole.removeFromSuperview() } |
| whole.attributedText = text.attributedText |