oficina / docs Public

Docs native S2a: the pill and Word count read an observed history, pinned by tests

S1a takes DocsModel.projection out of observation, so the undo/redo pill,
Tools ▸ Word count's enabled state and the word-count sheet, which read
it, would have stopped updating after the merge with nothing going red
(Fable on #169, merge hazard). DocsModel now derives two observed values
from every projection it holds, each assigned only when it changes:
history (loaded, canUndo, canRedo) and contentRevision. The three readers
use those. DocsHistoryObservationTests pins each one through
withObservationTracking: the pill's body and the open sheet's re-evaluate
after an edit, and Word count's enabled state follows the document
opening. With the projection unobserved and the old readers, the pill and
sheet tests go red. A merge that stops assigning the projection reddens
all three.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1e1e53e1685f5fc208cca9c1cc95c3998d868817 parent d12bdde
6 files changed, +123 −10
  • native/apple/Sources/DocsKit/DocsDocumentHeader.swift +4 −3
  • native/apple/Sources/DocsKit/DocsEditorCommands.swift +1 −1
  • native/apple/Sources/DocsKit/DocsModel.swift +29 −1
  • native/apple/Sources/DocsKit/DocsToolsControls.swift +14 −0
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +1 −5
  • native/apple/Tests/DocsKitTests/DocsHistoryObservationTests.swift +74 −0

CI cancelled — superseded by a newer push — run details

diff --git a/native/apple/Sources/DocsKit/DocsDocumentHeader.swift b/native/apple/Sources/DocsKit/DocsDocumentHeader.swift
index acaeed3..f99b013 100644
--- a/native/apple/Sources/DocsKit/DocsDocumentHeader.swift
+++ b/native/apple/Sources/DocsKit/DocsDocumentHeader.swift
@@ -122,11 +122,12 @@ enum DocsInspectorState {
@MainActor struct DocsUndoRedoPill: View {
let model: DocsModel
var body: some View {
- let projection = model.projection
+ // The observed history, never the projection (S1a unobserves it).
+ let history = model.history
HStack(spacing: 0) {
- button("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: projection?.canUndo == true)
+ button("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: history.canUndo)
Rectangle().fill(OficinaPalette.line).frame(width: 1, height: DocsSpacing.sp3)
- button("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: projection?.canRedo == true)
+ button("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: history.canRedo)
}
.background(Capsule().fill(OficinaPalette.sunk))
.overlay(Capsule().stroke(OficinaPalette.line, lineWidth: 1))
diff --git a/native/apple/Sources/DocsKit/DocsEditorCommands.swift b/native/apple/Sources/DocsKit/DocsEditorCommands.swift
index 0693b6a..5899904 100644
--- a/native/apple/Sources/DocsKit/DocsEditorCommands.swift
+++ b/native/apple/Sources/DocsKit/DocsEditorCommands.swift
@@ -88,7 +88,7 @@ public struct DocsEditorCommands: Commands {
}
CommandMenu(text("docs.editor.menu.tools")) {
Button { editor?.wordCount.wrappedValue = true } label: { text("docs.editor.menu.tools.wordcount") }
- .disabled(editor?.model.projection == nil)
+ .disabled(editor?.model.history.loaded != true)
}
}
}
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 49493e9..665603d 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -11,7 +11,21 @@ import RastrilloNative
var canCreate = false
var errorKey: String?
var detail: DocumentDetail?
- var projection: CRDTProjection?
+ var projection: CRDTProjection? {
+ didSet {
+ let next = DocumentHistoryState(projection)
+ if next != history { history = next }
+ contentRevision &+= 1
+ }
+ }
+ /// Undo, redo and whether a document is shown, observed on their own:
+ /// the header's pill and Tools ▸ Word count read these, never the
+ /// projection, which S1a takes out of observation. Assigned only when
+ /// they differ.
+ private(set) var history = DocumentHistoryState()
+ /// Moves on every new projection: what a live count (the word-count
+ /// sheet) watches to recompute.
+ private(set) var contentRevision: UInt64 = 0
var projectionGeneration: UInt64 = 0
var renderedGeneration: UInt64 = 0
var composing = false
@@ -724,3 +738,17 @@ import RastrilloNative
}
}
+
+/// What the undo/redo pill and the word-count command show (S2a), derived
+/// from each projection the model holds.
+struct DocumentHistoryState: Equatable, Sendable {
+ var loaded = false
+ var canUndo = false
+ var canRedo = false
+ init() {}
+ init(_ projection: CRDTProjection?) {
+ loaded = projection != nil
+ canUndo = projection?.canUndo == true
+ canRedo = projection?.canRedo == true
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocsToolsControls.swift b/native/apple/Sources/DocsKit/DocsToolsControls.swift
index 8c364ef..2058dc1 100644
--- a/native/apple/Sources/DocsKit/DocsToolsControls.swift
+++ b/native/apple/Sources/DocsKit/DocsToolsControls.swift
@@ -86,3 +86,17 @@ struct DocsToolsControls: View {
LabeledContent { Text(value, format: .number).monospacedDigit() } label: { Text(key, bundle: DocsResources.bundle) }
}
}
+
+/// Tools ▸ Word count… on the Mac: the counts of the document as it is now,
+/// recomputed as it changes. It watches the model's content revision, not
+/// the projection, which S1a takes out of observation.
+@MainActor struct DocsLiveWordCountSheet: View {
+ let model: DocsModel
+ let close: () -> Void
+ var body: some View {
+ let _ = model.contentRevision
+ if let projection = model.projection {
+ DocsWordCountSheet(projection: projection, content: NativeTextProjection.render(projection), selection: model.selection, close: close)
+ }
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index fc8f3f1..38dd179 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -356,11 +356,7 @@ import SwiftUI
}
.focusedSceneValue(\.docsJump, $jumping)
.focusedSceneValue(\.docsEditor, DocsEditorContext(model: model, rename: beginRename, client: liveClient, zoom: $zoom, paged: $paged, sharing: $sharing, exportRequest: $exportRequest, jumping: $jumping, wordCount: $countingWords, shortcuts: $showingShortcuts))
- .sheet(isPresented: $countingWords) {
- if let projection = model.projection {
- DocsWordCountSheet(projection: projection, content: NativeTextProjection.render(projection), selection: model.selection) { countingWords = false }
- }
- }
+ .sheet(isPresented: $countingWords) { DocsLiveWordCountSheet(model: model) { countingWords = false } }
.sheet(isPresented: $showingShortcuts) { DocsShortcutsSheet { showingShortcuts = false } }
#endif
diff --git a/native/apple/Tests/DocsKitTests/DocsHistoryObservationTests.swift b/native/apple/Tests/DocsKitTests/DocsHistoryObservationTests.swift
new file mode 100644
index 0000000..6b55586
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocsHistoryObservationTests.swift
@@ -0,0 +1,74 @@
+#if os(macOS)
+import Foundation
+import Observation
+import RastrilloApple
+import RastrilloNative
+import RastrilloTestSupport
+import Synchronization
+import XCTest
+@testable import DocsKit
+
+/// The merge hazard Fable named on #169: S1a takes `DocsModel.projection`
+/// out of observation, and three S2a readers (the undo/redo pill, Tools ▸
+/// Word count's enabled state, the word-count sheet) would then silently
+/// stop updating. These pin each one changing after an edit, through the
+/// observation SwiftUI uses, so a merge that loses it goes red.
+@MainActor final class DocsHistoryObservationTests: XCTestCase {
+ private func open() async throws -> DocsModel {
+ let server = AccessServer()
+ try await server.inner.seed([.object(["type": .string("paragraph"), "children": .array([
+ .object(["type": .string("text"), "runs": .array([.object(["insert": .string("Hello"), "marks": .object([:])])])])])])])
+ let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity, transport: { server })
+ let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
+ await model.open("doc")
+ return model
+ }
+
+ private func type(_ model: DocsModel) async throws {
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("X")]))
+ let deadline = Date().addingTimeInterval(5)
+ while !model.history.canUndo {
+ guard Date() < deadline else { return XCTFail("the edit never became undoable") }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ }
+
+ /// Whether evaluating `read` registered a dependency that `change` fires.
+ private func observes(_ read: () -> Void, after change: () async throws -> Void) async throws -> Bool {
+ let fired = Mutex(false)
+ withObservationTracking(read) { fired.withLock { $0 = true } }
+ try await change()
+ return fired.withLock { $0 }
+ }
+
+ func testTheUndoPillFollowsAnEdit() async throws {
+ let model = try await open()
+ XCTAssertFalse(model.history.canUndo)
+ let pill = DocsUndoRedoPill(model: model)
+ let followed = try await observes({ _ = pill.body }) { try await type(model) }
+ XCTAssertTrue(followed, "the pill's body re-evaluates when undo becomes possible")
+ XCTAssertTrue(model.history.canUndo)
+ await model.stop()
+ }
+
+ func testWordCountsEnabledStateFollowsTheDocumentOpening() async throws {
+ let server = AccessServer()
+ try await server.inner.seed([])
+ let model = DocsModel(transport: { server }, connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)))
+ XCTAssertFalse(model.history.loaded, "nothing open: Word count is disabled")
+ let followed = try await observes({ _ = model.history.loaded }) { await model.open("doc") }
+ XCTAssertTrue(followed)
+ XCTAssertTrue(model.history.loaded)
+ await model.stop()
+ }
+
+ func testTheWordCountSheetFollowsAnEdit() async throws {
+ let model = try await open()
+ let sheet = DocsLiveWordCountSheet(model: model) {}
+ let followed = try await observes({ _ = sheet.body }) { try await type(model) }
+ XCTAssertTrue(followed, "the open sheet recounts as the document changes")
+ await model.stop()
+ }
+}
+#endif