oficina / docs Public

native: the iPhone document on TextKit 2 (S3)

Plan S3, spec 2026-11-22 §3, §6, §7, §9, §11. iPad keeps today's layout
until S5.

The editor. The iPhone and iPad text view is rebuilt on TextKit 2: a plain
NSTextContainer, so UIKit never falls 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 carried by the previous
paragraph's layout fragment. Measurements are fragment-local, because
TextKit 2 leaves stale origins below an edit. Opening lays out the first
screen only; idle chunks measure the rest; a jump lays out from the top
once (the §7 fallback). The content reaches the last page's foot through
contentSize, never the inset, which would re-lay out the screen per key.
p200h paged: open 159–168 ms with 11 of 1,260 paragraphs laid out; per key
median 6.4–6.5 ms, max 12.4–12.7 ms; 0 breaks misplaced, 0 lines away from
a whole layout (native/benchmarks/README.md).

The 72.7 pt caret was real: on TextKit 1, UIKit ignored the custom
container's push of each page's first line, so glyphs and caret were drawn
72 pt above the layout's lines everywhere; no iPhone page had a top
margin. On TextKit 2 the margin is textContainerInset.

The document. The library is a NavigationStack root and pushes the
document. The large title and subtitle are hosted in the text view's own
scroll view (DocumentHeaderState) and fold into a two-line bar title on
scroll, the keyboard and the Format sheet. The bar has back, the
undo/redo pill, Aa and •••; readers get back and ••• only. ••• holds
Share…, Rename (an alert), Export, Word count, Open, Paged/Infinite, Help
(shortcuts, Colophon) and Delete…, each per capability. 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 its
selection. The keyboard bar is the writer's inputAccessoryView.

Accessibility (the XCUITest audit on the document, keyboard, Share sheet
and Format sheet): chrome fonts follow Dynamic Type on iOS (DocsType); the
Share panel's email field is exposed again (iOS had folded it into an
unlabelled element), its heading wraps, its icon buttons are 44 pt; the
style chips wrap (DocsFlowLayout); the bar title has the Large Content
Viewer; a folded subtitle does not announce twice. The audit's remaining
exemptions are each commented in NativeUITests.

