Docs native S1b: keep typing out of the window's SwiftUI views
Step 0 found more than 2 ms a key outside pagination, all in the window's own views, which SwiftUI evaluated again on every key: - The display pass after a key spent 2–4 ms in NSHostingView.layout: the workspace's body read the outbox summary (the offline banner, the lost-changes alert), which moves twice a key; the Format inspector, the iPhone toolbar and the Format menu read DocumentCommands.isEnabled, which is false while input is pending. The banner and alert now read it in their own view; the panels and menu read isAvailable (access only) and each command checks isEnabled as it runs, as it already did; the iPhone's sync and error rows, and its library's Accounts and Sign out (disabled while anything is unsent), read theirs in their own views. - The toolbar's state, refreshed several times a key, walked the whole projection four times (allocating a path per node) and decoded the marks JSON once per mark asked: about 0.5 ms a refresh at 200 pages. It now reads the marks once and searches only the selection's top-level block. New probe counters for the workspace's and the inspector's bodies; the render-isolation test holds both at zero per key after the first (which makes Undo possible). It counted 88 workspace bodies over 40 keys before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+133
−50
native/apple/Sources/DocsKit/DocsEditorCommands.swift+4 −1native/apple/Sources/DocsKit/DocsFormatInspector.swift+6 −2native/apple/Sources/DocsKit/DocsProbes.swift+8 −2native/apple/Sources/DocsKit/DocsWorkspace.swift+62 −24native/apple/Sources/DocsKit/DocumentCommands.swift+34 −14native/apple/Sources/DocsKit/DocumentToolbarSelection.swift+8 −5native/apple/Sources/DocsKit/EditorToolbar.swift+3 −2native/apple/Tests/DocsKitTests/RenderIsolationTests.swift+8 −0
diff --git a/native/apple/Sources/DocsKit/DocsEditorCommands.swift b/native/apple/Sources/DocsKit/DocsEditorCommands.swift| index 5899904..9556ae7 100644 |
| --- a/native/apple/Sources/DocsKit/DocsEditorCommands.swift |
| +++ b/native/apple/Sources/DocsKit/DocsEditorCommands.swift |
| @@ -56,7 +56,10 @@ public struct DocsEditorCommands: Commands { |
| Button { editor?.actions?.perform("indent") } label: { text("docs.editor.menu.format.indent") } |
| Button { editor?.actions?.perform("outdent") } label: { text("docs.editor.menu.format.outdent") } |
| Button { editor?.actions?.perform("clear-format") } label: { text("docs.editor.menu.format.clear") } |
| - }.disabled(editor?.actions?.isEnabled != true || !(NSApp.keyWindow?.firstResponder is DocsTextView)) |
| + // isAvailable, not isEnabled: that one moves on every key (input |
| + // pending), and the menu bar's commands were evaluated again with |
| + // it. Each command checks it as it runs. |
| + }.disabled(editor?.actions?.isAvailable != true || !(NSApp.keyWindow?.firstResponder is DocsTextView)) |
| } |
| CommandGroup(after: .toolbar) { |
| // Disabled in a reader's window and in the home window (no |
diff --git a/native/apple/Sources/DocsKit/DocsFormatInspector.swift b/native/apple/Sources/DocsKit/DocsFormatInspector.swift| index fd1cfb5..c9dbc6f 100644 |
| --- a/native/apple/Sources/DocsKit/DocsFormatInspector.swift |
| +++ b/native/apple/Sources/DocsKit/DocsFormatInspector.swift |
| @@ -27,6 +27,9 @@ import SwiftUI |
| private var actions: DocumentCommands { DocumentCommands(model: model, content: model.surface.content) } |
| var body: some View { |
| + #if DOCS_PROBES |
| + let _ = DocsProbes.inspectorBodies += 1 |
| + #endif |
| let actions = self.actions |
| let selection = model.toolbarSelection |
| VStack(alignment: .leading, spacing: DocsSpacing.sp4) { |
| @@ -77,9 +80,10 @@ import SwiftUI |
| .compositingGroup() |
| .shadow(color: .black.opacity(colorScheme == .dark ? 0.4 : 0.14), radius: 16, y: 6) |
| // Replica work briefly gates commands on every keystroke; keep that |
| - // out of the disabled styling so the panel does not blink. |
| + // out of the disabled styling so the panel does not blink. Each |
| + // command checks it as it runs (DocumentCommands.isEnabled): read |
| + // here, it re-evaluated this panel twice a key (S1b, step 0). |
| .disabled(!actions.isAvailable) |
| - .allowsHitTesting(actions.isEnabled) |
| .accessibilityElement(children: .contain) |
| .accessibilityLabel(Text("docs.editor.inspector.label", bundle: DocsResources.bundle)) |
| .accessibilityIdentifier("docs.format.inspector") |
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift| index 2835954..e33bd25 100644 |
| --- a/native/apple/Sources/DocsKit/DocsProbes.swift |
| +++ b/native/apple/Sources/DocsKit/DocsProbes.swift |
| @@ -24,6 +24,11 @@ public enum DocsProbes { |
| nonisolated(unsafe) public static var viewUpdateMs = 0.0 |
| /// Body evaluations of the view that hosts the text view. |
| nonisolated(unsafe) public static var hostBodies = 0 |
| + /// Body evaluations of the document window's own views that typing must |
| + /// not reach (S1b step 0: each key re-evaluated them, 2–4 ms a key): |
| + /// the workspace, and the Mac's Format inspector. |
| + nonisolated(unsafe) public static var workspaceBodies = 0 |
| + nonisolated(unsafe) public static var inspectorBodies = 0 |
| /// iOS `UITextView.attributedText` assignments by the editor. |
| nonisolated(unsafe) public static var attributedTextAssignments = 0 |
| /// Publications applied to the text view, and the main-thread time from |
| @@ -55,6 +60,7 @@ public enum DocsProbes { |
| wholeRenders = 0; wholeRenderMs = 0; blockRenders = 0; blockRenderMs = 0 |
| 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 |
| textLayouts = 0; textLayoutMs = 0; draws = 0; drawMs = 0 |
| toolbarRefreshes = 0; toolbarRefreshMs = 0; commands = 0; commandMs = 0 |
| @@ -66,9 +72,9 @@ public enum DocsProbes { |
| } |
| /// The keystroke path's parts (S1b, step 0). |
| public static var pathSummary: String { |
| - String(format: "lineRequests=%d measureLineRequests=%d paginations=%d (%.1f ms) textLayouts=%d (%.1f ms) draws=%d (%.1f ms) toolbarRefreshes=%d (%.1f ms) commands=%d (%.1f ms)", |
| + String(format: "lineRequests=%d measureLineRequests=%d paginations=%d (%.1f ms) textLayouts=%d (%.1f ms) draws=%d (%.1f ms) toolbarRefreshes=%d (%.1f ms) commands=%d (%.1f ms) workspaceBodies=%d inspectorBodies=%d", |
| lineRequests, measureLineRequests, paginations, paginationMs, textLayouts, textLayoutMs, draws, drawMs, |
| - toolbarRefreshes, toolbarRefreshMs, commands, commandMs) |
| + toolbarRefreshes, toolbarRefreshMs, commands, commandMs, workspaceBodies, inspectorBodies) |
| } |
| static func now() -> UInt64 { DispatchTime.now().uptimeNanoseconds } |
| static func ms(since start: UInt64) -> Double { Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6 } |
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift| index e056025..9226ce1 100644 |
| --- a/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| +++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift |
| @@ -75,7 +75,9 @@ import SwiftUI |
| .toolbar { |
| if let accounts { |
| ToolbarItem(placement: .navigation) { |
| - Button(accountsLabel ?? docsMacString("Accounts"), systemImage: accountsLabel == nil ? "chevron.backward" : "person.crop.circle", action: accounts).disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + DocsUnsavedGatedButton(model: model, action: accounts) { |
| + Label(accountsLabel ?? docsMacString("Accounts"), systemImage: accountsLabel == nil ? "chevron.backward" : "person.crop.circle") |
| + } |
| .accessibilityIdentifier("docs.accounts") |
| } |
| } |
| @@ -83,7 +85,7 @@ import SwiftUI |
| ToolbarItemGroup { |
| DocsJumpControls(presented: $jumping) |
| if model.canCreate { Button { beginDocument() } label: { Label { Text("docs.list.create.label", bundle: DocsResources.bundle) } icon: { Image(systemName: "plus") } }.accessibilityIdentifier("docs.create") } |
| - Button { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } } label: { signOutText }.disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + DocsUnsavedGatedButton(model: model, action: { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } }) { signOutText } |
| #if os(iOS) |
| // The Colophon, beside Sign out: the iPhone app has no |
| // settings screen of its own. The Mac has it in the Help menu. |
| @@ -99,6 +101,9 @@ import SwiftUI |
| #endif |
| } |
| public var body: some View { |
| + #if DOCS_PROBES |
| + let _ = DocsProbes.workspaceBodies += 1 |
| + #endif |
| Group { |
| #if os(macOS) |
| if documentID != nil || newDocument { editor } else { home } |
| @@ -107,16 +112,7 @@ import SwiftUI |
| #endif |
| } |
| .safeAreaInset(edge: .top, spacing: 0) { |
| - NativeOfflineBanner(connectivity: model.connectivity, origin: client.origin, summary: model.outboxSummary) |
| - } |
| - |
| - .alert(NativeSyncStrings.kit.unsentLost, isPresented: Binding( |
| - get: { model.lostChangesNotice != nil }, |
| - set: { showing in if !showing { Task { await model.dismissLostChangesNotice() } } } |
| - )) { |
| - Button { Task { await model.dismissLostChangesNotice() } } label: { |
| - Text("native.close", bundle: DocsResources.bundle) |
| - } |
| + DocsOfflineBannerSlot(model: model, origin: client.origin) |
| } |
| .alert(signOutRefusal?.message ?? "", isPresented: Binding(get: { signOutRefusal != nil }, set: { if !$0 { signOutRefusal = nil } })) { |
| Button { signOutRefusal = nil } label: { Text("native.close", bundle: DocsResources.bundle) } |
| @@ -278,18 +274,7 @@ import SwiftUI |
| private var editor: some View { |
| VStack(spacing: 0) { |
| #if os(iOS) |
| - NativeSyncStatusView(status: model.syncStatus) |
| - #endif |
| - #if os(iOS) |
| - if let key = model.errorKey { |
| - HStack { |
| - Text(LocalizedStringKey(key), bundle: DocsResources.bundle) |
| - Button { Task { await model.retry() } } label: { Text("native.retry", bundle: DocsResources.bundle) } |
| - if model.hasUnsavedChanges { |
| - Button(role: .destructive) { discarding = true } label: { Text("native.discard.action", bundle: DocsResources.bundle) } |
| - } |
| - }.padding().accessibilityElement(children: .contain) |
| - } |
| + DocsPhoneStatusRows(model: model, discard: { discarding = true }) |
| #endif |
| if model.loading { ProgressView() } |
| if model.showsDocument { |
| @@ -424,3 +409,56 @@ import SwiftUI |
| #endif |
| } |
| + |
| +/// The offline banner and the lost-changes alert, reading the outbox |
| +/// summary in their own body: read in the workspace's, every key (an entry |
| +/// queued, then sent) evaluated the whole workspace again (S1b, step 0). |
| +private struct DocsOfflineBannerSlot: View { |
| + let model: DocsModel |
| + let origin: URL |
| + var body: some View { |
| + NativeOfflineBanner(connectivity: model.connectivity, origin: origin, summary: model.outboxSummary) |
| + .alert(NativeSyncStrings.kit.unsentLost, isPresented: Binding( |
| + get: { model.lostChangesNotice != nil }, |
| + set: { showing in if !showing { Task { await model.dismissLostChangesNotice() } } } |
| + )) { |
| + Button { Task { await model.dismissLostChangesNotice() } } label: { |
| + Text("native.close", bundle: DocsResources.bundle) |
| + } |
| + } |
| + } |
| +} |
| + |
| +#if os(iOS) |
| +/// The iPhone's sync status and error rows, reading the sync status in |
| +/// their own body: read in the workspace's, every key (pending, sending, |
| +/// saved) evaluated the whole workspace again (S1b, step 0). |
| +private struct DocsPhoneStatusRows: View { |
| + let model: DocsModel |
| + let discard: () -> Void |
| + var body: some View { |
| + NativeSyncStatusView(status: model.syncStatus) |
| + if let key = model.errorKey { |
| + HStack { |
| + Text(LocalizedStringKey(key), bundle: DocsResources.bundle) |
| + 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().accessibilityElement(children: .contain) |
| + } |
| + } |
| +} |
| +#endif |
| + |
| +/// A button disabled while anything is unsent or a draft is being created |
| +/// (Accounts, Sign out), reading that in its own body: read in the |
| +/// workspace's, every key evaluated the whole workspace again (S1b, step 0). |
| +private struct DocsUnsavedGatedButton<Title: View>: View { |
| + let model: DocsModel |
| + let action: () -> Void |
| + @ViewBuilder let title: () -> Title |
| + var body: some View { |
| + Button(action: action) { title() }.disabled(model.hasUnsavedChanges || model.creatingDocument) |
| + } |
| +} |
diff --git a/native/apple/Sources/DocsKit/DocumentCommands.swift b/native/apple/Sources/DocsKit/DocumentCommands.swift| index 60abaf5..6534ae1 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentCommands.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentCommands.swift |
| @@ -8,14 +8,19 @@ import Foundation |
| isAvailable && !model.composing && !model.hasPendingInput |
| && model.renderedGeneration == model.projectionGeneration |
| } |
| - func hasMark(_ name: String) -> Bool { |
| - guard validSelection else { return false } |
| - if model.selection.length == 0 { return (model.typingMarks ?? marksAtCaret)[name] != nil } |
| - var active = false |
| - content.enumerateAttribute(.docsMarks, in: model.selection) { value, _, stop in |
| - if let data = value as? Data, |
| - let marks = try? JSONDecoder().decode([String: JSONValue].self, from: data), marks[name] != nil { |
| - active = true; stop.pointee = true |
| + func hasMark(_ name: String) -> Bool { activeMarks.contains(name) } |
| + /// Every mark `hasMark` finds at the selection: at a caret, the typing |
| + /// marks or those the caret would type with; over a range, any mark any |
| + /// of its runs has. Read once for the toolbar's whole state. |
| + var activeMarks: Set<String> { |
| + guard validSelection else { return [] } |
| + if model.selection.length == 0 { return Set((model.typingMarks ?? marksAtCaret).keys) } |
| + var active = Set<String>() |
| + var seen = Set<Data>() |
| + content.enumerateAttribute(.docsMarks, in: model.selection) { value, _, _ in |
| + if let data = value as? Data, seen.insert(data).inserted, |
| + let marks = try? JSONDecoder().decode([String: JSONValue].self, from: data) { |
| + active.formUnion(marks.keys) |
| } |
| } |
| return active |
| @@ -25,6 +30,9 @@ import Foundation |
| guard let id = selectedBlocks.first else { return false } |
| return path(to: id)?.contains { $0.type == type } == true |
| } |
| + /// The path to the selection's first block (the toolbar's whole state |
| + /// reads it once). |
| + var selectedPath: [CRDTNode]? { selectedBlocks.first.flatMap { path(to: $0) } } |
| @discardableResult func perform(_ action: String) -> Bool { |
| guard isEnabled else { return false } |
| switch action { |
| @@ -165,16 +173,28 @@ import Foundation |
| } |
| return submit(commands) |
| } |
| + /// The nodes from the top level down to `id`. Searched first in the |
| + /// top-level block the selection is in (`.docsTopBlock`), so the |
| + /// toolbar's state, read on every key, costs one block and not the |
| + /// document; then everywhere, as before. |
| private func path(to id: String) -> [CRDTNode]? { |
| - func search(_ nodes: [CRDTNode], ancestors: [CRDTNode]) -> [CRDTNode]? { |
| + func search(_ nodes: [CRDTNode], _ path: inout [CRDTNode]) -> Bool { |
| for node in nodes { |
| - let path = ancestors + [node] |
| - if node.id == id { return path } |
| - if let result = search(node.children ?? [], ancestors: path) { return result } |
| + path.append(node) |
| + if node.id == id || search(node.children ?? [], &path) { return true } |
| + path.removeLast() |
| } |
| - return nil |
| + return false |
| + } |
| + let children = model.projection?.children ?? [] |
| + var path: [CRDTNode] = [] |
| + if validSelection, content.length > 0, |
| + let top = content.attribute(.docsTopBlock, at: min(model.selection.location, content.length - 1), effectiveRange: nil) as? String, |
| + let block = children.first(where: { $0.id == top }), search([block], &path) { |
| + return path |
| } |
| - return search(model.projection?.children ?? [], ancestors: []) |
| + path = [] |
| + return search(children, &path) ? path : nil |
| } |
| private func submit(_ commands: [[String: JSONValue]]) -> Bool { |
| guard !commands.isEmpty else { return false } |
diff --git a/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift b/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift| index c6585cc..d031ed5 100644 |
| --- a/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift |
| +++ b/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift |
| @@ -24,14 +24,17 @@ struct DocumentToolbarSelection: Equatable { |
| @MainActor init?(commands: DocumentCommands) { |
| guard commands.isEnabled else { return nil } |
| - marks = Set(["strong", "em", "code"].filter { commands.hasMark($0) }) |
| - blocks = Set(["bullet_list", "ordered_list", "blockquote"].filter { commands.hasBlock($0) }) |
| - if let block = commands.selectedBlock { |
| + // The marks and the block path once each: this runs on every key. |
| + let active = commands.activeMarks |
| + let path = commands.selectedPath |
| + marks = Set(["strong", "em", "code"].filter { active.contains($0) }) |
| + blocks = Set(["bullet_list", "ordered_list", "blockquote"].filter { type in path?.contains { $0.type == type } == true }) |
| + if let block = path?.last { |
| style = block.type == "heading" ? "heading" + (block.attrs?["level"] ?? "1") : "paragraph" |
| alignment = block.attrs?["align"] ?? "left" |
| } |
| - font = DocsFonts.family(forMarkNames: DocsFonts.marks.filter { commands.hasMark($0) }).key |
| - size = [8,9,10,11,12,14,18,24,36,48,72].first { commands.hasMark("size_\($0)") } ?? (commands.hasMark("size_sm") ? 10 : commands.hasMark("size_lg") ? 14 : commands.hasMark("size_xl") ? 18 : 12) |
| + font = DocsFonts.family(forMarkNames: DocsFonts.marks.filter { active.contains($0) }).key |
| + size = [8,9,10,11,12,14,18,24,36,48,72].first { active.contains("size_\($0)") } ?? (active.contains("size_sm") ? 10 : active.contains("size_lg") ? 14 : active.contains("size_xl") ? 18 : 12) |
| canUndo = commands.model.projection?.canUndo == true |
| canRedo = commands.model.projection?.canRedo == true |
| hasSelection = commands.model.selection.length > 0 |
diff --git a/native/apple/Sources/DocsKit/EditorToolbar.swift b/native/apple/Sources/DocsKit/EditorToolbar.swift| index c2ddda6..f6a11ec 100644 |
| --- a/native/apple/Sources/DocsKit/EditorToolbar.swift |
| +++ b/native/apple/Sources/DocsKit/EditorToolbar.swift |
| @@ -56,9 +56,10 @@ import SwiftUI |
| .fixedSize(horizontal: false, vertical: true) |
| .accessibilityIdentifier("docs.formatting-toolbar") |
| // Replica work briefly gates commands on every keystroke. Keep that |
| - // synchronization gate out of disabled styling so the bar does not blink. |
| + // synchronization gate out of disabled styling so the bar does not |
| + // blink; each command checks it as it runs (DocumentCommands.isEnabled), |
| + // since reading it here re-evaluated the bar on every key. |
| .disabled(!actions.isAvailable) |
| - .allowsHitTesting(actions.isEnabled) |
| } |
| private func command(_ key: String, icon: String, op: String, enabled: Bool) -> some View { |
| Button { actions.perform(op) } label: { Image(systemName: icon) } |
diff --git a/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift b/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift| index afca7a2..fde21e8 100644 |
| --- a/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift |
| @@ -81,17 +81,25 @@ import UIKit |
| Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text) |
| var typed = LoopFixture.middle |
| var perKey: [(blocks: Int, edits: Int)] = [] |
| + var chrome: [Int] = [] |
| for index in 0..<40 { |
| let blocks = DocsProbes.blockRenders, edits = storageEdits |
| + let bodies = DocsProbes.workspaceBodies + DocsProbes.inspectorBodies |
| let character = index % 10 == 9 ? " " : String(UnicodeScalar(UInt8(97 + index % 26))) |
| Keyboard.type(character, in: text) |
| typed += character |
| try await until("key \(index) drawn") { settled() && surface.content.string.contains(typed) && surface.appliedRevision > 0 } |
| try await Task.sleep(for: .milliseconds(20)) |
| perKey.append((DocsProbes.blockRenders - blocks, storageEdits - edits)) |
| + chrome.append(DocsProbes.workspaceBodies + DocsProbes.inspectorBodies - bodies) |
| } |
| XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole-document renders while typing") |
| XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations while typing") |
| + // S1b step 0: the workspace and the inspector were evaluated again |
| + // on every key (the offline banner's summary, the commands' pending |
| + // input), 2–4 ms of each key's display pass. Only the first key may |
| + // move them: it makes Undo possible. |
| + XCTAssertEqual(chrome.dropFirst().reduce(0, +), 0, "workspace and inspector body evaluations per key after the first: \(chrome)") |
| XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments while typing") |
| XCTAssertLessThanOrEqual(perKey.map(\.blocks).max() ?? 0, 3, "block renders per key: \(perKey.map(\.blocks))") |
| XCTAssertLessThanOrEqual(perKey.map(\.edits).max() ?? 0, 3, "text-storage edits per key: \(perKey.map(\.edits))") |