| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import Foundation |
| 4 | import Observation |
| 5 | import RastrilloApple |
| 6 | import RastrilloNative |
| 7 | import RastrilloTestSupport |
| 8 | import Synchronization |
| 9 | import SwiftUI |
| 10 | import XCTest |
| 11 | @testable import DocsKit |
| 12 | |
| 13 | /// S2a's chrome over S1a's surface (Fable on #170, findings 4 and 5): what |
| 14 | /// the Format menu, the toolbar, the pill and the live word count read |
| 15 | /// must follow an edit through observation, though the model's projection |
| 16 | /// and selection are no longer observed. |
| 17 | @MainActor final class SurfaceChromeTests: XCTestCase { |
| 18 | private var model: DocsModel! |
| 19 | private var text: DocsTextView! |
| 20 | private var server: AccessServer! |
| 21 | |
| 22 | override func setUp() async throws { |
| 23 | DocsFonts.register() |
| 24 | server = AccessServer() |
| 25 | try await server.inner.seed(LoopFixture.everything) |
| 26 | let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| 27 | let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity, transport: { [server] in server }) |
| 28 | model = DocsModel(transport: { [server] in server }, connectivity: connectivity, offlineAccount: account) |
| 29 | text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 800)) |
| 30 | model.surface.attach(text) |
| 31 | await model.open("doc") |
| 32 | model.suspendLiveUpdates() |
| 33 | } |
| 34 | override func tearDown() async throws { await model?.stop(); model = nil; text = nil; server = nil } |
| 35 | |
| 36 | private func observes(_ read: () -> Void, after change: () async throws -> Void) async throws -> Bool { |
| 37 | let fired = Mutex(false) |
| 38 | withObservationTracking(read) { fired.withLock { $0 = true } } |
| 39 | try await change() |
| 40 | return fired.withLock { $0 } |
| 41 | } |
| 42 | private func until(_ what: String, _ condition: () -> Bool) async throws { |
| 43 | let deadline = ContinuousClock.now + .seconds(5) |
| 44 | while !condition() { |
| 45 | guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } |
| 46 | try await Task.sleep(for: .milliseconds(5)) |
| 47 | } |
| 48 | } |
| 49 | private func typeInTheMiddle(_ characters: String) { |
| 50 | let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) |
| 51 | Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text) |
| 52 | Keyboard.type(characters, in: text) |
| 53 | } |
| 54 | |
| 55 | /// The Format menu (DocsEditorCommands) is disabled from |
| 56 | /// `DocumentCommands.isEnabled`: a key makes it false and the queue |
| 57 | /// draining makes it true again, and each change reaches observation, |
| 58 | /// so the menu's enablement updates. |
| 59 | func testTheFormatMenusEnablementFollowsAnEdit() async throws { |
| 60 | let commands = { [unowned self] in DocumentCommands(model: model, content: model.surface.content) } |
| 61 | XCTAssertTrue(commands().isEnabled) |
| 62 | let disabled = try await observes({ _ = commands().isEnabled }) { typeInTheMiddle("x") } |
| 63 | XCTAssertTrue(disabled, "a key re-evaluates the menu") |
| 64 | XCTAssertFalse(commands().isEnabled, "disabled while input is pending") |
| 65 | let enabled = try await observes({ _ = commands().isEnabled }) { try await until("the queue drained") { !model.hasPendingInput } } |
| 66 | XCTAssertTrue(enabled, "the queue draining re-evaluates the menu") |
| 67 | try await until("enabled again") { commands().isEnabled } |
| 68 | } |
| 69 | |
| 70 | /// A toolbar, inspector or menu command clicked while a key is still |
| 71 | /// pending is not dropped (Fable on #173, note 4): it runs once the key |
| 72 | /// has been drawn. Before, the panel's controls took the click and the |
| 73 | /// command refused it silently. |
| 74 | func testACommandClickedWhileInputIsPendingRunsOnceTheInputIsDrawn() async throws { |
| 75 | typeInTheMiddle("x") |
| 76 | XCTAssertTrue(model.hasPendingInput) |
| 77 | model.whenCommandsReady { $0.perform("bold") } |
| 78 | XCTAssertNil(model.typingMarks?["strong"], "not while the key is pending") |
| 79 | try await until("the bold clicked meanwhile") { model.typingMarks?["strong"] != nil } |
| 80 | XCTAssertFalse(model.commandsHeld) |
| 81 | } |
| 82 | |
| 83 | /// Two commands in one wait both apply, in order (delta review 4). |
| 84 | func testCommandsQueuedInOneWaitRunInOrder() async throws { |
| 85 | typeInTheMiddle("x") |
| 86 | model.whenCommandsReady { $0.perform("bold") } |
| 87 | model.whenCommandsReady { $0.perform("italic") } |
| 88 | try await until("both") { model.typingMarks?["strong"] != nil && model.typingMarks?["em"] != nil } |
| 89 | } |
| 90 | |
| 91 | /// A queued command applies only to the selection it was chosen with: |
| 92 | /// the person moving the selection drops it (delta review 2). |
| 93 | func testMovingTheSelectionDropsAQueuedCommand() async throws { |
| 94 | typeInTheMiddle("x") |
| 95 | model.whenCommandsReady { $0.perform("bold") } |
| 96 | Keyboard.select(NSRange(location: 3, length: 4), in: text) |
| 97 | try await until("the key drawn") { DocumentCommands(model: model, content: model.surface.content).isEnabled } |
| 98 | try await Task.sleep(for: .milliseconds(50)) |
| 99 | XCTAssertNil(model.typingMarks?["strong"]) |
| 100 | XCTAssertFalse(DocumentCommands(model: model, content: model.surface.content).hasMark("strong"), "the selection moved to is not made bold") |
| 101 | } |
| 102 | |
| 103 | /// Held longer than a glance by anything but a composition, commands |
| 104 | /// show disabled and what was queued is dropped: grey means the click |
| 105 | /// did not take (delta review 1). A key's own wait never greys. |
| 106 | func testALongHoldGreysOutAndDropsTheQueue() async throws { |
| 107 | typeInTheMiddle("y") |
| 108 | try await until("the key drawn") { DocumentCommands(model: model, content: model.surface.content).isEnabled } |
| 109 | try await Task.sleep(for: .milliseconds(100)) |
| 110 | XCTAssertFalse(model.commandsHeld, "a key's pending input never greys") |
| 111 | let after = DocsModel.commandsHeldAfter |
| 112 | DocsModel.commandsHeldAfter = .milliseconds(30) |
| 113 | defer { DocsModel.commandsHeldAfter = after } |
| 114 | // A generation that has not caught up: held, not composing. |
| 115 | let rendered = model.renderedGeneration |
| 116 | model.renderedGeneration = rendered &+ 1000 |
| 117 | model.whenCommandsReady { $0.perform("bold") } |
| 118 | try await until("held commands show disabled") { model.commandsHeld } |
| 119 | model.whenCommandsReady { $0.perform("italic") } |
| 120 | model.renderedGeneration = rendered |
| 121 | model.refreshToolbarSelection() |
| 122 | XCTAssertFalse(model.commandsHeld) |
| 123 | XCTAssertNil(model.typingMarks?["strong"], "dropped when the controls went grey") |
| 124 | XCTAssertNil(model.typingMarks?["em"], "not queued while grey") |
| 125 | } |
| 126 | |
| 127 | /// A composition never greys the controls, however long (CJK writers |
| 128 | /// compose constantly; ruling on #173): a command chosen meanwhile runs |
| 129 | /// right after the commit. |
| 130 | func testACompositionNeverGreysAndItsCommandRunsAfterTheCommit() async throws { |
| 131 | let after = DocsModel.commandsHeldAfter |
| 132 | DocsModel.commandsHeldAfter = .milliseconds(30) |
| 133 | defer { DocsModel.commandsHeldAfter = after } |
| 134 | model.compositionChanged(true) |
| 135 | model.whenCommandsReady { $0.perform("bold") } |
| 136 | try await Task.sleep(for: .milliseconds(150)) |
| 137 | XCTAssertFalse(model.commandsHeld, "a composition never greys") |
| 138 | XCTAssertNil(model.typingMarks?["strong"]) |
| 139 | model.compositionChanged(false) |
| 140 | try await until("the bold chosen while composing") { model.typingMarks?["strong"] != nil } |
| 141 | } |
| 142 | |
| 143 | /// ⌘B typed straight after a letter, through the text view's own key |
| 144 | /// equivalent (DocsTextView.performKeyEquivalent → DocsModel.perform), |
| 145 | /// applies once the letter is drawn (delta review 3); it was dropped. |
| 146 | func testBoldTypedRightAfterALetterApplies() async throws { |
| 147 | typeInTheMiddle("x") |
| 148 | XCTAssertTrue(model.hasPendingInput) |
| 149 | let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0, windowNumber: 0, |
| 150 | context: nil, characters: "b", charactersIgnoringModifiers: "b", isARepeat: false, keyCode: 11)) |
| 151 | XCTAssertTrue(text.performKeyEquivalent(with: event)) |
| 152 | try await until("the bold typed behind the letter") { model.typingMarks?["strong"] != nil } |
| 153 | } |
| 154 | |
| 155 | /// Undo and redo read the observed history, set with each publication: |
| 156 | /// it is current while input is still pending (the toolbar selection |
| 157 | /// keeps its last state then), and for a reader, whose toolbar |
| 158 | /// selection is never computed. |
| 159 | func testHistoryIsCurrentWhileInputIsPendingAndForAReader() async throws { |
| 160 | XCTAssertFalse(model.history.canUndo) |
| 161 | var pendingAtPublication: Bool?, historyAtPublication: Bool? |
| 162 | model.surface.willApply = { [unowned self] _ in |
| 163 | if pendingAtPublication == nil { pendingAtPublication = model.hasPendingInput; historyAtPublication = model.history.canUndo } |
| 164 | } |
| 165 | typeInTheMiddle("y") |
| 166 | try await until("the queue drained") { !model.hasPendingInput } |
| 167 | XCTAssertEqual(pendingAtPublication, true, "the publication arrived with input pending") |
| 168 | XCTAssertEqual(historyAtPublication, true, "and the history was already current") |
| 169 | |
| 170 | // A reader: access drops to read-only; a peer's edit still moves the history. |
| 171 | await server.answer(200, canWrite: false) |
| 172 | await model.revalidateAccess() |
| 173 | XCTAssertEqual(model.documentAccess, .readOnly) |
| 174 | XCTAssertNil(DocumentToolbarSelection(commands: DocumentCommands(model: model, content: model.surface.content)), "no toolbar selection for a reader") |
| 175 | XCTAssertTrue(model.history.loaded) |
| 176 | XCTAssertTrue(model.history.canUndo, "the reader's history is the projection's") |
| 177 | } |
| 178 | |
| 179 | /// The toolbar and the inspector show `toolbarSelection`: once input |
| 180 | /// settles it must equal one computed afresh from the live text at the |
| 181 | /// selection (Fable on #170, final check, finding 1). |
| 182 | private var fresh: DocumentToolbarSelection? { DocumentToolbarSelection(commands: DocumentCommands(model: model, content: model.surface.content)) } |
| 183 | private func settle() async throws { |
| 184 | try await until("the queue drained and drawn") { !model.hasPendingInput && model.surface.newest.map { $0.revision == model.surface.appliedRevision } ?? false } |
| 185 | try await Task.sleep(for: .milliseconds(20)) |
| 186 | } |
| 187 | |
| 188 | /// Return at the end of a heading: the caret is in a new paragraph. |
| 189 | func testTheToolbarFollowsReturnAtTheEndOfAHeading() async throws { |
| 190 | let heading = (model.surface.content.string as NSString).range(of: "Lists, an image and a rule") |
| 191 | Keyboard.select(NSRange(location: NSMaxRange(heading), length: 0), in: text) |
| 192 | try await settle() |
| 193 | XCTAssertEqual(model.toolbarSelection.style, "heading1") |
| 194 | Keyboard.type("\n", in: text) |
| 195 | try await settle() |
| 196 | let now = try XCTUnwrap(fresh) |
| 197 | XCTAssertEqual(now.style, "paragraph") |
| 198 | XCTAssertEqual(model.toolbarSelection, now, "the toolbar shows the new paragraph's style") |
| 199 | } |
| 200 | |
| 201 | /// Typing over a selection: nothing is selected afterwards, so Clear |
| 202 | /// formatting is disabled. |
| 203 | func testTheToolbarFollowsTypingOverASelection() async throws { |
| 204 | let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) |
| 205 | Keyboard.select(NSRange(location: line.location, length: 8), in: text) |
| 206 | try await settle() |
| 207 | XCTAssertTrue(model.toolbarSelection.hasSelection) |
| 208 | Keyboard.type("q", in: text) |
| 209 | try await settle() |
| 210 | let now = try XCTUnwrap(fresh) |
| 211 | XCTAssertFalse(now.hasSelection) |
| 212 | XCTAssertEqual(model.toolbarSelection, now, "nothing selected after typing over it") |
| 213 | } |
| 214 | |
| 215 | /// The caret moves while input is paused (a 401), then the re-minted |
| 216 | /// session's 200 resumes it: the toolbar shows where the caret is now. |
| 217 | func testTheToolbarFollowsTheCaretMovedWhileInputWasPaused() async throws { |
| 218 | let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) |
| 219 | Keyboard.select(NSRange(location: line.location + 2, length: 0), in: text) |
| 220 | try await settle() |
| 221 | XCTAssertEqual(model.toolbarSelection.style, "paragraph") |
| 222 | await server.answer(401) |
| 223 | await model.revalidateAccess() |
| 224 | XCTAssertTrue(model.inputBlocked) |
| 225 | let heading = (model.surface.content.string as NSString).range(of: "Lists, an image and a rule") |
| 226 | Keyboard.select(NSRange(location: heading.location + 2, length: 0), in: text) |
| 227 | await server.answer(200) |
| 228 | await model.revalidateAccess() |
| 229 | XCTAssertFalse(model.inputBlocked) |
| 230 | try await settle() |
| 231 | let now = try XCTUnwrap(fresh) |
| 232 | XCTAssertEqual(now.style, "heading1") |
| 233 | XCTAssertEqual(model.toolbarSelection, now, "the toolbar shows the heading the caret moved into") |
| 234 | } |
| 235 | |
| 236 | /// A reader given write access again can type again: the pause the |
| 237 | /// read-only answer set is lifted by the writable one (Fable on #170, |
| 238 | /// final check, note 4; before S1a too). |
| 239 | func testAReaderGivenWriteAccessAgainCanType() async throws { |
| 240 | await server.answer(200, canWrite: false) |
| 241 | await model.revalidateAccess() |
| 242 | XCTAssertEqual(model.documentAccess, .readOnly) |
| 243 | XCTAssertFalse(text.isEditable) |
| 244 | await server.answer(200, canWrite: true) |
| 245 | await model.revalidateAccess() |
| 246 | XCTAssertEqual(model.documentAccess, .writable) |
| 247 | XCTAssertFalse(model.inputBlocked, "the reader's pause is lifted") |
| 248 | XCTAssertTrue(text.isEditable, "the text view takes typing again") |
| 249 | } |
| 250 | |
| 251 | #if DOCS_PROBES |
| 252 | /// The live word count recounts after a draw without rendering the |
| 253 | /// document: it reads the projection's text and the text view's storage. |
| 254 | func testTheLiveWordCountDoesNoWholeRender() async throws { |
| 255 | try await Task.sleep(for: .milliseconds(20)) |
| 256 | let sheet = DocsLiveWordCountSheet(model: model) {} |
| 257 | DocsProbes.reset() |
| 258 | let followed = try await observes({ _ = sheet.body }) { |
| 259 | typeInTheMiddle("z") |
| 260 | try await until("the queue drained") { !model.hasPendingInput } |
| 261 | try await Task.sleep(for: .milliseconds(20)) |
| 262 | } |
| 263 | XCTAssertTrue(followed, "the sheet recounts after the draw") |
| 264 | _ = sheet.body |
| 265 | XCTAssertEqual(DocsProbes.wholeRenders, 0, "no whole render for the count") |
| 266 | } |
| 267 | #endif |
| 268 | } |
| 269 | #endif |
| 270 | |