#if os(macOS) import AppKit import Foundation import Observation import RastrilloApple import RastrilloNative import RastrilloTestSupport import Synchronization import SwiftUI import XCTest @testable import DocsKit /// S2a's chrome over S1a's surface (Fable on #170, findings 4 and 5): what /// the Format menu, the toolbar, the pill and the live word count read /// must follow an edit through observation, though the model's projection /// and selection are no longer observed. @MainActor final class SurfaceChromeTests: XCTestCase { private var model: DocsModel! private var text: DocsTextView! private var server: AccessServer! override func setUp() async throws { DocsFonts.register() server = AccessServer() try await server.inner.seed(LoopFixture.everything) let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity, transport: { [server] in server }) model = DocsModel(transport: { [server] in server }, connectivity: connectivity, offlineAccount: account) 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 func observes(_ read: () -> Void, after change: () async throws -> Void) async throws -> Bool { let fired = Mutex(false) withObservationTracking(read) { fired.withLock { $0 = true } } try await change() return fired.withLock { $0 } } 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(5)) } } private func typeInTheMiddle(_ characters: String) { let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text) Keyboard.type(characters, in: text) } /// The Format menu (DocsEditorCommands) is disabled from /// `DocumentCommands.isEnabled`: a key makes it false and the queue /// draining makes it true again, and each change reaches observation, /// so the menu's enablement updates. func testTheFormatMenusEnablementFollowsAnEdit() async throws { let commands = { [unowned self] in DocumentCommands(model: model, content: model.surface.content) } XCTAssertTrue(commands().isEnabled) let disabled = try await observes({ _ = commands().isEnabled }) { typeInTheMiddle("x") } XCTAssertTrue(disabled, "a key re-evaluates the menu") XCTAssertFalse(commands().isEnabled, "disabled while input is pending") let enabled = try await observes({ _ = commands().isEnabled }) { try await until("the queue drained") { !model.hasPendingInput } } XCTAssertTrue(enabled, "the queue draining re-evaluates the menu") try await until("enabled again") { commands().isEnabled } } /// A toolbar, inspector or menu command clicked while a key is still /// pending is not dropped (Fable on #173, note 4): it runs once the key /// has been drawn. Before, the panel's controls took the click and the /// command refused it silently. func testACommandClickedWhileInputIsPendingRunsOnceTheInputIsDrawn() async throws { typeInTheMiddle("x") XCTAssertTrue(model.hasPendingInput) model.whenCommandsReady { $0.perform("bold") } XCTAssertNil(model.typingMarks?["strong"], "not while the key is pending") try await until("the bold clicked meanwhile") { model.typingMarks?["strong"] != nil } XCTAssertFalse(model.commandsHeld) } /// Two commands in one wait both apply, in order (delta review 4). func testCommandsQueuedInOneWaitRunInOrder() async throws { typeInTheMiddle("x") model.whenCommandsReady { $0.perform("bold") } model.whenCommandsReady { $0.perform("italic") } try await until("both") { model.typingMarks?["strong"] != nil && model.typingMarks?["em"] != nil } } /// A queued command applies only to the selection it was chosen with: /// the person moving the selection drops it (delta review 2). func testMovingTheSelectionDropsAQueuedCommand() async throws { typeInTheMiddle("x") model.whenCommandsReady { $0.perform("bold") } Keyboard.select(NSRange(location: 3, length: 4), in: text) try await until("the key drawn") { DocumentCommands(model: model, content: model.surface.content).isEnabled } try await Task.sleep(for: .milliseconds(50)) XCTAssertNil(model.typingMarks?["strong"]) XCTAssertFalse(DocumentCommands(model: model, content: model.surface.content).hasMark("strong"), "the selection moved to is not made bold") } /// Held longer than a glance by anything but a composition, commands /// show disabled and what was queued is dropped: grey means the click /// did not take (delta review 1). A key's own wait never greys. func testALongHoldGreysOutAndDropsTheQueue() async throws { typeInTheMiddle("y") try await until("the key drawn") { DocumentCommands(model: model, content: model.surface.content).isEnabled } try await Task.sleep(for: .milliseconds(100)) XCTAssertFalse(model.commandsHeld, "a key's pending input never greys") let after = DocsModel.commandsHeldAfter DocsModel.commandsHeldAfter = .milliseconds(30) defer { DocsModel.commandsHeldAfter = after } // A generation that has not caught up: held, not composing. let rendered = model.renderedGeneration model.renderedGeneration = rendered &+ 1000 model.whenCommandsReady { $0.perform("bold") } try await until("held commands show disabled") { model.commandsHeld } model.whenCommandsReady { $0.perform("italic") } model.renderedGeneration = rendered model.refreshToolbarSelection() XCTAssertFalse(model.commandsHeld) XCTAssertNil(model.typingMarks?["strong"], "dropped when the controls went grey") XCTAssertNil(model.typingMarks?["em"], "not queued while grey") } /// A composition never greys the controls, however long (CJK writers /// compose constantly; ruling on #173): a command chosen meanwhile runs /// right after the commit. func testACompositionNeverGreysAndItsCommandRunsAfterTheCommit() async throws { let after = DocsModel.commandsHeldAfter DocsModel.commandsHeldAfter = .milliseconds(30) defer { DocsModel.commandsHeldAfter = after } model.compositionChanged(true) model.whenCommandsReady { $0.perform("bold") } try await Task.sleep(for: .milliseconds(150)) XCTAssertFalse(model.commandsHeld, "a composition never greys") XCTAssertNil(model.typingMarks?["strong"]) model.compositionChanged(false) try await until("the bold chosen while composing") { model.typingMarks?["strong"] != nil } } /// ⌘B typed straight after a letter, through the text view's own key /// equivalent (DocsTextView.performKeyEquivalent → DocsModel.perform), /// applies once the letter is drawn (delta review 3); it was dropped. func testBoldTypedRightAfterALetterApplies() async throws { typeInTheMiddle("x") XCTAssertTrue(model.hasPendingInput) let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0, windowNumber: 0, context: nil, characters: "b", charactersIgnoringModifiers: "b", isARepeat: false, keyCode: 11)) XCTAssertTrue(text.performKeyEquivalent(with: event)) try await until("the bold typed behind the letter") { model.typingMarks?["strong"] != nil } } /// Undo and redo read the observed history, set with each publication: /// it is current while input is still pending (the toolbar selection /// keeps its last state then), and for a reader, whose toolbar /// selection is never computed. func testHistoryIsCurrentWhileInputIsPendingAndForAReader() async throws { XCTAssertFalse(model.history.canUndo) var pendingAtPublication: Bool?, historyAtPublication: Bool? model.surface.willApply = { [unowned self] _ in if pendingAtPublication == nil { pendingAtPublication = model.hasPendingInput; historyAtPublication = model.history.canUndo } } typeInTheMiddle("y") try await until("the queue drained") { !model.hasPendingInput } XCTAssertEqual(pendingAtPublication, true, "the publication arrived with input pending") XCTAssertEqual(historyAtPublication, true, "and the history was already current") // A reader: access drops to read-only; a peer's edit still moves the history. await server.answer(200, canWrite: false) await model.revalidateAccess() XCTAssertEqual(model.documentAccess, .readOnly) XCTAssertNil(DocumentToolbarSelection(commands: DocumentCommands(model: model, content: model.surface.content)), "no toolbar selection for a reader") XCTAssertTrue(model.history.loaded) XCTAssertTrue(model.history.canUndo, "the reader's history is the projection's") } /// The toolbar and the inspector show `toolbarSelection`: once input /// settles it must equal one computed afresh from the live text at the /// selection (Fable on #170, final check, finding 1). private var fresh: DocumentToolbarSelection? { DocumentToolbarSelection(commands: DocumentCommands(model: model, content: model.surface.content)) } private func settle() async throws { try await until("the queue drained and drawn") { !model.hasPendingInput && model.surface.newest.map { $0.revision == model.surface.appliedRevision } ?? false } try await Task.sleep(for: .milliseconds(20)) } /// Return at the end of a heading: the caret is in a new paragraph. func testTheToolbarFollowsReturnAtTheEndOfAHeading() async throws { let heading = (model.surface.content.string as NSString).range(of: "Lists, an image and a rule") Keyboard.select(NSRange(location: NSMaxRange(heading), length: 0), in: text) try await settle() XCTAssertEqual(model.toolbarSelection.style, "heading1") Keyboard.type("\n", in: text) try await settle() let now = try XCTUnwrap(fresh) XCTAssertEqual(now.style, "paragraph") XCTAssertEqual(model.toolbarSelection, now, "the toolbar shows the new paragraph's style") } /// Typing over a selection: nothing is selected afterwards, so Clear /// formatting is disabled. func testTheToolbarFollowsTypingOverASelection() async throws { let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) Keyboard.select(NSRange(location: line.location, length: 8), in: text) try await settle() XCTAssertTrue(model.toolbarSelection.hasSelection) Keyboard.type("q", in: text) try await settle() let now = try XCTUnwrap(fresh) XCTAssertFalse(now.hasSelection) XCTAssertEqual(model.toolbarSelection, now, "nothing selected after typing over it") } /// The caret moves while input is paused (a 401), then the re-minted /// session's 200 resumes it: the toolbar shows where the caret is now. func testTheToolbarFollowsTheCaretMovedWhileInputWasPaused() async throws { let line = (model.surface.content.string as NSString).range(of: LoopFixture.middle) Keyboard.select(NSRange(location: line.location + 2, length: 0), in: text) try await settle() XCTAssertEqual(model.toolbarSelection.style, "paragraph") await server.answer(401) await model.revalidateAccess() XCTAssertTrue(model.inputBlocked) let heading = (model.surface.content.string as NSString).range(of: "Lists, an image and a rule") Keyboard.select(NSRange(location: heading.location + 2, length: 0), in: text) await server.answer(200) await model.revalidateAccess() XCTAssertFalse(model.inputBlocked) try await settle() let now = try XCTUnwrap(fresh) XCTAssertEqual(now.style, "heading1") XCTAssertEqual(model.toolbarSelection, now, "the toolbar shows the heading the caret moved into") } /// A reader given write access again can type again: the pause the /// read-only answer set is lifted by the writable one (Fable on #170, /// final check, note 4; before S1a too). func testAReaderGivenWriteAccessAgainCanType() async throws { await server.answer(200, canWrite: false) await model.revalidateAccess() XCTAssertEqual(model.documentAccess, .readOnly) XCTAssertFalse(text.isEditable) await server.answer(200, canWrite: true) await model.revalidateAccess() XCTAssertEqual(model.documentAccess, .writable) XCTAssertFalse(model.inputBlocked, "the reader's pause is lifted") XCTAssertTrue(text.isEditable, "the text view takes typing again") } #if DOCS_PROBES /// The live word count recounts after a draw without rendering the /// document: it reads the projection's text and the text view's storage. func testTheLiveWordCountDoesNoWholeRender() async throws { try await Task.sleep(for: .milliseconds(20)) let sheet = DocsLiveWordCountSheet(model: model) {} DocsProbes.reset() let followed = try await observes({ _ = sheet.body }) { typeInTheMiddle("z") try await until("the queue drained") { !model.hasPendingInput } try await Task.sleep(for: .milliseconds(20)) } XCTAssertTrue(followed, "the sheet recounts after the draw") _ = sheet.body XCTAssertEqual(DocsProbes.wholeRenders, 0, "no whole render for the count") } #endif } #endif