oficina / docs Public

Docs native S1a: the document surface, per-block drawing and render isolation

Spec 2026-11-22 §7 Design 3, 5, 6, 8–11.

DocumentSurface (one per document model, not observed) holds the text
view's storage state: the revision it reflects, the newest publication,
pendingDirty / fullDiff, a cache of what each block was drawn from, and
the block index. apply() drops a stale publication (revision at or below
what is drawn) and gathers what changed; flushIfDeferred() draws it when
the text view can take it. It re-renders only the changed blocks (dirty,
new, differing under a full comparison) and those whose context moved
(a neighbour's top margin, first or last), keeps every other block as an
anchor if it is one contiguous run of the index, and reconciles each gap
between anchors into its own characters. The optimistic-text, marked-text
and generation guards are as before; iOS assigns attributedText once,
when a document opens. Images re-render only the blocks that hold them.

Triggers: (a) a publication applied, (b) the edit queue drained,
(c) composition ended, (d) projectionGeneration changing or didRender
advancing, (e) inputPaused cleared. SwiftUI no longer retries a render.

One addition to the spec: a block the text view edited itself (typing,
paste, composition) is drawn again at the next publication whatever the
replica's dirty set says, so an edit the replica refused, or one only a
dropped publication carried, cannot stay on screen (the delta-safety test
found it; DocumentSurface.typed(around:)).

Render isolation: the text view is created once per document, and its
host (DocumentEditorHost, equatable) reads only the surface, Pages and
zoom. The model's projection and selection are no longer observed; the
toolbar reads one equality-guarded DocumentToolbarSelection; commands,
word counts and the Mac editor context read the live storage; editability
and typing marks are pushed to the text view; detail, pendingTitle,
draftToken, errorKey and inputPaused assign only when they differ.
DocsWorkspace changes only the editor's page (the host, image loading,
⌘K) and the two DocsToolsControls lines, plus a connectivity parameter
for tests. Pagination is untouched (S1b).

Tests, each seen to fail with its mechanism broken: block render
equivalence (a skipped neighbour re-spacing), the block index under
optimistic typing, delta safety through the real text view (dropped,
delayed and extra projections, ja/zh marked text with peer edits, log
overflow), the five flush triggers with no later publication (a flush
wired to didRender only), and render isolation with §7's counters. The
iPhone half runs them in DocsPhoneTests. The S0 snapshot harness takes
the new wiring; its pictures are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 3ad5cd2a254152b971a41dcc2629bcdfcdadd4a5 parent 9ea85f2
21 files changed, +1,644 −427
  • native/apple/Sources/DocsKit/DocsAttachments.swift +11 −3
  • native/apple/Sources/DocsKit/DocsEditorContext.swift +2 −2
  • native/apple/Sources/DocsKit/DocsFormatInspector.swift +6 −10
  • native/apple/Sources/DocsKit/DocsModel.swift +171 −23
  • native/apple/Sources/DocsKit/DocsToolsControls.swift +10 −8
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +38 −26
  • native/apple/Sources/DocsKit/DocumentSurface.swift +473 −0
  • native/apple/Sources/DocsKit/EditorToolbar.swift +9 −11
  • native/apple/Sources/DocsKit/NativeDocumentTextView.swift +53 −244
  • native/apple/Tests/DocsKitTests/BlockIndexTests.swift +66 −0
  • native/apple/Tests/DocsKitTests/BlockRenderEquivalenceTests.swift +123 −0
  • native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift +142 −0
  • native/apple/Tests/DocsKitTests/DocsFontsTests.swift +3 −3
  • native/apple/Tests/DocsKitTests/FlushTriggerTests.swift +133 −0
  • native/apple/Tests/DocsKitTests/NativeClipboardInputTests.swift +25 −29
  • native/apple/Tests/DocsKitTests/NativeRenderTests.swift +23 −43
  • native/apple/Tests/DocsKitTests/RenderIsolationTests.swift +151 −0
  • native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift +173 −0
  • native/apple/Tests/DocsSnapshots/EditorSnapshots.swift +14 −20
  • native/apple/Tests/DocsSnapshots/WindowSnapshots.swift +2 −2
  • native/ios/project.yml +16 −3
