oficina / docs Public

native: idle finishes a restack, so scrolling on walks nothing

Fable's delta review on #180, F3. An edit above the screen is restacked
through the screen's end only; `editedFrom` then sat at that end, and
every later layout reaching past it (each frame of a scroll down) walked
everything from the top again. Idle now also starts for a pending
restack and, once there is nothing to measure, place or build and typing
has paused for 300 ms, finishes it with one walk over everything laid
out, which clears `editedFrom`. The idle loop is reorganised around that
end: it continues while it gets somewhere, and stops when done or stuck,
as before.

Test: PhonePaginationTests.testIdleFinishesTheRestack (failed before:
`editedFrom` stayed set and three scroll steps walked three times). New
probe: DocsProbes.restackWalks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0793e05963245a70b7e7698fcabde9daee29ca6f parent c8f8c40
4 files changed, +75 −11
  • native/apple/Sources/DocsKit/DocsPagedTextView.swift +26 −10
  • native/apple/Sources/DocsKit/DocsPhonePages.swift +3 −0
  • native/apple/Sources/DocsKit/DocsProbes.swift +4 −1
  • native/apple/Tests/DocsKitTests/PhonePaginationTests.swift +42 −0
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
index e15be2d..8084aa5 100644
--- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift
+++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
@@ -335,6 +335,7 @@ import UIKit
func storageEdited(_ edited: NSRange, delta: Int) {
pages.edited(edited, delta: delta)
if !pages.regenerating {
+ lastEdit = .now
if edited.location < screenTop { editedAboveScreen = true }
// The anchor moves with the text.
if var kept = anchor, edited.location < kept.offset {
@@ -503,8 +504,10 @@ import UIKit
/// The rest of the document, a chunk per turn, while nothing else runs.
private func scheduleIdle() {
- // Also for breaks a key left below the screen (Fable's delta review, F2).
- guard idle == nil, pages.firstUnmeasured != nil || pages.settleFrom != nil || (pages.hasChanges && markedTextRange == nil) else { return }
+ // Also for breaks a key left below the screen (Fable's delta review,
+ // F2), and for a restack to finish (F3).
+ guard idle == nil, pages.firstUnmeasured != nil || pages.settleFrom != nil
+ || (pages.hasChanges && markedTextRange == nil) || pages.editedFrom != nil else { return }
idle = Task { @MainActor [weak self] in
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(2))
@@ -514,18 +517,31 @@ import UIKit
self.pages.measure(hole..<min(self.pages.paragraphs.count, hole + DocsPhonePages.chunk), in: layout)
}
self.pages.settle()
- // A pass that got nowhere (a paragraph that cannot be
- // measured: an empty document; breaks held for a
- // composition) ends it; layout starts it again when there is
- // something new, and so does a composition ending.
- if (self.pages.firstUnmeasured, self.pages.settleFrom) == before, !self.pages.hasChanges || self.markedTextRange != nil {
- self.idle = nil; return
+ if self.pages.hasChanges && self.markedTextRange == nil { self.applyBreaks(); self.setNeedsLayout(); continue }
+ let progressed = (self.pages.firstUnmeasured, self.pages.settleFrom) != before
+ if progressed, self.pages.firstUnmeasured != nil || self.pages.settleFrom != nil { continue }
+ // Measured and placed, or nowhere to go (a paragraph that
+ // cannot be measured: an empty document; breaks held for a
+ // composition). An edit's restack is finished with one walk
+ // over everything laid out (F3), once typing pauses: until
+ // then each frame that scrolls past the last walk walks again.
+ if self.pages.editedFrom != nil, self.markedTextRange == nil {
+ let quiet = ContinuousClock.now - self.lastEdit
+ if quiet < Self.restackPause { try? await Task.sleep(for: Self.restackPause - quiet); continue }
+ self.pages.ensureLayout(through: self.pages.laidOutThrough, in: layout)
+ self.setNeedsLayout()
}
- if self.pages.hasChanges && self.markedTextRange == nil { self.applyBreaks(); self.setNeedsLayout() }
- if self.pages.firstUnmeasured == nil && self.pages.settleFrom == nil { self.idle = nil; self.setNeedsLayout(); return }
+ // Layout starts it again when there is something new, and so
+ // does a composition ending.
+ self.idle = nil
+ return
}
}
}
+ /// When the text last changed, and how long typing must pause before
+ /// idle walks everything laid out to finish a restack.
+ private var lastEdit = ContinuousClock.now
+ private static let restackPause = Duration.milliseconds(300)
/// Measures and places every paragraph now (tests: a whole layout).
func paginateEverything() {
diff --git a/native/apple/Sources/DocsKit/DocsPhonePages.swift b/native/apple/Sources/DocsKit/DocsPhonePages.swift
index 5f6b607..dd6bb24 100644
--- a/native/apple/Sources/DocsKit/DocsPhonePages.swift
+++ b/native/apple/Sources/DocsKit/DocsPhonePages.swift
@@ -293,6 +293,9 @@ import UIKit
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 }
+ #if DOCS_PROBES
+ if offset <= laidOutThrough { DocsProbes.restackWalks += 1 }
+ #endif
layout.ensureLayout(for: range)
// Restacked through `offset`; what is laid out below it is not.
if let edited = editedFrom, edited < offset { editedFrom = offset < laidOutThrough ? offset : nil }
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift
index 0019377..4048de3 100644
--- a/native/apple/Sources/DocsKit/DocsProbes.swift
+++ b/native/apple/Sources/DocsKit/DocsProbes.swift
@@ -56,6 +56,9 @@ public enum DocsProbes {
/// from the top (DocsPagedTextView.paginate, a screen placed at an
/// estimate: spec §7 Fallback).
nonisolated(unsafe) public static var relaidParagraphs = 0
+ /// iOS: walks from the top over what is laid out, to stack fragments
+ /// below an edit again (DocsPhonePages.ensureLayout).
+ nonisolated(unsafe) public static var restackWalks = 0
nonisolated(unsafe) public static var measureLineRequests = 0
/// Mac pagination passes, and their main-thread time.
nonisolated(unsafe) public static var paginations = 0
@@ -81,7 +84,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; relaidParagraphs = 0; measureLineRequests = 0; paginations = 0; paginationMs = 0; paginationRedraws = 0
+ lineRequests = 0; layoutFragments = 0; pageBreakChanges = 0; measureFragments = 0; breakParagraphs = 0; relaidParagraphs = 0; restackWalks = 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/PhonePaginationTests.swift b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift
index 59cdaa4..18bd4ec 100644
--- a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift
+++ b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift
@@ -208,6 +208,48 @@ import XCTest
try checkScreen(text, "a jump to the end")
}
+ /// After a peer's key above the screen, idle finishes the restack once
+ /// typing pauses (Fable's delta review, F3), so scrolling on does not
+ /// walk from the top on every frame.
+ func testIdleFinishesTheRestack() 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 = 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: 1200), animated: false)
+ text.layoutIfNeeded()
+ func settle() async throws {
+ let deadline = Date().addingTimeInterval(3)
+ while text.isMeasuringWhileIdle && Date() < deadline { try await Task.sleep(for: .milliseconds(20)) }
+ XCTAssertFalse(text.isMeasuringWhileIdle)
+ }
+ try await settle()
+ let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p0-1" })
+ nodes[peer].children?[0].runs?[0].insert += "x"
+ state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: ["p0-1"])
+ text.layoutIfNeeded()
+ try await settle()
+ XCTAssertNil(text.pages.editedFrom, "the restack is finished")
+ let walks = DocsProbes.restackWalks
+ for step in 1...3 {
+ text.setContentOffset(CGPoint(x: 0, y: 1200 + CGFloat(step) * 300), animated: false)
+ text.layoutIfNeeded()
+ }
+ XCTAssertEqual(DocsProbes.restackWalks, walks, "scrolling on walks nothing from the top")
+ try checkScreen(text, "scrolled on")
+ }
+
/// 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