New strings (drafted, copy review later, #171): native.more,
native.keyboard.hide, native.format.size.smaller, native.format.size.larger,
native.back, docs.editor.menu.help.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 587f32fef16a6d13df41ec5a2d6ac89f12e76bea parent ec28e8f
37 files changed, +2,584 −190
  • internal/docs/native_review_test.go +7 −0
  • native/PARITY.md +1 −1
  • native/apple/Sources/DocsKit/DocsDesk.swift +15 −0
  • native/apple/Sources/DocsKit/DocsFontPicker.swift +3 −1
  • native/apple/Sources/DocsKit/DocsPagedTextView.swift +335 −49
  • native/apple/Sources/DocsKit/DocsPaging.swift +4 −1
  • native/apple/Sources/DocsKit/DocsPhoneDocument.swift +177 −0
  • native/apple/Sources/DocsKit/DocsPhoneFormat.swift +345 −0
  • native/apple/Sources/DocsKit/DocsPhoneHeader.swift +119 −0
  • native/apple/Sources/DocsKit/DocsPhonePages.swift +343 −0
  • native/apple/Sources/DocsKit/DocsProbes.swift +8 −1
  • native/apple/Sources/DocsKit/DocsSharePanel.swift +46 −13
  • native/apple/Sources/DocsKit/DocsSubtitle.swift +16 −4
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +153 −6
  • native/apple/Sources/DocsKit/DocumentSurface.swift +32 −1
  • native/apple/Sources/DocsKit/NativeDocumentTextView.swift +16 −2
  • native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings +8 −0
  • native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings +8 −0
  • native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift +19 −0
  • native/apple/Tests/DocsKitTests/PhoneDocumentTests.swift +107 −0
  • native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift +263 −110
  • native/apple/Tests/DocsKitTests/PhonePaginationTests.swift +113 −0
  • native/apple/Tests/DocsSnapshots/EditorSnapshots.swift +2 −1
  • native/apple/Tests/DocsSnapshots/PhoneSnapshots.swift +143 −0
  • native/benchmarks/README.md +35 −0
  • native/ios/UITests/NativeUITests.swift +184 −0
  • native/ios/project.yml +2 −0

CI cancelled — superseded by a newer push — run details

diff --git a/internal/docs/native_review_test.go b/internal/docs/native_review_test.go
index be1578b..c4c2177 100644
--- a/internal/docs/native_review_test.go
+++ b/internal/docs/native_review_test.go
@@ -25,6 +25,13 @@ func TestNativeReviewFixture(t *testing.T) {
browser := signInCookies(t, app, "native-review@example.test")
sqid := createDoc(t, app, browser, "Native review document")
createDoc(t, app, browser, "Second review document")
+ // A reader's document (Docs native S3: the iPhone's reader chrome):
+ // another person's, shared with the reviewer to read.
+ other := app.TestPerson(t, "native-review-owner@example.test")
+ readOnly := app.TestCreatePrivate(t, other, "Read-only review document")
+ if err := app.Store().Grant(t.Context(), other, readOnly.Sqid, "native-review@example.test", docs.RoleReader); err != nil {
+ t.Fatal(err)
+ }
owner := app.TestPerson(t, "native-review@example.test")
doc, err := app.Store().Get(t.Context(), owner, sqid)
if err != nil {
diff --git a/native/PARITY.md b/native/PARITY.md
index 4ba7a82..e83e6a3 100644
--- a/native/PARITY.md
+++ b/native/PARITY.md
@@ -16,7 +16,7 @@ CRDT engine. No web editor or HTML rendering engine is embedded.
| Rich paste and copy, pasted links/images/rules/code/H4–6 | Native clipboard schema/HTML parser, attributed projection and attachments | Clipboard schema tests, actual WASM paste then immediate typing; newest UIKit clipboard flow pending |
| Own-edit undo/redo | Authoritative own-origin undo with native responder routing | Peer-update undo tests, command tests; newest standard Mac menu behavior pending interactive acceptance |
| Live collaboration and reconnect | Bounded authenticated SSE and incremental Yjs updates | Native/browser wire fixture and generation/anchor/rollback tests; expanded simultaneous live UI session pending |
-| Pages/pageless, word count and shortcut help | Native TextKit page geometry and SwiftUI tools | Real glyph geometry tests; iPad screenshot review; counts exclude inline atoms |
+| Pages/pageless, word count and shortcut help | Mac: TextKit 1 page geometry, breaks by block (S1b). iPhone and iPad (S3): TextKit 2, which lays out only what is on screen; breaks by paragraph (`DocsPhonePages`), a paragraph taller than a page's body running over the gap. SwiftUI tools | Real glyph geometry tests; `PhoneLargeDocumentTests` (200 pages: open, typing, a jump to the end against a whole layout); iPad screenshot review; counts exclude inline atoms |
| Sharing and once-only public URL | The web's Share panel (`docs.share.panel.*`): a popover under Share… on the Mac, a sheet on iPhone; invite, remove, team and link switches that hold and revert, the once-only URL kept only in the panel's memory (S2b) | Real backend capability tests; `DocsSharePanelModelTests`; `SharePopoverTests` (real clicks and keys in a hosted window: focus, Share… while open, outside click with and without the URL, Esc); physical-device pass pending |
| Delete… (owners) | File ▸ Delete… on the Mac, the toolbar on iPhone until S3's •••; the server's `{"ok":true}`, or a check of `/d/{sqid}` for anything else (an older server's 303, a 404); only a deleted answer drops the lane and replica (S2b) | Go matrix (`delete_native_test.go`, `TestTeamNativeDelete`); `DocsDeletionTests`; the window closing and File ▸ Recent forgetting it are not covered by a hosted test |
| PDF/Markdown export, PDF print | Bounded streaming export to native destinations | Real iPad PDF and Markdown picker/cancel tests, staging cleanup; actual destination write/print dialog acceptance pending |
diff --git a/native/apple/Sources/DocsKit/DocsDesk.swift b/native/apple/Sources/DocsKit/DocsDesk.swift
index 9c255be..be2ae51 100644
--- a/native/apple/Sources/DocsKit/DocsDesk.swift
+++ b/native/apple/Sources/DocsKit/DocsDesk.swift
@@ -1,3 +1,4 @@
+import SwiftUI
import Foundation
#if os(macOS)
import AppKit
@@ -145,3 +146,17 @@ enum DocsSpacing {
static let sp5: CGFloat = 24
static let sp6: CGFloat = 40
}
+
+/// Type for the chrome: the Mac's fixed sizes (no Dynamic Type there), and
+/// on iPhone and iPad the text style of that size, which follows Dynamic
+/// Type to AX5 (spec §9). A fixed size on iOS is one the accessibility
+/// audit refuses.
+enum DocsType {
+ static func font(_ size: CGFloat, _ weight: Font.Weight = .regular, ios style: Font.TextStyle) -> Font {
+ #if os(macOS)
+ .system(size: size, weight: weight)
+ #else
+ .system(style, weight: weight)
+ #endif
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocsFontPicker.swift b/native/apple/Sources/DocsKit/DocsFontPicker.swift
index afce75f..b642c61 100644
--- a/native/apple/Sources/DocsKit/DocsFontPicker.swift
+++ b/native/apple/Sources/DocsKit/DocsFontPicker.swift
@@ -98,11 +98,13 @@ struct DocsFontPickerButton: View {
let selected: String
let choose: (String) -> Void
@State private var open = false
+ /// The family's name scales with Dynamic Type, in its own face (spec §9).
+ @ScaledMetric(relativeTo: .body) private var scale: CGFloat = 1
var body: some View {
let entries = DocsFontPicker.entries
let current = entries.first { $0.key == selected } ?? entries[0]
Button { open = true } label: {
- Text(current.name).font(Font(current.font as CTFont)).lineLimit(1).frame(minWidth: 80, alignment: .leading)
+ Text(current.name).font(Font(current.font.withSize(current.font.pointSize * scale) as CTFont)).lineLimit(1).frame(minWidth: 80, alignment: .leading)
}
.accessibilityLabel(Text("native.font", bundle: DocsResources.bundle))
.accessibilityValue(Text(current.name))
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
index a63db50..df113ce 100644
--- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift
+++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
@@ -177,69 +177,355 @@ import AppKit
#else
import UIKit
-@MainActor class DocsPagedTextView: UITextView {
- var paged = false { didSet { if oldValue != paged { setNeedsLayout(); setNeedsDisplay() } } }
- private var updatingGeometry = false
- override init(frame: CGRect = .zero, textContainer: NSTextContainer? = nil) {
- let storage = NSTextStorage()
- let manager = NSLayoutManager()
- manager.usesFontLeading = false
- let pages = DocsPageTextContainer(size: CGSize(width: max(320, frame.width), height: 1_000_000))
- pages.lineFragmentPadding = 0
- storage.addLayoutManager(manager)
- manager.addTextContainer(pages)
- super.init(frame: frame, textContainer: pages)
- textContainerInset = .zero
- backgroundColor = .clear
+/// The iPhone's text view, on TextKit 2 (S3; spec 2026-11-22 §7 "iPhone
+/// layout" and the S1b ruling on #173). TextKit 1 laid the whole document
+/// out at open and again inside any edit that changed a line count (1.27 s
+/// and 0.48 s at 200 pages); TextKit 2 lays out what is on screen, and an
+/// edit lays out its own paragraph again.
+///
+/// The container is a plain rectangle, as wide as the page's text: UIKit
+/// runs a text view whose container overrides `lineFragmentRect` on
+/// TextKit 1, so the page breaks are `DocsPhonePages`'s, per paragraph, made
+/// by the layout fragments this view's layout delegate hands TextKit 2.
+/// The paper is views behind the text, only the pages on screen.
+///
+/// TextKit 1 also drew every line 72 pt above where its container placed it
+/// (UIKit took the first line's origin as the text's top, dropping the top
+/// margin the container added), so no iPhone page had a top margin and the
+/// caret probe read 72.7 pt above its line (#173). The insets here carry
+/// the margin instead.
+///
+/// Nothing here may touch `layoutManager`: asking for it switches the view
+/// back to TextKit 1 for good.
+@MainActor class DocsPagedTextView: UITextView, @preconcurrency NSTextLayoutManagerDelegate {
+ var paged = false { didSet { if oldValue != paged { pagedChanged() } } }
+ /// The height above the first page: the iPhone's large title, hosted
+ /// in this scroll view (S3, spec §3), or nothing.
+ var headerHeight: CGFloat = 0 { didSet { if abs(oldValue - headerHeight) > 0.25 { applyInsets() } } }
+ /// What covers the bottom of the view (the Format sheet): the text can
+ /// scroll clear of it.
+ var bottomObstruction: CGFloat = 0 { didSet { if abs(oldValue - bottomObstruction) > 0.25 { setNeedsLayout() } } }
+ private(set) var geometry = DocsPageGeometry(viewportWidth: 402, paged: false)
+ let pages = DocsPhonePages()
+ private var firstMargin: CGFloat = 0
+ private var pageViews: [Int: DocsPageView] = [:]
+ private var paginating = false
+ private var idle: Task<Void, Never>?
+
+ /// The iPhone's large title, hosted above the text (S3); nil on iPad
+ /// and in tests.
+ var header: DocsPhoneHeaderHost? {
+ didSet {
+ oldValue?.view.removeFromSuperview()
+ guard let header else { headerHeight = 0; return }
+ addSubview(header.view)
+ header.heightChanged = { [weak self] height in
+ guard let self, abs(height - self.headerHeight) > 0.5 else { return }
+ self.headerHeight = height
+ }
+ headerHeight = header.height(forWidth: max(160, bounds.width))
+ // A Dynamic Type change measures the title again (spec §9).
+ if headerTraits == nil {
+ headerTraits = registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: DocsPagedTextView, _: UITraitCollection) in
+ guard let header = view.header else { return }
+ view.headerHeight = header.height(forWidth: max(160, view.bounds.width))
+ view.setNeedsLayout()
+ }
+ }
+ }
+ }
+ private var headerTraits: (any UITraitChangeRegistration)?
+ /// The keyboard bar (writers only, S3): shown above the keyboard while
+ /// the text view has it, and not while the Format sheet is open.
+ var keyboardBar: UIView? { didSet { updateAccessory() } }
+ var showsKeyboardBar = false { didSet { if oldValue != showsKeyboardBar { updateAccessory() } } }
+ /// The Format sheet is open: the keyboard goes but the text view keeps
+ /// first responder, so the selection stays visible above the sheet
+ /// (spec §3, "The selection stays visible").
+ var keyboardSuppressed = false {
+ didSet {
+ guard oldValue != keyboardSuppressed else { return }
+ inputView = keyboardSuppressed ? UIView(frame: .zero) : nil
+ updateAccessory()
+ if isFirstResponder { reloadInputViews() }
+ }
+ }
+ private func updateAccessory() {
+ let wanted = showsKeyboardBar && !keyboardSuppressed ? keyboardBar : nil
+ guard inputAccessoryView !== wanted else { return }
+ inputAccessoryView = wanted
+ if isFirstResponder { reloadInputViews() }
+ }
+
+ override func becomeFirstResponder() -> Bool {
+ let became = super.becomeFirstResponder()
+ if became { reportEditing(true) }
+ return became
+ }
+ override func resignFirstResponder() -> Bool {
+ let resigned = super.resignFirstResponder()
+ if resigned { reportEditing(false) }
+ return resigned
+ }
+ /// Told on the next turn: a responder change can happen inside a
+ /// SwiftUI update, where observed state must not change.
+ private func reportEditing(_ editing: Bool) {
+ guard let state = header?.state else { return }
+ DispatchQueue.main.async { if state.editing != editing { state.editing = editing } }
+ }
+ private func reportScroll() {
+ guard let state = header?.state else { return }
+ let past = contentOffset.y + adjustedContentInset.top > max(8, headerHeight - 8)
+ guard past != state.scrolledPast else { return }
+ DispatchQueue.main.async { if state.scrolledPast != past { state.scrolledPast = past } }
+ }
+
+ init(frame: CGRect = .zero) {
+ let container = NSTextContainer(size: CGSize(width: max(160, frame.width), height: 0))
+ container.lineFragmentPadding = 0
+ container.widthTracksTextView = true
+ let layout = NSTextLayoutManager()
+ layout.textContainer = container
+ let content = NSTextContentStorage()
+ content.addTextLayoutManager(layout)
+ content.primaryTextLayoutManager = layout
+ super.init(frame: frame, textContainer: container)
+ pages.storage = textStorage
+ layout.delegate = self
+ backgroundColor = .systemGroupedBackground
textColor = .black
- isOpaque = false
+ alwaysBounceVertical = true
+ applyInsets()
}
required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+
+ // MARK: Geometry
+
+ private func applyInsets() {
+ let width = max(160, bounds.width)
+ let left = geometry.textX
+ let right = max(0, width - geometry.textX - geometry.textWidth)
+ // The header, then the first page's top margin (and the first
+ // block's own), above the text; the page's bottom margin below it.
+ let insets = UIEdgeInsets(top: headerHeight + DocsPageGeometry.verticalMargin + firstMargin, left: left,
+ bottom: DocsPageGeometry.verticalMargin, right: right)
+ if insets != textContainerInset { textContainerInset = insets }
+ pages.origin = firstMargin
+ setNeedsLayout()
+ }
+ private func pagedChanged() {
+ pages.paged = paged
+ if paged { pages.restartSettling() } else { pages.clearBreaks() }
+ setNeedsLayout()
+ }
+ private func updateGeometry() {
+ let width = max(160, bounds.width)
+ let next = DocsPageGeometry(viewportWidth: width, paged: paged)
+ let margin = (textStorage.length > 0 ? textStorage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat : nil) ?? 0
+ guard next != geometry || abs(margin - firstMargin) > 0.01 else { return }
+ let widthChanged = next.textWidth != geometry.textWidth
+ geometry = next; firstMargin = margin
+ if let header { headerHeight = header.height(forWidth: width) }
+ applyInsets()
+ // The text's width changed: every paragraph wraps anew.
+ if widthChanged { pages.forgetMeasurements() } else { pages.restartSettling() }
+ }
+
+ /// The text storage changed (DocumentSurface's storage delegate).
+ func storageEdited(_ edited: NSRange, delta: Int) {
+ pages.edited(edited, delta: delta)
+ setNeedsLayout()
+ }
+
override func layoutSubviews() {
#if DOCS_PROBES
let probeStart = DocsProbes.now()
defer { DocsProbes.textLayouts += 1; DocsProbes.textLayoutMs += DocsProbes.ms(since: probeStart) }
#endif
+ updateGeometry()
super.layoutSubviews()
- guard !updatingGeometry, let pages = textContainer as? DocsPageTextContainer else { return }
- updatingGeometry = true
- defer { updatingGeometry = false }
- let width = max(160, bounds.width)
- let size = CGSize(width: width, height: 1_000_000)
- if pages.size != size { pages.size = size }
- pages.geometry = DocsPageGeometry(viewportWidth: width, paged: paged)
- layoutManager.ensureLayout(for: pages)
- let height = pages.geometry.documentHeight(usedHeight: layoutManager.usedRect(for: pages).maxY)
- if abs(contentSize.height - height) > 0.5 || abs(contentSize.width - width) > 0.5 {
- contentSize = CGSize(width: width, height: height)
+ paginate()
+ 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()
}
- setNeedsDisplay()
}
- override func draw(_ rect: CGRect) {
- #if DOCS_PROBES
- let probeStart = DocsProbes.now()
- defer { DocsProbes.draws += 1; DocsProbes.drawMs += DocsProbes.ms(since: probeStart) }
- #endif
- UIColor.systemGroupedBackground.setFill()
- UIRectFill(rect)
- if let pages = textContainer as? DocsPageTextContainer {
- let geometry = pages.geometry
- if paged {
- for page in geometry.page(at: rect.minY)...geometry.page(at: rect.maxY) {
- UIColor.white.setFill()
- UIRectFill(geometry.pageRect(page))
- let label = String(localized: "docs.editor.page.number", bundle: DocsResources.bundle)
- .replacingOccurrences(of: "{n}", with: String(page + 1))
- (label as NSString).draw(at: CGPoint(x: geometry.paperX + geometry.paperWidth - 80,
- y: CGFloat(page) * geometry.stride + DocsPageGeometry.paperHeight - 35),
- withAttributes: [.font: UIFont.systemFont(ofSize: 10), .foregroundColor: UIColor.darkGray])
+
+ /// 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.
+ /// The rest is measured while idle.
+ private func paginate() {
+ guard !paginating, let layout = textLayoutManager, let content = layout.textContentManager else { return }
+ paginating = true
+ defer { paginating = false }
+ pages.rebuildIfStale()
+ // Breaks moving the text can bring other paragraphs on screen: look
+ // again, a few times at most.
+ for _ in 0..<3 {
+ 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)
+ }
+ pages.settle()
+ guard pages.hasChanges else { break }
+ pages.applyChanges()
+ pages.ensureLayout(through: end, in: layout)
+ layout.textViewportLayoutController.layoutViewport()
+ }
+ scheduleIdle()
+ }
+
+ /// 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 }
+ idle = Task { @MainActor [weak self] in
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .milliseconds(2))
+ guard let self, let layout = self.textLayoutManager else { return }
+ if let hole = self.pages.firstUnmeasured {
+ self.pages.measure(hole..<min(self.pages.paragraphs.count, hole + DocsPhonePages.chunk), in: layout)
}
- } else {
- UIColor.white.setFill()
- UIRectFill(CGRect(x: geometry.paperX, y: 0, width: geometry.paperWidth, height: max(bounds.height, contentSize.height)))
+ self.pages.settle()
+ if self.pages.hasChanges { self.pages.applyChanges(); self.setNeedsLayout() }
+ if self.pages.firstUnmeasured == nil && self.pages.settleFrom == nil { self.idle = nil; self.setNeedsLayout(); return }
}
}
- super.draw(rect)
+ }
+
+ /// Measures and places every paragraph now (tests: a whole layout).
+ func paginateEverything() {
+ guard let layout = textLayoutManager else { return }
+ while let hole = pages.firstUnmeasured {
+ pages.measure(hole..<pages.paragraphs.count, in: layout)
+ if pages.firstUnmeasured == hole { break }
+ }
+ pages.settle()
+ pages.applyChanges()
+ pages.ensureLayout(through: textStorage.length, in: layout)
+ layout.textViewportLayoutController.layoutViewport()
+ 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
+ override var contentSize: CGSize {
+ get { super.contentSize }
+ set { super.contentSize = CGSize(width: newValue.width, height: max(newValue.height, pageFoot)) }
+ }
+
+ /// The pages on screen, behind the text: white paper on the desk, and
+ /// its number. Only the visible ones exist. The content reaches the
+ /// last page's foot, and clears whatever covers the bottom.
+ private func tilePages() {
+ let geometry = self.geometry
+ let paperTop = headerHeight
+ let used = textLayoutManager?.usageBoundsForTextContainer.maxY ?? 0
+ let lastPage = paged ? geometry.page(at: max(0, firstMargin + used - 1) + DocsPageGeometry.verticalMargin) : 0
+ let wantedHeight = paged ? paperTop + CGFloat(lastPage + 1) * DocsPageGeometry.paperHeight + CGFloat(lastPage) * DocsPageGeometry.gap
+ : max(contentSize.height, paperTop + DocsPageGeometry.paperHeight)
+ // Only what covers the bottom moves the inset: changing it re-lays
+ // out the whole screen, so it never follows TextKit 2's height
+ // estimate (which moves with every key). The content reaches the
+ // last page's foot through `contentSize` instead, which lays out
+ // nothing.
+ if abs(contentInset.bottom - bottomObstruction) > 0.5 { contentInset.bottom = bottomObstruction }
+ let foot = paged ? wantedHeight : 0
+ if abs(foot - pageFoot) > 0.5 {
+ pageFoot = foot
+ // The text's own height, as the text view would set it.
+ contentSize = CGSize(width: contentSize.width, height: textContainerInset.top + used + textContainerInset.bottom)
+ }
+ if abs(verticalScrollIndicatorInsets.bottom - bottomObstruction) > 0.5 { verticalScrollIndicatorInsets.bottom = bottomObstruction }
+ let visible = CGRect(x: 0, y: contentOffset.y - paperTop, width: bounds.width, height: bounds.height)
+ var wanted: [Int: CGRect] = [:]
+ if paged {
+ let first = geometry.page(at: max(0, visible.minY)), last = min(lastPage, geometry.page(at: max(0, visible.maxY)))
+ if first <= last { for page in first...last { wanted[page] = geometry.pageRect(page).offsetBy(dx: 0, dy: paperTop) } }
+ } else {
+ wanted[0] = CGRect(x: geometry.paperX, y: paperTop, width: geometry.paperWidth, height: max(wantedHeight - paperTop, bounds.height))
+ }
+ for (page, view) in pageViews where wanted[page] == nil { view.removeFromSuperview(); pageViews[page] = nil }
+ for (page, frame) in wanted {
+ let view = pageViews[page] ?? {
+ let made = DocsPageView()
+ insertSubview(made, at: 0)
+ pageViews[page] = made
+ return made
+ }()
+ if view.frame != frame { view.frame = frame }
+ view.number = paged ? page + 1 : nil
+ if subviews.first !== view { sendSubviewToBack(view) }
+ }
+ }
+
+ // MARK: TextKit 2
+
+ /// The layout fragments TextKit 2 makes: what laying out costs (spec §7's
+ /// line-request counter, in TextKit 2's unit: one per paragraph laid out).
+ func textLayoutManager(_ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: any NSTextLocation,
+ in textElement: NSTextElement) -> NSTextLayoutFragment {
+ #if DOCS_PROBES
+ DocsProbes.layoutFragments += 1
+ #endif
+ guard paged, let content = textLayoutManager.textContentManager else {
+ return NSTextLayoutFragment(textElement: textElement, range: textElement.elementRange)
+ }
+ // A paragraph that starts a page carries the break's space (DocsPhonePages).
+ return pages.fragment(for: content.offset(from: content.documentRange.location, to: location), element: textElement)
+ }
+}
+
+/// One sheet of paper behind the text, with its page number.
+final class DocsPageView: UIView {
+ var number: Int? {
+ didSet {
+ guard oldValue != number else { return }
+ label.text = number.map { String(localized: "docs.editor.page.number", bundle: DocsResources.bundle).replacingOccurrences(of: "{n}", with: String($0)) }
+ label.isHidden = number == nil
+ setNeedsLayout()
+ }
+ }
+ private let label = UILabel()
+ override init(frame: CGRect) {
+ super.init(frame: frame)
+ backgroundColor = .white
+ isUserInteractionEnabled = false
+ isAccessibilityElement = false
+ label.font = .systemFont(ofSize: 10)
+ label.textColor = .darkGray
+ label.isHidden = true
+ addSubview(label)
+ }
+ required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ label.sizeToFit()
+ label.frame.origin = CGPoint(x: bounds.width - 80, y: DocsPageGeometry.paperHeight - 35 - label.bounds.height / 2)
}
}
#endif
diff --git a/native/apple/Sources/DocsKit/DocsPaging.swift b/native/apple/Sources/DocsKit/DocsPaging.swift
index a20c929..a876f33 100644
--- a/native/apple/Sources/DocsKit/DocsPaging.swift
+++ b/native/apple/Sources/DocsKit/DocsPaging.swift
@@ -72,6 +72,9 @@ final class DocsPageTextContainer: NSTextContainer {
}
/// A layout stack that measures and never draws (probe counts only).
var isMeasurement = false
+ /// The text, when no TextKit 1 layout manager holds it (the iPhone's
+ /// TextKit 2 view, S3).
+ weak var storage: NSTextStorage?
override var isSimpleRectangularTextContainer: Bool { false }
override func lineFragmentRect(
forProposedRect proposedRect: CGRect, at characterIndex: Int,
@@ -86,7 +89,7 @@ final class DocsPageTextContainer: NSTextContainer {
#if os(macOS)
if let top = tops?.top(at: characterIndex) { rect.origin.y = max(rect.minY, top) }
#endif
- if let storage = layoutManager?.textStorage, characterIndex < storage.length {
+ if let storage = layoutManager?.textStorage ?? storage, characterIndex < storage.length {
if characterIndex == 0, let margin = storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat {
rect.origin.y = max(rect.minY, DocsPageGeometry.verticalMargin + margin)
}
diff --git a/native/apple/Sources/DocsKit/DocsPhoneDocument.swift b/native/apple/Sources/DocsKit/DocsPhoneDocument.swift
new file mode 100644
index 0000000..717e1bd
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsPhoneDocument.swift
@@ -0,0 +1,177 @@
+#if os(iOS)
+import RastrilloApple
+import SwiftUI
+
+/// What the iPhone document's ••• menu and controls ask of the window.
+struct DocsPhoneActions {
+ var share: () -> Void = {}
+ var rename: () -> Void = {}
+ var export: (String) -> Void = { _ in }
+ var wordCount: () -> Void = {}
+ var openDocument: () -> Void = {}
+ var shortcuts: () -> Void = {}
+ var colophon: () -> Void = {}
+ var delete: () -> Void = {}
+ var format: () -> Void = {}
+}
+
+/// The bar's trailing controls (spec §3): the undo/redo pill, Aa and •••
+/// for a writer; ••• alone for a reader. No Share pill (Paul's ruling 4):
+/// Share lives in •••. Their own view, reading the access, the history and
+/// the connectivity, so the text view's host reads none of them.
+@MainActor struct DocsPhoneDocumentControls: View {
+ let model: DocsModel
+ let origin: URL
+ @Binding var paged: Bool
+ let actions: DocsPhoneActions
+ var body: some View {
+ HStack(spacing: DocsSpacing.sp2) {
+ if model.documentAccess == .writable {
+ DocsPhoneUndoRedoPill(model: model)
+ Button(action: actions.format) {
+ Text(verbatim: "Aa").font(.body.weight(.semibold)).frame(minWidth: 44, minHeight: 44)
+ }
+ .accessibilityLabel(Text("docs.editor.inspector.toggle", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.format.toggle")
+ }
+ DocsPhoneMoreMenu(model: model, origin: origin, paged: $paged, actions: actions)
+ }
+ }
+}
+
+/// Undo and redo in one pill, each enabled from the history.
+@MainActor struct DocsPhoneUndoRedoPill: View {
+ let model: DocsModel
+ var body: some View {
+ let history = model.history
+ HStack(spacing: 0) {
+ button("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: history.canUndo)
+ Rectangle().fill(OficinaPalette.line).frame(width: 1, height: 20)
+ button("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: history.canRedo)
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text("docs.editor.toolbar.history", bundle: DocsResources.bundle))
+ }
+ private func button(_ key: String, icon: String, op: String, enabled: Bool) -> some View {
+ Button {
+ DocumentCommands(model: model, content: model.surface.content).perform(op)
+ } label: {
+ Image(systemName: icon).font(.body.weight(.semibold))
+ .flipsForRightToLeftLayoutDirection(true)
+ .frame(minWidth: 44, minHeight: 44)
+ }
+ .disabled(!enabled)
+ .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs." + op)
+ }
+}
+
+/// ••• (spec §3): the web's File, View, Tools and Help, in that order. What
+/// a capability forbids is absent, not disabled; what needs the server waits
+/// while the origin is offline (disabled, as the Mac's menus are).
+@MainActor struct DocsPhoneMoreMenu: View {
+ let model: DocsModel
+ let origin: URL
+ @Binding var paged: Bool
+ let actions: DocsPhoneActions
+ var body: some View {
+ let offline = model.connectivity.isOffline(origin)
+ let owner = model.detail?.can_share == true && !model.isDraft && model.documentAccess != .unavailable
+ let writer = model.documentAccess == .writable
+ let saved = model.detail != nil && !model.isDraft
+ Menu {
+ Section {
+ if owner {
+ Button(action: actions.share) { Label { Text("docs.share.action", bundle: DocsResources.bundle) } icon: { Image(systemName: "person.crop.circle.badge.plus") } }
+ .disabled(offline)
+ }
+ if writer {
+ Button(action: actions.rename) { Label { Text("docs.document.rename", bundle: DocsResources.bundle) } icon: { Image(systemName: "pencil") } }
+ }
+ }
+ Section {
+ if saved {
+ Menu {
+ Button { actions.export("pdf") } label: { Text("docs.export.pdf.label", bundle: DocsResources.bundle) }
+ Button { actions.export("markdown") } label: { Text("docs.export.markdown.label", bundle: DocsResources.bundle) }
+ Button { actions.export("print") } label: { Text("docs.editor.menu.file.print", bundle: DocsResources.bundle) }
+ } label: { Label { Text("native.export", bundle: DocsResources.bundle) } icon: { Image(systemName: "square.and.arrow.up") } }
+ .disabled(offline)
+ }
+ Button(action: actions.wordCount) { Label { Text("docs.editor.menu.tools.wordcount", bundle: DocsResources.bundle) } icon: { Image(systemName: "number") } }
+ .disabled(!model.showsDocument)
+ Button(action: actions.openDocument) { Label { Text("docs.editor.menu.file.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text.magnifyingglass") } }
+ Picker(selection: $paged) {
+ Text("docs.editor.menu.view.paged", bundle: DocsResources.bundle).tag(true)
+ Text("docs.editor.menu.view.infinite", bundle: DocsResources.bundle).tag(false)
+ } label: { EmptyView() }
+ .pickerStyle(.inline)
+ }
+ Section {
+ Menu {
+ Button(action: actions.shortcuts) { Text("docs.editor.menu.tools.shortcuts", bundle: DocsResources.bundle) }
+ Button(action: actions.colophon) { Text(verbatim: DocsColophonView.title) }
+ } label: { Label { Text("docs.editor.menu.help", bundle: DocsResources.bundle) } icon: { Image(systemName: "questionmark.circle") } }
+ if owner {
+ Button(role: .destructive, action: actions.delete) { Label { Text("docs.editor.menu.file.delete", bundle: DocsResources.bundle) } icon: { Image(systemName: "trash") } }
+ .disabled(offline)
+ }
+ }
+ } label: {
+ Image(systemName: "ellipsis").font(.body.weight(.semibold)).frame(minWidth: 44, minHeight: 44)
+ }
+ .accessibilityLabel(Text("native.more", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.more")
+ }
+}
+
+/// The iPhone's callouts under the bar (spec §6, banners): the session
+/// ended (rows 5 and 6), No longer available (row 1) with Back, and today's
+/// `errorKey` text with Try again. Their own view.
+@MainActor struct DocsPhoneCallouts: View {
+ let model: DocsModel
+ @Environment(\.locale) private var locale
+ let discard: () -> Void
+ let back: () -> Void
+ var signIn: () -> Void = {}
+ var body: some View {
+ VStack(spacing: DocsSpacing.sp2) {
+ if model.documentAccess != .unavailable, case .needsSignIn(let pending) = model.syncStatus {
+ let sync = NativeSyncStrings.kit
+ callout(Text(verbatim: pending > 0 ? sync.needsSignIn(pending) : DocsStrings(locale: locale)("native.subtitle.signedOut")), negative: true) {
+ Button { signIn() } label: { Text(verbatim: sync.signIn) }
+ }
+ }
+ if model.documentAccess == .unavailable {
+ callout(Text("native.unavailable.body", bundle: DocsResources.bundle), negative: true) {
+ Button(action: back) { Text("native.back", bundle: DocsResources.bundle) }
+ if model.hasUnsavedChanges {
+ Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
+ }
+ }
+ } else if let key = model.errorKey {
+ callout(Text(LocalizedStringKey(key), bundle: DocsResources.bundle), negative: false) {
+ Button { Task { await model.retry() } } label: { Text("native.retry", bundle: DocsResources.bundle) }
+ if model.hasUnsavedChanges {
+ Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
+ }
+ }
+ }
+ }
+ .padding(.horizontal, DocsSpacing.sp3)
+ }
+ private func callout<Actions: View>(_ text: Text, negative: Bool, @ViewBuilder actions: () -> Actions) -> some View {
+ VStack(alignment: .leading, spacing: DocsSpacing.sp2) {
+ text.font(.callout).foregroundStyle(negative ? OficinaPalette.negative : OficinaPalette.text)
+ .fixedSize(horizontal: false, vertical: true)
+ HStack(spacing: DocsSpacing.sp3) { actions() }.font(.callout.weight(.semibold))
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(DocsSpacing.sp3)
+ .background(RoundedRectangle(cornerRadius: 12).fill(negative ? OficinaPalette.negativeSoft : OficinaPalette.surface))
+ .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(OficinaPalette.line, lineWidth: 1))
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier(negative ? "docs.callout.negative" : "docs.callout.error")
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsPhoneFormat.swift b/native/apple/Sources/DocsKit/DocsPhoneFormat.swift
new file mode 100644
index 0000000..08d5807
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsPhoneFormat.swift
@@ -0,0 +1,345 @@
+#if os(iOS)
+import RastrilloApple
+import SwiftUI
+import UIKit
+
+/// What the iPhone document's text view needs from its window, created once
+/// per document window and compared by identity: the header's state, the
+/// keyboard bar's model, and how Aa opens the Format sheet.
+@MainActor final class DocsPhoneEditorChrome {
+ let model: DocsModel
+ let team: String?
+ let header = DocumentHeaderState()
+ /// Aa, from the keyboard bar.
+ var openFormat: () -> Void = {}
+ init(model: DocsModel, team: String?) { self.model = model; self.team = team }
+
+ /// The keyboard bar: a `UIInputView` hosting the SwiftUI capsule (spec
+ /// §3, "Keyboard bar"), never `ToolbarItemGroup(placement: .keyboard)`,
+ /// which does not attach reliably to a wrapped UITextView.
+ func makeKeyboardBar(hide: @escaping () -> Void) -> UIView {
+ let input = UIInputView(frame: CGRect(x: 0, y: 0, width: 320, height: 60), inputViewStyle: .keyboard)
+ input.allowsSelfSizing = true
+ let host = UIHostingController(rootView: DocsKeyboardBar(model: model, openFormat: { [weak self] in self?.openFormat() }, hide: hide))
+ host.view.backgroundColor = .clear
+ host.view.translatesAutoresizingMaskIntoConstraints = false
+ host.sizingOptions = [.intrinsicContentSize]
+ input.addSubview(host.view)
+ NSLayoutConstraint.activate([
+ host.view.leadingAnchor.constraint(equalTo: input.leadingAnchor),
+ host.view.trailingAnchor.constraint(equalTo: input.trailingAnchor),
+ host.view.topAnchor.constraint(equalTo: input.topAnchor),
+ host.view.bottomAnchor.constraint(equalTo: input.bottomAnchor),
+ ])
+ objc_setAssociatedObject(input, &DocsPhoneEditorChrome.hostKey, host, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ return input
+ }
+ nonisolated(unsafe) private static var hostKey = 0
+}
+
+/// The quick format bar above the keyboard, a writer's: Aa, Bold, Italic,
+/// Bulleted list, Numbered list, Quote, then Hide keyboard. Marks and lists
+/// show `.isSelected` from `DocumentToolbarSelection`; targets are 44pt, and
+/// at accessibility sizes the capsule scrolls rather than shrinking.
+@MainActor struct DocsKeyboardBar: View {
+ let model: DocsModel
+ let openFormat: () -> Void
+ let hide: () -> Void
+ var body: some View {
+ let selection = model.toolbarSelection
+ ScrollView(.horizontal) {
+ HStack(spacing: 0) {
+ button("docs.editor.inspector.toggle", identifier: "docs.keyboard.format", selected: false) {
+ Text(verbatim: "Aa").font(.body.weight(.semibold))
+ } action: { openFormat() }
+ symbol("docs.editor.toolbar.bold", "bold", identifier: "docs.keyboard.bold", selected: selection.marks.contains("strong")) { ready { $0.perform("bold") } }
+ symbol("docs.editor.toolbar.italic", "italic", identifier: "docs.keyboard.italic", selected: selection.marks.contains("em")) { ready { $0.perform("italic") } }
+ symbol("docs.editor.toolbar.bulletlist", "list.bullet", identifier: "docs.keyboard.bullets", selected: selection.blocks.contains("bullet_list")) { ready { $0.block("bullet_list") } }
+ symbol("docs.editor.toolbar.orderedlist", "list.number", identifier: "docs.keyboard.numbers", selected: selection.blocks.contains("ordered_list")) { ready { $0.block("ordered_list") } }
+ symbol("docs.editor.toolbar.quote", "text.quote", identifier: "docs.keyboard.quote", selected: selection.blocks.contains("blockquote")) { ready { $0.block("blockquote") } }
+ Rectangle().fill(OficinaPalette.line).frame(width: 1, height: 24).padding(.horizontal, DocsSpacing.sp1)
+ symbol("native.keyboard.hide", "keyboard.chevron.compact.down", identifier: "docs.keyboard.hide", selected: false) { hide() }
+ }
+ .padding(.horizontal, DocsSpacing.sp1)
+ .background(Capsule().fill(OficinaPalette.surface).shadow(color: .black.opacity(0.12), radius: 8, y: 2))
+ .padding(.horizontal, DocsSpacing.sp2)
+ .padding(.vertical, DocsSpacing.sp1)
+ }
+ .scrollIndicators(.hidden)
+ .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
+ .disabled(model.commandsHeld)
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("docs.keyboard.bar")
+ }
+
+ private func ready(_ command: @escaping @MainActor (DocumentCommands) -> Void) { model.whenCommandsReady(command) }
+
+ private func symbol(_ key: String, _ name: String, identifier: String, selected: Bool, action: @escaping () -> Void) -> some View {
+ button(key, identifier: identifier, selected: selected) {
+ Image(systemName: name).font(.body.weight(.medium))
+ } action: { action() }
+ }
+
+ private func button<Label: View>(_ key: String, identifier: String, selected: Bool, @ViewBuilder label: () -> Label, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ label()
+ .frame(minWidth: 44, minHeight: 44)
+ .foregroundStyle(selected ? OficinaPalette.accent(.docs) : OficinaPalette.text)
+ .background(Circle().fill(selected ? OficinaPalette.accentSoft(.docs) : .clear).frame(width: 38, height: 38))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle))
+ .accessibilityAddTraits(selected ? .isSelected : [])
+ .accessibilityIdentifier(identifier)
+ }
+}
+
+/// The Format sheet (Paul's ruling 3; spec §3, "Format sheet"): the web
+/// inspector's sections in one screen at the default size, at the `.medium`
+/// detent with the text still live above it. Every control applies to the
+/// current selection and the sheet stays up.
+@MainActor struct DocsFormatSheet: View {
+ let model: DocsModel
+ let close: () -> Void
+ @Environment(\.dynamicTypeSize) private var typeSize
+ @Environment(\.locale) private var locale
+ static let sizes = [8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72]
+
+ var body: some View {
+ let selection = model.toolbarSelection
+ let twoRows = typeSize >= .accessibility1
+ ScrollView {
+ VStack(alignment: .leading, spacing: DocsSpacing.sp4) {
+ HStack {
+ Text("docs.editor.inspector.label", bundle: DocsResources.bundle)
+ .font(.title3.bold())
+ .accessibilityAddTraits(.isHeader)
+ Spacer()
+ Button(action: close) {
+ Image(systemName: "xmark").font(.body.weight(.semibold))
+ .frame(width: 44, height: 44)
+ .background(Circle().fill(OficinaPalette.sunk).frame(width: 32, height: 32))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text("native.close", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.format.close")
+ }
+ section("docs.editor.toolbar.group.style") { styles(selection) }
+ section("docs.editor.toolbar.font") { fontAndSize(selection, twoRows: twoRows) }
+ section("docs.editor.toolbar.group.text") {
+ rows(twoRows, [
+ DocsSheetSegment(key: "docs.editor.toolbar.bold", icon: "bold", on: selection.marks.contains("strong"), identifier: "docs.format.bold") { ready { $0.perform("bold") } },
+ DocsSheetSegment(key: "docs.editor.toolbar.italic", icon: "italic", on: selection.marks.contains("em"), identifier: "docs.format.italic") { ready { $0.perform("italic") } },
+ DocsSheetSegment(key: "docs.editor.toolbar.code", icon: "chevron.left.forwardslash.chevron.right", on: selection.marks.contains("code"), identifier: "docs.format.code") { ready { $0.perform("code") } },
+ ], ["left", "center", "right"].map { value in
+ DocsSheetSegment(key: "docs.editor.toolbar.align." + value, icon: "text.align" + value, on: selection.alignment == value, identifier: "docs.format.align." + value) {
+ ready { $0.blockAttribute("align", value: value == "left" ? nil : value) }
+ }
+ })
+ }
+ section("docs.editor.toolbar.group.lists") {
+ rows(twoRows, [
+ DocsSheetSegment(key: "docs.editor.toolbar.bulletlist", icon: "list.bullet", on: selection.blocks.contains("bullet_list"), identifier: "docs.format.bullets") { ready { $0.block("bullet_list") } },
+ DocsSheetSegment(key: "docs.editor.toolbar.orderedlist", icon: "list.number", on: selection.blocks.contains("ordered_list"), identifier: "docs.format.numbers") { ready { $0.block("ordered_list") } },
+ DocsSheetSegment(key: "docs.editor.toolbar.quote", icon: "text.quote", on: selection.blocks.contains("blockquote"), identifier: "docs.format.quote") { ready { $0.block("blockquote") } },
+ ], [
+ DocsSheetSegment(key: "docs.editor.menu.format.outdent", icon: "decrease.indent", on: false, mirrors: true, identifier: "docs.format.outdent") { ready { $0.perform("outdent") } },
+ DocsSheetSegment(key: "docs.editor.menu.format.indent", icon: "increase.indent", on: false, mirrors: true, identifier: "docs.format.indent") { ready { $0.perform("indent") } },
+ DocsSheetSegment(key: "docs.editor.menu.format.clear", icon: "eraser", on: false, enabled: selection.hasSelection, identifier: "docs.format.clear") { ready { $0.perform("clear-format") } },
+ ])
+ }
+ }
+ .padding(.horizontal, DocsSpacing.sp5)
+ .padding(.top, DocsSpacing.sp4)
+ .padding(.bottom, DocsSpacing.sp5)
+ }
+ .scrollBounceBehavior(.basedOnSize)
+ .disabled(model.commandsHeld)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text("docs.editor.inspector.label", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.format.sheet")
+ }
+
+ private func ready(_ command: @escaping @MainActor (DocumentCommands) -> Void) { model.whenCommandsReady(command) }
+
+ private func section<Content: View>(_ key: String, @ViewBuilder content: () -> Content) -> some View {
+ VStack(alignment: .leading, spacing: DocsSpacing.sp2) {
+ Text(LocalizedStringKey(key), bundle: DocsResources.bundle)
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(OficinaPalette.textMuted)
+ .accessibilityAddTraits(.isHeader)
+ content()
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle))
+ }
+
+ /// Body text and Heading 1–3 as chips, each in its own face; the current
+ /// one outlined in the accent. They wrap onto more rows when they do not
+ /// fit (spec §9: the sheet re-flows, nothing is clipped).
+ private func styles(_ selection: DocumentToolbarSelection) -> some View {
+ let strings = DocsStrings(locale: locale)
+ let entries: [(id: String, key: String, size: CGFloat, heading: Bool)] = [
+ ("paragraph", "docs.editor.toolbar.block.paragraph", 17, false),
+ ("heading1", EditorToolbar.headingKey(1), 24, true),
+ ("heading2", EditorToolbar.headingKey(2), 20, true),
+ ("heading3", EditorToolbar.headingKey(3), 17, true),
+ ]
+ return DocsFlowLayout(spacing: DocsSpacing.sp2) {
+ ForEach(entries, id: \.id) { entry in
+ let on = selection.style == entry.id
+ Button {
+ if entry.heading, let level = Int(entry.id.dropFirst("heading".count)) { ready { $0.block("heading", level: level) } }
+ else { ready { $0.block("paragraph") } }
+ } label: {
+ Text(verbatim: strings(entry.key))
+ // The style's own face, scaling with Dynamic
+ // Type from its size (spec §9).
+ .font(.custom(DocsFonts.font(marks: [:], size: entry.size, heading: entry.heading).fontName,
+ size: entry.size, relativeTo: .body))
+ // Whole at every size: a chip wider than the
+ // row wraps its words.
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, DocsSpacing.sp4)
+ .frame(minHeight: 52)
+ .foregroundStyle(on ? OficinaPalette.accent(.docs) : OficinaPalette.text)
+ .background(RoundedRectangle(cornerRadius: 14).fill(on ? OficinaPalette.accentSoft(.docs) : OficinaPalette.sunk))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(on ? OficinaPalette.accent(.docs) : .clear, lineWidth: 1.5))
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ .accessibilityIdentifier("docs.format.style." + entry.id)
+ }
+ }
+ }
+
+ /// The font picker (families in their own faces), then the size: − the
+ /// value + over the eleven sizes.
+ @ViewBuilder private func fontAndSize(_ selection: DocumentToolbarSelection, twoRows: Bool) -> some View {
+ let layout = twoRows ? AnyLayout(VStackLayout(alignment: .leading, spacing: DocsSpacing.sp2)) : AnyLayout(HStackLayout(spacing: DocsSpacing.sp2))
+ layout {
+ DocsFontPickerButton(selected: selection.font) { key in ready { $0.setFont(key) } }
+ .padding(.horizontal, DocsSpacing.sp3)
+ .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)
+ .background(RoundedRectangle(cornerRadius: 12).strokeBorder(OficinaPalette.line, lineWidth: 1))
+ stepper(selection.size)
+ }
+ }
+
+ private func stepper(_ size: Int) -> some View {
+ let sizes = Self.sizes
+ let index = sizes.firstIndex(of: size) ?? sizes.firstIndex { $0 > size }.map { max(0, $0 - 1) } ?? sizes.count - 1
+ func set(_ value: Int) {
+ ready { $0.format("size_" + String(value), exclusive: sizes.map { "size_" + String($0) } + ["size_sm", "size_lg", "size_xl"]) }
+ }
+ return HStack(spacing: 0) {
+ Button { if index > 0 { set(sizes[index - 1]) } } label: {
+ Image(systemName: "minus").frame(width: 44, height: 44).contentShape(Rectangle())
+ }
+ .disabled(index == 0)
+ .accessibilityLabel(Text("native.format.size.smaller", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.format.size.smaller")
+ Text(size.formatted(.number.locale(locale)))
+ .font(.body.monospacedDigit())
+ .frame(minWidth: 36)
+ .accessibilityLabel(Text("docs.editor.toolbar.size", bundle: DocsResources.bundle))
+ .accessibilityValue(Text(size.formatted(.number.locale(locale))))
+ Button { if index + 1 < sizes.count { set(sizes[index + 1]) } } label: {
+ Image(systemName: "plus").frame(width: 44, height: 44).contentShape(Rectangle())
+ }
+ .disabled(index + 1 >= sizes.count)
+ .accessibilityLabel(Text("native.format.size.larger", bundle: DocsResources.bundle))
+ .accessibilityIdentifier("docs.format.size.larger")
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(OficinaPalette.text)
+ .background(RoundedRectangle(cornerRadius: 12).fill(OficinaPalette.sunk))
+ .fixedSize()
+ }
+
+ /// Two groups on one row, or one each from AX1 (spec §9).
+ private func rows(_ twoRows: Bool, _ first: [DocsSheetSegment], _ second: [DocsSheetSegment]) -> some View {
+ let layout = twoRows ? AnyLayout(VStackLayout(spacing: DocsSpacing.sp2)) : AnyLayout(HStackLayout(spacing: DocsSpacing.sp2))
+ return layout {
+ DocsSheetSegmentRow(items: first)
+ DocsSheetSegmentRow(items: second)
+ }
+ }
+}
+
+/// One button of a joined row in the Format sheet.
+struct DocsSheetSegment {
+ let key: String
+ let icon: String
+ let on: Bool
+ var mirrors = false
+ var enabled = true
+ let identifier: String
+ let action: @MainActor () -> Void
+}
+
+/// A joined row of 44pt buttons: Bold, Italic, Code and the like.
+@MainActor struct DocsSheetSegmentRow: View {
+ let items: [DocsSheetSegment]
+ var body: some View {
+ HStack(spacing: 2) {
+ ForEach(items, id: \.identifier) { item in
+ Button { item.action() } label: {
+ Image(systemName: item.icon)
+ .font(.body.weight(.medium))
+ .flipsForRightToLeftLayoutDirection(item.mirrors)
+ .frame(maxWidth: .infinity, minHeight: 44)
+ .foregroundStyle(item.on ? OficinaPalette.accent(.docs) : OficinaPalette.text)
+ .background(RoundedRectangle(cornerRadius: 10).fill(item.on ? OficinaPalette.accentSoft(.docs) : .clear))
+ .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(item.on ? OficinaPalette.accent(.docs) : .clear, lineWidth: 1.5))
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .disabled(!item.enabled)
+ .opacity(item.enabled ? 1 : 0.4)
+ .accessibilityLabel(Text(LocalizedStringKey(item.key), bundle: DocsResources.bundle))
+ .accessibilityAddTraits(item.on ? .isSelected : [])
+ .accessibilityIdentifier(item.identifier)
+ }
+ }
+ .padding(2)
+ .background(RoundedRectangle(cornerRadius: 12).fill(OficinaPalette.sunk))
+ }
+}
+/// Its subviews left to right (leading to trailing), onto a new row when
+/// the next would not fit; one wider than a row is offered the row's width.
+struct DocsFlowLayout: Layout {
+ var spacing: CGFloat
+ private func rows(_ subviews: Subviews, width: CGFloat) -> [[(index: Int, size: CGSize)]] {
+ var rows: [[(index: Int, size: CGSize)]] = [[]]
+ var x: CGFloat = 0
+ for index in subviews.indices {
+ var size = subviews[index].sizeThatFits(.unspecified)
+ if size.width > width { size = subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil)) }
+ if !rows[rows.count - 1].isEmpty, x + spacing + size.width > width { rows.append([]); x = 0 }
+ x += (rows[rows.count - 1].isEmpty ? 0 : spacing) + size.width
+ rows[rows.count - 1].append((index, size))
+ }
+ return rows
+ }
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ let rows = rows(subviews, width: proposal.width ?? .infinity)
+ let widths = rows.map { row in row.reduce(0) { $0 + $1.size.width } + spacing * CGFloat(max(row.count - 1, 0)) }
+ let heights = rows.map { row in row.map(\.size.height).max() ?? 0 }
+ return CGSize(width: proposal.width ?? widths.max() ?? 0,
+ height: heights.reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0)))
+ }
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ var y = bounds.minY
+ for row in rows(subviews, width: bounds.width) {
+ var x = bounds.minX
+ for item in row {
+ subviews[item.index].place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(item.size))
+ x += item.size.width + spacing
+ }
+ y += (row.map(\.size.height).max() ?? 0) + spacing
+ }
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsPhoneHeader.swift b/native/apple/Sources/DocsKit/DocsPhoneHeader.swift
new file mode 100644
index 0000000..c9baa21
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsPhoneHeader.swift
@@ -0,0 +1,119 @@
+#if os(iOS)
+import RastrilloApple
+import SwiftUI
+import UIKit
+
+/// The iPhone document's large title (spec 2026-11-22 §3, "Header and
+/// scrolling"): the title, bold, at most three lines, with the §6 subtitle
+/// under it. It is hosted inside the text view's own scroll view, above the
+/// text (`DocsPagedTextView.headerHeight` is its measured height), so it
+/// scrolls with the text and there is no outer scroll view.
+///
+/// Its state is this small object, separate from the text view's host: the
+/// text view reports scrolling and editing here by callback, the workspace
+/// the Format sheet, and only the header and the bar's inline title read it.
+@MainActor @Observable final class DocumentHeaderState {
+ /// Scrolled past the large title.
+ var scrolledPast = false { didSet { if oldValue != scrolledPast { update() } } }
+ /// The text view has the keyboard (typing).
+ var editing = false { didSet { if oldValue != editing { update() } } }
+ /// The Format sheet is open.
+ var sheetOpen = false { didSet { if oldValue != sheetOpen { update() } } }
+ /// The title folds into the bar: on scroll, on the keyboard, on the
+ /// sheet; it unfolds only at the top with the keyboard down (§3).
+ private(set) var collapsed = false
+ private func update() {
+ let next = scrolledPast || editing || sheetOpen
+ if next != collapsed { collapsed = next }
+ }
+}
+
+/// The large title and its subtitle, as the text view hosts them.
+@MainActor struct DocsPhoneLargeTitle: View {
+ let model: DocsModel
+ let team: String?
+ let state: DocumentHeaderState
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ var body: some View {
+ VStack(alignment: .leading, spacing: DocsSpacing.sp1) {
+ Text(verbatim: model.detail?.title ?? " ")
+ .font(.title2.bold())
+ .foregroundStyle(OficinaPalette.text)
+ .lineLimit(3)
+ .fixedSize(horizontal: false, vertical: true)
+ .accessibilityAddTraits(.isHeader)
+ .accessibilityIdentifier("docs.document.title")
+ DocsSubtitleView(model: model, team: team, announces: !state.collapsed)
+ }
+ // Its own height whatever frame it is in, so a larger Dynamic Type
+ // size never squeezes the subtitle while the bar measures it again.
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, DocsSpacing.sp5)
+ .padding(.top, DocsSpacing.sp2)
+ .padding(.bottom, DocsSpacing.sp4)
+ // Folded into the bar: it fades (and under Reduce Motion too, with
+ // no movement: the title in the bar takes its place).
+ .opacity(state.collapsed ? 0 : 1)
+ .animation(reduceMotion ? .linear(duration: 0.12) : .easeOut(duration: 0.2), value: state.collapsed)
+ .accessibilityHidden(state.collapsed)
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("docs.document.header")
+ }
+}
+
+/// The bar's two-line title while the large one is folded away: the title,
+/// truncated, and the subtitle under it.
+@MainActor struct DocsPhoneInlineTitle: View {
+ let model: DocsModel
+ let team: String?
+ let state: DocumentHeaderState
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ var body: some View {
+ // Present only while folded, so the bar holds nothing (and
+ // VoiceOver reads nothing) while the large title shows.
+ ZStack(alignment: .leading) {
+ if state.collapsed {
+ VStack(alignment: .leading, spacing: 0) {
+ Text(verbatim: model.detail?.title ?? "")
+ .font(.headline)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ DocsSubtitleView(model: model, team: team)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .transition(.opacity)
+ .accessibilityElement(children: .combine)
+ // The bar caps its type at the largest sizes, as every bar
+ // does: a long press shows it large (spec §9).
+ .accessibilityShowsLargeContentViewer()
+ .accessibilityIdentifier("docs.document.inlineTitle")
+ }
+ }
+ .animation(reduceMotion ? .linear(duration: 0.12) : .easeOut(duration: 0.2), value: state.collapsed)
+ }
+}
+
+/// What the text view hosts above its text: the large title's hosting
+/// controller, sized by the text view, reporting its height as it changes.
+@MainActor final class DocsPhoneHeaderHost {
+ let controller: UIHostingController<AnyView>
+ let state: DocumentHeaderState
+ /// The height the title measured, for the text view's top inset.
+ var heightChanged: ((CGFloat) -> Void)?
+ init(model: DocsModel, team: String?, state: DocumentHeaderState) {
+ self.state = state
+ var report: ((CGFloat) -> Void)?
+ controller = UIHostingController(rootView: AnyView(EmptyView()))
+ controller.rootView = AnyView(DocsPhoneLargeTitle(model: model, team: team, state: state)
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { report?($0) })
+ controller.view.backgroundColor = .clear
+ controller.sizingOptions = []
+ report = { [weak self] height in self?.heightChanged?(height) }
+ }
+ var view: UIView { controller.view }
+ func height(forWidth width: CGFloat) -> CGFloat {
+ controller.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)).height
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsPhonePages.swift b/native/apple/Sources/DocsKit/DocsPhonePages.swift
new file mode 100644
index 0000000..52066fc
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsPhonePages.swift
@@ -0,0 +1,343 @@
+#if os(iOS)
+import UIKit
+
+/// The iPhone's page breaks on TextKit 2 (S3; spec 2026-11-22 §7 "iPhone
+/// layout", S1b ruling #173).
+///
+/// TextKit 1 paginated by line in the text container's `lineFragmentRect`.
+/// UIKit runs any view whose container does that on TextKit 1 (a container
+/// that is not a plain rectangle switches it back), and TextKit 2's own
+/// exclusion paths lay the whole document out on open and on every key
+/// (1.27 s and 0.53 s at 200 pages). So the breaks are by paragraph, as the
+/// Mac's are by block: a paragraph that would cross a page's bottom margin
+/// starts on the next page instead. The space before it is display-only: the
+/// layout fragment of the paragraph before it is that much taller at the
+/// bottom (`DocsPageBreakFragment`), so TextKit 2 stacks the next one lower,
+/// and the text storage, which the surface reconciles against the replica,
+/// never holds it. (Neither the content storage's delegate, which
+/// `UITextView` does not ask about list items, nor a fragment's `topMargin`,
+/// which stacking ignores, can do it.)
+///
+/// Positions come from each paragraph's own measurements, cached: the space
+/// above its first line and below its last inside its layout fragment, and
+/// its lines' span. They come from a layout of the paragraph alone, never
+/// from where TextKit 2 placed it, and none depends on the breaks. The breaks are then arithmetic over the cache, from the
+/// first paragraph that changed until a paragraph lands where it was.
+/// Measuring is TextKit 2 layout, so it is done a few paragraphs at a time:
+/// the ones on screen as they are drawn, the rest in idle chunks, and, on a
+/// jump past what is measured, everything up to the target at once (spec §7
+/// "Fallback": once per jump, never per key).
+///
+/// A paragraph taller than a page's body cannot fit one: it starts at a page
+/// top and runs over the gap (rare; TextKit 2 offers no line-level break
+/// that keeps layout lazy).
+@MainActor final class DocsPhonePages: NSObject {
+ struct Paragraph: Equatable {
+ var length: Int
+ /// Inside its layout fragment: the space above its first line, its
+ /// lines' span, and the space below its last line (less any break
+ /// space it carries). TextKit 2 stacks fragments frame to frame, so
+ /// a paragraph's lead is the one before's `tail` plus its `head`:
+ /// all local to the fragments, never their positions, which TextKit
+ /// 2 leaves stale after a paragraph above changes size.
+ var head: CGFloat?
+ var height: CGFloat?
+ var tail: CGFloat?
+ /// The space added before it to start it on a new page.
+ var extra: CGFloat = 0
+ /// Its last line's bottom, as the breaks place it.
+ var bottom: CGFloat?
+ }
+ private(set) var paragraphs: [Paragraph] = []
+ private var startsCache: [Int]?
+ var paged = false
+ /// Where the text container's top sits below the first page's body top
+ /// (the first block's own top margin, `docsFirstMargin`).
+ var origin: CGFloat = 0
+ /// The first paragraph whose position may have changed, nil when every
+ /// measured paragraph is placed.
+ private(set) var settleFrom: Int?
+ /// The last paragraph measured (or edited) since it was placed: placing
+ /// may stop once a paragraph lands where it was only past this one, as
+ /// the ones up to it were never placed from their new measurements.
+ private var settleThrough = -1
+ /// Paragraphs whose extra changed and whose element TextKit 2 must build again.
+ private var changed = IndexSet()
+ /// 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.
+ 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.
+ private(set) var editedFrom: Int?
+ weak var storage: NSTextStorage?
+ /// Chunk size for the idle measurement.
+ static let chunk = 40
+
+ static let stride = DocsPageGeometry.paperHeight + DocsPageGeometry.gap
+ static let body = DocsPageGeometry.paperHeight - DocsPageGeometry.verticalMargin * 2
+
+ // MARK: Paragraphs
+
+ var starts: [Int] {
+ if let startsCache { return startsCache }
+ var at = 0, made: [Int] = []
+ made.reserveCapacity(paragraphs.count)
+ for paragraph in paragraphs { made.append(at); at += paragraph.length }
+ startsCache = made
+ return made
+ }
+ /// The paragraph holding character `location` (the last for the end).
+ func paragraph(at location: Int) -> Int? {
+ guard !paragraphs.isEmpty else { return nil }
+ let starts = self.starts
+ var low = 0, high = starts.count - 1
+ while low < high {
+ let mid = (low + high + 1) / 2
+ if starts[mid] <= location { low = mid } else { high = mid - 1 }
+ }
+ return low
+ }
+ func range(of index: Int) -> NSRange { NSRange(location: starts[index], length: paragraphs[index].length) }
+
+ static func lengths(in string: NSString, range: NSRange) -> [Int] {
+ var lengths: [Int] = []
+ string.enumerateSubstrings(in: range, options: [.byParagraphs, .substringNotRequired]) { _, _, enclosing, _ in
+ lengths.append(enclosing.length)
+ }
+ return lengths
+ }
+
+ /// The paragraphs no longer add up to the text: an edit nobody reported
+ /// (a text view with no surface), so everything again.
+ func rebuildIfStale() {
+ let total = (starts.last ?? 0) + (paragraphs.last?.length ?? 0)
+ if paragraphs.isEmpty || total != (storage?.length ?? 0) { rebuild() }
+ }
+
+ /// Everything again (a new text, a new width): nothing is measured.
+ func rebuild() {
+ let string = (storage?.string ?? "") as NSString
+ paragraphs = Self.lengths(in: string, range: NSRange(location: 0, length: string.length)).map { Paragraph(length: $0) }
+ if paragraphs.isEmpty { paragraphs = [Paragraph(length: 0)] }
+ startsCache = nil
+ settleFrom = 0
+ settleThrough = -1
+ changed = IndexSet()
+ laidOutThrough = 0; editedFrom = nil
+ }
+
+ /// Forgets every measurement (the text's width changed), keeping the
+ /// paragraphs and their breaks until they are measured again.
+ func forgetMeasurements() {
+ for index in paragraphs.indices { paragraphs[index].head = nil; paragraphs[index].height = nil; paragraphs[index].tail = nil }
+ settleFrom = 0
+ laidOutThrough = 0; editedFrom = nil
+ }
+
+ /// The storage's characters changed in `edited` (after the edit), by
+ /// `delta`: the paragraphs it touched are split again and measured
+ /// again, with the one after them (its lead depends on its neighbour).
+ func edited(_ edited: NSRange, delta: Int) {
+ guard !regenerating, let storage else { return }
+ let string = storage.string as NSString
+ let oldTotal = (starts.last ?? 0) + (paragraphs.last?.length ?? 0)
+ guard !paragraphs.isEmpty, oldTotal == string.length - delta else { rebuild(); return }
+ // The old paragraphs the edit touched (old coordinates), through
+ // the one its end falls in: deleting a paragraph's end joins it to
+ // the next.
+ 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
+ guard from <= to, to <= string.length else { rebuild(); return }
+ 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
+ // settling can tell where the shift stops.
+ for index in replacement.indices where first + index <= last {
+ replacement[index].bottom = paragraphs[first + index].bottom
+ replacement[index].extra = paragraphs[first + index].extra
+ }
+ paragraphs.replaceSubrange(first...last, with: replacement)
+ let after = first + replacement.count
+ startsCache = nil
+ settleFrom = min(settleFrom ?? first, first)
+ settleThrough = max(settleThrough + (replacement.count - (last - first + 1)), after)
+ }
+
+ // MARK: Measuring
+
+ /// The first paragraph not yet measured, if any.
+ var firstUnmeasured: Int? { paragraphs.firstIndex { $0.height == nil || $0.head == nil || $0.tail == nil } }
+
+ /// Lays out paragraphs `range` (and the one before, for the lead) and
+ /// records what it measures.
+ 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)
+ let upper = min(paragraphs.count, indices.upperBound)
+ let first = starts[lower]
+ let last = starts[upper - 1] + paragraphs[upper - 1].length
+ guard let start = content.location(content.documentRange.location, offsetBy: first),
+ content.location(content.documentRange.location, offsetBy: last) != nil else { return }
+ #if DOCS_PROBES
+ 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.
+ 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)
+ guard let at = self.paragraph(at: offset), at < upper else { return false }
+ let lines = fragment.textLineFragments
+ guard let top = lines.first?.typographicBounds.minY, let bottom = lines.last?.typographicBounds.maxY else { return true }
+ let space = (fragment as? DocsPageBreakFragment)?.space ?? 0
+ self.paragraphs[at].head = top
+ self.paragraphs[at].height = bottom - top
+ self.paragraphs[at].tail = fragment.layoutFragmentFrame.height - space - bottom
+ return true
+ }
+ if indices.lowerBound < (settleFrom ?? .max) { settleFrom = indices.lowerBound }
+ settleThrough = max(settleThrough, upper - 1)
+ }
+
+ // MARK: Breaks
+
+ /// Places paragraphs from `settleFrom` on: each starts where the one
+ /// before ends plus its lead, or at the next page's top if it would
+ /// cross this page's bottom margin. Stops at a paragraph not measured,
+ /// or once one lands where it was (everything after is unchanged).
+ func settle() {
+ guard let from = settleFrom else { return }
+ var index = from
+ var bottom: CGFloat = index == 0 ? 0 : (paragraphs[index - 1].bottom ?? 0)
+ if index > 0 && paragraphs[index - 1].bottom == nil { settleFrom = 0; index = 0; bottom = 0 }
+ while index < paragraphs.count {
+ guard let head = paragraphs[index].head, let height = paragraphs[index].height,
+ let before = index == 0 ? 0 : paragraphs[index - 1].tail else { settleFrom = index; return }
+ let lead = before + head
+ let natural = bottom + lead
+ var extra: CGFloat = 0
+ if paged {
+ // In the pages' coordinates: 0 is the first page's body top.
+ let y = natural + origin
+ let page = max(0, (y / Self.stride).rounded(.down))
+ let pageTop = page * Self.stride - origin, bodyBottom = pageTop + Self.body
+ if natural > bodyBottom + 0.01 { extra = pageTop + Self.stride - natural }
+ else if natural + height > bodyBottom + 0.01 && natural > pageTop + 0.5 { extra = pageTop + Self.stride - natural }
+ }
+ let newBottom = natural + extra + height
+ let old = paragraphs[index]
+ if abs(old.extra - extra) > 0.01 { paragraphs[index].extra = extra; changed.insert(index) }
+ paragraphs[index].bottom = newBottom
+ if index > from, index > settleThrough, abs(old.extra - extra) <= 0.01, let oldBottom = old.bottom, abs(oldBottom - newBottom) <= 0.01 {
+ settleFrom = nil
+ settleThrough = -1
+ return
+ }
+ bottom = newBottom
+ index += 1
+ }
+ settleFrom = nil
+ 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) }
+
+ /// 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.
+ @discardableResult func ensureLayout(through offset: Int, in layout: NSTextLayoutManager) -> Bool {
+ guard offset > exactThrough, 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
+ return true
+ }
+
+ /// TextKit 2 builds again the paragraphs before those whose extra
+ /// 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() {
+ guard !changed.isEmpty, let storage else { return }
+ let indices = changed
+ changed = IndexSet()
+ #if DOCS_PROBES
+ DocsProbes.pageBreakChanges += indices.count
+ #endif
+ // The paragraphs before them get new fragments
+ // (`fragment(for:element:)`), with the new space below. TextKit 2
+ // 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]) }
+ regenerating = true
+ storage.beginEditing()
+ for index in indices where index > 0 && index < paragraphs.count {
+ let span = range(of: index - 1)
+ if span.length > 0 { storage.edited(.editedAttributes, range: span, changeInLength: 0) }
+ }
+ storage.endEditing()
+ regenerating = false
+ }
+
+ var hasChanges: Bool { !changed.isEmpty }
+ /// Every measured paragraph is placed again (the pages' origin moved).
+ func restartSettling() { settleFrom = 0; settleThrough = paragraphs.count }
+
+ /// Paged off: every extra goes.
+ func clearBreaks() {
+ for index in paragraphs.indices where paragraphs[index].extra != 0 { paragraphs[index].extra = 0; changed.insert(index) }
+ settleFrom = 0
+ settleThrough = paragraphs.count
+ }
+
+ // MARK: Fragments
+
+ /// 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.
+ 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 {
+ return NSTextLayoutFragment(textElement: element, range: element.elementRange)
+ }
+ #if DOCS_PROBES
+ DocsProbes.breakParagraphs += 1
+ #endif
+ let fragment = DocsPageBreakFragment(textElement: element, range: range)
+ fragment.space = paragraphs[index + 1].extra
+ return fragment
+ }
+}
+
+/// The paragraph before one that starts a page: the break's space below
+/// its lines, which TextKit 2 stacks the next paragraph after. Its own lines
+/// do not move.
+final class DocsPageBreakFragment: NSTextLayoutFragment {
+ var space: CGFloat = 0
+ override var layoutFragmentFrame: CGRect {
+ var frame = super.layoutFragmentFrame
+ frame.size.height += space
+ return frame
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift
index 7b89a87..fbf934e 100644
--- a/native/apple/Sources/DocsKit/DocsProbes.swift
+++ b/native/apple/Sources/DocsKit/DocsProbes.swift
@@ -45,6 +45,13 @@ public enum DocsProbes {
/// again, ours or its own re-layout (S1b's gate), and to the Mac's
/// measurement container (`measureLineRequests`).
nonisolated(unsafe) public static var lineRequests = 0
+ /// iOS, TextKit 2: layout fragments made (one per paragraph laid out).
+ nonisolated(unsafe) public static var layoutFragments = 0
+ /// iOS: paragraphs whose page-break space changed (DocsPhonePages).
+ nonisolated(unsafe) public static var pageBreakChanges = 0
+ /// iOS: layout fragments made while DocsPhonePages measured.
+ nonisolated(unsafe) public static var measureFragments = 0
+ nonisolated(unsafe) public static var breakParagraphs = 0
nonisolated(unsafe) public static var measureLineRequests = 0
/// Mac pagination passes, and their main-thread time.
nonisolated(unsafe) public static var paginations = 0
@@ -70,7 +77,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; measureLineRequests = 0; paginations = 0; paginationMs = 0; paginationRedraws = 0
+ lineRequests = 0; layoutFragments = 0; pageBreakChanges = 0; measureFragments = 0; breakParagraphs = 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/Sources/DocsKit/DocsSharePanel.swift b/native/apple/Sources/DocsKit/DocsSharePanel.swift
index 2657c1e..2280673 100644
--- a/native/apple/Sources/DocsKit/DocsSharePanel.swift
+++ b/native/apple/Sources/DocsKit/DocsSharePanel.swift
@@ -66,15 +66,15 @@ import UIKit
Text(verbatim: strings("docs.share.panel.heading").replacingOccurrences(of: "{title}", with: model.title))
.font(.headline)
.foregroundStyle(OficinaPalette.text)
- .lineLimit(2)
+ .lineLimit(headingLines)
.fixedSize(horizontal: false, vertical: true)
.accessibilityAddTraits(.isHeader)
.accessibilityFocused($headFocused)
.accessibilityIdentifier("docs.share.heading")
Spacer(minLength: DocsSpacing.sp2)
Button(action: close) {
- Image(systemName: "xmark").font(.system(size: 12, weight: .semibold))
- .frame(width: 28, height: 28).contentShape(Rectangle())
+ Image(systemName: "xmark").font(DocsType.font(12, .semibold, ios: .callout))
+ .frame(minWidth: buttonSide, minHeight: buttonSide).contentShape(Rectangle())
}
.buttonStyle(.plain)
.foregroundStyle(OficinaPalette.textMuted)
@@ -109,9 +109,10 @@ import UIKit
// words would not fit beside the menu and Invite (ru, ga: spec §9).
DocsInviteLayout(spacing: DocsSpacing.sp2) {
ZStack(alignment: .leading) {
- // The placeholder's own width, so the layout knows what fits.
+ // The placeholder's own width, so the layout knows what fits; no
+ // height, so it is never an element over the field's own text.
Text("docs.share.panel.invite_placeholder", bundle: DocsResources.bundle)
- .lineLimit(1).fixedSize().hidden().accessibilityHidden(true)
+ .lineLimit(1).fixedSize().frame(height: 0).hidden().accessibilityHidden(true)
TextField(text: Binding(get: { model.inviteAddress }, set: { model.inviteAddress = $0 })) {
Text("docs.share.panel.invite_placeholder", bundle: DocsResources.bundle)
}
@@ -127,6 +128,10 @@ import UIKit
.accessibilityLabel(Text("docs.share.address", bundle: DocsResources.bundle))
.accessibilityIdentifier("docs.share.email")
}
+ // Without it iOS folds the field into one unlabelled element and
+ // VoiceOver cannot reach it (the accessibility audit's "text not
+ // represented").
+ .accessibilityElement(children: .contain)
Picker(selection: Binding(get: { model.inviteRole }, set: { model.inviteRole = $0 })) {
Text("docs.share.panel.can_read", bundle: DocsResources.bundle).tag(DocsSharePanelModel.Role.reader)
Text("docs.share.panel.can_edit", bundle: DocsResources.bundle).tag(DocsSharePanelModel.Role.writer)
@@ -155,7 +160,7 @@ import UIKit
private func section(_ key: String) -> some View {
Text(LocalizedStringKey(key), bundle: DocsResources.bundle)
- .font(.system(size: 11, weight: .semibold))
+ .font(DocsType.font(11, .semibold, ios: .footnote))
.foregroundStyle(OficinaPalette.textMuted)
.accessibilityAddTraits(.isHeader)
.padding(.top, DocsSpacing.sp1)
@@ -182,10 +187,10 @@ import UIKit
.foregroundStyle(OficinaPalette.textMuted)
Button { Task { await model.remove(grant.address) } } label: {
ZStack {
- Image(systemName: "xmark").font(.system(size: 11, weight: .semibold)).opacity(model.spinning == .remove(grant.address) ? 0 : 1)
+ Image(systemName: "xmark").font(DocsType.font(11, .semibold, ios: .callout)).opacity(model.spinning == .remove(grant.address) ? 0 : 1)
if model.spinning == .remove(grant.address) { ProgressView().controlSize(.mini) }
}
- .frame(width: 28, height: 28).contentShape(Rectangle())
+ .frame(minWidth: buttonSide, minHeight: buttonSide).contentShape(Rectangle())
}
.buttonStyle(.plain)
.foregroundStyle(OficinaPalette.textMuted)
@@ -201,7 +206,7 @@ import UIKit
@ViewBuilder trailing: () -> Trailing) -> some View {
HStack(spacing: DocsSpacing.sp2) {
Text(verbatim: initial)
- .font(.system(size: 12, weight: .semibold))
+ .font(DocsType.font(12, .semibold, ios: .footnote))
.frame(width: 28, height: 28)
.foregroundStyle(mine ? OficinaPalette.onAccent : OficinaPalette.accent(.docs))
.background(Circle().fill(mine ? OficinaPalette.accent(.docs) : OficinaPalette.accentSoft(.docs)))
@@ -251,7 +256,7 @@ import UIKit
identifier: String, set: @escaping (Bool) -> Void) -> some View {
HStack(spacing: DocsSpacing.sp3) {
Image(systemName: icon)
- .font(.system(size: 14, weight: .medium))
+ .font(DocsType.font(14, .medium, ios: .callout))
.frame(width: 28, height: 28)
.foregroundStyle(OficinaPalette.textMuted)
.background(Circle().fill(OficinaPalette.sunk))
@@ -305,7 +310,27 @@ import UIKit
}
}
- /// The panel's rows: 28pt targets on the Mac, 44pt on iPhone (spec §9).
+ /// The heading's lines: two in the Mac's popover; on iPhone all it
+ /// needs, as the sheet scrolls and Dynamic Type reaches AX5 (spec §9).
+ private var headingLines: Int? {
+ #if os(macOS)
+ 2
+ #else
+ nil
+ #endif
+ }
+
+ /// The panel's icon buttons (close, remove): 28pt on the Mac, a 44pt
+ /// target on iPhone (spec §9).
+ private var buttonSide: CGFloat {
+ #if os(macOS)
+ 28
+ #else
+ 44
+ #endif
+ }
+
+ /// The panel's rows: 32pt on the Mac, 44pt on iPhone (spec §9).
private var rowHeight: CGFloat {
#if os(macOS)
32
@@ -408,14 +433,22 @@ struct DocsSwitchStyle: ToggleStyle {
/// The panel's one accent action (Invite, Copy link): a small filled pill.
struct DocsSharePillStyle: ButtonStyle {
+ /// 26pt on the Mac; a 44pt target on iPhone (spec §9).
+ static var height: CGFloat {
+ #if os(macOS)
+ 26
+ #else
+ 44
+ #endif
+ }
@Environment(\.isEnabled) private var isEnabled
func makeBody(configuration: Configuration) -> some View {
configuration.label
- .font(.system(size: 13, weight: .semibold))
+ .font(DocsType.font(13, .semibold, ios: .subheadline))
.lineLimit(1)
.fixedSize()
.padding(.horizontal, DocsSpacing.sp3)
- .frame(minHeight: 26)
+ .frame(minHeight: DocsSharePillStyle.height)
.foregroundStyle(OficinaPalette.onAccent)
.background(Capsule().fill(OficinaPalette.accent(.docs)))
.opacity(configuration.isPressed ? 0.8 : isEnabled ? 1 : 0.45)
diff --git a/native/apple/Sources/DocsKit/DocsSubtitle.swift b/native/apple/Sources/DocsKit/DocsSubtitle.swift
index 585643f..a7b478e 100644
--- a/native/apple/Sources/DocsKit/DocsSubtitle.swift
+++ b/native/apple/Sources/DocsKit/DocsSubtitle.swift
@@ -137,8 +137,13 @@ struct DocsStrings {
@MainActor struct DocsSubtitleView: View {
let model: DocsModel
let team: String?
+ /// Whether its changes are announced: false for a copy that is folded
+ /// away while another shows (the iPhone's large title under its bar
+ /// title), so each change is heard once.
+ var announces = true
var body: some View {
- DocsSubtitleBody(status: model.syncStatus, access: model.documentAccess, loading: model.loading, draft: model.isDraft, team: team)
+ DocsSubtitleBody(status: model.syncStatus, access: model.documentAccess, loading: model.loading, draft: model.isDraft, team: team,
+ announces: announces)
}
}
@@ -151,6 +156,7 @@ struct DocsStrings {
let draft: Bool
let team: String?
var observe: ((DocsSubtitleRow) -> Void)? = nil
+ var announces = true
@Environment(\.locale) private var locale
/// The 1 s debounce for row 9, set only from the `.task` below.
@State private var savingShown = false
@@ -170,7 +176,7 @@ struct DocsStrings {
observe?(new)
defer { shown = new }
// Nothing is announced as the window opens, only changes.
- guard let previous = shown, previous != new, DocsSubtitleRow.announces(from: old, to: new) else { return }
+ guard announces, let previous = shown, previous != new, DocsSubtitleRow.announces(from: old, to: new) else { return }
AccessibilityNotification.Announcement(DocsStrings(locale: locale).state(new) ?? "").post()
}
}
@@ -187,12 +193,18 @@ struct DocsSubtitleLine: View {
var body: some View {
let text = strings.subtitle(team: team, row: row)
HStack(spacing: DocsSpacing.sp1) {
- if row == .viewOnly { Image(systemName: "eye").font(.system(size: 9, weight: .semibold)) }
+ if row == .viewOnly {
+ Image(systemName: "eye").font(DocsType.font(9, .semibold, ios: .caption2))
+ #if os(iOS)
+ .imageScale(.small)
+ #endif
+ }
Text(verbatim: text.isEmpty ? " " : text)
.lineLimit(1)
.truncationMode(.tail)
}
- .font(.system(size: 11, weight: row.isEmphasised ? .semibold : .regular))
+ // 11pt; on iPhone and iPad it scales with Dynamic Type, to AX5 (§9).
+ .font(DocsType.font(11, row.isEmphasised ? .semibold : .regular, ios: .caption2))
.foregroundStyle(row.isNegative ? OficinaPalette.negative : OficinaPalette.textMuted)
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(verbatim: text))
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index 321cf15..87e05d5 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -29,6 +29,16 @@ import SwiftUI
@State private var discarding = false
@State private var images = DocsImageStore()
@State private var column: NavigationSplitViewColumn = .sidebar
+ #if os(iOS)
+ /// iPhone (S3): the library is the stack's root and the document is pushed.
+ @State private var phonePath: [DocsPhoneRoute] = []
+ /// The iPhone document's large title and keyboard bar, one per window.
+ @State private var phoneChrome: DocsPhoneEditorChrome
+ /// The Format sheet (Aa), and Rename's alert.
+ @State private var formatting = false
+ @State private var renamingAlert = false
+ @State private var renameText = ""
+ #endif
private let updateRecents: (([(String, String)]) -> Void)?
private let canSignOut: Bool
@Binding private var accountsRequested: Bool
@@ -72,12 +82,16 @@ import SwiftUI
self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged
self.accountID = accountID
let offline = accountID.map { DocsOfflineAccount.account($0, origin: client.origin, fallback: client, transport: transport) }
- _model = State(initialValue: DocsModel(transport: transport ?? { client }, connectivity: connectivity, draft: newDocument, offlineAccount: offline)); self.signOut = signOut; self.accounts = accounts; self.client = client; self.transport = transport
+ let made = DocsModel(transport: transport ?? { client }, connectivity: connectivity, draft: newDocument, offlineAccount: offline)
+ _model = State(initialValue: made); self.signOut = signOut; self.accounts = accounts; self.client = client; self.transport = transport
+ #if os(iOS)
+ _phoneChrome = State(initialValue: DocsPhoneEditorChrome(model: made, team: team))
+ #endif
}
private var library: some View {
List {
ForEach(model.documents) { document in
- Button { Task { await model.open(document.sqid) } } label: {
+ Button { openFromLibrary(document.sqid) } label: {
HStack { DocumentThumbnail(data: document.thumbnail); Text(document.title); if document.shared == true { Image(systemName: "person.2") } }
}.buttonStyle(.plain)
}
@@ -121,7 +135,15 @@ import SwiftUI
#if os(macOS)
if documentID != nil || newDocument { editor } else { home }
#else
- NavigationSplitView(preferredCompactColumn: $column) { library } detail: { editor }
+ if Self.phoneLayout {
+ // iPhone (S3, spec §3): a stack; iPad keeps today's split view
+ // until S5 (§5, the gate).
+ NavigationStack(path: $phonePath) {
+ library.navigationDestination(for: DocsPhoneRoute.self) { _ in phoneEditor }
+ }
+ } else {
+ NavigationSplitView(preferredCompactColumn: $column) { library } detail: { editor }
+ }
#endif
})
.safeAreaInset(edge: .top, spacing: 0) {
@@ -171,9 +193,15 @@ import SwiftUI
#if os(macOS)
.background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) }
#endif
- .onChange(of: model.detail?.sqid) { if model.detail != nil { column = .detail } }
+ .onChange(of: model.detail?.sqid) {
+ guard model.detail != nil else { return }
+ column = .detail
+ #if os(iOS)
+ if Self.phoneLayout, phonePath.isEmpty { phonePath = [.document] }
+ #endif
+ }
.confirmationDialog(Text("native.discard.title", bundle: DocsResources.bundle), isPresented: $discarding, titleVisibility: .visible) {
- Button(role: .destructive) { Task { await model.discardAll(); column = .sidebar } } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
+ Button(role: .destructive) { Task { await model.discardAll(); showLibrary() } } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
Button(role: .cancel) {} label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
} message: {
Text("native.close.pending.detail", bundle: DocsResources.bundle)
@@ -293,6 +321,21 @@ import SwiftUI
}
}
#endif
+ /// Back to the library: the split view's sidebar, the iPhone's root.
+ private func showLibrary() {
+ column = .sidebar
+ #if os(iOS)
+ phonePath = []
+ #endif
+ }
+ /// A library row: the document, pushed on iPhone (again, when it is the
+ /// one already open).
+ private func openFromLibrary(_ sqid: String) {
+ #if os(iOS)
+ if Self.phoneLayout, model.detail?.sqid == sqid, !model.isDraft { phonePath = [.document]; return }
+ #endif
+ Task { await model.open(sqid) }
+ }
/// On the Mac, a jump from a document or the home window opens or
/// focuses the result's own window instead of replacing this one.
private var jumpOpensWindows: Bool {
@@ -354,7 +397,7 @@ import SwiftUI
#if os(macOS)
closer.close()
#else
- column = .sidebar
+ showLibrary()
#endif
case .stillThere?, .unknown?:
deleteNotice = "native.delete.failed"
@@ -609,3 +652,107 @@ private struct DocsUnsavedGatedButton<Title: View>: View {
Button(action: action) { title() }.disabled(model.hasUnsavedChanges || model.creatingDocument)
}
}
+
+#if os(iOS)
+/// The iPhone stack's one destination: the open document.
+enum DocsPhoneRoute: Hashable { case document }
+
+extension DocsWorkspace {
+ /// iPhone gets the S3 layout; iPad keeps today's until S5 (spec §5: the
+ /// gate). Tests may force either.
+ nonisolated(unsafe) static var phoneLayoutOverride: Bool?
+ static var phoneLayout: Bool { phoneLayoutOverride ?? (UIDevice.current.userInterfaceIdiom == .phone) }
+
+ /// The iPhone document (spec §3): back, the undo/redo pill, Aa and •••
+ /// in the bar; the large title hosted in the text view's own scroll
+ /// view, folding into the bar; the Format sheet at the medium detent;
+ /// the keyboard bar; Rename by alert. No strip, no toolbar items, no
+ /// sync row: the subtitle says what the row did.
+ var phoneEditor: some View {
+ Group {
+ if model.showsDocument {
+ DocumentEditorHost(surface: model.surface, paged: paged, zoom: 1, phone: phoneChrome)
+ .equatable()
+ .id(model.editorIdentity)
+ .ignoresSafeArea(.container, edges: .bottom)
+ .task(id: ["/d/" + (model.detail?.sqid ?? "")] + model.imageSources) { await loadImages() }
+ .onChange(of: model.jumpRequests) { jumping = true }
+ } else if model.loading || model.detail != nil {
+ ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } }
+ }
+ }
+ .background(Color(uiColor: .systemGroupedBackground))
+ .safeAreaInset(edge: .top, spacing: 0) {
+ DocsPhoneCallouts(model: model, discard: { discarding = true }, back: { showLibrary() })
+ }
+ .navigationTitle(model.detail?.title ?? "")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ // Beside Back, where it can truncate: a centred title has no
+ // room left of the trailing controls, and the bar drops it.
+ // The empty principal keeps the navigation title (which names
+ // the page in Back's history) out of the bar.
+ ToolbarItem(placement: .topBarLeading) { DocsPhoneInlineTitle(model: model, team: team, state: phoneChrome.header) }
+ .sharedBackgroundVisibility(.hidden)
+ ToolbarItem(placement: .principal) { Color.clear.frame(width: 0, height: 0).accessibilityHidden(true) }
+ ToolbarItem(placement: .topBarTrailing) {
+ DocsPhoneDocumentControls(model: model, origin: client.origin, paged: $paged, actions: phoneActions)
+ }
+ }
+ .sheet(isPresented: $formatting) {
+ DocsFormatSheet(model: model, close: { formatting = false })
+ .presentationDetents([.medium])
+ .presentationBackgroundInteraction(.enabled(upThrough: .medium))
+ .presentationDragIndicator(.visible)
+ // The text scrolls clear of the sheet, selection above it.
+ .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in
+ model.surface.sheetCovers(height)
+ }
+ .onDisappear { model.surface.sheetCovers(0) }
+ }
+ .onChange(of: formatting) { _, open in
+ // The keyboard goes and the selection stays: the text view keeps
+ // first responder with an empty input view (spec §3).
+ model.surface.suppressKeyboard(open)
+ phoneChrome.header.sheetOpen = open
+ }
+ .onAppear { phoneChrome.openFormat = { formatting = true } }
+ .alert(Text("docs.document.rename", bundle: DocsResources.bundle), isPresented: $renamingAlert) {
+ TextField(text: $renameText) { Text("docs.list.create.placeholder", bundle: DocsResources.bundle) }
+ .accessibilityIdentifier("docs.rename.field")
+ Button { model.renameInput = renameText; _ = model.commitRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) }
+ .accessibilityIdentifier("docs.rename.confirm")
+ Button(role: .cancel) {} label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
+ }
+ .background {
+ if let detail = model.detail, !model.isDraft {
+ DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest)
+ .frame(width: 0, height: 0).hidden().accessibilityHidden(true)
+ }
+ }
+ .sheet(isPresented: $countingWords) { DocsLiveWordCountSheet(model: model) { countingWords = false } }
+ .sheet(isPresented: $showingShortcuts) { DocsShortcutsSheet { showingShortcuts = false } }
+ .sheet(isPresented: $showingColophon) { DocsColophonView { showingColophon = false } }
+ }
+
+ var phoneActions: DocsPhoneActions {
+ var actions = DocsPhoneActions()
+ actions.share = { share() }
+ actions.rename = {
+ guard model.documentAccess == .writable else { return }
+ renameText = model.detail?.title ?? ""
+ renamingAlert = true
+ }
+ actions.export = { kind in exportRequest = kind }
+ actions.wordCount = { countingWords = true }
+ actions.openDocument = { jumping = true }
+ actions.shortcuts = { showingShortcuts = true }
+ actions.colophon = { showingColophon = true }
+ actions.delete = { requestDelete() }
+ actions.format = { formatting = true }
+ return actions
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocumentSurface.swift b/native/apple/Sources/DocsKit/DocumentSurface.swift
index 967362b..8c371bc 100644
--- a/native/apple/Sources/DocsKit/DocumentSurface.swift
+++ b/native/apple/Sources/DocsKit/DocumentSurface.swift
@@ -96,7 +96,16 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
private var flushing = false
private var expectedSelection: NSRange?
- var isEditable = false { didSet { if oldValue != isEditable { textView?.isEditable = isEditable } } }
+ var isEditable = false {
+ didSet {
+ guard oldValue != isEditable else { return }
+ textView?.isEditable = isEditable
+ #if os(iOS)
+ // The keyboard bar is a writer's (spec §3).
+ textView?.showsKeyboardBar = isEditable
+ #endif
+ }
+ }
/// Marks chosen at a collapsed caret (DocsModel.typingMarks), so marked
/// text is drawn in the face it will commit in.
var typingMarks: [String: JSONValue]? { didSet { if oldValue != typingMarks { applyTypingFont() } } }
@@ -151,6 +160,9 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
text.delegate = self
storage?.delegate = self
text.isEditable = isEditable
+ #if os(iOS)
+ text.showsKeyboardBar = isEditable
+ #endif
text.ruleCommand = { [weak self] command in self?.ruleEdit(command) ?? false }
text.clipboardEdit = { [weak self] blocks, range, replacement in self?.clipboardEdit(blocks: blocks, range: range, replacement: replacement) ?? false }
text.compositionChanged = { [weak self] active in self?.hooks.compositionChanged(active) }
@@ -178,6 +190,19 @@ typealias DocsStorageEditActions = NSTextStorage.EditActions
text.compositionCommitted = nil; text.action = nil; text.canAction = nil
}
+ #if os(iOS)
+ /// The Format sheet is open (iPhone, S3): the keyboard goes, the text
+ /// view keeps first responder and the selection.
+ func suppressKeyboard(_ suppressed: Bool) { textView?.keyboardSuppressed = suppressed }
+ /// The sheet's height over the text: it scrolls clear of it, the
+ /// selection kept in view above it.
+ func sheetCovers(_ height: CGFloat) {
+ guard let text = textView, abs(text.bottomObstruction - height) > 0.5 else { return }
+ text.bottomObstruction = height
+ if height > 0 { text.scrollRangeToVisible(text.selectedRange) }
+ }
+ #endif
+
/// An explicit command (not typing) went to the model.
func explicitCommand() { textView?.lastInputRule = nil }
@@ -491,6 +516,12 @@ extension DocumentSurface: NSTextStorageDelegate {
MainActor.assumeIsolated {
guard edited === storage else { return }
index.processEditing(edited, edited: editedRange, delta: delta)
+ #if os(iOS)
+ // The iPhone's page breaks (TextKit 2, DocsPhonePages).
+ if editedMask.contains(.editedCharacters) || editedMask.contains(.editedAttributes) { textView?.storageEdited(editedRange, delta: delta) }
+ // The pages building paragraphs again: no text changed.
+ if textView?.pages.regenerating == true { return }
+ #endif
if !applying, editedMask.contains(.editedCharacters) { typed(around: editedRange) }
}
}
diff --git a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
index 7350075..e2ef242 100644
--- a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
+++ b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
@@ -66,8 +66,15 @@ struct NativeDocumentTextView: UIViewRepresentable {
let surface: DocumentSurface
var paged: Bool
var zoom: Double = 1
+ /// The iPhone's large title and keyboard bar (S3); nil on iPad.
+ var phone: DocsPhoneEditorChrome? = nil
func makeUIView(context: Context) -> UITextView {
let text = DocsTextView()
+ if let phone {
+ text.header = DocsPhoneHeaderHost(model: phone.model, team: phone.team, state: phone.header)
+ text.keyboardBar = phone.makeKeyboardBar(hide: { [weak text] in _ = text?.resignFirstResponder() })
+ text.keyboardDismissMode = .interactive
+ }
text.adjustsFontForContentSizeCategory = true
// Before the first render, and in an empty document, the caret and
// anything typed are in the default face, never the system's.
@@ -104,8 +111,15 @@ struct DocumentEditorHost: View, Equatable {
/// Mac: the side the floating Format inspector covers (S2a), nil while
/// it is hidden; identity-level, like Pages and zoom.
var inspector: DocsDeskLayout.Side? = nil
+ #if os(iOS)
+ /// iPhone: the large title and keyboard bar (S3), by identity.
+ var phone: DocsPhoneEditorChrome? = nil
+ #endif
nonisolated static func == (a: Self, b: Self) -> Bool {
- a.surface === b.surface && a.paged == b.paged && a.zoom == b.zoom && a.inspector == b.inspector
+ #if os(iOS)
+ guard a.phone === b.phone else { return false }
+ #endif
+ return a.surface === b.surface && a.paged == b.paged && a.zoom == b.zoom && a.inspector == b.inspector
}
var body: some View {
#if DOCS_PROBES
@@ -114,7 +128,7 @@ struct DocumentEditorHost: View, Equatable {
#if os(macOS)
NativeDocumentTextView(surface: surface, paged: paged, zoom: zoom, inspector: inspector)
#else
- NativeDocumentTextView(surface: surface, paged: paged, zoom: zoom)
+ NativeDocumentTextView(surface: surface, paged: paged, zoom: zoom, phone: phone)
#endif
}
}
diff --git a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
index a458296..33b9290 100644
--- a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "اتصل بالإنترنت لتصدير هذا المستند.";
"native.delete.unsent" = "انتظر حتى تُحفظ تغييراتك، ثم احذفه.";
"native.delete.failed" = "تعذّر حذف هذا المستند. تحقّق من اتصالك وحاول مرة أخرى.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "المزيد";
+"native.keyboard.hide" = "إخفاء لوحة المفاتيح";
+"native.format.size.smaller" = "أصغر";
+"native.format.size.larger" = "أكبر";
+"native.back" = "رجوع";
+"docs.editor.menu.help" = "المساعدة";
diff --git a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
index 37565c5..add421c 100644
--- a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "এই নথি এক্সপোর্ট করতে সংযোগ করুন।";
"native.delete.unsent" = "আপনার পরিবর্তনগুলো সংরক্ষিত হওয়া পর্যন্ত অপেক্ষা করুন, তারপর মুছুন।";
"native.delete.failed" = "এই নথিটি মোছা যায়নি। আপনার সংযোগ দেখে আবার চেষ্টা করুন।";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "আরও";
+"native.keyboard.hide" = "কীবোর্ড লুকান";
+"native.format.size.smaller" = "ছোট";
+"native.format.size.larger" = "বড়";
+"native.back" = "ফিরে যান";
+"docs.editor.menu.help" = "সহায়তা";
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
index 3a2de42..53c01e6 100644
--- a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
@@ -266,3 +266,11 @@
"native.export.offline" = "Connect to export this document.";
"native.delete.unsent" = "Wait until your changes are saved, then delete.";
"native.delete.failed" = "This document could not be deleted. Check your connection and try again.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "More";
+"native.keyboard.hide" = "Hide keyboard";
+"native.format.size.smaller" = "Smaller";
+"native.format.size.larger" = "Larger";
+"native.back" = "Back";
+"docs.editor.menu.help" = "Help";
diff --git a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
index fbfb10c..e0aa6c6 100644
--- a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "Conéctate para exportar este documento.";
"native.delete.unsent" = "Espera a que se guarden tus cambios y luego elimínalo.";
"native.delete.failed" = "No se pudo eliminar este documento. Comprueba tu conexión y vuelve a intentarlo.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "Más";
+"native.keyboard.hide" = "Ocultar teclado";
+"native.format.size.smaller" = "Más pequeño";
+"native.format.size.larger" = "Más grande";
+"native.back" = "Atrás";
+"docs.editor.menu.help" = "Ayuda";
diff --git a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
index 7a4b6f6..ee30b0a 100644
--- a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "Ceangail chun an doiciméad seo a easpórtáil.";
"native.delete.unsent" = "Fan go sábhálfar d’athruithe, ansin scrios é.";
"native.delete.failed" = "Níorbh fhéidir an doiciméad seo a scriosadh. Seiceáil do cheangal agus bain triail eile as.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "Tuilleadh";
+"native.keyboard.hide" = "Folaigh an méarchlár";
+"native.format.size.smaller" = "Níos lú";
+"native.format.size.larger" = "Níos mó";
+"native.back" = "Siar";
+"docs.editor.menu.help" = "Cabhair";
diff --git a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
index 9df9a59..cf2009e 100644
--- a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "यह दस्तावेज़ एक्सपोर्ट करने के लिए कनेक्ट करें।";
"native.delete.unsent" = "अपने बदलाव सहेजे जाने तक इंतज़ार करें, फिर मिटाएँ।";
"native.delete.failed" = "यह दस्तावेज़ मिटाया नहीं जा सका। अपना कनेक्शन जाँचें और फिर कोशिश करें।";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "और";
+"native.keyboard.hide" = "कीबोर्ड छिपाएँ";
+"native.format.size.smaller" = "छोटा";
+"native.format.size.larger" = "बड़ा";
+"native.back" = "वापस";
+"docs.editor.menu.help" = "सहायता";
diff --git a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
index 51ce208..dc624d1 100644
--- a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "このドキュメントを書き出すには接続してください。";
"native.delete.unsent" = "変更が保存されるまで待ってから削除してください。";
"native.delete.failed" = "このドキュメントを削除できませんでした。接続を確認して、もう一度お試しください。";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "その他";
+"native.keyboard.hide" = "キーボードを隠す";
+"native.format.size.smaller" = "小さく";
+"native.format.size.larger" = "大きく";
+"native.back" = "戻る";
+"docs.editor.menu.help" = "ヘルプ";
diff --git a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
index d131068..5dcf49b 100644
--- a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "Ligue-se para exportar este documento.";
"native.delete.unsent" = "Aguarde até as alterações serem guardadas e depois elimine.";
"native.delete.failed" = "Não foi possível eliminar este documento. Verifique a ligação à Internet e tente novamente.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "Mais";
+"native.keyboard.hide" = "Ocultar teclado";
+"native.format.size.smaller" = "Mais pequeno";
+"native.format.size.larger" = "Maior";
+"native.back" = "Voltar";
+"docs.editor.menu.help" = "Ajuda";
diff --git a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
index 953eec6..c9b4392 100644
--- a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "Подключитесь к сети, чтобы экспортировать этот документ.";
"native.delete.unsent" = "Дождитесь сохранения изменений, затем удалите.";
"native.delete.failed" = "Не удалось удалить документ. Проверьте подключение и попробуйте ещё раз.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "Ещё";
+"native.keyboard.hide" = "Скрыть клавиатуру";
+"native.format.size.smaller" = "Меньше";
+"native.format.size.larger" = "Больше";
+"native.back" = "Назад";
+"docs.editor.menu.help" = "Справка";
diff --git a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
index 120000a..047d605 100644
--- a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "Hãy kết nối để xuất tài liệu này.";
"native.delete.unsent" = "Hãy đợi đến khi các thay đổi được lưu, rồi xóa.";
"native.delete.failed" = "Không thể xóa tài liệu này. Hãy kiểm tra kết nối rồi thử lại.";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "Thêm";
+"native.keyboard.hide" = "Ẩn bàn phím";
+"native.format.size.smaller" = "Nhỏ hơn";
+"native.format.size.larger" = "Lớn hơn";
+"native.back" = "Quay lại";
+"docs.editor.menu.help" = "Trợ giúp";
diff --git a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
index f88913b..4a0f732 100644
--- a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "連線之後先可以匯出呢份文件。";
"native.delete.unsent" = "等你嘅變更儲存好之後,先刪除。";
"native.delete.failed" = "刪除唔到呢份文件。請檢查你嘅連線再試。";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "更多";
+"native.keyboard.hide" = "隱藏鍵盤";
+"native.format.size.smaller" = "細啲";
+"native.format.size.larger" = "大啲";
+"native.back" = "返回";
+"docs.editor.menu.help" = "說明";
diff --git a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
index 42787fb..3495588 100644
--- a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
@@ -261,3 +261,11 @@
"native.export.offline" = "请连接网络以导出此文档。";
"native.delete.unsent" = "请等待您的更改保存完毕,然后再删除。";
"native.delete.failed" = "无法删除此文档。请检查网络连接后重试。";
+
+/* S3: the iPhone document (spec 2026-11-22 §3, §8). Drafted; copy review follows (docs #171). */
+"native.more" = "更多";
+"native.keyboard.hide" = "隐藏键盘";
+"native.format.size.smaller" = "更小";
+"native.format.size.larger" = "更大";
+"native.back" = "返回";
+"docs.editor.menu.help" = "帮助";
diff --git a/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift b/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift
index d594ac6..6042259 100644
--- a/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift
+++ b/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift
@@ -112,4 +112,23 @@ final class DocsSubtitleTests: XCTestCase {
XCTAssertFalse(strings.subtitle(team: "T", row: .saved).contains("%"), language)
}
}
+
+ /// S3's keys (the iPhone document, spec §8): every one resolves in all
+ /// twelve tables, and no value is its own key.
+ func testEveryIPhoneDocumentKeyResolvesInEveryLanguage() {
+ let keys = ["native.more", "native.keyboard.hide", "native.format.size.smaller", "native.format.size.larger", "native.back",
+ "docs.editor.menu.help", "native.colophon", "docs.editor.menu.tools.wordcount", "docs.editor.menu.tools.shortcuts",
+ "docs.editor.menu.file.open", "docs.editor.menu.view.paged", "docs.editor.menu.view.infinite", "native.export",
+ "docs.export.pdf.label", "docs.export.markdown.label", "docs.editor.menu.file.print", "docs.document.rename",
+ "docs.editor.menu.file.delete", "docs.share.action", "docs.editor.inspector.label", "docs.editor.inspector.toggle",
+ "docs.editor.toolbar.font", "docs.editor.toolbar.size", "native.close.pending.cancel", "docs.list.create.placeholder"]
+ for language in DocsResources.bundle.localizations.filter({ $0 != "Base" }) {
+ let strings = DocsStrings(locale: Locale(identifier: language))
+ for key in keys {
+ let value = strings(key)
+ XCTAssertNotEqual(value, key, "\(language): \(key) has no value")
+ XCTAssertFalse(value.isEmpty, "\(language): \(key) is empty")
+ }
+ }
+ }
}
diff --git a/native/apple/Tests/DocsKitTests/PhoneDocumentTests.swift b/native/apple/Tests/DocsKitTests/PhoneDocumentTests.swift
new file mode 100644
index 0000000..b6fbb15
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/PhoneDocumentTests.swift
@@ -0,0 +1,107 @@
+#if os(iOS)
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import SwiftUI
+import UIKit
+import XCTest
+@testable import DocsKit
+
+/// The iPhone document (S3, spec 2026-11-22 §3, §11), in the real
+/// `DocsWorkspace` on an in-memory server, in a window.
+@MainActor final class PhoneDocumentTests: XCTestCase {
+ private var window: UIWindow?
+ override func tearDown() async throws {
+ window?.rootViewController = nil; window?.isHidden = true; window = nil
+ }
+
+ private func open() async throws -> (DocsTextView, DocumentSurface, LoopServer) {
+ DocsFonts.register()
+ let server = LoopServer()
+ try await server.seed(LoopFixture.everything)
+ let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", team: "Tito",
+ connectivity: connectivity)
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene { window.windowScene = scene }
+ window.rootViewController = UIHostingController(rootView: workspace)
+ window.makeKeyAndVisible()
+ self.window = window
+ func find(_ view: UIView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(find).first }
+ try await until("the document is shown") { find(window).map { $0.textStorage.string.contains(LoopFixture.middle) } ?? false }
+ let text = try XCTUnwrap(find(window))
+ let surface = try XCTUnwrap(text.delegate as? DocumentSurface)
+ try await until("open settled") { surface.newest.map { $0.revision == surface.appliedRevision } ?? false }
+ try await Task.sleep(for: .milliseconds(300))
+ return (text, surface, server)
+ }
+
+ private func until(_ what: String, _ condition: () -> Bool) async throws {
+ let deadline = Date().addingTimeInterval(10)
+ while !condition() {
+ guard Date() < deadline else { throw Failure(what: what) }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ }
+ private struct Failure: Error, CustomStringConvertible { let what: String; var description: String { "timed out: \(what)" } }
+
+ /// Spec §11 (Low 18): with the caret mid-paragraph, a peer's edit to
+ /// another block moves neither the caret nor the scroll, so the
+ /// VoiceOver cursor, which follows them, stays where it was.
+ func testAPeerEditElsewhereMovesNeitherTheCaretNorTheScroll() async throws {
+ let (text, surface, server) = try await open()
+ let content = text.textStorage.string as NSString
+ let middle = content.range(of: LoopFixture.middle)
+ let caret = NSRange(location: middle.location + 10, length: 0)
+ text.selectedRange = caret
+ _ = text.becomeFirstResponder()
+ try await Task.sleep(for: .milliseconds(200))
+ let offset = text.contentOffset
+ // The peer types into the last block, after the caret's.
+ let after = (text.textStorage.string as NSString).range(of: LoopFixture.afterRule).location
+ try await server.peerInsert("A peer’s note. ", at: after)
+ try await until("the peer's note is drawn") { surface.content.string.contains("A peer’s note.") }
+ try await Task.sleep(for: .milliseconds(200))
+ XCTAssertEqual(text.selectedRange, caret, "the caret did not move")
+ XCTAssertEqual(text.contentOffset.y, offset.y, accuracy: 0.5, "nor did the scroll")
+ }
+
+ /// Spec §3, "Header and scrolling": the title folds into the bar on the
+ /// keyboard and with the Format sheet, and unfolds only at the top with
+ /// the keyboard down and the sheet closed.
+ func testTheTitleFoldsOnTheKeyboardAndTheSheet() async throws {
+ let (text, _, _) = try await open()
+ let state = try XCTUnwrap(text.header?.state)
+ XCTAssertFalse(state.collapsed, "at the top, the large title")
+ XCTAssertTrue(text.becomeFirstResponder())
+ try await until("the keyboard folds the title") { state.collapsed }
+ XCTAssertTrue(text.resignFirstResponder())
+ try await until("the keyboard down at the top unfolds it") { !state.collapsed }
+ state.sheetOpen = true
+ XCTAssertTrue(state.collapsed, "the sheet folds it")
+ state.sheetOpen = false
+ XCTAssertFalse(state.collapsed)
+ }
+
+ /// The keyboard bar is a writer's, rides on the text view as its input
+ /// accessory (so a hardware keyboard shows it too, at the bottom), and
+ /// goes while the Format sheet is open, when the keyboard goes but the
+ /// text view keeps first responder and its selection.
+ func testTheKeyboardBarAndTheFormatSheetsKeyboard() async throws {
+ let (text, surface, _) = try await open()
+ XCTAssertNotNil(text.inputAccessoryView, "a writer's text view carries the keyboard bar")
+ text.selectedRange = NSRange(location: 3, length: 5)
+ XCTAssertTrue(text.becomeFirstResponder())
+ surface.suppressKeyboard(true)
+ XCTAssertTrue(text.isFirstResponder, "the Format sheet keeps first responder")
+ XCTAssertEqual(text.selectedRange, NSRange(location: 3, length: 5), "and the selection")
+ XCTAssertNotNil(text.inputView, "the keyboard is an empty input view meanwhile")
+ XCTAssertNil(text.inputAccessoryView, "and no keyboard bar under the sheet")
+ surface.suppressKeyboard(false)
+ XCTAssertNil(text.inputView, "the keyboard comes back as it was")
+ XCTAssertNotNil(text.inputAccessoryView)
+ surface.isEditable = false
+ XCTAssertNil(text.inputAccessoryView, "a reader's text view has none")
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
index 308cbc9..89fccc4 100644
--- a/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
+++ b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
@@ -3,128 +3,281 @@ import UIKit
import XCTest
@testable import DocsKit
-/// The iPhone's large-document check (spec 2026-11-22 §7 "iPhone layout";
-/// §11 "Large documents"), as a probe: skipped unless DOCS_PHONE_LARGE is
-/// set (TEST_RUNNER_DOCS_PHONE_LARGE=1 through xcodebuild). S1b found the
-/// spec's iPhone plan cannot hold with UIKit's TextKit 1 (discussion on
-/// perf/native-s1b): the container is not a simple rectangle, so the
-/// layout manager never lays out non-contiguously, and its background
-/// layout (on, and not public API on iOS) lays the rest of the document out
-/// synchronously after every edit that changes a line count. This prints
-/// what opening a 200-page document paged, typing in its middle and
-/// jumping to its end cost, and runs the check's assertions; then the same
-/// storage edits on a bare stack with the non-public `backgroundLayoutEnabled`
-/// off, for comparison (setting it on the text view's own manager ended the
-/// test process).
+/// The iPhone's large-document check (spec 2026-11-22 §7 "iPhone layout",
+/// §11 "Large documents"; plan S3 acceptance, carried from S1b #173), as a
+/// probe: skipped unless DOCS_PHONE_LARGE is set (TEST_RUNNER_DOCS_PHONE_LARGE=1
+/// through xcodebuild). A 200-page document, paged, on the production text
+/// view (TextKit 2 from S3):
+/// - opening lays out no further than the first screen, in ≤ 250 ms of
+/// main thread;
+/// - 40 keys in its middle, some making a new line: main-thread time per key
+/// ≤ 8 ms median, and no key over 16.7 ms;
+/// - jump to the end before anything past the first screen is laid out:
+/// the caret is on its glyph's line, no line crosses a page gap, and the
+/// lines near the end are where a whole layout puts them.
+/// Then the same document on TextKit 1 (`TextKit1PagedView`, the view as it
+/// shipped before S3), for the 72.7 pt caret finding.
@MainActor final class PhoneLargeDocumentTests: XCTestCase {
- func testJumpToTheEndOfALongPagedDocument() async throws {
+ private static let pages = 200
+
+ func testALongPagedDocumentOnTextKit2() async throws {
guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") }
DocsFonts.register()
- let projection = SurfaceFixture.projection(SurfaceFixture.pages(200))
- do {
- let mode = "as shipped"
- let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
- window.makeKeyAndVisible()
- let text = DocsTextView(frame: window.bounds)
- text.paged = true
- window.addSubview(text)
- let surface = DocumentSurface()
- var hooks = DocumentSurface.Hooks()
- hooks.edit = { _ in true }
- surface.hooks = hooks
- surface.isEditable = true
- surface.attach(text)
- var requests = DocsProbes.lineRequests
- var start = ContinuousClock.now
- surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
+ let projection = SurfaceFixture.projection(SurfaceFixture.pages(Self.pages))
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ window.makeKeyAndVisible()
+ defer { window.isHidden = true }
+ let text = DocsTextView(frame: window.bounds)
+ text.paged = true
+ window.addSubview(text)
+ defer { text.removeFromSuperview() }
+ let surface = DocumentSurface()
+ var hooks = DocumentSurface.Hooks()
+ hooks.edit = { _ in true }
+ surface.hooks = hooks
+ surface.isEditable = true
+ surface.attach(text)
+ let layout = try XCTUnwrap(text.textLayoutManager, "TextKit 2")
+ let storage = text.textStorage
+ // Open.
+ var fragments = DocsProbes.layoutFragments
+ let rendering = DocsProbes.wholeRenderMs, layouts = DocsProbes.textLayoutMs
+ var start = ContinuousClock.now
+ surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
+ text.layoutIfNeeded()
+ let open = Self.ms(start)
+ let openFragments = DocsProbes.layoutFragments - fragments
+ let paragraphs = text.pages.paragraphs.count
+ print(String(format: "PHONE LARGE textkit2: open breakdown: whole render %.1f ms, text view layout %.1f ms", DocsProbes.wholeRenderMs - rendering, DocsProbes.textLayoutMs - layouts))
+ print(String(format: "PHONE LARGE textkit2: open %.1f ms, %d of %d paragraphs laid out", open, openFragments, paragraphs))
+ XCTAssertNil(text.layoutManager(peeking: true), "still TextKit 2")
+ XCTAssertLessThan(openFragments, 200, "opening lays out about the first screen, not \(paragraphs) paragraphs")
+ // §7: a timing target holds within 20% of its value (median of three runs).
+ XCTAssertLessThanOrEqual(open, 250 * 1.2, "first screen within 250 ms of main thread")
+
+ // Keys in the middle, some making a new line: scrolled there as a
+ // person would (TextKit 2's scrollRangeToVisible does not scroll to
+ // text it has not laid out), then typing in a paragraph on screen.
+ text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height / 2), animated: false)
+ text.layoutIfNeeded()
+ let shown = try XCTUnwrap(layout.textViewportLayoutController.viewportRange)
+ let content = try XCTUnwrap(layout.textContentManager)
+ let middle = Self.lineStart(storage.string as NSString, near: content.offset(from: content.documentRange.location, to: shown.location) + 200)
+ text.selectedRange = NSRange(location: middle, length: 0)
+ text.layoutIfNeeded()
+ try await Task.sleep(for: .milliseconds(300))
+ let measuredBefore = text.pages.paragraphs.filter { $0.height != nil }.count
+ var keys: [Double] = [], newLineKeys: [Double] = [], perKeyFragments: [Int] = [], perKeyMeasured: [Int] = [], perKeyBreaks: [Int] = []
+ let wrap = String(repeating: "Words to wrap the line. ", count: 3)
+ for index in 0..<40 {
+ let typed = index % 8 == 4 ? wrap : "x"
+ let range = text.selectedRange
+ fragments = DocsProbes.layoutFragments
+ let measured = DocsProbes.measureFragments, breaks = DocsProbes.pageBreakChanges
+ start = .now
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: typed) ?? true {
+ storage.replaceCharacters(in: range, with: NSAttributedString(string: typed, attributes: text.typingAttributes))
+ text.selectedRange = NSRange(location: range.location + typed.utf16.count, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
text.layoutIfNeeded()
- let manager = text.layoutManager
- let container = text.textContainer
- let storage = text.textStorage
- print("PHONE LARGE \(mode): open \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests; laid out to \(manager.firstUnlaidCharacterIndex()) of \(storage.length)")
- XCTAssertNil(manager.textContainer(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil, withoutAdditionalLayout: true),
- "\(mode): nothing at the end is laid out at open")
+ let elapsed = Self.ms(start)
+ keys.append(elapsed)
+ if typed == wrap { newLineKeys.append(elapsed) }
+ perKeyFragments.append(DocsProbes.layoutFragments - fragments)
+ perKeyMeasured.append(DocsProbes.measureFragments - measured)
+ perKeyBreaks.append(DocsProbes.pageBreakChanges - breaks)
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ let sorted = keys.sorted()
+ print(String(format: "PHONE LARGE textkit2: per key median %.2f ms, max %.2f ms; keys making new lines max %.2f ms; fragments per key median %d max %d",
+ sorted[sorted.count / 2], sorted.last ?? 0, newLineKeys.max() ?? 0,
+ perKeyFragments.sorted()[perKeyFragments.count / 2], perKeyFragments.max() ?? 0))
+ let onScreen = try XCTUnwrap(layout.textViewportLayoutController.viewportRange)
+ let typedAt = text.selectedRange.location
+ XCTAssertTrue(content.offset(from: content.documentRange.location, to: onScreen.location) <= typedAt
+ && typedAt <= content.offset(from: content.documentRange.location, to: onScreen.endLocation), "typed on screen")
+ print("PHONE LARGE textkit2: typing at \(typedAt), \(measuredBefore) paragraphs measured when it began")
+ print("PHONE LARGE textkit2: per key, fragments measuring \(perKeyMeasured.max() ?? 0) at most, page breaks moved \(perKeyBreaks.reduce(0, +)) in all")
+ 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")
- // Keys in the middle, one of them making a new line.
- let middle = storage.length / 2
- for (index, typed) in ["x", "x", String(repeating: "Words to wrap the line. ", count: 4), "x"].enumerated() {
- let range = NSRange(location: middle, length: 0)
- requests = DocsProbes.lineRequests
- start = .now
- if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: typed) ?? true {
- storage.replaceCharacters(in: range, with: NSAttributedString(string: typed, attributes: text.typingAttributes))
- text.selectedRange = NSRange(location: range.location + typed.utf16.count, length: 0)
- text.delegate?.textViewDidChange?(text)
- }
- text.layoutIfNeeded()
- print("PHONE LARGE \(mode): key \(index) (\(typed.count) characters): \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
+ // A fresh view for the jump, laid out no further than its first screen.
+ let jumper = DocsTextView(frame: window.bounds)
+ jumper.paged = true
+ window.addSubview(jumper)
+ defer { jumper.removeFromSuperview() }
+ jumper.attributedText = NativeTextProjection.render(projection)
+ jumper.layoutIfNeeded()
+ let end = jumper.textStorage.length - 8
+ fragments = DocsProbes.layoutFragments
+ start = .now
+ // As the scroll indicator dragged to the bottom does: TextKit 2's
+ // scrollRangeToVisible does not scroll to text it has not laid out.
+ jumper.setContentOffset(CGPoint(x: 0, y: max(0, jumper.contentSize.height - jumper.bounds.height)), animated: false)
+ jumper.layoutIfNeeded()
+ jumper.selectedRange = NSRange(location: end, length: 0)
+ 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 }
+ // Every break laid out where it was placed.
+ if let layout = jumper.textLayoutManager, let content = layout.textContentManager {
+ var off = 0, worst: CGFloat = 0
+ for index in breaks {
+ guard let location = content.location(content.documentRange.location, offsetBy: jumper.pages.range(of: index).location),
+ let fragment = layout.textLayoutFragment(for: location), fragment.state == .layoutAvailable,
+ let placed = jumper.pages.paragraphs[index].bottom.map({ $0 - (jumper.pages.paragraphs[index].height ?? 0) }) else { continue }
+ let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0)
+ if abs(top - placed) > 0.5 { off += 1; worst = max(worst, abs(top - placed)) }
}
+ print("PHONE LARGE textkit2: \(breaks.count) page breaks; \(off) laid out away from where they were placed (worst \(worst) pt)")
+ XCTAssertEqual(off, 0, "every break is laid out where it was placed")
+ }
+ print(String(format: "PHONE LARGE textkit2: jump to the end %.1f ms, %d fragments laid out (measured contiguously: spec §7 Fallback, once per jump)", jump, jumpFragments))
+ // Measuring placed the document exactly, so its height changed under
+ // the jump: bring the caret on screen, as the text view does when the
+ // person types there.
+ let landed = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start)
+ jumper.setContentOffset(CGPoint(x: 0, y: max(0, landed.midY - jumper.bounds.height / 2)), animated: false)
+ jumper.layoutIfNeeded()
+ let caret = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start)
+ let lines = Self.lines(in: jumper, near: jumper.contentOffset.y, height: jumper.bounds.height)
+ let caretLine = lines.first { $0.range.contains(end) || NSMaxRange($0.range) == end }
+ print("PHONE LARGE textkit2: caret \(caret), its line \(String(describing: caretLine?.rect))")
+ let line = try XCTUnwrap(caretLine, "the caret's line is laid out")
+ XCTAssertTrue(caret.midY > line.rect.minY && caret.midY < line.rect.maxY, "the caret (\(caret)) is on its glyph's line (\(line.rect))")
+ let geometry = jumper.geometry
+ for line in lines {
+ let y = line.rect.minY - jumper.headerHeight
+ let page = geometry.page(at: y)
+ let top = CGFloat(page) * geometry.stride + DocsPageGeometry.verticalMargin
+ XCTAssertGreaterThanOrEqual(y, top - 0.01, "a line (\(line.rect)) starts in a gap")
+ XCTAssertLessThanOrEqual(y + line.rect.height, top + geometry.bodyHeight + 0.01, "a line (\(line.rect)) straddles a page gap")
+ }
+ // The same lines on a whole layout.
+ let whole = DocsTextView(frame: window.bounds)
+ whole.paged = true
+ window.addSubview(whole)
+ defer { whole.removeFromSuperview() }
+ whole.attributedText = jumper.attributedText
+ whole.layoutIfNeeded()
+ whole.paginateEverything()
+ let wholeLayout = try XCTUnwrap(whole.textLayoutManager)
+ wholeLayout.ensureLayout(for: wholeLayout.documentRange)
+ let reference = Dictionary(Self.lines(in: whole, near: 0, height: .greatestFiniteMagnitude).map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a })
+ var mismatches = 0
+ // Lines of text: the empty line after the last newline has no glyphs,
+ // and its x follows the typing attributes, not the layout.
+ for line in lines where line.range.length > 0 {
+ guard let other = reference[line.range.location] else { mismatches += 1; continue }
+ if abs(other.minY - line.rect.minY) > 0.5 || abs(other.minX - line.rect.minX) > 0.5 { mismatches += 1 }
+ }
+ print("PHONE LARGE textkit2: \(lines.count) lines near the end compared with a whole layout, \(mismatches) differ")
+ XCTAssertGreaterThan(lines.count, 5)
+ XCTAssertEqual(mismatches, 0, "lines near the end where a whole layout puts them")
+ withExtendedLifetime(layout) {}
+ }
- // The jump.
- let end = storage.length - 8
- requests = DocsProbes.lineRequests
- start = .now
- text.selectedRange = NSRange(location: end, length: 0)
+ /// The 72.7 pt caret (S1b, #173): TextKit 1's caret against its line,
+ /// as shipped and once the view has laid itself out.
+ func testTheTextKit1CaretAtTheEnd() async throws {
+ guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") }
+ DocsFonts.register()
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ window.makeKeyAndVisible()
+ defer { window.isHidden = true }
+ for paged in [true, false] {
+ let text = TextKit1PagedView(frame: window.bounds)
+ text.paged = paged
+ window.addSubview(text)
+ defer { text.removeFromSuperview() }
+ text.attributedText = NativeTextProjection.render(SurfaceFixture.projection(SurfaceFixture.pages(Self.pages)))
+ text.layoutIfNeeded()
+ let manager = text.layoutManager
+ for (name, location) in [("first line", 3), ("page 2", Self.lineStart(text.textStorage.string as NSString, near: 4000) + 5), ("end", text.textStorage.length - 8)] {
+ text.selectedRange = NSRange(location: location, length: 0)
text.scrollRangeToVisible(text.selectedRange)
+ let before = text.caretRect(for: text.selectedTextRange!.start)
text.layoutIfNeeded()
- print("PHONE LARGE \(mode): jump to the end \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
- let geometry = (container as! DocsPageTextContainer).geometry
- let glyph = manager.glyphIndexForCharacter(at: end)
+ try await Task.sleep(for: .milliseconds(50))
+ let after = text.caretRect(for: text.selectedTextRange!.start)
+ let glyph = manager.glyphIndexForCharacter(at: location)
let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
- let caret = text.caretRect(for: text.selectedTextRange!.start)
- print("PHONE LARGE \(mode): caret \(caret), its glyph's line \(line)")
- XCTAssertTrue(caret.midY > line.minY && caret.midY < line.maxY, "\(mode): the caret (\(caret)) is on its glyph's line (\(line))")
- let shown = manager.glyphRange(forBoundingRect: text.bounds, in: container)
- manager.enumerateLineFragments(forGlyphRange: shown) { rect, _, _, _, _ in
- let page = geometry.page(at: rect.minY)
- let top = CGFloat(page) * geometry.stride + DocsPageGeometry.verticalMargin
- XCTAssertGreaterThanOrEqual(rect.minY, top - 0.01, "\(mode): a line (\(rect)) starts in a gap")
- XCTAssertLessThanOrEqual(rect.maxY, top + geometry.bodyHeight + 0.01, "\(mode): a line (\(rect)) straddles a page gap")
- }
- // Settled: the lines near the end against a whole layout.
- let reference = NSTextStorage(attributedString: storage)
- let referenceManager = NSLayoutManager()
- referenceManager.usesFontLeading = false
- let referenceContainer = DocsPageTextContainer(size: container.size)
- referenceContainer.lineFragmentPadding = 0
- referenceContainer.geometry = geometry
- reference.addLayoutManager(referenceManager)
- referenceManager.addTextContainer(referenceContainer)
- referenceManager.ensureLayout(for: referenceContainer)
- var mismatches = 0, compared = 0
- manager.enumerateLineFragments(forGlyphRange: shown) { rect, _, _, glyphs, _ in
- let character = manager.characterIndexForGlyph(at: glyphs.location)
- let other = referenceManager.lineFragmentRect(forGlyphAt: referenceManager.glyphIndexForCharacter(at: character), effectiveRange: nil)
- compared += 1
- if abs(other.minY - rect.minY) > 0.5 || abs(other.minX - rect.minX) > 0.5 { mismatches += 1 }
- }
- XCTAssertGreaterThan(compared, 5)
- XCTAssertEqual(mismatches, 0, "\(mode): lines near the end where a whole layout puts them (\(mismatches) of \(compared) differ)")
- print("PHONE LARGE \(mode): \(compared) lines near the end compared with a whole layout, \(mismatches) differ")
- withExtendedLifetime(reference) {}
- text.removeFromSuperview()
- window.isHidden = true
+ let used = manager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil)
+ let point = manager.location(forGlyphAt: glyph)
+ let geometry = (text.textContainer as! DocsPageTextContainer).geometry
+ let first = text.firstRect(for: text.textRange(from: text.position(from: text.beginningOfDocument, offset: location)!, to: text.position(from: text.beginningOfDocument, offset: location + 1)!)!)
+ print("PHONE LARGE textkit1 paged=\(paged) \(name): firstRect \(first); caret before layout \(before), after \(after); line \(line), used \(used), glyph at \(point); page \(geometry.page(at: line.minY)), line's offset in its page \(line.minY - CGFloat(geometry.page(at: line.minY)) * geometry.stride); offset \(line.minY - after.minY)")
}
- // The layout manager alone, background layout on and off.
- let content = NativeTextProjection.render(projection)
- for background in [true, false] {
- let storage = NSTextStorage()
- let manager = NSLayoutManager()
- if !background { manager.setValue(false, forKey: "backgroundLayoutEnabled") }
- let container = DocsPageTextContainer(size: CGSize(width: 402, height: 1_000_000))
- container.lineFragmentPadding = 0
- container.geometry = DocsPageGeometry(viewportWidth: 402, paged: true)
- storage.addLayoutManager(manager)
- manager.addTextContainer(container)
- func report(_ what: String, _ body: () -> Void) {
- let requests = DocsProbes.lineRequests, start = ContinuousClock.now
- body()
- print("PHONE LARGE bare stack, background layout \(background ? "on" : "off"): \(what): \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
+ }
+ }
+
+ static func lineStart(_ string: NSString, near location: Int) -> Int {
+ var at = location
+ while at > 0, string.character(at: at - 1) != 10 { at -= 1 }
+ return at
+ }
+
+ /// The laid-out lines of a TextKit 2 view between two heights, in the
+ /// text view's coordinates, each with its character range.
+ static func lines(in text: UITextView, near top: CGFloat, height: CGFloat) -> [(range: NSRange, rect: CGRect)] {
+ guard let layout = text.textLayoutManager, let content = layout.textContentManager else { return [] }
+ let origin = text.textContainerInset
+ var found: [(NSRange, CGRect)] = []
+ let start = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top - origin.top)))?.rangeInElement.location ?? layout.documentRange.location
+ layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in
+ let frame = fragment.layoutFragmentFrame
+ if frame.minY + origin.top > top + height { return false }
+ let base = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
+ for line in fragment.textLineFragments {
+ let bounds = line.typographicBounds
+ let rect = CGRect(x: frame.minX + bounds.minX + origin.left, y: frame.minY + bounds.minY + origin.top, width: bounds.width, height: bounds.height)
+ found.append((NSRange(location: base + line.characterRange.location, length: line.characterRange.length), rect))
}
- report("the document set") { storage.setAttributedString(content) }
- report("the first screen laid out") { manager.ensureLayout(forBoundingRect: CGRect(x: 0, y: 0, width: 402, height: 874), in: container) }
- report("a new line typed near the start") { storage.replaceCharacters(in: NSRange(location: 10, length: 0), with: String(repeating: "Words to wrap the line. ", count: 4)) }
- report("the first screen laid out again") { manager.ensureLayout(forBoundingRect: CGRect(x: 0, y: 0, width: 402, height: 874), in: container) }
+ return true
+ }
+ return found
+ }
+
+ static func ms(_ start: ContinuousClock.Instant) -> Double {
+ let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15
+ }
+}
+
+extension UITextView {
+ /// The TextKit 1 layout manager only if the view already has one: asking
+ /// `layoutManager` itself would switch a TextKit 2 view to TextKit 1.
+ func layoutManager(peeking: Bool) -> NSLayoutManager? { textLayoutManager == nil ? layoutManager : nil }
+}
+
+/// The iPhone text view as it shipped before S3 (TextKit 1, the whole
+/// document laid out in `layoutSubviews`), kept for the caret comparison.
+final class TextKit1PagedView: UITextView {
+ var paged = false
+ init(frame: CGRect) {
+ let storage = NSTextStorage()
+ let manager = NSLayoutManager()
+ manager.usesFontLeading = false
+ let pages = DocsPageTextContainer(size: CGSize(width: max(320, frame.width), height: 1_000_000))
+ pages.lineFragmentPadding = 0
+ storage.addLayoutManager(manager)
+ manager.addTextContainer(pages)
+ super.init(frame: frame, textContainer: pages)
+ textContainerInset = .zero
+ }
+ required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ guard let pages = textContainer as? DocsPageTextContainer else { return }
+ let width = max(160, bounds.width)
+ let size = CGSize(width: width, height: 1_000_000)
+ if pages.size != size { pages.size = size }
+ pages.geometry = DocsPageGeometry(viewportWidth: width, paged: paged)
+ layoutManager.ensureLayout(for: pages)
+ let height = pages.geometry.documentHeight(usedHeight: layoutManager.usedRect(for: pages).maxY)
+ if abs(contentSize.height - height) > 0.5 || abs(contentSize.width - width) > 0.5 {
+ contentSize = CGSize(width: width, height: height)
}
}
}
diff --git a/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift
new file mode 100644
index 0000000..d63ba7d
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/PhonePaginationTests.swift
@@ -0,0 +1,113 @@
+#if os(iOS)
+import UIKit
+import XCTest
+@testable import DocsKit
+
+/// The iPhone's page breaks on TextKit 2 (S3, `DocsPhonePages`): a 20-page
+/// document, paged, edited through the text view (a Return, a deleted
+/// paragraph, a pasted run of paragraphs, typing that changes a line count).
+/// After each edit, once the pages have placed everything:
+/// - no line starts in a page gap or crosses a page's bottom margin (a
+/// paragraph taller than a page's body is the one exception, and the
+/// fixture has none);
+/// - every break is laid out where the pages placed it;
+/// - every line is where a fresh view of the same text, laid out whole,
+/// puts it.
+@MainActor final class PhonePaginationTests: XCTestCase {
+ func testBreaksFollowEditsAndMatchAWholeLayout() 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
+ state.publish(SurfaceFixture.projection(SurfaceFixture.pages(20)), generation: 1, dirty: nil)
+ text.layoutIfNeeded()
+ try check(text, "at open")
+
+ let storage = text.textStorage
+ func edit(_ range: NSRange, _ replacement: String, _ what: String) throws {
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: replacement) ?? true {
+ storage.replaceCharacters(in: range, with: NSAttributedString(string: replacement, attributes: text.typingAttributes))
+ text.selectedRange = NSRange(location: range.location + replacement.utf16.count, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
+ text.layoutIfNeeded()
+ try check(text, what)
+ }
+ let string = { storage.string as NSString }
+ try edit(NSRange(location: string().range(of: "\n", range: NSRange(location: 2000, length: string().length - 2000)).location, length: 0), "\n", "a Return")
+ let paragraph = string().paragraphRange(for: NSRange(location: 9000, length: 0))
+ try edit(paragraph, "", "a deleted paragraph")
+ try edit(NSRange(location: 4000, length: 0), String(repeating: "Pasted words that wrap across the line. ", count: 12) + "\nA second pasted paragraph.\n", "a pasted run of paragraphs")
+ try edit(NSRange(location: 15000, length: 0), String(repeating: "More words. ", count: 9), "typing that adds lines")
+ try edit(NSRange(location: 15000, length: 108), "", "deleting them again")
+ }
+
+ /// 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 {
+ DocsFonts.register()
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ window.makeKeyAndVisible()
+ defer { window.isHidden = true }
+ let text = DocsTextView(frame: window.bounds)
+ text.paged = true
+ window.addSubview(text)
+ defer { text.removeFromSuperview() }
+ text.attributedText = NSAttributedString(string: "One line.", attributes: [.font: DocsFonts.defaultFont()])
+ text.layoutIfNeeded()
+ XCTAssertGreaterThanOrEqual(text.contentSize.height, text.headerHeight + DocsPageGeometry.paperHeight - 0.5)
+ text.paged = false
+ text.layoutIfNeeded()
+ XCTAssertLessThan(text.contentSize.height, DocsPageGeometry.paperHeight, "pageless, the content is the text's")
+ }
+
+ /// Everything placed, then the three checks.
+ private func check(_ text: DocsTextView, _ when: String) throws {
+ text.paginateEverything()
+ let layout = try XCTUnwrap(text.textLayoutManager)
+ let content = try XCTUnwrap(layout.textContentManager)
+ let geometry = text.geometry
+ let lines = PhoneLargeDocumentTests.lines(in: text, near: 0, height: .greatestFiniteMagnitude)
+ XCTAssertGreaterThan(lines.count, 100, when)
+ var straddling = 0
+ for line in lines where line.range.length > 0 {
+ let y = line.rect.minY - text.headerHeight
+ let top = CGFloat(geometry.page(at: y)) * geometry.stride + DocsPageGeometry.verticalMargin
+ if y < top - 0.01 || y + line.rect.height > top + geometry.bodyHeight + 0.01 { straddling += 1 }
+ }
+ XCTAssertEqual(straddling, 0, "\(when): lines in a gap or across a page's bottom margin")
+ var off = 0
+ for index in text.pages.paragraphs.indices 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)
+ if abs(top - placed) > 0.5 { off += 1 }
+ }
+ XCTAssertEqual(off, 0, "\(when): breaks laid out away from where they were placed")
+ // A fresh view of the same text, laid out whole.
+ 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 lines where line.range.length > 0 {
+ 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 away from where a whole layout puts them")
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift b/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
index eef0309..a7fb754 100644
--- a/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
+++ b/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
@@ -302,7 +302,8 @@ enum EditorScript: Sendable {
}
text.setNeedsLayout()
text.layoutIfNeeded()
- text.layoutManager.ensureLayout(for: text.textContainer)
+ // TextKit 2 (S3): never `layoutManager`, which would switch to TextKit 1.
+ if let layout = text.textLayoutManager { layout.ensureLayout(for: layout.documentRange) }
text.setContentOffset(CGPoint(x: 0, y: scroll), animated: false)
#endif
}
diff --git a/native/apple/Tests/DocsSnapshots/PhoneSnapshots.swift b/native/apple/Tests/DocsSnapshots/PhoneSnapshots.swift
new file mode 100644
index 0000000..4f41d0b
--- /dev/null
+++ b/native/apple/Tests/DocsSnapshots/PhoneSnapshots.swift
@@ -0,0 +1,143 @@
+#if os(iOS)
+import Foundation
+import RastrilloApple
+import RastrilloSnapshots
+import RastrilloTestSupport
+import SwiftUI
+import UIKit
+import XCTest
+@testable import DocsKit
+
+/// The S3 iPhone document (spec 2026-11-22 §3, §11): the real
+/// `DocsWorkspace` opening a fixture document on the editor snapshots'
+/// in-memory server and pushing it, as a writer and as a reader; and the
+/// Format sheet and the Share sheet as the sheet draws them. Light and dark
+/// at the default size and AX3; the document, the sheets also in Arabic and
+/// Russian.
+final class DocsPhoneDocumentSnapshots: XCTestCase {
+ @MainActor func testPhoneDocumentScreens() async throws {
+ try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil,
+ "Run with native/scripts/snapshots.sh")
+ DocsFonts.register()
+ let settings = SnapshotSettings(tint: OficinaPalette.accent(.docs))
+ await assertSnapshots(of: SnapshotCatalog(app: "docs-phone", variants: [.init(.light, .standard), .init(.dark, .standard)],
+ settings: settings, screens: Self.screens + Self.languageScreens))
+ await assertSnapshots(of: SnapshotCatalog(app: "docs-phone-ax3", variants: [.init(.light, .accessibility), .init(.dark, .accessibility)],
+ settings: settings, screens: Self.screens))
+ await PhoneDocumentScreen.stopAll()
+ }
+
+ static let phone = SnapshotSize.fixed(width: 402, height: 874)
+ static let sheet = SnapshotSize.width(402)
+
+ @MainActor static var screens: [SnapshotScreen] {
+ [
+ SnapshotScreen("phone-document", mac: nil, iphone: phone) { PhoneDocumentScreen(reader: false) },
+ SnapshotScreen("phone-reader", mac: nil, iphone: phone) { PhoneDocumentScreen(reader: true) },
+ SnapshotScreen("phone-format-sheet", mac: nil, iphone: sheet) { PhoneFormatSheetScreen(language: "en") },
+ SnapshotScreen("phone-share-sheet", mac: nil, iphone: sheet) { PhoneShareSheetScreen(language: "en") },
+ ]
+ }
+ @MainActor static var languageScreens: [SnapshotScreen] {
+ ["ar", "ru"].flatMap { language in [
+ SnapshotScreen("phone-document-" + language, mac: nil, iphone: phone) { PhoneDocumentScreen(reader: false, language: language) },
+ SnapshotScreen("phone-format-sheet-" + language, mac: nil, iphone: sheet) { PhoneFormatSheetScreen(language: language) },
+ SnapshotScreen("phone-share-sheet-" + language, mac: nil, iphone: sheet) { PhoneShareSheetScreen(language: language) },
+ ] }
+ }
+}
+
+/// The document as the iPhone shows it: the workspace opening "doc" and
+/// pushing it, until its text is drawn and its title measured.
+@MainActor struct PhoneDocumentScreen: View {
+ let reader: Bool
+ var language = "en"
+ @State private var server: EditorServer?
+ @State private var ready = false
+ private let probe = ViewProbe()
+ private static var opened: [EditorServer] = []
+ static func stopAll() async { opened.removeAll() }
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ if let server {
+ DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", team: "Tito",
+ connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)))
+ .background { PhoneProbeView(probe: probe) }
+ }
+ if !ready { PhoneOpeningCounter() }
+ }
+ .environment(\.locale, Locale(identifier: language))
+ .environment(\.layoutDirection, language == "ar" ? .rightToLeft : .leftToRight)
+ .task { await open() }
+ }
+
+ private func open() async {
+ do {
+ let server = EditorServer()
+ if reader { await server.readOnly() }
+ let fixture: EditorFixture = language == "ar" ? .arabic : language == "ru" ? .russian : .millbrook
+ try await server.seed(fixture.blocks)
+ Self.opened.append(server)
+ self.server = server
+ let deadline = ContinuousClock.now + .seconds(10)
+ while ContinuousClock.now < deadline {
+ if let text = probe.textView, text.textStorage.length > 100, text.headerHeight > 0, await server.openStreams == 1 { break }
+ try await Task.sleep(for: .milliseconds(20))
+ }
+ guard let text = probe.textView, text.textStorage.length > 100 else { throw EditorScreenFailure("the document did not open") }
+ text.setContentOffset(CGPoint(x: 0, y: -text.adjustedContentInset.top), animated: false)
+ text.layoutIfNeeded()
+ try await Task.sleep(for: .milliseconds(400))
+ ready = true
+ } catch {
+ print("phone snapshot did not open: \(error)")
+ }
+ }
+}
+
+/// The Format sheet on its own, as the sheet's medium detent shows it.
+@MainActor struct PhoneFormatSheetScreen: View {
+ let language: String
+ @State private var model = DocsModel(transport: { nil })
+ var body: some View {
+ DocsFormatSheet(model: model, close: {})
+ .frame(height: 430, alignment: .top)
+ .background(Color(uiColor: .systemBackground))
+ .environment(\.locale, Locale(identifier: language))
+ .environment(\.layoutDirection, language == "ar" ? .rightToLeft : .leftToRight)
+ }
+}
+
+/// The Share sheet's panel, as the sheet shows it: two people, the team
+/// rung on, and the link published with the once-only URL showing.
+@MainActor struct PhoneShareSheetScreen: View {
+ let language: String
+ var body: some View {
+ let information = DocsShareInformation(sqid: "doc", title: "A History of the Millbrook Waterworks",
+ grants: [DocsShareGrant(address: "bob@example.com", role: "writer"),
+ DocsShareGrant(address: "carol.long-address@example.org", role: "reader")],
+ published: true, public_url: "", visibility: "team", error: "")
+ let model = DocsSharePanelModel(sqid: "doc", title: information.title, information: information,
+ onceURL: URL(string: "https://docs.oficina.works/p/Hx7kQ2mVb9tLr4sN"))
+ DocsSharePanel(model: model, me: "alice@example.com", focusOnAppear: false, close: {})
+ .background(Color(uiColor: .systemBackground))
+ .environment(\.locale, Locale(identifier: language))
+ .environment(\.layoutDirection, language == "ar" ? .rightToLeft : .leftToRight)
+ }
+}
+
+@MainActor private struct PhoneOpeningCounter: View {
+ @State private var frame = 0
+ var body: some View {
+ Text(verbatim: "opening \(frame)").padding(4).background(Color.red).foregroundStyle(.white)
+ .task { while !Task.isCancelled { frame &+= 1; try? await Task.sleep(for: .milliseconds(10)) } }
+ }
+}
+
+private struct PhoneProbeView: UIViewRepresentable {
+ let probe: ViewProbe
+ func makeUIView(context: Context) -> UIView { let view = UIView(); probe.view = view; return view }
+ func updateUIView(_ view: UIView, context: Context) {}
+}
+#endif
diff --git a/native/benchmarks/README.md b/native/benchmarks/README.md
index 9d9fdd3..7f30a02 100644
--- a/native/benchmarks/README.md
+++ b/native/benchmarks/README.md
@@ -222,3 +222,38 @@ measured 2.3–2.7 s after; keys median 2.9–3.9 ms, 4–17 stalls while the
chunks run. Before the last idle chunk fixed the storage's attributes, keys
typed during measuring stayed at about 7 ms (against 3.5) until the next
document was opened.
+
+## S3: the iPhone editor on TextKit 2 (2026-11-28, `native/iphone-document`)
+
+`PhoneLargeDocumentTests` (DocsPhoneTests, `TEST_RUNNER_DOCS_PHONE_LARGE=1`),
+p200h paged (200 pages, 1,260 paragraphs), iPhone 18 Pro simulator, iOS
+27.0, DocsKit Debug, three runs at load 8–9:
+
+| | TextKit 1 (as shipped) | TextKit 2 (S3) | Target |
+|---|---|---|---|
+| Open, main thread to the first screen | 1.27 s, the whole document | 159–168 ms (render 125–128 ms), 11 of 1,260 paragraphs laid out | ≤ 250 ms |
+| Per key, median (40 keys mid-document, on screen) | 1.3–2.7 ms | 6.4–6.5 ms | ≤ 8 ms |
+| Worst key (the worst are those that change a line count) | 250–480 ms | 12.4–12.7 ms | ≤ 16.7 ms |
+| Fragments laid out per key | (10,454 line requests) | median 1, max 6 | |
+| Jump to the end before anything below the first screen is laid out | (already laid out) | 465–472 ms, once (spec §7 Fallback) | |
+
+After the jump: 354 page breaks, 0 laid out away from where they were
+placed; the caret on its glyph's line; 41 lines near the end compared
+with a fresh view laid out whole, 0 differ. Breaks are per paragraph
+(`DocsPhonePages`): a paragraph that would cross a page's body moves to the
+next page's top, the space carried by the previous paragraph's layout
+fragment; measurements are fragment-local, because TextKit 2 leaves stale
+origins on fragments below an edit. `PhonePaginationTests` checks a 20-page
+document after a Return, a deleted paragraph, a paste and typing: no line
+in a gap or across a bottom margin, every break where it was placed, every
+line where a whole layout puts it (it fails with the break's space removed).
+
+**The 72.7 pt caret.** On TextKit 1, UIKit ignores 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 are both drawn 72 pt above where the layout
+manager says the line is, in paged and pageless alike, at the first line
+as at the end (`testTheTextKit1CaretAtTheEnd`, offsets 72.60–72.67 pt). So
+it was real and visible: no iPhone page had a top margin and the bottom
+margin was doubled (S0's "iPhone page-1 top margin missing"); the probe
+measured it by comparing the caret with container coordinates. On
+TextKit 2 the margin is `textContainerInset` and the caret sits on its line.
diff --git a/native/ios/UITests/NativeUITests.swift b/native/ios/UITests/NativeUITests.swift
index 418c8d8..b41ec41 100644
--- a/native/ios/UITests/NativeUITests.swift
+++ b/native/ios/UITests/NativeUITests.swift
@@ -201,4 +201,188 @@ final class NativeUITests: XCTestCase {
let screenshot = XCTAttachment(screenshot: app.screenshot())
screenshot.name = "Docs native editor"; screenshot.lifetime = .keepAlways; add(screenshot)
}
+
+ // MARK: - S3: the iPhone document (spec 2026-11-22 §3, §11; plan S3 acceptance)
+
+ /// The accessibility audit, saying which element each issue is on.
+ @MainActor private func audit(_ app: XCUIApplication) throws {
+ // Still first: mid-presentation a sheet is scaled, and the audit
+ // reads its text as clipped. Two equal readings of the tree a
+ // quarter second apart (at most 3 s).
+ var tree = app.debugDescription
+ for _ in 0..<12 {
+ usleep(250_000)
+ let next = app.debugDescription
+ if next == tree { break }
+ tree = next
+ }
+ let keyboard = app.keyboards.firstMatch
+ let keys = keyboard.exists ? keyboard.frame : nil
+ try app.performAccessibilityAudit { issue in
+ // The system keyboard is UIKit's, not ours: its prediction cells
+ // have no description, and its keys are text the audit cannot
+ // attribute to any element (it reports none). Both appear only
+ // while the keyboard is up, and not without it.
+ if let keys, issue.element.map({ keys.intersects($0.frame) }) ?? true { return true }
+ // The subtitle is a status line with no action (spec §6: one
+ // element, updating frequently, announced by its changes): the
+ // hit-area rule is for what a person taps. Its Dynamic Type
+ // check is unreliable on it: with the same build it passed one
+ // run and failed the next, and its element comes back with no
+ // identifier. It is the caption2 style on iOS, and the AX3
+ // snapshots (docs-phone-ax3) show it scaled.
+ let shown = self.anything(app, "docs.document.subtitle")
+ let subtitle = issue.element.map { $0.identifier == "docs.document.subtitle" || $0.identifier.isEmpty && shown.exists && $0.label == shown.label } ?? false
+ if subtitle, issue.auditType == .hitRegion || issue.auditType == .dynamicType { return true }
+ // A disabled control is dimmed on purpose (Invite before an
+ // address is typed); WCAG's contrast rule exempts inactive
+ // components.
+ if issue.auditType == .contrast, issue.element?.isEnabled == false { return true }
+ // The navigation bar caps its type at the largest sizes, as
+ // UIKit's bars do, and its title is truncated (spec §3: "title
+ // truncated"); a long press shows it whole in the Large Content
+ // Viewer.
+ let bar = app.navigationBars.firstMatch
+ if issue.auditType == .dynamicType || issue.auditType == .textClipped,
+ let element = issue.element, bar.exists, bar.frame.contains(element.frame) { return true }
+ // A sheet at the medium detent is drawn inset and scaled (by
+ // about 0.96: a 52pt chip measures 49.9pt), and the audit then
+ // reads its text as clipped. Nothing in the Format sheet
+ // truncates (its chips wrap: DocsFlowLayout); the AX3
+ // snapshots (docs-phone-ax3, phone-format-sheet) show it whole.
+ let format = self.anything(app, "docs.format.sheet")
+ if issue.auditType == .textClipped, let element = issue.element, format.exists, format.frame.contains(element.frame) { return true }
+ // With the sheet over it, the audit samples the sheet's pixels
+ // inside the text view's frame and reports them as the text
+ // view's contrast; the page's own text is black on white.
+ if issue.auditType == .contrast, issue.element?.identifier == "docs.editor", format.exists { return true }
+ // The page's text does not scale (spec §9): it is the
+ // document's own type, and System Zoom remains.
+ if issue.auditType == .dynamicType, issue.element?.identifier == "docs.editor" { return true }
+ print("AUDIT ISSUE: \(issue.auditType) \(issue.compactDescription) — \(issue.detailedDescription) — element: \(issue.element?.identifier ?? "?") \(issue.element?.label ?? "") \(String(describing: issue.element?.frame))")
+ return false
+ }
+ }
+
+ private func anything(_ app: XCUIApplication, _ identifier: String) -> XCUIElement {
+ app.descendants(matching: .any).matching(identifier: identifier).firstMatch
+ }
+
+ @MainActor private func openPhoneDocument(_ app: XCUIApplication, _ title: String) throws -> XCUIElement {
+ try XCTSkipUnless(UIDevice.current.userInterfaceIdiom == .phone, "the iPhone layout; iPad keeps today's until S5")
+ let row = app.buttons[title].firstMatch
+ XCTAssertTrue(row.waitForExistence(timeout: 15), "\(title) is listed")
+ row.tap()
+ let editor = app.textViews["docs.editor"]
+ XCTAssertTrue(editor.waitForExistence(timeout: 15), "\(title) opened")
+ return editor
+ }
+
+ /// A writer: the bar holds undo/redo, Aa and •••; ••• holds every item;
+ /// the keyboard brings the keyboard bar; the title folds into the bar on
+ /// typing, on scroll and with the Format sheet; Aa opens the sheet with
+ /// the text view still holding the keyboard focus (its selection
+ /// visible) and the keyboard gone; and the accessibility audit passes on
+ /// the document, the sheet and the Share sheet.
+ @MainActor func testPhoneDocumentForAWriter() throws {
+ continueAfterFailure = false
+ let app = XCUIApplication()
+ app.launch()
+ defer { app.terminate() }
+ let editor = try openPhoneDocument(app, "Native review document")
+ let inline = anything(app, "docs.document.inlineTitle")
+ XCTAssertTrue(app.staticTexts["docs.document.title"].waitForExistence(timeout: 5), "the large title shows")
+ XCTAssertFalse(inline.exists, "and the bar's title does not")
+ XCTAssertTrue(app.buttons["docs.format.toggle"].exists, "Aa")
+ XCTAssertTrue(app.buttons["docs.undo"].exists && app.buttons["docs.redo"].exists, "undo and redo")
+ XCTAssertFalse(app.buttons["docs.share"].exists, "no Share pill beside the title (ruling 4)")
+ try audit(app)
+
+ app.buttons["docs.more"].tap()
+ // A SwiftUI menu's items reach UIKit's menu without their
+ // identifiers: they are found by their (English) titles.
+ for item in ["Share…", "Rename document", "Export and print", "Word count", "Open a document", "Paged", "Infinite", "Help", "Delete…"] {
+ XCTAssertTrue(app.buttons[item].waitForExistence(timeout: 3), "••• holds \(item) for the owner")
+ }
+ app.buttons["Share…"].tap()
+ XCTAssertTrue(anything(app, "docs.share.panel").waitForExistence(timeout: 10), "Share… opens the panel as a sheet")
+ try audit(app)
+ app.buttons["docs.share.close"].tap()
+ XCTAssertTrue(app.buttons["docs.more"].waitForExistence(timeout: 5))
+
+ // The keyboard and its bar, writers only; typing folds the title.
+ editor.tap()
+ XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5), "the keyboard")
+ XCTAssertTrue(app.buttons["docs.keyboard.bold"].waitForExistence(timeout: 5), "the keyboard bar comes with it")
+ try audit(app)
+ editor.typeText("x")
+ XCTAssertTrue(inline.waitForExistence(timeout: 3), "typing folds the title into the bar")
+ let typed = XCTAttachment(screenshot: app.screenshot()); typed.name = "S3 keyboard bar"; typed.lifetime = .keepAlways; add(typed)
+
+ // Aa: the sheet, the keyboard gone, the text view still focused.
+ editor.doubleTap()
+ app.buttons["docs.keyboard.format"].tap()
+ XCTAssertTrue(anything(app, "docs.format.sheet").waitForExistence(timeout: 5), "Aa opens the Format sheet")
+ XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5), "the keyboard goes")
+ XCTAssertEqual(editor.value(forKey: "hasKeyboardFocus") as? Bool, true, "the text view keeps first responder, so its selection stays visible")
+ XCTAssertFalse(app.buttons["docs.keyboard.bold"].exists, "no keyboard bar under the sheet")
+ let sheet = XCTAttachment(screenshot: app.screenshot()); sheet.name = "S3 Format sheet over a selection"; sheet.lifetime = .keepAlways; add(sheet)
+ try audit(app)
+ app.buttons["docs.format.close"].tap()
+ XCTAssertTrue(anything(app, "docs.format.sheet").waitForNonExistence(timeout: 5))
+ XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5), "closing the sheet brings the keyboard back: it was up")
+
+ // Keyboard down, back at the top: the title unfolds; a scroll folds it.
+ app.buttons["docs.keyboard.hide"].tap()
+ XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5))
+ editor.swipeDown(); editor.swipeDown()
+ XCTAssertTrue(inline.waitForNonExistence(timeout: 5), "at the top with the keyboard down, the title unfolds")
+ editor.swipeUp()
+ XCTAssertTrue(inline.waitForExistence(timeout: 5), "scrolling past the title folds it")
+ }
+
+ /// A reader: back and ••• only, ••• without Share, Rename or Delete,
+ /// and no keyboard bar (the text cannot take typing).
+ @MainActor func testPhoneDocumentForAReader() throws {
+ continueAfterFailure = false
+ let app = XCUIApplication()
+ app.launch()
+ defer { app.terminate() }
+ let editor = try openPhoneDocument(app, "Read-only review document")
+ XCTAssertTrue(app.buttons["docs.more"].waitForExistence(timeout: 5), "••• for a reader")
+ XCTAssertFalse(app.buttons["docs.format.toggle"].exists, "no Aa for a reader")
+ XCTAssertFalse(app.buttons["docs.undo"].exists, "no undo for a reader")
+ app.buttons["docs.more"].tap()
+ XCTAssertTrue(app.buttons["Word count"].waitForExistence(timeout: 3), "••• holds Word count for a reader")
+ for item in ["Share…", "Rename document", "Delete…"] {
+ XCTAssertFalse(app.buttons[item].exists, "\(item) is absent for a reader")
+ }
+ XCTAssertTrue(app.buttons["Export and print"].exists, "Export is a reader's too")
+ // A tap outside the menu closes it.
+ app.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.95)).tap()
+ XCTAssertTrue(app.buttons["Word count"].waitForNonExistence(timeout: 3))
+ editor.tap()
+ XCTAssertFalse(app.buttons["docs.keyboard.bold"].waitForExistence(timeout: 2), "no keyboard bar for a reader")
+ try audit(app)
+ }
+
+ /// Plan S3 acceptance: iPad keeps today's layout until S5 (spec §5, the
+ /// gate): the split view, the formatting strip and the toolbar's items,
+ /// and none of the iPhone's ••• or large title.
+ @MainActor func testIPadKeepsTodaysLayout() throws {
+ try XCTSkipUnless(UIDevice.current.userInterfaceIdiom == .pad, "the iPad gate")
+ continueAfterFailure = false
+ let app = XCUIApplication()
+ app.launch()
+ defer { app.terminate() }
+ let row = app.buttons["Native review document"].firstMatch
+ XCTAssertTrue(row.waitForExistence(timeout: 15))
+ row.tap()
+ XCTAssertTrue(app.textViews["docs.editor"].waitForExistence(timeout: 15))
+ XCTAssertTrue(anything(app, "docs.formatting-toolbar").waitForExistence(timeout: 5), "today's formatting strip")
+ XCTAssertTrue(app.buttons["Export and print"].exists, "today's toolbar items")
+ XCTAssertFalse(app.buttons["docs.more"].exists, "no iPhone •••")
+ XCTAssertFalse(anything(app, "docs.document.header").exists, "no iPhone large title")
+ let shot = XCTAttachment(screenshot: app.screenshot()); shot.name = "S3 iPad keeps today's layout"; shot.lifetime = .keepAlways; add(shot)
+ }
}
diff --git a/native/ios/project.yml b/native/ios/project.yml
index 36337f5..f2b4ae1 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -143,6 +143,8 @@ targets:
- path: ../apple/Tests/DocsKitTests/SurfaceTimingTests.swift
- path: ../apple/Tests/DocsKitTests/SurfaceLifecycleTests.swift
- path: ../apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
+ - path: ../apple/Tests/DocsKitTests/PhoneDocumentTests.swift
+ - path: ../apple/Tests/DocsKitTests/PhonePaginationTests.swift
dependencies:
- package: DocsNative
product: DocsKit