oficina / docs Public

Docs native S3: the iPhone document on TextKit 2 open

On branch native/iphone-document

Plan slice S3 (docs/superpowers/plans/2026-11-22-native-redesign.md), spec §3, §6, §7 "iPhone layout", §9, §11. Two commits: 587f32f the code, b9285e5 the snapshot baselines (pushed separately for pack size). iPad keeps today's layout until S5.

The editor on TextKit 2 (plan 6a, S1b ruling #173)

The iPhone and iPad text view is rebuilt on TextKit 2. It uses a plain NSTextContainer: a container subclass, replacing the container, or touching layoutManager all make UIKit fall back to TextKit 1.

Page breaks are per paragraph (DocsPhonePages):

  • A paragraph that would cross a page's body moves to the next page's top. The space is carried by the previous paragraph's layout fragment (DocsPageBreakFragment). TextKit 2 ignores topMargin, and its content-storage delegate is never asked about list items.
  • Measurements are fragment-local (head, height, tail), because TextKit 2 leaves stale origins on fragments below an edit.
  • Opening lays out the first screen. Idle chunks of 40 paragraphs measure the rest. A jump to an unlaid place lays out from the top once (the §7 Fallback).
  • The content reaches the last page's foot through contentSize, never the inset: changing the inset re-lays out the whole screen, so it would cost that on every key.

p200h paged (1,260 paragraphs), iPhone 18 Pro simulator, iOS 27.0, Debug, three runs at load 8–9 (PhoneLargeDocumentTests, TEST_RUNNER_DOCS_PHONE_LARGE=1):

| | TextKit 1 (as shipped) | TextKit 2 | Target | |---|---|---|---| | Open to the first screen | 1.27 s (whole document) | 159–168 ms, 11 of 1,260 paragraphs laid out | ≤ 250 ms | | Per key, median (40 keys mid-document) | 1.3–2.7 ms | 6.4–6.5 ms | ≤ 8 ms | | Worst key (line-count changes) | 250–480 ms | 12.4–12.7 ms | ≤ 16.7 ms | | Jump to the end | (already laid out) | 465–472 ms, once | §7 Fallback |

After the jump: 354 breaks, 0 laid out away from where they were placed, the caret on its glyph's line, and 0 of 41 lines away from a fresh whole layout. PhonePaginationTests runs a 20-page document through a Return, a deleted paragraph, a paste, typing and deleting. After each edit it checks: no line in a gap or across a bottom margin, every break where it was placed, and every line where a whole layout puts it. Removing the break's space makes it fail.

The 72.7 pt caret: real, and fixed

On TextKit 1, UIKit ignored the custom container's push of each page's first line (the 72 pt top margin, plus 0.7 pt of font metrics). Glyphs and caret were both drawn 72 pt above where the layout manager put the line: in paged and pageless modes, at the first line as at the end (testTheTextKit1CaretAtTheEnd: 72.60–72.67 pt).

So no iPhone page had a top margin, and the bottom margin was doubled. This is S0's "iPhone page-1 top margin missing". The probe saw it because it compared the caret with container coordinates. On TextKit 2 the margin is textContainerInset and the caret sits on its line. The iPad screenshot from the gate test shows page 1's margin.

The document (plan 1–7)

  • Navigation: the iPhone library is a NavigationStack root and pushes the document. The iPad keeps its NavigationSplitView, strip and toolbar items.
  • The large title and §6 subtitle are hosted in the text view's own scroll view (DocumentHeaderState). They fold into a two-line bar title (truncated, beside Back) on scroll, on the keyboard and with the Format sheet, and unfold only at the top with the keyboard down.
  • The bar: Back, the undo/redo pill, Aa and •••. Readers get Back and ••• only. There is no Share pill.
  • ••• holds Share…, Rename… (an alert), Export ▸, Word count, Open a document…, the Paged/Infinite pair, Help ▸ (Keyboard shortcuts…, Colophon) and Delete… (S2b's rules). What a capability forbids is absent; what needs the server is disabled offline.
  • The Format sheet opens at the .medium detent with background interaction. The keyboard goes (an empty inputView), and the text view keeps first responder and the selection. It holds the styles in their own faces (the chips wrap), font, the size stepper, marks, alignment, lists and indent, with two rows per section from AX1.
  • The keyboard bar is the writer's inputAccessoryView, so a hardware keyboard shows it too, at the bottom.

Acceptance

  • XCUITest (review-ios.py, iPhone 18 Pro, iOS 27.0): testPhoneDocumentForAWriter and testPhoneDocumentForAReader pass. They cover: - the keyboard bar with the keyboard, writers only; - Aa opening the sheet with the keyboard gone and hasKeyboardFocus still true, so the selection stays drawn; - folding on typing, on scroll and with the sheet, and unfolding at the top; - ••• per capability, owner and reader.
  • Hardware keyboard: covered by PhoneDocumentTests.testTheKeyboardBarAndTheFormatSheetsKeyboard (the bar is the input accessory, which iOS shows with a hardware keyboard), not by an XCUITest.
  • iPad: testIPadKeepsTodaysLayout passes on an iPad Pro 11-inch (M5) simulator, iOS 27.0, created for the check and deleted after.
  • VoiceOver: testAPeerEditElsewhereMovesNeitherTheCaretNorTheScroll passes.
  • Accessibility: performAccessibilityAudit() passes on the document, the document with the keyboard, the Share sheet and the Format sheet, for writer and reader. What the audit found and was fixed: - Chrome fonts were fixed sizes. They now follow Dynamic Type on iOS (DocsType; the Mac keeps its sizes). - The Share panel's email field was not reachable on iOS. iOS had folded it into one unlabelled element, and the hidden placeholder-width text sat over it. This is fixed for S2b's panel too. - The Share heading clipped at large sizes (it now wraps on iPhone). Its icon buttons are 44 pt. - The style chips clipped (they now wrap: DocsFlowLayout). - The bar title now has the Large Content Viewer. - A short document could not scroll to its page's foot. This was the scroll-fold failure, and the fix is the contentSize above. - The two subtitles (large and bar) would each announce every change; the folded one no longer announces.
  • Audit exemptions, each commented in NativeUITests.audit: - The subtitle's hit region (a status line, not a control) and its Dynamic Type check (unreliable: the same build passed one run and failed the next). - The page text's Dynamic Type (spec §9: the page does not scale). - Disabled controls' contrast (Invite before an address; WCAG exempts inactive components). - The system keyboard's own issues (prediction cells, keys). - The navigation bar's Dynamic Type cap and truncation (spec §3: "title truncated"; Large Content Viewer). - Inside the Format sheet only: "text clipped" and the editor's contrast. iOS 26+ draws a medium-detent sheet inset and scaled by about 0.96 (a 52 pt chip measures 49.9 pt), and the audit samples the sheet's pixels within the text view's frame.
  • Performance: see above. The iOS §7 counters hold: the whole iPhone unit suite passes.
  • Gates: - iPhone unit suite (DocsPhoneTests): 26 tests, 0 failures, 4 skipped (the env-gated probes). - Mac swift test: 274 tests, 0 failures, 14 skipped. - Snapshots: iPhone recorded and reviewed (docs-phone, docs-phone-ax3 new; docs-editor iPhone pictures change with TextKit 2); Mac compares clean.

New string keys

These are in all 12 catalogues, drafted (copy review later, #171): native.more, native.keyboard.hide, native.format.size.smaller, native.format.size.larger, native.back, docs.editor.menu.help.

Deviations

  • Breaks are per paragraph, not geometric. A paragraph taller than a page's body runs over the gap.
  • The iPad is on TextKit 2 too. It uses the same text view, so it gets the same paragraph breaks and the top-margin fix; its chrome is unchanged.
  • The bar title sits beside Back, not centred. iOS 26+ drops a centred principal item when the trailing controls leave it no room. It gets about 45 pt, so long titles truncate hard ("Nat…").
  • The Format and Share sheets are snapshotted as components (the sheet's content at the phone's width), not presented.
  • List markers are now drawn on iPhone (TextKit 2 draws NSTextList markers).
  • Already on main, not new: Arabic body text is left-aligned, because the projection sets .left.

For Paul

  1. The collapsed bar title gets only about 45 pt beside the undo/redo pill, Aa and •••. Is that enough, or should the pill fold into ••• while the title is in the bar?
  2. At AX3 the Share sheet's addresses truncate hard ("ali…om") and the role wraps under them. Should the row stack (address above role) at accessibility sizes?
LLM

iPhone editor on TextKit 2 (open 159–168 ms, keys 6.4 ms median / 12.7 ms max at p200h); the 72.7 pt caret was real and is fixed; iPhone document chrome, ••• menu, Format sheet, keyboard bar; audits pass.

Review by Claude Fable (claude-fable-5-2) of b9285e5 — verdict: APPROVE AFTER FIXES. Read-only, plus two macOS NSTextContentStorage probes. No path found where break space, list markers or TK2 offsets reach the CRDT or export. Undo stays in the model. No observation loops.

Fix before merge:

  1. High DocsPhonePages.swift:156, DocsPagedTextView.swift:378-385: any edit above the viewport invalidates layout from that paragraph to the end and lays out from the top through the screen. A peer typing on page 2 while you're on page 150 costs ~465 ms of main thread per peer key. Re-measure the edited paragraphs first, and skip the invalidation when the head, height and tail are unchanged. Add a p200h "peer key above the viewport" timing.
  2. High (unconfirmed) DocsPhonePages.swift:280-297: applyChanges() issues storage.edited(.editedAttributes…) with no marked-text check. During ja/zh composition, a break moving onto the paragraph being composed edits it mid-composition. Skip while markedTextRange != nil and run it when composition ends. Add a test.

Should fix:

  1. Medium DocsWorkspace.swift:704-720: formatting / header.sheetOpen leak across Back, swipe, Delete, Discard and losing .writable. ••• presentations are likely dropped while the Format sheet is up. Reset in showLibrary(), on disappear, on losing writable, and before each ••• action. Reapply suppression in attach on an editorIdentity change.
  2. Medium (unconfirmed) DocsPhoneHeader.swift:104-113: the hosted large title probably picks up a top safe-area inset under the bar. Use safeAreaRegions = []. The same applies to the keyboard bar host; exercise the hardware-keyboard case for real.
  3. Low DocsPagedTextView.swift:405-414: the idle measuring loop has no no-progress exit (empty storage spins every 2 ms).
  4. Low: the rename alert ignores a commitRename() refusal (:725); a draft re-push after Back (:200, as on main); dead storage in DocsPageTextContainer (DocsPaging.swift:75).

Note: the perf numbers are synchronous main-thread time, which is sound, but keys are injected via replaceCharacters with a stubbed edit hook, drawing is excluded, and idle chunks aren't counted. The AX3 share snapshot needs checking for 28 pt circle clipping now that fonts scale.

For Paul: per-paragraph breaks on iPhone and iPad mean page numbers no longer match the Mac or PDF, long paragraphs leave big gaps, and a paragraph taller than the page body runs over the gap.

Fixes after Fable's review, on native/iphone-document at de7bd1b. One commit per item. Each has a test that failed without it, unless noted.

Required

1. A peer's key above the screen (589c1af).

The old path laid out everything again from the edit down to the screen: about 465 ms per peer key at p200h. TextKit 2 doesn't move the fragments below one that changed. Until something walks them from the top, it places the screen at an estimate, and UIKit scrolls to keep that estimate still. A walk over fragments already laid out lays out no line again. So now:

  • editedFrom means "restack below here". Edits and rebuilt breaks set it; a walk through it clears it.
  • Throwing layout away is only for a screen past what is laid out (a jump, the spec's §7 fallback).
  • An edit above the screen is handled before UIKit lays the screen out (restackEdits). The edited paragraphs are measured on their own (a run of holes at a time, never everything down to the screen), the breaks are placed, and a walk goes through the screen.
  • The screen's first fragment is kept where it was on screen, so a peer's edit above moves nothing you are reading. That holds even when a line cascades page breaks down to the screen.
  • On a key, only breaks through the screen's end are rebuilt; the rest wait for idle.

Fable's other suggestion, changing a break's space in place instead of rebuilding its fragment, doesn't work: 342 of 344 breaks went off. TextKit 2 restacks after a fragment only once that fragment has been laid out again.

Timing at p200h: a peer's 20 keys on page 2, screen at the middle, through the surface's publication path, three runs at load 9–10:

| | Before | After | |---|---|---| | Per peer key, median | ~465 ms | 13.2–13.6 ms (8.7–8.9 ms of it is the surface's publication) | | Worst peer key moving ≤ 1 break | ~465 ms | 15.8–17.2 ms (median of three: 16.5 ms) | | A line cascading 40 breaks above the screen | ~465 ms | 29.7–31.0 ms, once | | Paragraphs laid out again from the top | 1,000+ | 0 |

  • The screen's text didn't move on any key.
  • The cascade costs about 0.4 ms per moved break: each one rebuilds its paragraph's fragment.
  • The publication (block diffing and the storage edit) is a fixed 8–9 ms per peer change and predates S3. That's a follow-up in DocumentSurface, not this slice.
  • Local typing, open and jump are unchanged: - open 160–165 ms (12 of 1,260 paragraphs laid out); - keys median 6.5–6.9 ms, max 9.5–10.5 ms; - jump 478–482 ms, 0 breaks misplaced, 0 of 41 lines off.

Tests:

  • PhonePaginationTests.testAPeersKeysAboveTheScreenLayOutOnlyTheirParagraph: 20 pages, peer keys published above the screen. It checks that nothing is laid out again (it was 113 paragraphs per key before), the screen doesn't scroll or move, and its lines and breaks match a whole layout.
  • PhoneLargeDocumentTests adds the p200h peer-key timing and asserts the screen stays put on every key.

2. Page breaks wait for a composition to end (a6fb328). While there is marked text, the text view holds break rebuilds, at every call site. When the composition ends it lays out again, which builds them.

Test: testABreakWaitsForACompositionToEnd composes Japanese marked text (setMarkedText, as an IME does) at the end of the paragraph carrying the first break's space, adding a line.

  • No break is rebuilt during the composition (one was before), and the marked text survives.
  • After unmarkText, the break is built and the screen matches a whole layout.
  • Not confirmed with a live ja keyboard on the simulator.

Should fix

3. Format sheet state (d80b589).

  • closeFormatting() closes the sheet and undoes at once what it changed: keyboard suppression, the inset and sheetOpen. It runs from showLibrary(), on disappear and when access stops being writable. It can't rely on onChange, because a view that has gone runs none; the Back step below failed for exactly that reason.
  • Every ••• action closes the sheet first and runs in its onDismiss.
  • The surface remembers the suppression and the sheet's height, and gives both to a text view it attaches.

Tests:

  • testANewTextViewUnderTheSheetKeepsItsState (failed before).
  • The writer XCUITest opens Word count from ••• with the sheet up: the sheet goes, the count comes and the keyboard returns.
  • It also goes Back with the sheet up: no sheet on return, and the keyboard comes back rather than an empty input view.

4. safeAreaRegions = [] on the large title's host and the keyboard bar's host (681b884).

  • Test: testTheHostedChromeIgnoresTheSafeArea (failed before).
  • I couldn't measure the effect itself in a unit test. SwiftUI builds no accessibility tree there, so the bar's element positions can't be read.
  • The live hardware-keyboard case (I/O ▸ Keyboard) was not exercised. It's a Simulator.app menu, and the shared simulator isn't this session's to reconfigure.

5. Idle measuring ends on a pass that gets nowhere (66ce9e4). That covers an empty document, and breaks held for a composition. Test: testIdleMeasuringStopsWhenItGetsNowhere (failed before: the loop kept running).

6. (67bf324)

  • Rename: a refused rename brings the alert back, once the answered one has gone, with the title as typed and why. "That title is too long." covers the server's 1,024 bytes (new key native.rename.tooLong, drafted, in all 12 catalogues); otherwise it shows the model's error. The writer XCUITest covers it.
  • Dead storage: DocsPageTextContainer.storage is removed, and DocsPaging.swift is main's again.
  • AX3 share circles: the avatar and icon circles now scale with their letters (they clipped at AX3).
  • Not done: the draft re-push after Back (:200, as on main).

Rulings

  • (a) (01fdf4e): while the title is folded, the undo/redo pill leaves the bar and Undo and Redo head •••. When the title unfolds, the pill is back. With the room freed, the folded title is centred again and shows "Native review docu…" (it was "Nat…"). The writer XCUITest covers it.
  • (b) (0993c5a, baselines de7bd1b): at accessibility sizes, each person's row in Share stacks the address (up to three lines) above the role and ×. - SwiftUI hyphenates a long address when it wraps ("ex-ample.com"). There's no public SwiftUI switch for that, and inserting break hints would corrupt copied addresses.

Page breaks: the limitation, for Paul

Breaks on iPhone and iPad are per paragraph:

  • a paragraph that would cross a page's bottom margin starts the next page instead;
  • so page numbers don't match the Mac or the PDF;
  • a long paragraph can leave a large gap at the foot of a page;
  • a paragraph taller than a page's body starts at a page top and runs over the gap.

Line-level breaks would be a follow-up, not this slice.

Gates

  • iPhone unit suite: 31 tests, 0 failures (4 are the env-gated probes, skipped).
  • Mac swift test: 274 tests, 0 failures.
  • Writer and reader XCUITests pass.
  • Snapshots: - iPhone: only the AX3 Share sheet changed, and it was re-recorded and reviewed. - Mac: compares clean.
  • The iPad gate was not re-run: no iPad-path code changed.

Correction to the gates line: the iPad uses the same text view, so fixes 1, 2 and 5 reach it too, and the pagination unit tests cover them. What wasn't re-run is the iPad layout gate (testIPadKeepsTodaysLayout), because its chrome is unchanged.

Delta review by Claude Fable (claude-fable-5-2) of b9285e5..de7bd1b — APPROVE AFTER FIXES. Read-only (the changed code is iOS-only). The restack is supported API: ensureLayout(for:) with a low-water mark, and no fragment origins are set by hand. The stored text is not at risk.

Required:

  • F1 The walk is only tested where a page break absorbs the shift, and keep() never moves the offset in a test. Add a peer line-add above the screen in unpaged mode, and one paged on the screen's top page. Assert the offset moves by the line height; run checkScreen, scroll a screen up and down, and run it again.
  • F2 DocsPagedTextView.swift:463: breaks deferred below the screen are rebuilt only if idle happens to be running. Text below sits over the gaps until scrolled to, and a jump applies the whole cascade with no anchor. Add || (pages.hasChanges && markedTextRange == nil) to the guard, and fix the README line.

Recommended in the same pass:

  • F3 :368: finish the restack at idle with ensureLayout(through: laidOutThrough), so editedFrom clears (stale bottom layout each scroll frame; a no-anchor fast scroll).
  • F5 (hand check) keep() sets contentOffset inside layoutSubviews during a drag or fling. Check for a one-frame jump with a peer typing a wrapping line above.

Follow-ups:

  • F4: anchor on the caret's fragment (else the middle of the screen), not the first visible fragment, when the screen straddles a break.
  • F6: a held-flag setNeedsLayout() on resign, or on a cancelled composition.
  • F7: clear renameRefusal/renamingAlert on disappear (the re-presented alert lands on the next document).
  • F8: a queued ••• action is dropped if the sheet never presented.

Perf: 17.15 ms within §7's allowance is acceptable but has no margin, and 16.7 ms is 60 Hz, so one run on a device is wanted. The publication's 8.8 ms is the larger cost now (a pre-existing follow-up).

Delta-review fixes on native/iphone-document at c4e6c8e. One commit per item. Each has a test that failed without it, unless noted.

F1 + F4 (290d609). F1's tests found the anchor wrong wherever no page break absorbs a peer's added line:

  • Unpaged: the screen scrolled −16.7 pt, the wrong way.
  • Paged, on the screen's top page: it didn't scroll, and the caret moved up a line.

The cause: the anchor was the fragment at viewportRange.location. That includes TextKit 2's overscan above the screen, so it could be the edited paragraph or a fragment that had been rebuilt.

The fix (F4): the anchor is now a character, recorded at the end of every layout.

  • It's the caret's character when the caret is on screen, otherwise the one at the screen's middle, together with where its line sits on screen.
  • Edits before it move it with the text.
  • After an edit above the screen's top, the screen scrolls so that line is back where it was.

Tests: testAPeersLineAboveTheScreenUnpaged and testAPeersLineOnTheScreensTopPage. The peer's change is published as the replica publishes it: a new generation, with the selection mapped past the insert. They check that:

  • the offset moves by the line height;
  • the caret stays where it was on screen;
  • checkScreen passes on the screen, one screen up, and the screen again.

F2 (c8f8c40). scheduleIdle also starts for breaks waiting below the screen, with nothing marked. The README line is fixed. Test: testIdleBuildsTheBreaksAKeyLeftBelowTheScreen. With idle settled first, a peer's lines leave breaks waiting below the screen; idle builds them with no scroll, and a jump to the end afterwards matches a whole layout.

F3 (0793e05). Idle also starts for a pending restack. Once nothing is left to measure, place or build, and typing has paused for 300 ms, it walks everything laid out (ensureLayout(through: laidOutThrough)), which clears editedFrom. Test: testIdleFinishesTheRestack. It failed before: three scroll steps meant three walks. There's a new probe, DocsProbes.restackWalks.

F6 (7df4608). A breaksHeld flag; releaseHeldBreaks() runs on resign, on text changes and on selection changes, once nothing is marked. No test fails without it. A unit test has no input system, so resigning leaves the marked text in place, and every other way a composition ends goes through unmarkText or edits the text, which lays out anyway.

F7 (30b6aee). closeFormatting() also clears renameRefusal and renamingAlert, and the delayed re-presentation checks it's still the same document. The writer XCUITest refuses a rename, goes Back at once, and checks there is no alert over the library or on reopening. That step doesn't fail without the fix. SwiftUI doesn't present an alert whose binding was already true when its view appears, so the stale state didn't show here.

F8 (134c492). The sheet records when it's on screen (formatShown). A ••• action runs immediately if the sheet was requested but never appeared. No test: a sheet that fails to present can't be arranged in a test.

F5, measured on a simulator I created, booted and deleted (dee1ecf). There's no way here to have a peer type during a person's gesture. So the review app has a probe (DOCS_REVIEW_DRAG_PROBE=1, review target only). While testDragProbe drags slowly and then flings, the probe moves contentOffset by +40 pt once, as keep() does, and samples the offset every frame with a CADisplayLink:

  • Drag: kept. About 3.3 pt per frame before; after the +40 frame: 3.3, 7.3, 0.0, 4.0, 7.7, 4.0, 0.0. That's the finger's pace with no snap back.
  • Fling: kept. About 25.7 pt per frame before; after: 23.0, 22.0, 21.7, 20.7, 20.0, 19.7, 18.7. The deceleration carries on; it neither stops nor reverses.

So there's no one-frame jump, and I didn't defer keep(). In the editor the correction lands in the same layout pass as the content shift it makes up for.

p200h re-run (three runs at load 10–11, plus a fourth after the probe fix below):

| | Result | |---|---| | Peer key, median | 11.5–11.8 ms (publication 7.5–7.7 ms) | | Worst peer key moving ≤ 1 break | 14.2–14.6 ms (fourth run: 15.3 ms) | | 40-break cascade | 27.7–28.9 ms | | Paragraphs laid out again | 0 | | Open | 156–165 ms | | Local keys | median 6.2 ms, max 10.1–10.5 ms | | Jump to the end | 455–476 ms; 0 breaks misplaced; 0 of 41 lines off |

  • The probe used to check that the screen's first line stays put; now it checks the line F4 keeps still (c4e6c8e). On key 0 a break between the screen's top and its middle moves the top but not the middle, as intended.
  • No physical device was available, so all timings are from the simulator.

Gates

  • iPhone unit suite: 35 tests, 0 failures (4 skipped: the env-gated probes).
  • Writer and reader XCUITests pass.
  • Snapshots: iPhone and Mac both compare clean.
  • Mac swift test: 274 tests, 0 failures.

The branch is behind main by the web P2 change (1d03856), which touches nothing native and merges clean.