diff --git a/native/apple/Sources/DocsKit/DocsAttachments.swift b/native/apple/Sources/DocsKit/DocsAttachments.swift
index bebf1c1..1383d87 100644
--- a/native/apple/Sources/DocsKit/DocsAttachments.swift
+++ b/native/apple/Sources/DocsKit/DocsAttachments.swift
@@ -23,7 +23,12 @@ private final class ImageRedirectGuard: NSObject, URLSessionTaskDelegate, @unche
/// Document image bytes live only in this screen's memory. External hosts receive
/// no app credentials; same-origin protected assets use the ordinary client.
@MainActor @Observable final class DocsImageStore {
- private(set) var images: [String: DocsPlatformImage] = [:]
+ private(set) var images: [String: DocsPlatformImage] = [:] {
+ didSet { changed?(images) }
+ }
+ /// Told of every change to `images`: the open document's surface draws
+ /// again only the blocks that hold an image that arrived.
+ @ObservationIgnored var changed: (([String: DocsPlatformImage]) -> Void)?
private var generation = UUID()
private var documentURL: URL?
private let session: URLSession = {
@@ -34,13 +39,16 @@ private final class ImageRedirectGuard: NSObject, URLSessionTaskDelegate, @unche
return URLSession(configuration: config, delegate: ImageRedirectGuard(), delegateQueue: nil)
}()
static func sources(in projection: CRDTProjection) -> [String] {
+ projection.children.reduce(into: Set<String>()) { $0.formUnion(sources(in: $1)) }.sorted()
+ }
+ static func sources(in node: CRDTNode) -> Set<String> {
var found = Set<String>()
func visit(_ node: CRDTNode) {
if node.type == "image", let source = node.attrs?["src"] { found.insert(source) }
for child in node.children ?? [] { visit(child) }
}
- for node in projection.children { visit(node) }
- return found.sorted()
+ visit(node)
+ return found
}
func images(forDocumentPath path: String, client: NativeTransport) -> [String: DocsPlatformImage] {
documentURL == URL(string: path, relativeTo: client.origin)?.absoluteURL ? images : [:]
diff --git a/native/apple/Sources/DocsKit/DocsEditorContext.swift b/native/apple/Sources/DocsKit/DocsEditorContext.swift
index dfe4289..2fa3e3b 100644
--- a/native/apple/Sources/DocsKit/DocsEditorContext.swift
+++ b/native/apple/Sources/DocsKit/DocsEditorContext.swift
@@ -17,8 +17,8 @@ struct DocsEditorContext {
let wordCount: Binding<Bool>
let shortcuts: Binding<Bool>
@MainActor var actions: DocumentCommands? {
- guard NSApp.keyWindow?.firstResponder is DocsTextView, let projection = model.projection else { return nil }
- return DocumentCommands(model: model, content: NativeTextProjection.render(projection))
+ guard NSApp.keyWindow?.firstResponder is DocsTextView, model.history.loaded else { return nil }
+ return DocumentCommands(model: model, content: model.surface.content)
}
}
extension FocusedValues { @Entry var docsEditor: DocsEditorContext? }
diff --git a/native/apple/Sources/DocsKit/DocsFormatInspector.swift b/native/apple/Sources/DocsKit/DocsFormatInspector.swift
index c18aa20..fd1cfb5 100644
--- a/native/apple/Sources/DocsKit/DocsFormatInspector.swift
+++ b/native/apple/Sources/DocsKit/DocsFormatInspector.swift
@@ -12,24 +12,23 @@ import SwiftUI
/// Its controls act on the text view's selection: buttons and pop-ups on the
/// Mac do not take first responder from a click, so the caret stays where
/// it was. Selected states come from `DocumentToolbarSelection`, as the
-/// menus' do. It reads the selection itself, so moving the caret
-/// re-evaluates this and not the body hosting the text view.
+/// menus' do: the model's one observed `toolbarSelection`, computed from the
+/// live text at the selection and kept while input is pending (S1a), so
+/// moving the caret re-evaluates this and not the body hosting the text
+/// view. Its commands act on the text view's own storage, never a render.
@MainActor struct DocsFormatInspector: View {
let model: DocsModel
- let content: NSAttributedString
- @State private var settledSelection = DocumentToolbarSelection()
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
@Environment(\.colorScheme) private var colorScheme
@Environment(\.locale) private var locale
static let sizes = [8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72]
- private var actions: DocumentCommands { DocumentCommands(model: model, content: content) }
- private var currentSelection: DocumentToolbarSelection? { DocumentToolbarSelection(commands: actions) }
+ private var actions: DocumentCommands { DocumentCommands(model: model, content: model.surface.content) }
var body: some View {
let actions = self.actions
- let selection = currentSelection ?? settledSelection
+ let selection = model.toolbarSelection
VStack(alignment: .leading, spacing: DocsSpacing.sp4) {
section("docs.editor.toolbar.group.style") {
stylePicker(selection)
@@ -84,9 +83,6 @@ import SwiftUI
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("docs.editor.inspector.label", bundle: DocsResources.bundle))
.accessibilityIdentifier("docs.format.inspector")
- .onChange(of: currentSelection, initial: true) { _, value in
- if let value { settledSelection = value }
- }
}
@ViewBuilder private var panel: some View {
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index 0bf7ee7..edad274 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -9,34 +9,93 @@ import RastrilloNative
private var listRequest = UUID()
var documents: [DocumentSummary] = []
var canCreate = false
- var errorKey: String?
- var detail: DocumentDetail?
- var projection: CRDTProjection? {
+ // Observed state is assigned only when it differs (spec 2026-11-22 §7
+ // Design 11): an equal assignment still invalidates every view that
+ // reads it. These are written from many places, so the guard is in
+ // their setters.
+ @ObservationIgnored private var _errorKey: String?
+ var errorKey: String? {
+ get { access(keyPath: \.errorKey); return _errorKey }
+ set { guard newValue != _errorKey else { return }; withMutation(keyPath: \.errorKey) { _errorKey = newValue } }
+ }
+ @ObservationIgnored private var _detail: DocumentDetail?
+ var detail: DocumentDetail? {
+ get { access(keyPath: \.detail); return _detail }
+ set {
+ guard newValue != _detail else { return }
+ withMutation(keyPath: \.detail) { _detail = newValue }
+ pushEditability()
+ }
+ }
+ /// The newest projection published. Not observed: the editor draws it
+ /// through `surface`, never through SwiftUI (spec §7 Design 2). What
+ /// the chrome needs of it is `history`, observed on its own.
+ @ObservationIgnored var projection: CRDTProjection? {
didSet {
let next = DocumentHistoryState(projection)
if next != history { history = next }
- contentRevision &+= 1
}
}
+ /// The open document's text, as its text view holds it.
+ @ObservationIgnored let surface = DocumentSurface()
/// 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.
+ /// the header's pill, the toolbar's undo and redo, and Tools ▸ Word
+ /// count read these, never the projection. Set with each projection the
+ /// model publishes (publishCurrent), whatever the access and whether or
+ /// not input is pending; 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.
+ /// Moves after each draw that changed the text view's storage (the
+ /// surface's flush; S1a): what a live count (the word-count sheet)
+ /// watches to recompute. Never moves inside a view update.
private(set) var contentRevision: UInt64 = 0
- var projectionGeneration: UInt64 = 0
+ /// Whether a document has been published to the editor: what the
+ /// workspace shows instead of the projection itself.
+ var showsDocument: Bool { history.loaded }
+ /// The formatting at the selection, for the toolbar: one value,
+ /// assigned only when it differs (spec §7 Design 10).
+ private(set) var toolbarSelection = DocumentToolbarSelection()
+ /// The image sources of the document drawn, for the image loader.
+ private(set) var imageSources: [String] = []
+ /// Moves when the editor asks for Open a document… (⌘K): the window
+ /// shows its jump sheet (spec §1, menus).
+ private(set) var jumpRequests = 0
+ var projectionGeneration: UInt64 = 0 {
+ // Trigger (d): the generation caught up.
+ didSet { if oldValue != projectionGeneration { surface.flushIfDeferred() } }
+ }
var renderedGeneration: UInt64 = 0
var composing = false
- var inputPaused = false
+ @ObservationIgnored private var _inputPaused = false
+ var inputPaused: Bool {
+ get { access(keyPath: \.inputPaused); return _inputPaused }
+ set {
+ guard newValue != _inputPaused else { return }
+ withMutation(keyPath: \.inputPaused) { _inputPaused = newValue }
+ pushEditability()
+ // Not a flush trigger (spec §7 Design 6, "Two events are not
+ // triggers"): canRender does not read inputPaused, and must not,
+ // since a reader is paused for good and still sees peers'
+ // changes; a writer paused by a refused command still holds it
+ // as pending input, so the queue draining draws. The call costs
+ // nothing.
+ if !newValue { surface.flushIfDeferred() }
+ }
+ }
/// Spec §6 row 1: a 403 or 404 said the document was deleted or is no
/// longer shared. Left again on a later 200.
var unavailable = false
/// Input paused by a 401 while the session is re-minted (§6 notes): a
/// reason of its own, beside `inputPaused`, so the re-minted session's
/// 200 clears only this one and never a pause something else set.
- private(set) var sessionPaused = false
+ @ObservationIgnored private var _sessionPaused = false
+ private(set) var sessionPaused: Bool {
+ get { access(keyPath: \.sessionPaused); return _sessionPaused }
+ set {
+ guard newValue != _sessionPaused else { return }
+ withMutation(keyPath: \.sessionPaused) { _sessionPaused = newValue }
+ pushEditability()
+ }
+ }
/// Typing and commands are refused: paused for any reason.
var inputBlocked: Bool { inputPaused || sessionPaused }
/// What the window may do with the document (§6 rows 1 and 10).
@@ -45,17 +104,29 @@ import RastrilloNative
var loading = false
var creatingDocument = false
private var lifetime = UUID()
- private(set) var draftToken: String?
+ @ObservationIgnored private var _draftToken: String?
+ private(set) var draftToken: String? {
+ get { access(keyPath: \.draftToken); return _draftToken }
+ set { guard newValue != _draftToken else { return }; withMutation(keyPath: \.draftToken) { _draftToken = newValue } }
+ }
private var creationTask: Task<Void, Never>?
- private var pendingTitle: String?
+ @ObservationIgnored private var _pendingTitle: String?
+ private var pendingTitle: String? {
+ get { access(keyPath: \.pendingTitle); return _pendingTitle }
+ set { guard newValue != _pendingTitle else { return }; withMutation(keyPath: \.pendingTitle) { _pendingTitle = newValue } }
+ }
private var metadataDirty = false
var renameInput: String?
private var titleRevision: UInt64 = 0
var isDraft: Bool { draftToken != nil }
var editorIdentity = UUID()
- var selection = NSRange(location: 0, length: 0)
- var typingMarks: [String: JSONValue]?
+ /// Where the text view's selection is. The text view tells the model
+ /// by callback; nothing observes it (spec §7 Design 10).
+ @ObservationIgnored var selection = NSRange(location: 0, length: 0)
+ var typingMarks: [String: JSONValue]? {
+ didSet { if oldValue != typingMarks { surface.typingMarks = typingMarks; refreshToolbarSelection() } }
+ }
private var replica: CRDTReplica?
private var sequence: Int64 = 0
let offlineAccount: DocsOfflineAccount
@@ -112,6 +183,7 @@ import RastrilloNative
self.connectivity = connectivity ?? .shared
self.offlineAccount = offlineAccount ?? DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity ?? .shared, transport: transport)
if draft { draftToken = UUID().uuidString }
+ configureSurface()
}
convenience init(client: NativeTransport, connectivity: NativeConnectivity? = nil, draft: Bool = false) {
self.init(transport: { client }, connectivity: connectivity, draft: draft)
@@ -234,7 +306,7 @@ import RastrilloNative
// presentations with that document's generations (after `stop`
// they would all be refused as older).
sequence = 0; resetRemoteState()
- projectionGeneration = 0; renderedGeneration = 0
+ projectionGeneration = 0; renderedGeneration = 0; resetSurface()
replica = local
configurePersistence(key: "draft-" + draftToken!, replica: local)
detail = DocumentDetail(sqid: "draft-" + draftToken!, title: String(localized: "docs.document.untitled", bundle: DocsResources.bundle), guid: guid, can_write: true, can_share: false)
@@ -336,7 +408,7 @@ import RastrilloNative
laneSummary = await offlineAccount.outbox.summary.only("doc:" + key)
if cached == nil { try saveMetadata() }
try await offlineAccount.ensureMetadataEntry(key)
- projectionGeneration = 0; renderedGeneration = 0
+ projectionGeneration = 0; renderedGeneration = 0; resetSurface()
selection = NSRange(location: 0, length: 0); typingMarks = nil
composing = false; inputPaused = false
updateLaneSummary(laneSummary)
@@ -361,14 +433,22 @@ import RastrilloNative
if case .number(let generation) = command["generation"], let value = UInt64(exactly: generation) { didRender(value) }
if command["generation"] == nil, renderedGeneration != 0 { command["generation"] = .number(Double(renderedGeneration)) }
if [JSONValue.string("replace_text"), .string("display_edit")].contains(command["op"] ?? .null), let typingMarks { command["marks"] = .object(typingMarks) }
- if ![JSONValue.string("display_edit"), .string("display_autoformat"), .string("display_revert_rule"), .string("display_exit_list"), .string("insert_element")].contains(command["op"] ?? .null) { explicitCommandRevision &+= 1 }
+ if ![JSONValue.string("display_edit"), .string("display_autoformat"), .string("display_revert_rule"), .string("display_exit_list"), .string("insert_element")].contains(command["op"] ?? .null) {
+ explicitCommandRevision &+= 1; surface.explicitCommand()
+ }
editing.append(command)
if editingTask == nil { editingTask = Task { await drainEdits() } }
return true
}
private func drainEdits() async {
let epoch = documentEpoch
- defer { if documentEpoch == epoch { editingTask = nil } }
+ defer {
+ if documentEpoch == epoch {
+ editingTask = nil
+ // Trigger (b): the queue drained.
+ surface.flushIfDeferred()
+ }
+ }
while documentEpoch == epoch, !editing.isEmpty, let replica {
let command = editing.removeFirst()
do {
@@ -386,7 +466,11 @@ import RastrilloNative
}
func compositionChanged(_ active: Bool) {
composing = active
- if !active && editingTask == nil { Task { await publish() } }
+ if !active {
+ // Trigger (c): composition ended.
+ surface.flushIfDeferred()
+ if editingTask == nil { Task { await publish() } }
+ }
}
func canRender(_ generation: UInt64) -> Bool { !hasPendingInput && !composing && generation == projectionGeneration }
func currentSelection() -> NSRange { selection }
@@ -395,6 +479,9 @@ import RastrilloNative
// A delayed acknowledgement cannot retire the currently displayed source.
guard generation > renderedGeneration else { return }
renderedGeneration = generation
+ // Trigger (d): the generation caught up.
+ surface.flushIfDeferred()
+ refreshToolbarSelection()
}
private func publish() async { await publications.run { await self.publishCurrent() } }
private func publishCurrent() async {
@@ -404,8 +491,15 @@ import RastrilloNative
guard documentEpoch == epoch, editing.isEmpty else { return }
do {
let source = renderedGeneration; let selected = selection
- if let presented = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, presented.generation >= projectionGeneration {
+ // What the text view has drawn: the replica answers with what
+ // changed since then, in the same call (spec §7 Design 2).
+ let since = surface.appliedRevision
+ if let presented = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration, since: since), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, presented.generation >= projectionGeneration {
selection = presented.selection; projectionGeneration = presented.generation; projection = presented.projection
+ // Trigger (a), and (d): the generation caught up.
+ surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection,
+ revision: presented.revision, dirty: presented.dirty))
+ refreshToolbarSelection()
schedulePersistence()
}
} catch { if documentEpoch == epoch { errorKey = "native.recovered" } }
@@ -477,7 +571,7 @@ import RastrilloNative
selection = NSRange(location: 0, length: 0)
let previous = replica; replica = nil; detail = nil; projection = nil
sequence = 0; resetRemoteState()
- projectionGeneration = 0; renderedGeneration = 0; errorKey = nil
+ projectionGeneration = 0; renderedGeneration = 0; resetSurface(); errorKey = nil
if let previous { await previous.close() }
}
func saveAll() async -> Bool {
@@ -698,6 +792,60 @@ import RastrilloNative
private func sessionReopened(_ sqid: String, epoch: UUID) async {
if sessionPaused { await refreshAccess(sqid, epoch: epoch) }
}
+
+ // MARK: - The editor's surface
+
+ private func configureSurface() {
+ var hooks = DocumentSurface.Hooks()
+ hooks.edit = { [weak self] command in self?.enqueue(command) ?? false }
+ hooks.canRender = { [weak self] generation in self?.canRender(generation) ?? false }
+ hooks.currentSelection = { [weak self] in self?.selection ?? NSRange(location: 0, length: 0) }
+ // Each draw: the generation drawn, and the content revision (a live
+ // word count recomputes). The surface calls this after a flush, on
+ // the next turn when the flush ran inside SwiftUI's update.
+ hooks.didRender = { [weak self] generation in
+ self?.didRender(generation)
+ self?.contentRevision &+= 1
+ }
+ hooks.compositionChanged = { [weak self] active in self?.compositionChanged(active) }
+ hooks.selectionChanged = { [weak self] range in self?.selectionChanged(range) }
+ hooks.selectionMoved = { [weak self] in self?.selectionMovedExplicitly() }
+ hooks.action = { [weak self] action in self?.perform(action) ?? false }
+ hooks.canAction = { [weak self] action in self?.canPerform(action) ?? false }
+ hooks.imageSourcesChanged = { [weak self] sources in
+ guard let self, self.imageSources != sources else { return }
+ self.imageSources = sources
+ }
+ surface.hooks = hooks
+ pushEditability()
+ }
+ private func resetSurface() {
+ surface.reset()
+ if toolbarSelection != DocumentToolbarSelection() { toolbarSelection = DocumentToolbarSelection() }
+ }
+ private func pushEditability() { surface.isEditable = detail?.can_write == true && !inputBlocked }
+ /// The text view's selection moved.
+ func selectionChanged(_ range: NSRange) {
+ selection = range
+ refreshToolbarSelection()
+ }
+ /// The toolbar's state, from the live text at the selection; kept while
+ /// input is pending, as before.
+ func refreshToolbarSelection() {
+ guard let value = DocumentToolbarSelection(commands: DocumentCommands(model: self, content: surface.content)),
+ value != toolbarSelection else { return }
+ toolbarSelection = value
+ }
+ /// A command from the text view's keys.
+ func perform(_ action: String) -> Bool {
+ if action == "jump" { jumpRequests &+= 1; return true }
+ return DocumentCommands(model: self, content: surface.content).perform(action)
+ }
+ func canPerform(_ action: String) -> Bool {
+ detail?.can_write == true && !hasPendingInput && !composing && !inputBlocked
+ && (action == "undo" ? history.canUndo : history.canRedo)
+ }
+
/// Revalidate capability after stream/write rejection while retaining the draft.
private func refreshAccess(_ sqid: String, epoch: UUID) async {
let revision = titleRevision
diff --git a/native/apple/Sources/DocsKit/DocsToolsControls.swift b/native/apple/Sources/DocsKit/DocsToolsControls.swift
index 2058dc1..24e44f4 100644
--- a/native/apple/Sources/DocsKit/DocsToolsControls.swift
+++ b/native/apple/Sources/DocsKit/DocsToolsControls.swift
@@ -2,9 +2,9 @@ import SwiftUI
@MainActor
struct DocsToolsControls: View {
- let projection: CRDTProjection
- let content: NSAttributedString
- let selection: NSRange
+ /// Read when the word count opens, never in the body: the counts come
+ /// from the live text, not from a render (spec 2026-11-22 §7 Design 9).
+ let model: DocsModel
@State private var showingCount = false
@State private var showingShortcuts = false
@@ -20,7 +20,7 @@ struct DocsToolsControls: View {
Label { Text("docs.editor.menu.tools", bundle: DocsResources.bundle) } icon: { Image(systemName: "wrench.and.screwdriver") }
}
.sheet(isPresented: $showingShortcuts) { DocsShortcutsSheet { showingShortcuts = false } }
- .sheet(isPresented: $showingCount) { DocsWordCountSheet(projection: projection, content: content, selection: selection) { showingCount = false } }
+ .sheet(isPresented: $showingCount) { DocsLiveWordCountSheet(model: model) { showingCount = false } }
}
}
@@ -87,16 +87,18 @@ struct DocsToolsControls: View {
}
}
-/// 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.
+/// Word count, live: the counts of the document as it is now, recomputed
+/// as it changes (Tools ▸ Word count… on the Mac, Tools on the iPhone). It
+/// watches the model's content revision, which moves after each draw, and
+/// counts from the projection's text and the text view's own storage: no
+/// render, so a publication costs the count's walk, not a whole render.
@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)
+ DocsWordCountSheet(projection: projection, content: model.surface.content, selection: model.selection, close: close)
}
}
}
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index c12f2da..e056025 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -52,14 +52,14 @@ import SwiftUI
@State private var signOutRefusal: DocsLeaveBlock?
/// `transport` supplies the account's current session to the model on every
/// request; without one the model keeps `client` for its whole lifetime.
- public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, useAnother: (() -> Void)? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil, team: String? = nil) {
+ public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, useAnother: (() -> Void)? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil, team: String? = nil, connectivity: NativeConnectivity? = nil) {
self.team = team
self._signOutRequested = signOutRequested; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel; self.useAnother = useAnother
self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
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 }, draft: newDocument, offlineAccount: offline)); self.signOut = signOut; self.accounts = accounts; self.client = client; self.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
}
private var library: some View {
List {
@@ -198,6 +198,17 @@ import SwiftUI
}
#endif
}
+ /// The document's images, loaded for the sources its blocks hold; the
+ /// surface draws again only the blocks holding one that arrives.
+ private func loadImages() async {
+ let documentPath = "/d/" + (model.detail?.sqid ?? "")
+ let client = liveClient
+ let surface = model.surface
+ images.changed = { [weak images] _ in
+ surface.imagesChanged(images?.images(forDocumentPath: documentPath, client: client) ?? [:])
+ }
+ await images.load(sources: model.imageSources, client: client, documentPath: documentPath)
+ }
private func beginRename() {
// Only a writer gets an editable title (spec §1, rename).
guard model.documentAccess == .writable else { return }
@@ -255,12 +266,17 @@ import SwiftUI
/// open; a reader's never does, and never writes the state (spec §1).
private var showsInspector: Bool { inspectorOpen && model.documentAccess == .writable }
#endif
+ /// The side the floating inspector covers, for the desk's centring: an
+ /// input of the text view's host, like Pages and zoom.
+ private var inspectorSide: DocsDeskLayout.Side? {
+ #if os(macOS)
+ showsInspector ? (layoutDirection == .rightToLeft ? .left : .right) : nil
+ #else
+ nil
+ #endif
+ }
private var editor: some View {
- #if DOCS_PROBES
- // Today the workspace's body is the text view's host.
- let _ = DocsProbes.hostBodies += 1
- #endif
- return VStack(spacing: 0) {
+ VStack(spacing: 0) {
#if os(iOS)
NativeSyncStatusView(status: model.syncStatus)
#endif
@@ -276,36 +292,32 @@ import SwiftUI
}
#endif
if model.loading { ProgressView() }
- if let projection = model.projection {
- let documentPath = "/d/" + (model.detail?.sqid ?? "")
- let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: liveClient))
+ if model.showsDocument {
+ // The text view's host reads only the surface, Pages,
+ // zoom and the inspector's side (spec 2026-11-22 §7
+ // Design 9): the text reaches it through the surface,
+ // never through this body.
#if os(iOS)
- EditorToolbar(model: model, content: text)
+ EditorToolbar(model: model)
Divider()
#endif
- NativeDocumentTextView(content: text, generation: model.projectionGeneration, didRender: model.didRender, compositionChanged: model.compositionChanged, isEditable: model.detail?.can_write == true && !model.inputBlocked, paged: paged, pendingInput: model.hasPendingInput, canRender: model.canRender, currentSelection: model.currentSelection, selection: $model.selection, edit: model.enqueue, action: { action in
- if action == "jump" {
- // Open a document… (⌘K): the jump palette as a sheet
- // over this window, on the Mac too (spec §1, menus).
- jumping = true
- return true
- }
- return DocumentCommands(model: model, content: text).perform(action)
- }, selectionMoved: model.selectionMovedExplicitly, canAction: { action in model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputBlocked && (action == "undo" ? projection.canUndo : projection.canRedo) }, explicitCommandRevision: model.explicitCommandRevision, zoom: zoom, typingMarks: model.typingMarks)
- #if os(macOS)
- .inspectorSide(showsInspector ? (layoutDirection == .rightToLeft ? .left : .right) : nil)
- #endif
+ DocumentEditorHost(surface: model.surface, paged: paged, zoom: zoom, inspector: inspectorSide)
+ .equatable()
.id(model.editorIdentity)
#if os(macOS)
.overlay(alignment: .topTrailing) {
if showsInspector {
- DocsFormatInspector(model: model, content: text)
+ DocsFormatInspector(model: model)
.padding(.top, DocsDeskLayout.inspectorInset)
.padding(.trailing, DocsDeskLayout.inspectorInset)
}
}
#endif
- .task(id: [documentPath] + DocsImageStore.sources(in: projection)) { await images.load(sources: DocsImageStore.sources(in: projection), client: liveClient, documentPath: documentPath) }
+ .task(id: ["/d/" + (model.detail?.sqid ?? "")] + model.imageSources) { await loadImages() }
+ // Open a document… (⌘K) from the text view's keys: the
+ // jump palette as a sheet over this window, on the Mac
+ // too (spec §1, menus).
+ .onChange(of: model.jumpRequests) { jumping = true }
} else {
ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } }
}
@@ -343,7 +355,7 @@ import SwiftUI
DocumentExportControls(client: liveClient, sqid: detail.sqid, title: detail.title) {
return await model.saveAll()
}.id(detail.sqid)
- if let projection = model.projection { DocsToolsControls(projection: projection, content: NativeTextProjection.render(projection), selection: model.selection) }
+ if model.showsDocument { DocsToolsControls(model: model) }
}
if model.detail?.can_share == true {
Button {
diff --git a/native/apple/Sources/DocsKit/DocumentSurface.swift b/native/apple/Sources/DocsKit/DocumentSurface.swift
new file mode 100644
index 0000000..01fbed6
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentSurface.swift
@@ -0,0 +1,473 @@
+import Foundation
+#if os(macOS)
+import AppKit
+typealias DocsStorageEditActions = NSTextStorageEditActions
+#else
+import UIKit
+typealias DocsStorageEditActions = NSTextStorage.EditActions
+#endif
+
+/// The open document's text, as the text view holds it (spec 2026-11-22
+/// §7 Design 3–9). One per document model; deliberately not observed, so
+/// nothing SwiftUI draws depends on it. Publications go model → surface →
+/// storage by direct call:
+///
+/// - `apply(_:)` keeps the newest publication, drops a stale one, and
+/// gathers what changed into `pendingDirty` (or `fullDiff`, when the
+/// replica could not say);
+/// - `flushIfDeferred()` draws it once the text view can take it,
+/// re-rendering only the blocks that changed and their neighbours, and
+/// reconciling only their characters, found through the block index;
+/// - the text view's delegate callbacks (typing, selection, input rules,
+/// composition) come here, and reach the model through `hooks`.
+@MainActor final class DocumentSurface: NSObject {
+ struct Publication: Sendable {
+ let generation: UInt64
+ let projection: CRDTProjection
+ let revision: UInt64
+ let dirty: Set<String>?
+ }
+
+ /// What the surface asks of its model. Every one is a call, never an
+ /// observed read, so the text view's host observes nothing.
+ struct Hooks {
+ var edit: @MainActor ([String: JSONValue]) -> Bool = { _ in false }
+ var canRender: @MainActor (UInt64) -> Bool = { _ in true }
+ var currentSelection: @MainActor () -> NSRange = { NSRange(location: 0, length: 0) }
+ var didRender: @MainActor (UInt64) -> Void = { _ in }
+ var compositionChanged: @MainActor (Bool) -> Void = { _ in }
+ /// The caret or selection moved (any reason but a render).
+ var selectionChanged: @MainActor (NSRange) -> Void = { _ in }
+ /// …and the move was the person's, not their typing's.
+ var selectionMoved: @MainActor () -> Void = {}
+ var action: @MainActor (String) -> Bool = { _ in false }
+ var canAction: @MainActor (String) -> Bool = { _ in false }
+ /// The image sources the drawn blocks hold, when that set changes.
+ var imageSourcesChanged: @MainActor ([String]) -> Void = { _ in }
+ }
+ var hooks = Hooks()
+
+ #if os(macOS)
+ private(set) weak var textView: DocsTextView?
+ #else
+ private(set) weak var textView: DocsTextView?
+ #endif
+
+ /// The replica revision the storage reflects.
+ private(set) var appliedRevision: UInt64 = 0
+ /// The generation the storage reflects: edits name it as their source.
+ private(set) var generation: UInt64 = 0
+ /// The newest publication, drawn or waiting to be.
+ private(set) var newest: Publication?
+ /// Blocks changed since `appliedRevision` (or since they were drawn).
+ private(set) var pendingDirty = Set<String>()
+ /// The replica could not say what changed: compare every block.
+ private(set) var fullDiff = false
+ private(set) var index = DocumentBlockIndex()
+ /// Publications handed to `apply`, drawn or not (tests: "no later
+ /// publication").
+ private(set) var publicationsReceived = 0
+ /// Tests only: runs as a publication arrives, before it is applied.
+ var willApply: ((Publication) -> Void)?
+
+ /// What each drawn block was drawn from.
+ private struct Entry {
+ var node: CRDTNode
+ var context: DocumentBlockSpacing.Context
+ /// Its first paragraph's top margin when not first of the document.
+ var firstBefore: CGFloat?
+ var sources: Set<String>
+ }
+ private var entries: [String: Entry] = [:]
+ private var order: [String] = []
+ private var sourceCounts: [String: Int] = [:]
+ private var reportedSources: [String] = []
+ private var images: [String: DocsPlatformImage] = [:]
+
+ /// True while the surface itself edits the storage or the selection:
+ /// the text view's callbacks then change nothing in the model.
+ private(set) var applying = false
+ private var flushing = false
+ private var expectedSelection: NSRange?
+
+ var isEditable = false { didSet { if oldValue != isEditable { textView?.isEditable = isEditable } } }
+ /// 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() } } }
+
+ // MARK: - Content
+
+ /// The live text, which commands, word counts and the toolbar read.
+ var content: NSAttributedString {
+ #if os(macOS)
+ textView?.textStorage ?? NSAttributedString()
+ #else
+ textView?.textStorage ?? NSAttributedString()
+ #endif
+ }
+ private var storage: NSTextStorage? { textView?.textStorage }
+ var selectedRange: NSRange? {
+ #if os(macOS)
+ textView?.selectedRange()
+ #else
+ textView?.selectedRange
+ #endif
+ }
+
+ /// Forget the document drawn: a new one (or a new replica) follows,
+ /// whose revisions start again. The next publication is drawn whole.
+ func reset() {
+ appliedRevision = 0; generation = 0; newest = nil
+ pendingDirty = []; fullDiff = false
+ entries = [:]; order = []; sourceCounts = [:]; images = [:]
+ expectedSelection = nil
+ report(sources: [])
+ }
+
+ // MARK: - The text view
+
+ func attach(_ text: DocsTextView) {
+ textView = text
+ text.delegate = self
+ storage?.delegate = self
+ text.isEditable = isEditable
+ 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) }
+ text.compositionCommitted = { [weak self] before, after in self?.commitComposition(before: before, after: after) ?? true }
+ text.action = { [weak self, weak text] action in
+ text?.lastInputRule = nil
+ return self?.hooks.action(action) ?? false
+ }
+ text.canAction = { [weak self] action in self?.hooks.canAction(action) ?? false }
+ if let storage { index.rebuild(from: storage) }
+ // Inside SwiftUI's update: draw now, so the first frame is final,
+ // but tell the model on the next turn, not during the update.
+ flushIfDeferred(notifyLater: true)
+ }
+
+ /// An explicit command (not typing) went to the model.
+ func explicitCommand() { textView?.lastInputRule = nil }
+
+ // MARK: - Publications
+
+ /// A publication from the model (trigger (a)). Stale ones are dropped:
+ /// the storage already reflects that revision or a later one.
+ func apply(_ publication: Publication) {
+ publicationsReceived += 1
+ willApply?(publication)
+ if let newest, publication.revision <= newest.revision { return }
+ guard publication.revision > appliedRevision else { return }
+ if let dirty = publication.dirty { pendingDirty.formUnion(dirty) } else { fullDiff = true }
+ newest = publication
+ flushIfDeferred()
+ }
+
+ /// Images arrived (or went): only the blocks that hold them are drawn again.
+ func imagesChanged(_ loaded: [String: DocsPlatformImage]) {
+ let changed = Set(loaded.keys).symmetricDifference(images.keys)
+ .union(loaded.keys.filter { key in images[key].map { $0 !== loaded[key] } ?? false })
+ images = loaded
+ guard !changed.isEmpty else { return }
+ for (id, entry) in entries where !entry.sources.isDisjoint(with: changed) { pendingDirty.insert(id) }
+ flushIfDeferred()
+ }
+
+ /// Draws what is waiting, if the text view can take it now: no input
+ /// pending, nothing composing, the newest generation current, and no
+ /// marked text (spec §7 Design 6). Called on every event that can make
+ /// that true: (a) a publication applied, (b) the edit queue draining,
+ /// (c) composition ending, (d) the generation catching up, (e) input
+ /// unpaused.
+ func flushIfDeferred(notifyLater: Bool = false) {
+ guard !flushing, let newest, let text = textView, let storage = text.textStorage as NSTextStorage? else { return }
+ let waiting = newest.revision > appliedRevision || !pendingDirty.isEmpty || fullDiff
+ guard waiting, hooks.canRender(newest.generation), !Self.hasMarkedText(text) else { return }
+ #if DOCS_PROBES
+ let probeStart = DocsProbes.now()
+ defer { DocsProbes.publications += 1; DocsProbes.publicationMs += DocsProbes.ms(since: probeStart) }
+ #endif
+ flushing = true
+ defer { flushing = false }
+ let advancing = newest.revision > appliedRevision
+ let newGeneration = generation != newest.generation
+ let selected = newGeneration ? hooks.currentSelection() : (selectedRange ?? NSRange(location: 0, length: 0))
+ applying = true
+ if entries.isEmpty { drawWhole(newest.projection, into: text, storage: storage) }
+ else { drawChanged(newest.projection, storage: storage, textOnly: !advancing) }
+ let length = storage.length
+ let range = NSRange(location: min(selected.location, length), length: min(selected.length, max(0, length - selected.location)))
+ if selectedRange != range { Self.select(range, in: text) }
+ applying = false
+ appliedRevision = newest.revision
+ generation = newest.generation
+ if !Self.hasMarkedText(text) { applyTypingFont() }
+ let rendered = newest.generation
+ if notifyLater { Task { @MainActor [weak self] in self?.hooks.didRender(rendered) } }
+ else { hooks.didRender(rendered) }
+ }
+
+ /// Open, or after `reset`: the one whole render, and on iOS the one
+ /// `attributedText` assignment.
+ private func drawWhole(_ projection: CRDTProjection, into text: DocsTextView, storage: NSTextStorage) {
+ let content = NativeTextProjection.render(projection, images: images)
+ #if os(macOS)
+ DocumentRenderReconciliation.apply(content, to: storage)
+ #else
+ text.attributedText = content
+ #if DOCS_PROBES
+ DocsProbes.attributedTextAssignments += 1
+ #endif
+ #endif
+ index.rebuild(from: storage)
+ entries = [:]; sourceCounts = [:]
+ let contexts = DocumentBlockSpacing.contexts(projection.children)
+ for (node, context) in zip(projection.children, contexts) { remember(node, context: context) }
+ order = projection.children.map(\.id)
+ pendingDirty = []; fullDiff = false
+ report(sources: sourceCounts.keys.sorted())
+ }
+
+ /// Everything since: the blocks that changed (or whose neighbours
+ /// changed their spacing), drawn on their own and reconciled into
+ /// their own characters. `textOnly`: nothing new from the replica (an
+ /// image arrived), so a block whose text no longer matches what is
+ /// shown (typing the replica has not answered yet) waits.
+ private func drawChanged(_ projection: CRDTProjection, storage: NSTextStorage, textOnly: Bool) {
+ let nodes = projection.children
+ let ids = nodes.map(\.id)
+ guard Set(ids).count == ids.count else {
+ // Two blocks under one id: no per-block identity to go by.
+ DocumentRenderReconciliation.apply(NativeTextProjection.render(projection, images: images), to: storage)
+ index.rebuild(from: storage)
+ let contexts = DocumentBlockSpacing.contexts(nodes)
+ entries = [:]; sourceCounts = [:]
+ for (node, context) in zip(nodes, contexts) { remember(node, context: context) }
+ order = ids; pendingDirty = []; fullDiff = false
+ report(sources: sourceCounts.keys.sorted())
+ return
+ }
+ // What changed, by id.
+ var changed = pendingDirty
+ for node in nodes where entries[node.id] == nil || (fullDiff && entries[node.id]?.node != node) { changed.insert(node.id) }
+ // Each block's context; a block whose context moved is drawn again
+ // (its neighbour changed its top margin, or it became first or last).
+ var contexts = Array(repeating: DocumentBlockSpacing.Context(), count: nodes.count)
+ var next: CGFloat?
+ for index in nodes.indices.reversed() {
+ contexts[index].first = index == 0
+ contexts[index].last = index == nodes.count - 1
+ contexts[index].nextBefore = next
+ let node = nodes[index]
+ let before: CGFloat? = index == 0 || changed.contains(node.id) || entries[node.id] == nil
+ ? DocumentBlockSpacing.firstBefore(node, first: index == 0) : entries[node.id]!.firstBefore
+ if let before { next = before }
+ }
+ for index in nodes.indices {
+ contexts[index].leading = true
+ let node = nodes[index]
+ let empty = changed.contains(node.id) || entries[node.id] == nil
+ ? DocumentBlockSpacing.firstBefore(node) == nil : entries[node.id]!.firstBefore == nil
+ if !empty { break }
+ }
+ var draw = changed
+ for (index, node) in nodes.enumerated() where entries[node.id]?.context != contexts[index] { draw.insert(node.id) }
+ if draw.isEmpty && order == ids { pendingDirty = []; fullDiff = false; return }
+
+ // Anchors: blocks kept as they are, each one contiguous run of the
+ // index, in order. Everything between two anchors is one gap.
+ let positions = index.positions()
+ var anchors: [(block: Int, run: DocumentBlockIndex.Run)] = []
+ var lastEnd = 0
+ for (block, id) in ids.enumerated() where !draw.contains(id) {
+ guard let runs = positions[id], runs.count == 1 else { draw.insert(id); continue }
+ let run = index.runs[runs[0]]
+ guard run.location >= lastEnd else { draw.insert(id); continue }
+ anchors.append((block, run)); lastEnd = run.end
+ }
+ // Gaps, last first, so earlier ranges stay where they are.
+ var gaps: [(blocks: Range<Int>, range: NSRange)] = []
+ var previousBlock = -1, previousEnd = 0
+ for (block, run) in anchors + [(nodes.count, DocumentBlockIndex.Run(id: nil, location: storage.length, length: 0))] {
+ let range = NSRange(location: previousEnd, length: run.location - previousEnd)
+ if block > previousBlock + 1 || range.length > 0 { gaps.append(((previousBlock + 1)..<block, range)) }
+ previousBlock = block; previousEnd = run.end
+ }
+ var waiting = Set<String>()
+ for gap in gaps.reversed() {
+ let rendered = NSMutableAttributedString()
+ for block in gap.blocks {
+ rendered.append(NativeTextProjection.renderBlock(nodes[block], context: contexts[block], images: images))
+ }
+ if textOnly, (storage.string as NSString).substring(with: gap.range) != rendered.string {
+ for block in gap.blocks { waiting.insert(nodes[block].id) }
+ continue
+ }
+ DocumentRenderReconciliation.apply(rendered, to: storage, in: gap.range)
+ for block in gap.blocks { remember(nodes[block], context: contexts[block]) }
+ }
+ for (block, _) in anchors { entries[nodes[block].id]?.context = contexts[block] }
+ let kept = Set(ids)
+ for id in order where !kept.contains(id) { forget(id) }
+ order = ids
+ pendingDirty = waiting; fullDiff = false
+ report(sources: sourceCounts.keys.sorted())
+ }
+
+ private func remember(_ node: CRDTNode, context: DocumentBlockSpacing.Context) {
+ forget(node.id)
+ let sources = DocsImageStore.sources(in: node)
+ for source in sources { sourceCounts[source, default: 0] += 1 }
+ entries[node.id] = Entry(node: node, context: context, firstBefore: DocumentBlockSpacing.firstBefore(node), sources: sources)
+ }
+ private func forget(_ id: String) {
+ guard let old = entries.removeValue(forKey: id) else { return }
+ for source in old.sources {
+ let count = (sourceCounts[source] ?? 1) - 1
+ sourceCounts[source] = count > 0 ? count : nil
+ }
+ }
+ private func report(sources: [String]) {
+ guard sources != reportedSources else { return }
+ reportedSources = sources
+ hooks.imageSourcesChanged(sources)
+ }
+
+ // MARK: - Typing and selection (the text view's delegate)
+
+ /// The text view changed its own text (typing, a paste, a composition):
+ /// those blocks are drawn again at the next publication, whatever the
+ /// replica says changed. Usually the replica names them too; but an
+ /// edit it refused (or one a dropped publication carried) would
+ /// otherwise stay on screen until something else touched the block.
+ private func typed(around edited: NSRange) {
+ // The characters inserted, or the two either side of a deletion.
+ let first = edited.length > 0 ? edited.location : max(0, edited.location - 1)
+ let last = edited.length > 0 ? NSMaxRange(edited) - 1 : edited.location
+ let touched = index.runs(holding: first, through: last)
+ for run in touched { if let id = run.id { pendingDirty.insert(id) } }
+ // Text typed with no block (UIKit's typing attributes may not carry
+ // it) belongs to the block before it.
+ if let start = touched.first, start.id == nil, touched.startIndex > 0, let id = index.runs[touched.startIndex - 1].id {
+ pendingDirty.insert(id)
+ }
+ }
+
+ private func applyTypingFont() {
+ guard let text = textView, let marks = typingMarks, let selected = selectedRange, selected.length == 0, !Self.hasMarkedText(text),
+ let font = NativeTextProjection.typingFont(in: content, at: selected.location, marks: marks) else { return }
+ if text.typingAttributes[.font] as? DocsPlatformFont != font { text.typingAttributes[.font] = font }
+ }
+
+ func ruleEdit(_ command: [String: JSONValue]) -> Bool {
+ var command = command; command["generation"] = .number(Double(generation))
+ let accepted = hooks.edit(command)
+ if accepted, case .number(let at)? = command["at"] {
+ let inserted: Int
+ if command["op"] == .string("display_revert_rule"), case .string(let text)? = command["text"] { inserted = text.utf16.count } else { inserted = 0 }
+ expectedSelection = NSRange(location: Int(at) + inserted, length: 0)
+ }
+ return accepted
+ }
+ func clipboardEdit(blocks: [JSONValue]?, range: NSRange, replacement: String) -> Bool {
+ var command: [String: JSONValue] = ["op": .string(blocks == nil ? "display_edit" : "display_paste"), "at": .number(Double(range.location)), "length": .number(Double(range.length)), "generation": .number(Double(generation))]
+ if let blocks { command["blocks"] = .array(blocks) } else { command["text"] = .string(replacement) }
+ let accepted = hooks.edit(command)
+ if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
+ return accepted
+ }
+ func commitComposition(before: NSAttributedString, after: String) -> Bool {
+ guard let (range, replacement) = DocumentComposition.replacement(before: before.string, after: after) else { return true }
+ guard var command = TextEditMapping.displayCommand(in: before, range: range, replacement: replacement) else { return false }
+ command["generation"] = .number(Double(generation))
+ let accepted = hooks.edit(command)
+ if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
+ return accepted
+ }
+ /// Typing: the command first, then (if the model took it) the text view
+ /// shows it at once, before any publication.
+ func shouldChange(_ text: DocsTextView, in range: NSRange, replacement: String) -> Bool {
+ if text.isComposing { return true }
+ if text.interceptInput(replacement, range: range) { return false }
+ guard var command = TextEditMapping.displayCommand(in: content, range: range, replacement: replacement) else { return false }
+ command["generation"] = .number(Double(generation))
+ let accepted = hooks.edit(command)
+ if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
+ return accepted
+ }
+ func selectionDidChange(_ text: DocsTextView) {
+ // A render moves the caret (iOS: assigning the text moves it to the
+ // end and back) and then puts it where the model has it. Telling
+ // the model here would change it in the middle of that (the iOS
+ // render loop, TestFlight 0.1.10 (12)).
+ guard !applying else { return }
+ let string = content.string
+ let selected = selectedRange ?? NSRange(location: 0, length: 0)
+ if selected.length == 0 && selected.location == string.utf16.count && string.hasSuffix("\n") {
+ Self.select(NSRange(location: max(0, selected.location - 1), length: 0), in: text); return
+ }
+ if !text.isComposing {
+ if selected != expectedSelection && selected != hooks.currentSelection() {
+ hooks.selectionMoved()
+ text.lastInputRule = nil
+ }
+ expectedSelection = nil
+ }
+ hooks.selectionChanged(selected)
+ }
+
+ private static func hasMarkedText(_ text: DocsTextView) -> Bool {
+ #if os(macOS)
+ text.hasMarkedText()
+ #else
+ text.markedTextRange != nil
+ #endif
+ }
+ private static func select(_ range: NSRange, in text: DocsTextView) {
+ #if os(macOS)
+ text.setSelectedRange(range)
+ #else
+ text.selectedRange = range
+ #endif
+ }
+}
+
+// MARK: - Delegates
+
+extension DocumentSurface: NSTextStorageDelegate {
+ nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: DocsStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) {
+ // TextKit edits the text view's storage on the main thread only.
+ nonisolated(unsafe) let edited = textStorage
+ MainActor.assumeIsolated {
+ guard edited === storage else { return }
+ index.processEditing(edited, edited: editedRange, delta: delta)
+ if !applying, editedMask.contains(.editedCharacters) { typed(around: editedRange) }
+ }
+ }
+}
+
+#if os(macOS)
+extension DocumentSurface: NSTextViewDelegate {
+ func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
+ guard let text = textView as? DocsTextView else { return false }
+ if text.isComposing { return true }
+ guard let replacementString else { return false }
+ return shouldChange(text, in: affectedCharRange, replacement: replacementString)
+ }
+ func textViewDidChangeSelection(_ notification: Notification) {
+ guard let text = notification.object as? DocsTextView else { return }
+ selectionDidChange(text)
+ }
+}
+#else
+extension DocumentSurface: UITextViewDelegate {
+ func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
+ guard let view = textView as? DocsTextView else { return false }
+ return shouldChange(view, in: range, replacement: text)
+ }
+ func textViewDidChangeSelection(_ textView: UITextView) {
+ guard let text = textView as? DocsTextView else { return }
+ selectionDidChange(text)
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/EditorToolbar.swift b/native/apple/Sources/DocsKit/EditorToolbar.swift
index 82e80c9..c2ddda6 100644
--- a/native/apple/Sources/DocsKit/EditorToolbar.swift
+++ b/native/apple/Sources/DocsKit/EditorToolbar.swift
@@ -1,16 +1,17 @@
import SwiftUI
@MainActor struct EditorToolbar: View {
@Bindable var model: DocsModel
- let content: NSAttributedString
- @State private var settledSelection = DocumentToolbarSelection()
- private var selection: DocumentToolbarSelection { currentSelection ?? settledSelection }
- private var currentSelection: DocumentToolbarSelection? { DocumentToolbarSelection(commands: actions) }
var body: some View {
- let selection = self.selection
+ // One observed value, assigned only when it differs; kept while
+ // input is pending (DocsModel.refreshToolbarSelection).
+ let selection = model.toolbarSelection
ScrollView(.horizontal) {
HStack(spacing: 12) {
- command("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: selection.canUndo)
- command("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: selection.canRedo)
+ // The observed history, set with each publication: current
+ // for a reader too, and while input is pending, when the
+ // toolbar selection keeps its last state.
+ command("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: model.history.canUndo)
+ command("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: model.history.canRedo)
Divider().frame(height: 24)
Menu {
Button { block("paragraph") } label: { Text("docs.editor.toolbar.block.paragraph", bundle: DocsResources.bundle) }
@@ -58,9 +59,6 @@ import SwiftUI
// synchronization gate out of disabled styling so the bar does not blink.
.disabled(!actions.isAvailable)
.allowsHitTesting(actions.isEnabled)
- .onChange(of: currentSelection, initial: true) { _, value in
- if let value { settledSelection = value }
- }
}
private func command(_ key: String, icon: String, op: String, enabled: Bool) -> some View {
Button { actions.perform(op) } label: { Image(systemName: icon) }
@@ -71,7 +69,7 @@ import SwiftUI
.foregroundStyle(active ? Color.accentColor : Color.primary)
.accessibilityAddTraits(active ? .isSelected : [])
}
- private var actions: DocumentCommands { DocumentCommands(model: model, content: content) }
+ private var actions: DocumentCommands { DocumentCommands(model: model, content: model.surface.content) }
private func format(_ name: String, exclusive: [String] = []) { actions.format(name, exclusive: exclusive) }
private func block(_ type: String, level: Int = 1) { actions.block(type, level: level) }
private func blockAttribute(_ name: String, value: String) { actions.blockAttribute(name, value: value == "left" ? nil : value) }
diff --git a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
index 661fbc0..7350075 100644
--- a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
+++ b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
@@ -1,30 +1,19 @@
import SwiftUI
+
+/// The document's text view, embedded once per document (spec 2026-11-22
+/// §7 Design 9). Its inputs are identity-level only: the surface, Pages
+/// and zoom. The text itself never passes through SwiftUI: publications go
+/// model → `DocumentSurface` → storage by direct call, and the text view's
+/// callbacks go to the surface.
#if os(macOS)
import AppKit
struct NativeDocumentTextView: NSViewRepresentable {
- let content: NSAttributedString
- let generation: UInt64
- let didRender: @MainActor (UInt64) -> Void
- let compositionChanged: @MainActor (Bool) -> Void
- let isEditable: Bool
- let paged: Bool
- let pendingInput: Bool
- let canRender: @MainActor (UInt64) -> Bool
- let currentSelection: @MainActor () -> NSRange
- @Binding var selection: NSRange
- let edit: @MainActor ([String: JSONValue]) -> Bool
- var action: @MainActor (String) -> Bool = { _ in false }
- var selectionMoved: @MainActor () -> Void = {}
- var canAction: @MainActor (String) -> Bool = { _ in false }
- var explicitCommandRevision: UInt64 = 0
+ let surface: DocumentSurface
+ var paged: Bool
var zoom: Double = 1
- /// Marks chosen at a collapsed caret (DocsModel.typingMarks), so marked
- /// text is drawn in the face it will commit in.
- var typingMarks: [String: JSONValue]? = nil
/// The side the floating inspector covers, nil while it is hidden: the
/// desk centres the page clear of it (spec §1, page centring).
var inspector: DocsDeskLayout.Side? = nil
- func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasVerticalScroller = true
@@ -37,17 +26,6 @@ struct NativeDocumentTextView: NSViewRepresentable {
text.isVerticallyResizable = false
// The page is a fixed paper band on the desk, which centres it (S2a).
scroll.documentView = DocsDeskView(page: text)
- text.delegate = context.coordinator
- let coordinator = context.coordinator
- text.action = { [weak text] action in
- text?.lastInputRule = nil
- return coordinator.parent.action(action)
- }
- text.canAction = { coordinator.parent.canAction($0) }
- text.ruleCommand = coordinator.ruleEdit
- text.clipboardEdit = { blocks, range, replacement in coordinator.clipboardEdit(blocks: blocks, range: range, replacement: replacement) }
- text.compositionChanged = { coordinator.parent.compositionChanged($0) }
- text.compositionCommitted = { before, after in coordinator.commitComposition(before: before, after: after) }
text.isRichText = true
// Before the first render, and in an empty document, the caret and
// anything typed are in the default face, never the system's.
@@ -58,6 +36,9 @@ struct NativeDocumentTextView: NSViewRepresentable {
text.allowsUndo = false
text.setAccessibilityIdentifier("docs.editor")
text.setAccessibilityLabel(String(localized: "native.editor", bundle: DocsResources.bundle))
+ text.paged = paged
+ applyZoom(scroll, text)
+ surface.attach(text)
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
@@ -65,140 +46,28 @@ struct NativeDocumentTextView: NSViewRepresentable {
let probeStart = DocsProbes.now()
defer { DocsProbes.viewUpdates += 1; DocsProbes.viewUpdateMs += DocsProbes.ms(since: probeStart) }
#endif
- guard let desk = scroll.documentView as? DocsDeskView, let text = desk.page as? NSTextView else { return }
+ guard let desk = scroll.documentView as? DocsDeskView, let text = desk.page as? DocsTextView else { return }
desk.inspector = inspector
+ if surface.textView !== text { surface.attach(text) }
+ applyZoom(scroll, text)
+ text.paged = paged
+ }
+ private func applyZoom(_ scroll: NSScrollView, _ text: NSTextView) {
let magnification = zoom * 4.0 / 3.0
if abs(scroll.magnification - magnification) > 0.001 {
scroll.setMagnification(magnification, centeredAt: scroll.contentView.bounds.origin)
text.needsLayout = true
}
- context.coordinator.applyRender(self, to: text)
- }
- @MainActor final class Coordinator: NSObject, NSTextViewDelegate {
- var parent: NativeDocumentTextView
- var rendered: NSAttributedString?
- var generation: UInt64 = 0
- var expectedSelection: NSRange?
- var applying = false
- var explicitCommandRevision: UInt64 = 0
- init(_ parent: NativeDocumentTextView) { self.parent = parent }
- func applyRender(_ candidate: NativeDocumentTextView, to text: NSTextView) {
- parent = candidate
- if candidate.explicitCommandRevision > explicitCommandRevision {
- explicitCommandRevision = candidate.explicitCommandRevision
- (text as? DocsTextView)?.lastInputRule = nil
- }
- text.isEditable = candidate.isEditable
- (text as? DocsTextView)?.paged = candidate.paged
- defer { if !text.hasMarkedText() { applyTypingFont(candidate, to: text) } }
- // pendingInput makes SwiftUI observe drain completion; only this live
- // callback can authorize a delayed candidate at application time.
- guard candidate.canRender(candidate.generation), !text.hasMarkedText() else { return }
- let newGeneration = generation != candidate.generation
- guard newGeneration || (rendered.map { DocumentRenderReconciliation.isEquivalent($0, candidate.content) } != true && text.string == candidate.content.string) else { return }
- let selected = newGeneration ? candidate.currentSelection() : text.selectedRange()
- applying = true
- defer { applying = false }
- rendered = NSAttributedString(attributedString: candidate.content)
- generation = candidate.generation
- if let storage = text.textStorage { DocumentRenderReconciliation.apply(candidate.content, to: storage) }
- let range = NSRange(location: min(selected.location, candidate.content.length), length: min(selected.length, max(0, candidate.content.length - selected.location)))
- if text.selectedRange() != range { text.setSelectedRange(range) }
- candidate.didRender(candidate.generation)
- }
- func applyTypingFont(_ candidate: NativeDocumentTextView, to text: NSTextView) {
- guard let marks = candidate.typingMarks, text.selectedRange().length == 0,
- let font = NativeTextProjection.typingFont(in: text.attributedString(), at: text.selectedRange().location, marks: marks) else { return }
- if text.typingAttributes[.font] as? NSFont != font { text.typingAttributes[.font] = font }
- }
- func ruleEdit(_ command: [String: JSONValue]) -> Bool {
- var command = command; command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted, case .number(let at)? = command["at"] {
- let inserted: Int
- if command["op"] == .string("display_revert_rule"), case .string(let text)? = command["text"] { inserted = text.utf16.count } else { inserted = 0 }
- expectedSelection = NSRange(location: Int(at) + inserted, length: 0)
- }
- return accepted
- }
- func clipboardEdit(blocks: [JSONValue]?, range: NSRange, replacement: String) -> Bool {
- var command: [String: JSONValue] = ["op": .string(blocks == nil ? "display_edit" : "display_paste"), "at": .number(Double(range.location)), "length": .number(Double(range.length)), "generation": .number(Double(generation))]
- if let blocks { command["blocks"] = .array(blocks) } else { command["text"] = .string(replacement) }
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
- return accepted
- }
- func commitComposition(before: NSAttributedString, after: String) -> Bool {
- guard let (range, replacement) = DocumentComposition.replacement(before: before.string, after: after) else { return true }
- guard var command = TextEditMapping.displayCommand(in: before, range: range, replacement: replacement) else { return false }
- command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
- return accepted
- }
- func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
- if (textView as? DocsTextView)?.isComposing == true { return true }
- if let replacementString, (textView as? DocsTextView)?.interceptInput(replacementString, range: affectedCharRange) == true { return false }
- guard let replacementString, var command = TextEditMapping.displayCommand(in: textView.attributedString(), range: affectedCharRange, replacement: replacementString) else { return false }
- command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: affectedCharRange.location + replacementString.utf16.count, length: 0) }
- return accepted
- }
- func textViewDidChangeSelection(_ notification: Notification) {
- guard let text = notification.object as? NSTextView else { return }
- guard !applying else { return }
- let selected = text.selectedRange()
- if selected.length == 0 && selected.location == text.string.utf16.count && text.string.hasSuffix("\n") {
- text.setSelectedRange(NSRange(location: max(0, selected.location - 1), length: 0)); return
- }
- if !applying, (text as? DocsTextView)?.isComposing != true {
- if selected != expectedSelection && selected != parent.selection {
- parent.selectionMoved()
- (text as? DocsTextView)?.lastInputRule = nil
- }
- expectedSelection = nil
- }
- parent.selection = selected
- }
}
}
#else
import UIKit
struct NativeDocumentTextView: UIViewRepresentable {
- let content: NSAttributedString
- let generation: UInt64
- let didRender: @MainActor (UInt64) -> Void
- let compositionChanged: @MainActor (Bool) -> Void
- let isEditable: Bool
- let paged: Bool
- let pendingInput: Bool
- let canRender: @MainActor (UInt64) -> Bool
- let currentSelection: @MainActor () -> NSRange
- @Binding var selection: NSRange
- let edit: @MainActor ([String: JSONValue]) -> Bool
- var action: @MainActor (String) -> Bool = { _ in false }
- var selectionMoved: @MainActor () -> Void = {}
- var canAction: @MainActor (String) -> Bool = { _ in false }
- var explicitCommandRevision: UInt64 = 0
+ let surface: DocumentSurface
+ var paged: Bool
var zoom: Double = 1
- /// Marks chosen at a collapsed caret (DocsModel.typingMarks), so marked
- /// text is drawn in the face it will commit in.
- var typingMarks: [String: JSONValue]? = nil
- func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeUIView(context: Context) -> UITextView {
let text = DocsTextView()
- text.delegate = context.coordinator
- let coordinator = context.coordinator
- text.action = { [weak text] action in
- text?.lastInputRule = nil
- return coordinator.parent.action(action)
- }
- text.canAction = { coordinator.parent.canAction($0) }
- text.ruleCommand = coordinator.ruleEdit
- text.clipboardEdit = { blocks, range, replacement in coordinator.clipboardEdit(blocks: blocks, range: range, replacement: replacement) }
- text.compositionChanged = { coordinator.parent.compositionChanged($0) }
- text.compositionCommitted = { before, after in coordinator.commitComposition(before: before, after: after) }
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.
@@ -206,106 +75,46 @@ struct NativeDocumentTextView: UIViewRepresentable {
text.typingAttributes[.font] = DocsFonts.defaultFont()
text.accessibilityIdentifier = "docs.editor"
text.accessibilityLabel = String(localized: "native.editor", bundle: DocsResources.bundle)
+ text.paged = paged
+ surface.attach(text)
return text
}
- func updateUIView(_ text: UITextView, context: Context) {
+ func updateUIView(_ view: UITextView, context: Context) {
#if DOCS_PROBES
let probeStart = DocsProbes.now()
defer { DocsProbes.viewUpdates += 1; DocsProbes.viewUpdateMs += DocsProbes.ms(since: probeStart) }
#endif
- context.coordinator.applyRender(self, to: text)
- }
- @MainActor final class Coordinator: NSObject, UITextViewDelegate {
- var parent: NativeDocumentTextView
- var rendered: NSAttributedString?
- var generation: UInt64 = 0
- var expectedSelection: NSRange?
- var applying = false
- var explicitCommandRevision: UInt64 = 0
- init(_ parent: NativeDocumentTextView) { self.parent = parent }
- func applyRender(_ candidate: NativeDocumentTextView, to text: UITextView) {
- parent = candidate
- if candidate.explicitCommandRevision > explicitCommandRevision {
- explicitCommandRevision = candidate.explicitCommandRevision
- (text as? DocsTextView)?.lastInputRule = nil
- }
- text.isEditable = candidate.isEditable
- (text as? DocsTextView)?.paged = candidate.paged
- defer { if text.markedTextRange == nil { applyTypingFont(candidate, to: text) } }
- guard candidate.canRender(candidate.generation), text.markedTextRange == nil else { return }
- let newGeneration = generation != candidate.generation
- guard newGeneration || (rendered.map { DocumentRenderReconciliation.isEquivalent($0, candidate.content) } != true && text.text == candidate.content.string) else { return }
- let selected = newGeneration ? candidate.currentSelection() : text.selectedRange
- applying = true
- defer { applying = false }
- rendered = NSAttributedString(attributedString: candidate.content)
- generation = candidate.generation
- text.attributedText = candidate.content
- #if DOCS_PROBES
- DocsProbes.attributedTextAssignments += 1
- #endif
- text.selectedRange = NSRange(location: min(selected.location, candidate.content.length), length: min(selected.length, max(0, candidate.content.length - selected.location)))
- candidate.didRender(candidate.generation)
- }
- func applyTypingFont(_ candidate: NativeDocumentTextView, to text: UITextView) {
- guard let marks = candidate.typingMarks, text.selectedRange.length == 0,
- let font = NativeTextProjection.typingFont(in: text.attributedText, at: text.selectedRange.location, marks: marks) else { return }
- if text.typingAttributes[.font] as? UIFont != font { text.typingAttributes[.font] = font }
- }
- func ruleEdit(_ command: [String: JSONValue]) -> Bool {
- var command = command; command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted, case .number(let at)? = command["at"] {
- let inserted: Int
- if command["op"] == .string("display_revert_rule"), case .string(let text)? = command["text"] { inserted = text.utf16.count } else { inserted = 0 }
- expectedSelection = NSRange(location: Int(at) + inserted, length: 0)
- }
- return accepted
- }
- func clipboardEdit(blocks: [JSONValue]?, range: NSRange, replacement: String) -> Bool {
- var command: [String: JSONValue] = ["op": .string(blocks == nil ? "display_edit" : "display_paste"), "at": .number(Double(range.location)), "length": .number(Double(range.length)), "generation": .number(Double(generation))]
- if let blocks { command["blocks"] = .array(blocks) } else { command["text"] = .string(replacement) }
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
- return accepted
- }
- func commitComposition(before: NSAttributedString, after: String) -> Bool {
- guard let (range, replacement) = DocumentComposition.replacement(before: before.string, after: after) else { return true }
- guard var command = TextEditMapping.displayCommand(in: before, range: range, replacement: replacement) else { return false }
- command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) }
- return accepted
- }
- func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
- if (textView as? DocsTextView)?.isComposing == true { return true }
- if (textView as? DocsTextView)?.interceptInput(text, range: range) == true { return false }
- guard var command = TextEditMapping.displayCommand(in: textView.attributedText, range: range, replacement: text) else { return false }
- command["generation"] = .number(Double(generation))
- let accepted = parent.edit(command)
- if accepted { expectedSelection = NSRange(location: range.location + text.utf16.count, length: 0) }
- return accepted
- }
- func textViewDidChangeSelection(_ textView: UITextView) {
- // As on the Mac: assigning a render moves the caret to the end
- // and back, and applyRender then puts it where the model has it.
- // Writing the binding here would change the model inside the
- // view update that is applying it, which asks for another update
- // (the iOS render loop, TestFlight 0.1.10 (12)).
- guard !applying else { return }
- if textView.selectedRange.length == 0 && textView.selectedRange.location == textView.text.utf16.count && textView.text.hasSuffix("\n") {
- textView.selectedRange = NSRange(location: max(0, textView.selectedRange.location - 1), length: 0); return
- }
- let selected = textView.selectedRange
- if (textView as? DocsTextView)?.isComposing != true {
- if selected != expectedSelection && selected != parent.selection {
- parent.selectionMoved()
- (textView as? DocsTextView)?.lastInputRule = nil
- }
- expectedSelection = nil
- }
- parent.selection = selected
- }
+ guard let text = view as? DocsTextView else { return }
+ if surface.textView !== text { surface.attach(text) }
+ text.paged = paged
}
}
#endif
+
+/// The view that holds the text view: it reads nothing the model
+/// publishes (sync status, selection, metadata, typing, the projection),
+/// only the surface and the identity-level settings, so it is evaluated
+/// when the document opens and when Pages or zoom change, and never per
+/// keystroke, per peer change or per sync-status change (spec §7 Design 9;
+/// DocsProbes.hostBodies counts it).
+struct DocumentEditorHost: View, Equatable {
+ let surface: DocumentSurface
+ let paged: Bool
+ var zoom: Double = 1
+ /// 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
+ nonisolated static func == (a: Self, b: Self) -> Bool {
+ a.surface === b.surface && a.paged == b.paged && a.zoom == b.zoom && a.inspector == b.inspector
+ }
+ var body: some View {
+ #if DOCS_PROBES
+ let _ = DocsProbes.hostBodies += 1
+ #endif
+ #if os(macOS)
+ NativeDocumentTextView(surface: surface, paged: paged, zoom: zoom, inspector: inspector)
+ #else
+ NativeDocumentTextView(surface: surface, paged: paged, zoom: zoom)
+ #endif
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/BlockIndexTests.swift b/native/apple/Tests/DocsKitTests/BlockIndexTests.swift
new file mode 100644
index 0000000..6012dd9
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/BlockIndexTests.swift
@@ -0,0 +1,66 @@
+import Foundation
+import XCTest
+@testable import DocsKit
+
+/// The block index under optimistic typing (spec 2026-11-22 §7 Design 4,
+/// §11): typing, Return, Backspace at a block's start and a paste go
+/// through the real text view with no publication. The index always equals
+/// the `.docsTopBlock` runs read afresh from the storage, provisional
+/// blocks included; when the publication then arrives, the storage is a
+/// whole render's.
+@MainActor final class BlockIndexTests: XCTestCase {
+ func testIndexFollowsTypingBeforeAnyPublication() async throws {
+ let replica = CRDTReplica(guid: "block-index")
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(BlockRenderEquivalenceTests.fixture)])
+ let state = SurfaceState(width: 640)
+ let text = state.text
+ func publish() async throws {
+ await replica.retainGenerations([state.surface.generation])
+ let answer = try await replica.presentation(source: state.surface.generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision)
+ let presented = try XCTUnwrap(answer)
+ state.allowed = presented.generation
+ state.surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty))
+ }
+ try await publish()
+ func checkIndex(_ step: String, file: StaticString = #filePath, line: UInt = #line) {
+ XCTAssertEqual(state.surface.index.runs, DocumentBlockIndex.runs(in: state.surface.content), "after \(step)", file: file, line: line)
+ }
+ checkIndex("opening")
+ let shown = state.surface.content.string as NSString
+ let survey = shown.range(of: "The survey began")
+ Keyboard.select(NSRange(location: NSMaxRange(survey), length: 0), in: text)
+ Keyboard.type(" Typed", in: text)
+ checkIndex("typing")
+ // An optimistic Return: the new paragraph keeps its block's id.
+ Keyboard.type("\nA new line", in: text)
+ checkIndex("Return")
+ let provisional = state.surface.index.runs.contains { run in
+ run.id != nil && (state.surface.content.string as NSString).substring(with: run.range).dropLast().contains("\n")
+ }
+ XCTAssertTrue(provisional, "a Return before any publication leaves one id over two paragraphs")
+ // Backspace at the start of the next block: one paragraph, two runs.
+ let next = (state.surface.content.string as NSString).range(of: "Run make check")
+ Keyboard.select(NSRange(location: next.location, length: 0), in: text)
+ Keyboard.backspace(in: text)
+ checkIndex("Backspace at a block's start")
+ let merged = (state.surface.content.string as NSString).paragraphRange(for: NSRange(location: next.location - 1, length: 0))
+ XCTAssertGreaterThan(DocumentBlockIndex.runs(in: state.surface.content, range: merged).count, 1, "the merged paragraph holds two runs")
+ // A paste of two blocks.
+ let end = (state.surface.content.string as NSString).range(of: "The end.")
+ Keyboard.select(NSRange(location: NSMaxRange(end), length: 0), in: text)
+ Keyboard.paste(BlockRenderEquivalenceTests.pasted, in: text, surface: state.surface)
+ checkIndex("a paste")
+ XCTAssertEqual(state.acknowledgements.count, 1, "no publication was drawn while typing")
+
+ // The model's queue: every command, in order, then a publication.
+ for command in state.commands { _ = try await replica.command(command) }
+ state.pending = false
+ try await publish()
+ checkIndex("the publication")
+ SurfaceFixture.assertMatchesWholeRender(state.surface.content, try await replica.projection(), "after the publication")
+ XCTAssertTrue(state.surface.content.string.contains("The survey began Typed\nA new line in spring."))
+ await replica.close()
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/BlockRenderEquivalenceTests.swift b/native/apple/Tests/DocsKitTests/BlockRenderEquivalenceTests.swift
new file mode 100644
index 0000000..ba14fa1
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/BlockRenderEquivalenceTests.swift
@@ -0,0 +1,123 @@
+import Foundation
+import XCTest
+@testable import DocsKit
+
+/// Block render equivalence (spec 2026-11-22 §11, Low 17): random edit
+/// sequences on the production replica, published to a `DocumentSurface`
+/// as the model publishes them. After each publication the storage built
+/// block by block equals a whole render of the same projection, attribute
+/// for attribute.
+@MainActor final class BlockRenderEquivalenceTests: XCTestCase {
+ /// A document with nested lists, a quote, headings, inline code, an
+ /// image, a rule and alignment.
+ static var fixture: [JSONValue] {
+ func text(_ insert: String, _ marks: [String: JSONValue] = [:]) -> JSONValue {
+ .object(["type": .string("text"), "runs": .array([.object(["insert": .string(insert), "marks": .object(marks)])])])
+ }
+ func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue {
+ var object: [String: JSONValue] = ["type": .string(type)]
+ if !children.isEmpty { object["children"] = .array(children) }
+ if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues(JSONValue.string)) }
+ return .object(object)
+ }
+ func paragraph(_ insert: String, _ marks: [String: JSONValue] = [:], attrs: [String: String] = [:]) -> JSONValue { block("paragraph", [text(insert, marks)], attrs: attrs) }
+ func item(_ children: [JSONValue]) -> JSONValue { block("list_item", children) }
+ return [
+ block("heading", [text("Millbrook water report")], attrs: ["level": "1"]),
+ paragraph("The survey began in spring."),
+ block("paragraph", [text("Run "), text("make check", ["code": .object([:])]), text(" before the "), text("bold", ["strong": .object([:])]), text(" part.")]),
+ block("bullet_list", [item([paragraph("Private wells")]), item([paragraph("Shared pumps"), block("bullet_list", [item([paragraph("North pump")]), item([paragraph("South pump")])])])]),
+ block("heading", [text("Findings")], attrs: ["level": "2"]),
+ block("blockquote", [paragraph("Water is life."), paragraph("— a resident")]),
+ block("ordered_list", [item([paragraph("Survey the creek")]), item([paragraph("Build the dam")])], attrs: ["order": "3"]),
+ paragraph("Centred note.", attrs: ["align": "center"]),
+ block("paragraph", [.object(["type": .string("image"), "attrs": .object(["src": .string(LoopFixture.picture), "alt": .string("A reservoir")])])]),
+ block("horizontal_rule", []),
+ block("code_block", [text("let x = 1\nlet y = 2")]),
+ block("heading", [text("Small heading")], attrs: ["level": "3"]),
+ paragraph("The end."),
+ ]
+ }
+ static var pasted: [JSONValue] {
+ [.object(["type": .string("heading"), "attrs": .object(["level": .string("2")]), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted heading"), "marks": .object([:])])])])])]),
+ .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted words"), "marks": .object([:])])])])])])]
+ }
+
+ func testBlocksDrawnOnTheirOwnEqualAWholeRender() async throws {
+ for seed: UInt64 in [1, 2, 3, 4, 5, 6] {
+ try await run(seed: seed, steps: 50)
+ }
+ }
+
+ private func run(seed: UInt64, steps: Int) async throws {
+ var random = SeededRandom(seed: seed)
+ let replica = CRDTReplica(guid: "equivalence-\(seed)")
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(Self.fixture)])
+ let state = SurfaceState(width: 640)
+ let image = try XCTUnwrap(DocsAttachments.decode(Data(base64Encoded: String(LoopFixture.picture.split(separator: ",")[1]))!))
+ let images = [LoopFixture.picture: image]
+ state.surface.imagesChanged(images)
+ var generation: UInt64 = 0
+ var projection = try await replica.projection()
+ func publish() async throws {
+ await replica.retainGenerations([generation])
+ guard let presented = try await replica.presentation(source: generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision) else { return }
+ generation = presented.generation; projection = presented.projection
+ state.allowed = generation
+ state.surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: presented.revision, dirty: presented.dirty))
+ SurfaceFixture.assertMatchesWholeRender(state.surface.content, projection, images: images, "seed \(seed)")
+ }
+ try await publish()
+ for step in 0..<steps {
+ let content = NativeTextProjection.render(projection)
+ let length = content.length
+ let at = step % 7 == 0 ? 0 : Int(random.next() % UInt64(max(1, length - 1)))
+ let command: [String: JSONValue]
+ switch random.next() % 10 {
+ case 0: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("typed ")]
+ case 1: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(Double(min(3, max(0, length - 1 - at)))), "text": .string("")]
+ case 2: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("\n")]
+ case 3:
+ // Merge: delete a paragraph end.
+ let ends = (content.string as NSString)
+ var end = ends.range(of: "\n", range: NSRange(location: at, length: length - at)).location
+ if end == NSNotFound || end >= length - 1 { end = ends.range(of: "\n").location }
+ command = ["op": .string("display_edit"), "at": .number(Double(end)), "length": .number(1), "text": .string("")]
+ case 4: command = ["op": .string("display_paste"), "at": .number(Double(at)), "length": .number(0), "blocks": .array(Self.pasted)]
+ case 5: command = ["op": .string("undo")]
+ case 6: command = ["op": .string("redo")]
+ case 7:
+ let range = NSRange(location: at, length: min(6, max(0, length - 1 - at)))
+ let marks: [String: JSONValue] = random.next() % 2 == 0 ? ["code": .object([:])] : ["strong": .object([:])]
+ command = ["op": .string("batch"), "commands": .array(DocumentCommands.markCommands(content: content, selection: range, marks: marks).map(JSONValue.object))]
+ case 8:
+ let node = projection.children[Int(random.next() % UInt64(projection.children.count))]
+ command = ["op": .string("block"), "node": .string(node.id), "type": .string(random.next() % 2 == 0 ? "heading" : "paragraph"), "level": .number(2)]
+ default:
+ let node = projection.children[Int(random.next() % UInt64(projection.children.count))]
+ command = ["op": .string("attribute"), "node": .string(node.id), "name": .string("align"), "value": .string(random.next() % 2 == 0 ? "right" : "center")]
+ }
+ _ = try? await replica.command(command)
+ // Not every change is published: some accumulate, as when
+ // publications are dropped or deferred.
+ if random.next() % 3 != 0 { try await publish() }
+ }
+ try await publish()
+ await replica.close()
+ }
+}
+
+/// SplitMix64: the same sequence on every run and platform.
+struct SeededRandom {
+ private var state: UInt64
+ init(seed: UInt64) { state = seed }
+ mutating func next() -> UInt64 {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return z ^ (z >> 31)
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift b/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift
new file mode 100644
index 0000000..48bca07
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DeltaSafetyTests.swift
@@ -0,0 +1,142 @@
+import Foundation
+import XCTest
+@testable import DocsKit
+
+/// Delta safety through the real text view (spec 2026-11-22 §11, finding
+/// 1): a `DocsTextView` taking optimistic typing, fed by the production
+/// replica as `DocsModel` feeds it, while publications are dropped (as
+/// `publishCurrent`'s guards drop them), delayed past later ones, and
+/// interleaved with extra `projection()` calls; while ja and zh marked text
+/// is composed with a peer editing the same block and another; and with a
+/// dirty log so short it overflows. At quiescence the storage equals a
+/// whole render of the replica's projection.
+@MainActor final class DeltaSafetyTests: XCTestCase {
+ func testPublicationsDroppedDelayedAndExtraProjections() async throws {
+ for seed: UInt64 in [11, 12, 13] { try await run(seed: seed, logLimit: 512) }
+ }
+ func testALogThatOverflows() async throws {
+ for seed: UInt64 in [21, 22, 23] { try await run(seed: seed, logLimit: 2) }
+ }
+
+ private final class Harness {
+ let replica: CRDTReplica
+ let peer: CRDTReplica
+ let state: SurfaceState
+ var queue: [[String: JSONValue]] = []
+ var projectionGeneration: UInt64 = 0
+ var held: DocumentSurface.Publication?
+ init(replica: CRDTReplica, peer: CRDTReplica, state: SurfaceState) { self.replica = replica; self.peer = peer; self.state = state }
+ }
+
+ private func run(seed: UInt64, logLimit: Int) async throws {
+ var random = SeededRandom(seed: seed)
+ let replica = CRDTReplica(guid: "delta-\(seed)", dirtyLogLimit: logLimit)
+ try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(BlockRenderEquivalenceTests.fixture)])
+ let peer = CRDTReplica(guid: "delta-\(seed)")
+ try await peer.open(update: try await replica.persistentState().state)
+ let state = SurfaceState(width: 640)
+ let h = Harness(replica: replica, peer: peer, state: state)
+ state.surface.hooks.edit = { command in h.queue.append(command); state.pending = true; return true }
+ state.surface.hooks.compositionChanged = { active in if !active { state.surface.flushIfDeferred() } }
+ let text = state.text
+
+ /// The model's drain: every queued command to the replica (and the
+ /// peer hears it), then input is no longer pending.
+ func drain() async throws {
+ while !h.queue.isEmpty {
+ let command = h.queue.removeFirst()
+ if let update = try? await replica.command(command) { try? await peer.apply(update) }
+ }
+ state.pending = false
+ state.surface.flushIfDeferred() // trigger (b)
+ }
+ /// The model's publish; `fate` decides whether it is drawn now,
+ /// dropped, or held back and delivered after a later one.
+ enum Fate { case publish, drop, hold }
+ func publish(_ fate: Fate) async throws {
+ await replica.retainGenerations([state.surface.generation, h.projectionGeneration])
+ guard let presented = try await replica.presentation(source: state.surface.generation, selection: state.selection, allowReuse: false, since: state.surface.appliedRevision) else { return }
+ let publication = DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty)
+ switch fate {
+ case .drop: return
+ case .hold: h.held = publication
+ case .publish:
+ h.projectionGeneration = presented.generation; state.allowed = presented.generation
+ state.selection = presented.selection
+ state.surface.apply(publication)
+ if let held = h.held, random.next() % 2 == 0 { h.held = nil; state.surface.apply(held) } // delayed: stale, dropped
+ }
+ }
+ func peerEdit(near location: Int) async throws {
+ let shown = NativeTextProjection.render(try await peer.projection()).string as NSString
+ let at = min(max(0, location), max(0, shown.length - 1))
+ // A position the engine refuses (inside an image) changes nothing.
+ guard let update = try? await peer.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("P")]) else { return }
+ try await replica.apply(update)
+ }
+ func caret() -> Int {
+ let length = state.surface.content.length
+ return Int(random.next() % UInt64(max(1, length - 1)))
+ }
+
+ try await publish(.publish)
+ for step in 0..<60 {
+ switch random.next() % 9 {
+ case 0, 1:
+ Keyboard.select(NSRange(location: caret(), length: 0), in: text)
+ Keyboard.type(step % 5 == 0 ? "a\nb" : "xy", in: text)
+ case 2: try await drain()
+ case 3: try await publish(random.next() % 3 == 0 ? .drop : random.next() % 2 == 0 ? .hold : .publish)
+ case 4: for _ in 0..<Int(random.next() % 4) { _ = try await replica.projection() }
+ case 5: try await peerEdit(near: caret())
+ case 7:
+ // A peer far from the caret, then the replica's own extra
+ // projections: only the log (or a full comparison) knows.
+ try await peerEdit(near: Int(random.next() % 4000))
+ for _ in 0..<Int(random.next() % 3) { _ = try await replica.projection() }
+ case 6:
+ // Compose ja or zh while the peer edits this block and another,
+ // and publications arrive.
+ try await drain()
+ let at = caret()
+ Keyboard.select(NSRange(location: at, length: 0), in: text)
+ let words = step % 2 == 0 ? ["に", "にほ", "日本"] : ["z", "zh", "中文"]
+ for word in words.dropLast() { Self.mark(word, in: text) }
+ try await peerEdit(near: at)
+ try await peerEdit(near: at + 40)
+ try await publish(.publish)
+ XCTAssertTrue(Self.hasMarkedText(text), "seed \(seed): a publication must not replace marked text")
+ Self.mark(words.last!, in: text)
+ Self.commit(text)
+ try await drain()
+ default:
+ try await drain(); try await publish(.publish)
+ }
+ }
+ // Quiescence.
+ try await drain()
+ try await publish(.publish)
+ let final = try await replica.projection()
+ SurfaceFixture.assertMatchesWholeRender(state.surface.content, final, "seed \(seed), log \(logLimit)")
+ XCTAssertEqual(state.surface.index.runs, DocumentBlockIndex.runs(in: state.surface.content), "seed \(seed): the index")
+ await replica.close(); await peer.close()
+ }
+
+ private static func mark(_ word: String, in text: DocsTextView) {
+ #if os(macOS)
+ text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
+ #else
+ text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0))
+ #endif
+ }
+ private static func commit(_ text: DocsTextView) { text.unmarkText() }
+ private static func hasMarkedText(_ text: DocsTextView) -> Bool {
+ #if os(macOS)
+ text.hasMarkedText()
+ #else
+ text.markedTextRange != nil
+ #endif
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/DocsFontsTests.swift b/native/apple/Tests/DocsKitTests/DocsFontsTests.swift
index 0de46cc..fcd1811 100644
--- a/native/apple/Tests/DocsKitTests/DocsFontsTests.swift
+++ b/native/apple/Tests/DocsKitTests/DocsFontsTests.swift
@@ -213,9 +213,9 @@ final class DocsFontsTests: XCTestCase {
CRDTNode(id: "h", type: "heading", attrs: ["level": "1"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Report", marks: marks)])]),
CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "pt", type: "text", runs: [CRDTRun(insert: words, marks: marks)])]),
], canUndo: false, canRedo: false)
- let view = NativeDocumentTextView(content: NativeTextProjection.render(projection), generation: 1, didRender: { _ in }, compositionChanged: { _ in },
- isEditable: false, paged: false, pendingInput: false, canRender: { _ in true }, currentSelection: { NSRange(location: 0, length: 0) },
- selection: .constant(NSRange(location: 0, length: 0)), edit: { _ in true })
+ let surface = DocumentSurface()
+ surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
+ let view = DocumentEditorHost(surface: surface, paged: false)
let host = NSHostingView(rootView: view.frame(width: 640, height: 240))
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 240), styleMask: [.borderless], backing: .buffered, defer: false)
window.contentView = host
diff --git a/native/apple/Tests/DocsKitTests/FlushTriggerTests.swift b/native/apple/Tests/DocsKitTests/FlushTriggerTests.swift
new file mode 100644
index 0000000..d75f0b8
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/FlushTriggerTests.swift
@@ -0,0 +1,133 @@
+import Foundation
+import RastrilloApple
+import XCTest
+@testable import DocsKit
+
+/// The deferred-flush triggers (spec 2026-11-22 §7 Design 6, finding 2):
+/// a publication arrives while something stops the text view taking it,
+/// and *no later publication* follows. When that something clears, its
+/// event alone must bring the storage to a whole render of the newest
+/// projection. The production `DocsModel` and replica, an in-memory
+/// server, and a real `DocsTextView`; the live stream is closed after open,
+/// so nothing else publishes.
+@MainActor final class FlushTriggerTests: XCTestCase {
+ private var server: LoopServer!
+ private var model: DocsModel!
+ private var text: DocsTextView!
+
+ override func setUp() async throws {
+ DocsFonts.register()
+ server = LoopServer()
+ try await server.seed(LoopFixture.everything)
+ model = DocsModel(client: server)
+ text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 800))
+ model.surface.attach(text)
+ await model.open("doc")
+ model.suspendLiveUpdates()
+ }
+ override func tearDown() async throws {
+ await model?.stop()
+ model = nil; text = nil; server = nil
+ }
+
+ private var shown: NSAttributedString { model.surface.content }
+ private func assertDrawn(_ what: String, file: StaticString = #filePath, line: UInt = #line) throws {
+ let projection = try XCTUnwrap(model.projection, file: file, line: line)
+ SurfaceFixture.assertMatchesWholeRender(shown, projection, images: [:], what, file: file, line: line)
+ }
+ private func until(_ what: String, _ condition: () -> Bool) async throws {
+ let deadline = ContinuousClock.now + .seconds(5)
+ while !condition() {
+ guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") }
+ try await Task.sleep(for: .milliseconds(2))
+ }
+ }
+ private func typeInTheMiddle(_ characters: String) {
+ let line = (shown.string as NSString).range(of: LoopFixture.middle)
+ Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text)
+ Keyboard.type(characters, in: text)
+ }
+ /// A publication the replica did not make: block `index` changed.
+ private func fabricated(generation: UInt64, changing index: Int) throws -> DocumentSurface.Publication {
+ var projection = try XCTUnwrap(model.projection)
+ let node = projection.children[index]
+ projection.children[index] = SurfaceFixture.paragraph(node.id, "Changed while waiting.")
+ return DocumentSurface.Publication(generation: generation, projection: projection, revision: model.surface.appliedRevision + 1, dirty: [node.id])
+ }
+
+ /// (a) A publication applied, nothing in the way: drawn at once.
+ func testAPublicationIsDrawnWhenItArrives() throws {
+ try assertDrawn("open")
+ let publication = try fabricated(generation: model.projectionGeneration, changing: 1)
+ model.surface.apply(publication)
+ SurfaceFixture.assertMatchesWholeRender(shown, publication.projection, "a publication with nothing in the way")
+ }
+
+ /// (b) The publication from typing arrives while the edit queue is
+ /// still draining; the queue's end alone draws it. A Return, so the
+ /// publication differs from what the text view shows optimistically:
+ /// the new paragraph gets its own block id only from it.
+ func testTheEditQueueDrainingDrawsTheWaitingPublication() async throws {
+ var deferred = 0
+ model.surface.willApply = { [unowned self] _ in if model.hasPendingInput { deferred = model.surface.publicationsReceived } }
+ typeInTheMiddle(" typed\nNew")
+ try await until("the queue drained") { !model.hasPendingInput }
+ XCTAssertGreaterThan(deferred, 0, "a publication arrived while input was pending")
+ XCTAssertEqual(model.surface.publicationsReceived, deferred, "no later publication")
+ try assertDrawn("after the queue drained")
+ XCTAssertTrue(shown.string.contains(LoopFixture.middle + " typed\nNew"))
+ }
+
+ /// (c) Composition starts as a publication arrives; ending it (with no
+ /// text, so nothing is sent) alone draws the publication.
+ func testCompositionEndingDrawsTheWaitingPublication() async throws {
+ var composed = false
+ model.surface.willApply = { [unowned self] _ in
+ guard !composed else { return }
+ composed = true
+ Self.mark("", in: text)
+ }
+ typeInTheMiddle("x")
+ try await until("the queue drained") { !model.hasPendingInput }
+ XCTAssertTrue(composed)
+ let received = model.surface.publicationsReceived
+ let waiting = try XCTUnwrap(model.surface.newest)
+ XCTAssertGreaterThan(waiting.revision, model.surface.appliedRevision, "the publication waits for the composition")
+ text.unmarkText()
+ XCTAssertEqual(model.surface.publicationsReceived, received, "no later publication")
+ XCTAssertEqual(model.surface.appliedRevision, waiting.revision)
+ try assertDrawn("after the composition ended")
+ }
+
+ /// (d) A publication for a generation the model has not reached waits;
+ /// the generation catching up alone draws it.
+ func testTheGenerationCatchingUpDrawsTheWaitingPublication() throws {
+ let next = model.projectionGeneration + 1
+ let publication = try fabricated(generation: next, changing: 1)
+ model.surface.apply(publication)
+ XCTAssertLessThan(model.surface.appliedRevision, publication.revision, "not the current generation yet")
+ model.projectionGeneration = next
+ SurfaceFixture.assertMatchesWholeRender(shown, publication.projection, "after the generation caught up")
+ }
+
+ /// (e) With rendering held while input is paused, unpausing alone
+ /// draws the waiting publication.
+ func testInputUnpausedDrawsTheWaitingPublication() throws {
+ let canRender = model.surface.hooks.canRender
+ model.surface.hooks.canRender = { [unowned self] generation in canRender(generation) && !model.inputPaused }
+ model.inputPaused = true
+ let publication = try fabricated(generation: model.projectionGeneration, changing: 4)
+ model.surface.apply(publication)
+ XCTAssertLessThan(model.surface.appliedRevision, publication.revision)
+ model.inputPaused = false
+ SurfaceFixture.assertMatchesWholeRender(shown, publication.projection, "after input was unpaused")
+ }
+
+ static func mark(_ word: String, in text: DocsTextView) {
+ #if os(macOS)
+ text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
+ #else
+ text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0))
+ #endif
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/NativeClipboardInputTests.swift b/native/apple/Tests/DocsKitTests/NativeClipboardInputTests.swift
index 095c57c..d96463f 100644
--- a/native/apple/Tests/DocsKitTests/NativeClipboardInputTests.swift
+++ b/native/apple/Tests/DocsKitTests/NativeClipboardInputTests.swift
@@ -6,49 +6,45 @@ import XCTest
final class NativeClipboardInputTests: XCTestCase {
@MainActor func testDelegateTextReplacementAlsoRunsStructuralInputRule() {
- var commands: [[String: JSONValue]] = []
- let candidate = NativeDocumentTextView(content: NSAttributedString(string: "-\n"), generation: 1, didRender: { _ in }, compositionChanged: { _ in }, isEditable: true, paged: false, pendingInput: false, canRender: { _ in true }, currentSelection: { NSRange(location: 1, length: 0) }, selection: .constant(NSRange(location: 1, length: 0)), edit: { commands.append($0); return true })
- let coordinator = candidate.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- text.delegate = coordinator
- text.ruleCommand = coordinator.ruleEdit
- coordinator.applyRender(candidate, to: text)
- let allowed = coordinator.textView(text, shouldChangeTextIn: NSRange(location: 1, length: 0), replacementString: " ")
+ let state = SurfaceState()
+ state.markPendingOnEdit = false
+ state.publish(SurfaceFixture.projection([SurfaceFixture.paragraph("p", "-")]), generation: 1, dirty: nil)
+ let text = state.text
+ text.setSelectedRange(NSRange(location: 1, length: 0))
+ let allowed = state.surface.textView(text, shouldChangeTextIn: NSRange(location: 1, length: 0), replacementString: " ")
XCTAssertFalse(allowed)
XCTAssertEqual(text.string, "\n")
- XCTAssertEqual(commands.last?["op"], .string("display_autoformat"))
- XCTAssertEqual(commands.last?["generation"], .number(1))
+ XCTAssertEqual(state.commands.last?["op"], .string("display_autoformat"))
+ XCTAssertEqual(state.commands.last?["generation"], .number(1))
}
@MainActor func testDelayedDuplicateRuleSelectionNotificationDoesNotCancelReversal() {
- var commands: [[String: JSONValue]] = []
- var selected = NSRange(location: 1, length: 0)
- let candidate = NativeDocumentTextView(content: NSAttributedString(string: "-\n"), generation: 1, didRender: { _ in }, compositionChanged: { _ in }, isEditable: true, paged: false, pendingInput: false, canRender: { _ in true }, currentSelection: { selected }, selection: Binding(get: { selected }, set: { selected = $0 }), edit: { commands.append($0); return true })
- let coordinator = candidate.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- text.delegate = coordinator; text.ruleCommand = coordinator.ruleEdit
- coordinator.applyRender(candidate, to: text)
+ let state = SurfaceState()
+ state.markPendingOnEdit = false
+ state.publish(SurfaceFixture.projection([SurfaceFixture.paragraph("p", "-")]), generation: 1, dirty: nil)
+ let text = state.text
+ text.setSelectedRange(NSRange(location: 1, length: 0))
+ state.selection = NSRange(location: 1, length: 0)
text.insertText(" ", replacementRange: NSRange(location: NSNotFound, length: 0))
- coordinator.textViewDidChangeSelection(Notification(name: NSTextView.didChangeSelectionNotification, object: text))
- coordinator.textViewDidChangeSelection(Notification(name: NSTextView.didChangeSelectionNotification, object: text))
+ state.surface.textViewDidChangeSelection(Notification(name: NSTextView.didChangeSelectionNotification, object: text))
+ state.surface.textViewDidChangeSelection(Notification(name: NSTextView.didChangeSelectionNotification, object: text))
XCTAssertNotNil(text.lastInputRule)
text.deleteBackward(nil)
XCTAssertEqual(text.string, "- \n")
- XCTAssertEqual(commands.last?["op"], .string("display_revert_rule"))
+ XCTAssertEqual(state.commands.last?["op"], .string("display_revert_rule"))
}
@MainActor func testDirectDelegateBackspaceReversesRuleBeforeGenericDeletion() {
- var commands: [[String: JSONValue]] = []
- var selected = NSRange(location: 1, length: 0)
- let candidate = NativeDocumentTextView(content: NSAttributedString(string: "-\n"), generation: 1, didRender: { _ in }, compositionChanged: { _ in }, isEditable: true, paged: false, pendingInput: false, canRender: { _ in true }, currentSelection: { selected }, selection: Binding(get: { selected }, set: { selected = $0 }), edit: { commands.append($0); return true })
- let coordinator = candidate.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- text.delegate = coordinator; text.ruleCommand = coordinator.ruleEdit
- coordinator.applyRender(candidate, to: text)
+ let state = SurfaceState()
+ state.markPendingOnEdit = false
+ state.publish(SurfaceFixture.projection([SurfaceFixture.paragraph("p", "-")]), generation: 1, dirty: nil)
+ let text = state.text
+ text.setSelectedRange(NSRange(location: 1, length: 0))
+ state.selection = NSRange(location: 1, length: 0)
text.insertText(" ", replacementRange: NSRange(location: NSNotFound, length: 0))
XCTAssertNotNil(text.lastInputRule)
- let allowed = coordinator.textView(text, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementString: "")
+ let allowed = state.surface.textView(text, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementString: "")
XCTAssertFalse(allowed)
XCTAssertEqual(text.string, "- \n")
- XCTAssertEqual(commands.last?["op"], .string("display_revert_rule"))
+ XCTAssertEqual(state.commands.last?["op"], .string("display_revert_rule"))
}
@MainActor func testRichPasteOptimisticMarksMatchImmediateTyping() throws {
let blocks: [JSONValue] = [.object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("bold😀"), "marks": .object(["strong": .object([:])])])])])])])]
diff --git a/native/apple/Tests/DocsKitTests/NativeRenderTests.swift b/native/apple/Tests/DocsKitTests/NativeRenderTests.swift
index 7d6e355..7434694 100644
--- a/native/apple/Tests/DocsKitTests/NativeRenderTests.swift
+++ b/native/apple/Tests/DocsKitTests/NativeRenderTests.swift
@@ -4,62 +4,44 @@ import SwiftUI
import XCTest
@testable import DocsKit
-@MainActor private final class RenderState {
- var pending = false
- var allowed: UInt64 = 1
- var selection = NSRange(location: 0, length: 0)
- var acknowledgements: [UInt64] = []
- var commands: [[String: JSONValue]] = []
- func candidate(_ content: NSAttributedString, generation: UInt64) -> NativeDocumentTextView {
- NativeDocumentTextView(content: content, generation: generation,
- didRender: { self.acknowledgements.append($0) }, compositionChanged: { _ in },
- isEditable: true, paged: false, pendingInput: pending,
- canRender: { !self.pending && self.allowed == $0 }, currentSelection: { self.selection },
- selection: Binding(get: { self.selection }, set: { self.selection = $0 }),
- edit: { self.pending = true; self.commands.append($0); return true })
- }
-}
+/// The text view's render guards, now on `DocumentSurface`: a publication
+/// never overwrites typing the model has not answered, nor marked text,
+/// nor a generation that is not current.
final class NativeRenderTests: XCTestCase {
+ private func one(_ text: String, marks: [String: JSONValue]? = nil) -> CRDTProjection {
+ SurfaceFixture.projection([SurfaceFixture.paragraph("p", text, marks: marks)])
+ }
@MainActor func testDelayedCandidateCannotOverwriteAcceptedNativeTyping() {
- let state = RenderState()
- let initial = state.candidate(NSAttributedString(string: "a😀b\n"), generation: 1)
- let coordinator = initial.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- text.delegate = coordinator
- coordinator.applyRender(initial, to: text)
+ let state = SurfaceState()
+ let text = state.text
+ state.publish(one("a😀b"), generation: 1, dirty: nil)
+ XCTAssertEqual(text.string, "a😀b\n")
state.allowed = 2
- let delayed = state.candidate(NSAttributedString(string: "older server view\n"), generation: 2)
- XCTAssertFalse(delayed.pendingInput)
text.insertText("X", replacementRange: NSRange(location: 4, length: 0))
XCTAssertTrue(state.pending)
XCTAssertEqual(text.string, "a😀bX\n")
XCTAssertEqual(state.commands.last?["generation"], .number(1))
- coordinator.applyRender(delayed, to: text)
+ state.publish(one("older server view"), generation: 2, dirty: ["p"])
XCTAssertEqual(text.string, "a😀bX\n")
XCTAssertEqual(state.acknowledgements, [1])
state.pending = false; state.allowed = 3
- coordinator.applyRender(delayed, to: text)
+ state.surface.flushIfDeferred()
XCTAssertEqual(text.string, "a😀bX\n")
state.selection = NSRange(location: 6, length: 0)
- let current = state.candidate(NSAttributedString(string: "a😀bX!\n"), generation: 3)
- coordinator.applyRender(current, to: text)
+ state.publish(one("a😀bX!"), generation: 3, dirty: ["p"])
XCTAssertEqual(text.string, "a😀bX!\n")
XCTAssertEqual(text.selectedRange(), NSRange(location: 6, length: 0))
XCTAssertEqual(state.acknowledgements, [1, 3])
}
@MainActor func testMarkedTextSurvivesPeerPresentationAndCommitsOnce() {
- let state = RenderState()
- let initial = state.candidate(NSAttributedString(string: "a😀b\n"), generation: 1)
- let coordinator = initial.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- text.delegate = coordinator
- text.compositionCommitted = { coordinator.commitComposition(before: $0, after: $1) }
- coordinator.applyRender(initial, to: text)
+ let state = SurfaceState()
+ let text = state.text
+ state.publish(one("a😀b"), generation: 1, dirty: nil)
text.setMarkedText("に", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: 1, length: 2))
XCTAssertTrue(text.hasMarkedText())
XCTAssertTrue(state.commands.isEmpty)
state.allowed = 2
- coordinator.applyRender(state.candidate(NSAttributedString(string: "peer update\n"), generation: 2), to: text)
+ state.publish(one("peer update"), generation: 2, dirty: ["p"])
XCTAssertEqual(text.string, "aにb\n")
XCTAssertEqual(state.acknowledgements, [1])
text.unmarkText()
@@ -71,17 +53,15 @@ final class NativeRenderTests: XCTestCase {
}
@MainActor func testAttributeOnlyRefreshPreservesNativeCaret() {
- let state = RenderState()
- let initial = state.candidate(NSAttributedString(string: "abcdef\n"), generation: 1)
- let coordinator = initial.makeCoordinator()
- let text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 500, height: 700))
- coordinator.applyRender(initial, to: text)
+ let state = SurfaceState()
+ let text = state.text
+ state.publish(one("abcdef"), generation: 1, dirty: nil)
text.setSelectedRange(NSRange(location: 4, length: 0))
state.selection = NSRange(location: 0, length: 0)
- let changed = NSAttributedString(string: "abcdef\n", attributes: [.foregroundColor: NSColor.red])
- coordinator.applyRender(state.candidate(changed, generation: 1), to: text)
+ let before = text.textStorage?.attribute(.font, at: 0, effectiveRange: nil) as? NSFont
+ state.publish(one("abcdef", marks: ["strong": .object([:])]), generation: 1, dirty: ["p"])
XCTAssertEqual(text.selectedRange(), NSRange(location: 4, length: 0))
- XCTAssertEqual(text.textStorage?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor, .red)
+ XCTAssertNotEqual(text.textStorage?.attribute(.font, at: 0, effectiveRange: nil) as? NSFont, before)
}
}
#endif
diff --git a/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift b/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift
new file mode 100644
index 0000000..afca7a2
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/RenderIsolationTests.swift
@@ -0,0 +1,151 @@
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import SwiftUI
+import XCTest
+@testable import DocsKit
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// Render isolation and §7's hard counters (spec 2026-11-22 §7 Design 9,
+/// "Measurement and targets"; §11 "Render isolation"). The production
+/// `DocsWorkspace` for one document in a real window, on an in-memory
+/// server: type 40 keys, flip the sync status 10 times, move the selection
+/// 20 times and take 5 peer changes. After open, the text view's host is
+/// never evaluated again, nothing renders the whole document, iOS never
+/// assigns `attributedText`, and each key or peer change renders at most
+/// its block and two neighbours.
+#if DOCS_PROBES
+@MainActor final class RenderIsolationTests: XCTestCase {
+ private var window: AnyObject?
+
+ func testTheHostObservesNothingThatMovesPerKey() async throws {
+ DocsFonts.register()
+ let server = LoopServer()
+ try await server.seed(LoopFixture.everything)
+ let path = ScriptedPathSource(.satisfied)
+ let connectivity = NativeConnectivity(source: path)
+ let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", connectivity: connectivity)
+ #if os(macOS)
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = NSHostingView(rootView: workspace)
+ window.orderFront(nil)
+ #else
+ 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()
+ #endif
+ self.window = window
+ defer {
+ #if os(macOS)
+ window.contentView = nil; window.close()
+ #else
+ window.rootViewController = nil; window.isHidden = true
+ #endif
+ }
+ func find() -> DocsTextView? {
+ #if os(macOS)
+ func search(_ view: NSView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first }
+ return window.contentView.flatMap(search)
+ #else
+ func search(_ view: UIView) -> DocsTextView? { (view as? DocsTextView) ?? view.subviews.lazy.compactMap(search).first }
+ return search(window)
+ #endif
+ }
+ try await until("the document is shown") { find().map { Keyboard.storage(of: $0).string.contains(LoopFixture.middle) } ?? false }
+ let text = try XCTUnwrap(find())
+ let surface = try XCTUnwrap(text.delegate as? DocumentSurface)
+ // Drawn: nothing waiting, and no character without its block (typed
+ // text carries its block's id only once a publication drew it on
+ // iOS, whose typing attributes may leave it out).
+ func settled() -> Bool {
+ (surface.newest.map { $0.revision == surface.appliedRevision } ?? false) && surface.pendingDirty.isEmpty
+ && !surface.index.runs.contains { $0.id == nil }
+ }
+ try await until("open settled") { settled() }
+ try await Task.sleep(for: .milliseconds(300))
+ var storageEdits = 0
+ let observer = NotificationCenter.default.addObserver(forName: NSTextStorage.didProcessEditingNotification, object: Keyboard.storage(of: text), queue: nil) { _ in
+ MainActor.assumeIsolated { storageEdits += 1 }
+ }
+ defer { NotificationCenter.default.removeObserver(observer) }
+ DocsProbes.reset()
+
+ // 40 keys, each drawn before the next.
+ let line = (surface.content.string as NSString).range(of: LoopFixture.middle)
+ Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text)
+ var typed = LoopFixture.middle
+ var perKey: [(blocks: Int, edits: Int)] = []
+ for index in 0..<40 {
+ let blocks = DocsProbes.blockRenders, edits = storageEdits
+ 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))
+ }
+ XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole-document renders while typing")
+ XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations while typing")
+ 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))")
+ print("RENDER ISOLATION per key: block renders \(perKey.map(\.blocks)), storage edits \(perKey.map(\.edits)); \(DocsProbes.summary)")
+
+ // The sync status, ten times.
+ DocsProbes.reset(); storageEdits = 0
+ for index in 0..<10 {
+ path.send(index % 2 == 0 ? .unsatisfied : .satisfied)
+ try await Task.sleep(for: .milliseconds(40))
+ }
+ path.send(.satisfied)
+ try await Task.sleep(for: .milliseconds(200))
+ XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per sync-status change")
+ XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per sync-status change")
+ XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per sync-status change")
+ XCTAssertEqual(storageEdits, 0, "storage edits per sync-status change")
+
+ // The selection, twenty times.
+ DocsProbes.reset(); storageEdits = 0
+ let length = surface.content.length
+ for index in 0..<20 {
+ Keyboard.select(NSRange(location: (index * 37) % max(1, length - 1), length: index % 3), in: text)
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ try await Task.sleep(for: .milliseconds(200))
+ XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per selection change")
+ XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per selection change")
+ XCTAssertEqual(DocsProbes.blockRenders, 0, "block renders per selection change")
+ XCTAssertEqual(storageEdits, 0, "storage edits per selection change")
+
+ // Five peer changes, in one block.
+ DocsProbes.reset()
+ for index in 0..<5 {
+ let note = "Peer\(index) "
+ let at = (surface.content.string as NSString).range(of: LoopFixture.afterRule).location
+ let blocks = DocsProbes.blockRenders
+ try await server.peerInsert(note, at: at)
+ try await until("peer change \(index) shown") { surface.content.string.contains(note) && settled() }
+ try await Task.sleep(for: .milliseconds(20))
+ XCTAssertLessThanOrEqual(DocsProbes.blockRenders - blocks, 3, "block renders for peer change \(index)")
+ }
+ XCTAssertEqual(DocsProbes.wholeRenders, 0, "whole renders per peer change")
+ XCTAssertEqual(DocsProbes.hostBodies, 0, "host body evaluations per peer change")
+ XCTAssertEqual(DocsProbes.attributedTextAssignments, 0, "attributedText assignments per peer change")
+ print("RENDER ISOLATION peers: \(DocsProbes.summary)")
+ }
+
+ private func until(_ what: String, _ condition: () -> Bool) async throws {
+ let deadline = ContinuousClock.now + .seconds(10)
+ while !condition() {
+ guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") }
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
new file mode 100644
index 0000000..a158e2b
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/SurfaceTestSupport.swift
@@ -0,0 +1,173 @@
+import Foundation
+import XCTest
+@testable import DocsKit
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+/// A `DocumentSurface` driven by hand: hooks that record, a model state the
+/// tests set, and helpers to build projections and publications.
+@MainActor final class SurfaceState {
+ var pending = false
+ var allowed: UInt64 = 1
+ var selection = NSRange(location: 0, length: 0)
+ var acknowledgements: [UInt64] = []
+ var commands: [[String: JSONValue]] = []
+ var accept = true
+ var markPendingOnEdit = true
+ let surface = DocumentSurface()
+ let text: DocsTextView
+ var revision: UInt64 = 0
+
+ init(width: CGFloat = 500) {
+ #if os(macOS)
+ text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700))
+ #else
+ text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700))
+ #endif
+ var hooks = DocumentSurface.Hooks()
+ hooks.edit = { [unowned self] command in
+ if markPendingOnEdit { pending = true }
+ commands.append(command); return accept
+ }
+ hooks.canRender = { [unowned self] generation in !pending && allowed == generation }
+ hooks.currentSelection = { [unowned self] in selection }
+ hooks.didRender = { [unowned self] generation in acknowledgements.append(generation) }
+ hooks.selectionChanged = { [unowned self] range in selection = range }
+ surface.hooks = hooks
+ surface.isEditable = true
+ surface.attach(text)
+ }
+
+ /// Publishes `projection` as the next revision.
+ func publish(_ projection: CRDTProjection, generation: UInt64, dirty: Set<String>?) {
+ revision += 1
+ surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: revision, dirty: dirty))
+ }
+
+ var string: String { surface.content.string }
+}
+
+enum SurfaceFixture {
+ static func paragraph(_ id: String, _ text: String, marks: [String: JSONValue]? = nil, attrs: [String: String]? = nil) -> CRDTNode {
+ CRDTNode(id: id, type: "paragraph", attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])])
+ }
+ static func heading(_ id: String, _ text: String, level: Int = 1) -> CRDTNode {
+ CRDTNode(id: id, type: "heading", attrs: ["level": String(level)], children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text)])])
+ }
+ static func list(_ id: String, _ type: String, _ items: [String]) -> CRDTNode {
+ CRDTNode(id: id, type: type, children: items.enumerated().map { index, item in
+ CRDTNode(id: "\(id)i\(index)", type: "list_item", children: [paragraph("\(id)p\(index)", item)])
+ })
+ }
+ static func quote(_ id: String, _ items: [String]) -> CRDTNode {
+ CRDTNode(id: id, type: "blockquote", children: items.enumerated().map { index, item in paragraph("\(id)p\(index)", item) })
+ }
+ static func projection(_ nodes: [CRDTNode]) -> CRDTProjection { CRDTProjection(children: nodes, canUndo: false, canRedo: false) }
+
+ /// Whether `storage` draws what a whole render of `projection` draws,
+ /// attribute for attribute (lists and attachments by what they draw).
+ @MainActor static func assertMatchesWholeRender(_ storage: NSAttributedString, _ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:], _ message: String = "", file: StaticString = #filePath, line: UInt = #line) {
+ // As a text view's storage holds it: TextKit fixes attributes (a
+ // CJK character's font falls back, and UIKit notes the original),
+ // so compare with the storage a whole render makes in a fresh one.
+ let oracle = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 700))
+ let whole = Keyboard.storage(of: oracle)
+ whole.setAttributedString(NativeTextProjection.render(projection, images: images))
+ XCTAssertEqual(storage.string, whole.string, "text: \(message)", file: file, line: line)
+ if storage.string == whole.string {
+ let equivalent = DocumentRenderReconciliation.isEquivalent(storage, whole)
+ if !equivalent { print("FIRST DIFFERENCE (\(message)): \(firstDifference(storage, whole))") }
+ XCTAssertTrue(equivalent, "attributes differ from a whole render: \(message)", file: file, line: line)
+ }
+ }
+ @MainActor static func firstDifference(_ a: NSAttributedString, _ b: NSAttributedString) -> String {
+ var location = 0
+ while location < min(a.length, b.length) {
+ var ra = NSRange(), rb = NSRange()
+ let x = a.attributes(at: location, effectiveRange: &ra), y = b.attributes(at: location, effectiveRange: &rb)
+ let single = NSAttributedString(string: (a.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: x)
+ let other = NSAttributedString(string: (b.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: y)
+ if !DocumentRenderReconciliation.isEquivalent(single, other) {
+ return "at \(location) (\((a.string as NSString).substring(with: NSRange(location: location, length: 1)).debugDescription)):\n \(x)\n vs\n \(y)"
+ }
+ location = min(NSMaxRange(ra), NSMaxRange(rb))
+ }
+ return "lengths \(a.length) / \(b.length)"
+ }
+}
+
+/// The keyboard's path into a real `DocsTextView`, on both platforms.
+@MainActor enum Keyboard {
+ static func select(_ range: NSRange, in text: DocsTextView) {
+ #if os(macOS)
+ text.setSelectedRange(range)
+ #else
+ text.selectedRange = range
+ text.delegate?.textViewDidChangeSelection?(text)
+ #endif
+ }
+ static func selection(_ text: DocsTextView) -> NSRange {
+ #if os(macOS)
+ text.selectedRange()
+ #else
+ text.selectedRange
+ #endif
+ }
+ /// Types `characters` at the caret, one at a time, Return included.
+ static func type(_ characters: String, in text: DocsTextView) {
+ for character in characters {
+ let piece = String(character)
+ #if os(macOS)
+ if piece == "\n" { text.insertNewline(nil) } else { text.insertText(piece, replacementRange: text.selectedRange()) }
+ #else
+ // UITextView.insertText from code skips the delegate: take the
+ // keyboard's path by hand.
+ let range = text.selectedRange
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true {
+ text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes))
+ text.selectedRange = NSRange(location: range.location + piece.utf16.count, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
+ #endif
+ }
+ }
+ static func backspace(in text: DocsTextView) {
+ #if os(macOS)
+ text.deleteBackward(nil)
+ #else
+ let caret = text.selectedRange
+ guard caret.location > 0 || caret.length > 0 else { return }
+ let range = caret.length > 0 ? caret : NSRange(location: caret.location - 1, length: 1)
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: "") ?? true {
+ text.textStorage.replaceCharacters(in: range, with: "")
+ text.selectedRange = NSRange(location: range.location, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
+ #endif
+ }
+ /// A rich paste of `blocks` at the selection, as `DocsTextView.paste`
+ /// does it once the clipboard is read.
+ static func paste(_ blocks: [JSONValue], in text: DocsTextView, surface: DocumentSurface) {
+ let range = selection(text)
+ guard let replacement = DocumentClipboardInsertion.attributed(blocks: blocks, in: surface.content, range: range),
+ surface.clipboardEdit(blocks: blocks, range: range, replacement: replacement.string) else { return }
+ storage(of: text).replaceCharacters(in: range, with: replacement)
+ select(NSRange(location: range.location + replacement.length, length: 0), in: text)
+ }
+ static func storage(of text: DocsTextView) -> NSTextStorage {
+ #if os(macOS)
+ text.textStorage!
+ #else
+ text.textStorage
+ #endif
+ }
+}
+
+#if os(iOS)
+extension DocsTextView {
+ func string() -> String { text }
+}
+#endif
diff --git a/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift b/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
index 0997ba3..eef0309 100644
--- a/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
+++ b/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift
@@ -202,6 +202,7 @@ enum EditorScript: Sendable {
await model.open("doc")
guard let projection = model.projection else { throw EditorScreenFailure("the fixture did not open") }
await images.load(sources: DocsImageStore.sources(in: projection), client: server, documentPath: "/d/doc")
+ EditorPage.link(images, to: model, client: server)
self.server = server
self.model = model
try await until("the stream opened") { await server.openStreams == 1 }
@@ -342,8 +343,8 @@ struct EditorScreenFailure: Error, CustomStringConvertible {
init(_ description: String) { self.description = description }
}
-/// The page as `DocsWorkspace.editor` draws it: the projection rendered with
-/// its images, in `NativeDocumentTextView`, wired to the model.
+/// The page as `DocsWorkspace.editor` draws it: the model's surface in
+/// `DocumentEditorHost`, with the document's images.
@MainActor struct EditorPage: View {
/// Held as `DocsWorkspace` holds it, in `@State`.
@State private var model: DocsModel
@@ -359,27 +360,20 @@ struct EditorScreenFailure: Error, CustomStringConvertible {
}
var body: some View {
- if let projection = model.projection {
- let documentPath = "/d/" + (model.detail?.sqid ?? "")
- let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: client))
- NativeDocumentTextView(content: text, generation: model.projectionGeneration, didRender: model.didRender,
- compositionChanged: model.compositionChanged,
- isEditable: model.detail?.can_write == true && !model.inputPaused, paged: paged,
- pendingInput: model.hasPendingInput, canRender: model.canRender,
- currentSelection: model.currentSelection, selection: $model.selection, edit: model.enqueue,
- action: { DocumentCommands(model: model, content: text).perform($0) },
- selectionMoved: model.selectionMovedExplicitly,
- canAction: { action in
- model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputPaused
- && (action == "undo" ? projection.canUndo : projection.canRedo)
- },
- explicitCommandRevision: model.explicitCommandRevision, zoom: zoom, typingMarks: model.typingMarks)
- #if os(macOS)
- .inspectorSide(inspector)
- #endif
+ if model.showsDocument {
+ DocumentEditorHost(surface: model.surface, paged: paged, zoom: zoom, inspector: inspector)
+ .equatable()
.id(model.editorIdentity)
}
}
+
+ /// The images the screen loaded before it opened, handed to the
+ /// surface as `DocsWorkspace` hands them, so the first frame has them.
+ static func link(_ images: DocsImageStore, to model: DocsModel, client: NativeTransport) {
+ let surface = model.surface
+ images.changed = { [weak images] _ in surface.imagesChanged(images?.images(forDocumentPath: "/d/doc", client: client) ?? [:]) }
+ surface.imagesChanged(images.images(forDocumentPath: "/d/doc", client: client))
+ }
}
// MARK: - Finding the text view
diff --git a/native/apple/Tests/DocsSnapshots/WindowSnapshots.swift b/native/apple/Tests/DocsSnapshots/WindowSnapshots.swift
index 80a25ee..03bf842 100644
--- a/native/apple/Tests/DocsSnapshots/WindowSnapshots.swift
+++ b/native/apple/Tests/DocsSnapshots/WindowSnapshots.swift
@@ -106,8 +106,8 @@ final class DocsWindowSnapshots: XCTestCase {
.overlay(alignment: .bottom) { Rectangle().fill(OficinaPalette.line).frame(height: 1) }
page
.overlay(alignment: .topTrailing) {
- if chrome.inspectorSide != nil, let projection = model.projection {
- DocsFormatInspector(model: model, content: NativeTextProjection.render(projection))
+ if chrome.inspectorSide != nil, model.showsDocument {
+ DocsFormatInspector(model: model)
.padding(.top, DocsDeskLayout.inspectorInset)
.padding(.trailing, DocsDeskLayout.inspectorInset)
}
diff --git a/native/ios/project.yml b/native/ios/project.yml
index 2b14847..30d6d73 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -122,23 +122,36 @@ targets:
base:
GENERATE_INFOPLIST_FILE: true
PRODUCT_BUNDLE_IDENTIFIER: works.oficina.docs.snapshots
- # The editor's render-loop regression (TestFlight 0.1.10 build 12) on the
- # iOS text view: the Mac half runs in `swift test`; this runs the same file
- # in the simulator. native/scripts/test-iphone.sh runs it.
+ # Editor tests that need UIKit's text view: the render-loop regression
+ # (TestFlight 0.1.10 build 12) and the per-block rendering of the native
+ # redesign's S1a (the surface's flush triggers, delta safety, the block
+ # index, block render equivalence, render isolation and §7's counters).
+ # The Mac half runs the same files in `swift test`; this runs them in the
+ # simulator. native/scripts/test-iphone.sh runs it. DOCS_PROBES compiles
+ # the counters' test, as DocsKit's debug build compiles the counters.
DocsPhoneTests:
type: bundle.unit-test
platform: iOS
sources:
- path: ../apple/Tests/DocsKitTests/EditorRenderLoopTests.swift
+ - path: ../apple/Tests/DocsKitTests/SurfaceTestSupport.swift
+ - path: ../apple/Tests/DocsKitTests/FlushTriggerTests.swift
+ - path: ../apple/Tests/DocsKitTests/DeltaSafetyTests.swift
+ - path: ../apple/Tests/DocsKitTests/BlockIndexTests.swift
+ - path: ../apple/Tests/DocsKitTests/BlockRenderEquivalenceTests.swift
+ - path: ../apple/Tests/DocsKitTests/RenderIsolationTests.swift
dependencies:
- package: DocsNative
product: DocsKit
- package: RastrilloNative
product: RastrilloApple
+ - package: RastrilloNative
+ product: RastrilloTestSupport
settings:
base:
GENERATE_INFOPLIST_FILE: true
PRODUCT_BUNDLE_IDENTIFIER: works.oficina.docs.phonetests
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: $(inherited) DOCS_PROBES
schemes:
DocsPhoneTests:
build: