@testable import BaseKit import SwiftUI import XCTest /// Paul's bug in Base Mac 0.1.0: Shift Return sent the message. Return /// sends; Shift and Option Return are a new line at the cursor; an input /// method's Return is its own. final class ComposerReturnTests: XCTestCase { func testWhatReturnDoes() { XCTAssertEqual(ComposerReturn.action([], composing: false), .send) XCTAssertEqual(ComposerReturn.action(.shift, composing: false), .newline) XCTAssertEqual(ComposerReturn.action(.option, composing: false), .newline) XCTAssertEqual(ComposerReturn.action([.shift, .option], composing: false), .newline) XCTAssertEqual(ComposerReturn.action(.command, composing: false), .send) for modifiers: EventModifiers in [[], .shift, .option, .command] { XCTAssertEqual(ComposerReturn.action(modifiers, composing: true), .pass, "an input method's Return finishes its word") } XCTAssertTrue(ComposerReturn.keys.contains(.return)) } } #if os(macOS) import AppKit /// The real composer in a real window, driven by key events as the /// keyboard sends them. @MainActor final class ComposerKeyTests: XCTestCase { private var window: NSWindow! private var model: AskModel! private var transport: GatedTransport! override func setUp() { _ = NSApplication.shared transport = GatedTransport() model = AskModel(client: BaseClient(transport: transport) {}, schedule: { _, _ in }) window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 420, height: 300), styleMask: [.titled], backing: .buffered, defer: false) window.isReleasedWhenClosed = false window.contentView = NSHostingView(rootView: FocusedComposer(model: model).frame(width: 420)) window.makeKeyAndOrderFront(nil) for _ in 0..<40 where editor == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.05)) } XCTAssertNotNil(editor, "the composer never took the keyboard") } override func tearDown() { window.close() } private var editor: NSTextView? { window.firstResponder as? NSTextView } private func type(_ text: String, cursor: Int? = nil, selecting length: Int = 0) throws { let editor = try XCTUnwrap(editor) editor.insertText(text, replacementRange: NSRange(location: 0, length: (editor.string as NSString).length)) editor.setSelectedRange(NSRange(location: cursor ?? (text as NSString).length, length: length)) settle() XCTAssertEqual(model.text, text) } private func press(_ modifiers: NSEvent.ModifierFlags = [], keyCode: UInt16 = 36, characters: String = "\r") throws { let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: modifiers, timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: keyCode)) window.sendEvent(event) settle() } private func settle() { RunLoop.main.run(until: Date().addingTimeInterval(0.15)) } private var sent: Bool { !transport.calls.isEmpty } func testReturnSends() throws { try type("What's on tomorrow?") try press() XCTAssertTrue(sent, "Return sends") } func testKeypadEnterSends() throws { try type("What's on tomorrow?") try press(.numericPad, keyCode: 76, characters: "\u{3}") XCTAssertTrue(sent, "the keypad's Enter sends") } func testShiftReturnIsANewLineAtTheEnd() throws { try type("Three things") try press(.shift) XCTAssertFalse(sent, "Shift Return sent the message") XCTAssertEqual(model.text, "Three things\n") XCTAssertEqual(editor?.selectedRange(), NSRange(location: 13, length: 0)) } func testShiftReturnIsANewLineAtTheCursor() throws { try type("Flour delivery", cursor: 5) try press(.shift) XCTAssertFalse(sent) XCTAssertEqual(model.text, "Flour\n delivery") XCTAssertEqual(editor?.selectedRange(), NSRange(location: 6, length: 0), "the cursor follows the new line") // And typing goes on from there. editor?.insertText("x", replacementRange: editor!.selectedRange()) settle() XCTAssertEqual(model.text, "Flour\nx delivery") } func testShiftReturnReplacesTheSelection() throws { try type("Flour, then Ana", cursor: 5, selecting: 7) try press(.shift) XCTAssertFalse(sent) XCTAssertEqual(model.text, "Flour\nAna") } func testOptionReturnIsANewLine() throws { try type("Flour delivery", cursor: 5) try press(.option) XCTAssertFalse(sent, "Option Return sent the message") XCTAssertEqual(model.text, "Flour\n delivery") } /// Return while an input method composes (marked text) finishes the /// word; nothing is sent until the next Return. func testReturnWhileComposingDoesNotSend() throws { try type("Tomorrow ") let editor = try XCTUnwrap(editor) editor.setMarkedText("あした", selectedRange: NSRange(location: 3, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) XCTAssertTrue(editor.hasMarkedText()) try press() XCTAssertFalse(sent, "Return while composing sent the message") XCTAssertFalse(editor.hasMarkedText(), "the composition is finished") XCTAssertTrue(model.text.hasPrefix("Tomorrow あした"), model.text) try press() XCTAssertTrue(sent, "the next Return sends") } } extension ComposerKeyTests { /// The menu's Paste (or Paste and Match Style) as AppKit sends it: /// the item's will- and did-send around the field reading `board`. private func paste(from board: NSPasteboard, action: Selector = #selector(NSText.paste(_:))) throws { let editor = try XCTUnwrap(editor) let item = NSMenuItem(title: "Paste", action: action, keyEquivalent: "v") let menu = NSMenu(title: "Edit") menu.addItem(item) NotificationCenter.default.post(name: NSMenu.willSendActionNotification, object: menu, userInfo: ["MenuItem": item]) XCTAssertTrue(editor.readSelection(from: board)) NotificationCenter.default.post(name: NSMenu.didSendActionNotification, object: menu, userInfo: ["MenuItem": item]) settle() } private func richBoard() -> NSPasteboard { let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) board.clearContents() board.setString("

The flour comes Thursday:

", forType: .html) board.setString("The flour comes Thursday:\nRye\nThe order", forType: .string) return board } /// A rich paste comes in as Markdown at the cursor (2026-11-26), and /// one Undo takes it all back, in the model too (S1); a plain one is /// pasted as it is. A pasteboard of the test's own, never the person's. func testARichPasteIsMarkdown() throws { let board = richBoard() defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } ComposerInput.pasteboard = board try type("Note: ") try paste(from: board) XCTAssertEqual(model.text, "Note: The **flour** comes *Thursday*:\n\n- Rye\n- [The order](https://fennel.example/order)") XCTAssertEqual(editor?.selectedRange().location, (model.text as NSString).length, "the cursor after the paste") XCTAssertFalse(sent) editor?.undoManager?.undo() settle() XCTAssertEqual(model.text, "Note: ", "one Undo takes the paste back") editor?.undoManager?.redo() settle() XCTAssertTrue(model.text.contains("**flour**"), "and Redo brings it back") editor?.undoManager?.undo() settle() try press() XCTAssertEqual(sentText, "Note:", "Return after Undo sends what the field shows") } func testAPlainPasteIsAsCopied() throws { let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } ComposerInput.pasteboard = board board.clearContents() board.setString("plain *as* copied", forType: .string) try type("Note: ") try paste(from: board) XCTAssertEqual(model.text, "Note: plain *as* copied") } /// Fable's N1: Paste and Match Style, and an insert that is no Paste /// (dictation, a drop, an input method's word) of the very same text, /// stay as they are. func testOnlyPasteIsConverted() throws { let board = richBoard() defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } ComposerInput.pasteboard = board try type("") try paste(from: board, action: #selector(NSTextView.pasteAsPlainText(_:))) XCTAssertEqual(model.text, "The flour comes Thursday:\nRye\nThe order", "Paste and Match Style") let editor = try XCTUnwrap(editor) editor.insertText("\nThe flour comes Thursday:\nRye\nThe order", replacementRange: editor.selectedRange()) settle() XCTAssertFalse(model.text.contains("**"), model.text) } /// The Paste key is the Edit menu's: it sends the item's will-send, /// which is what lets a paste be told from other inserts. func testThePasteKeyIsTheMenus() throws { final class Target: NSObject { var pasted = false; @objc func paste(_ sender: Any?) { pasted = true } } let target = Target() let item = NSMenuItem(title: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v") item.target = target let menu = NSMenu(title: "Edit") menu.addItem(item) var told: Selector? let watch = NotificationCenter.default.addObserver(forName: NSMenu.willSendActionNotification, object: menu, queue: nil) { note in told = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action } defer { NotificationCenter.default.removeObserver(watch) } let key = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: "v", charactersIgnoringModifiers: "v", isARepeat: false, keyCode: 9)) XCTAssertTrue(menu.performKeyEquivalent(with: key)) XCTAssertTrue(target.pasted) XCTAssertEqual(told, #selector(NSText.paste(_:))) } private var sentText: String? { transport.bodies("/ask/messages").last.flatMap { $0 }.flatMap { URLComponents(string: "?" + String(decoding: $0, as: UTF8.self))?.queryItems?.first { $0.name == "text" }?.value } } /// Fable's S1: Undo in a Mac field told the field and not the model, so /// Return sent the text that had been taken back. func testReturnSendsWhatUndoLeft() throws { try type("Flour") let editor = try XCTUnwrap(editor) editor.breakUndoCoalescing() editor.insertText(" delivery", replacementRange: editor.selectedRange()) settle() XCTAssertEqual(model.text, "Flour delivery") editor.undoManager?.undo() settle() XCTAssertEqual(editor.string, "Flour") XCTAssertEqual(model.text, "Flour", "Undo reaches the model") editor.undoManager?.redo() settle() XCTAssertEqual(model.text, "Flour delivery", "and so does Redo") editor.undoManager?.undo() settle() try press() XCTAssertEqual(sentText, "Flour", "Return sends what the field shows") } func testUndoingANewLineReachesTheModel() throws { try type("Flour delivery", cursor: 5) try press(.shift) XCTAssertEqual(model.text, "Flour\n delivery") editor?.undoManager?.undo() settle() XCTAssertEqual(model.text, "Flour delivery") editor?.undoManager?.redo() settle() XCTAssertEqual(model.text, "Flour\n delivery") XCTAssertFalse(sent) } } private struct FocusedComposer: View { let model: AskModel @FocusState private var focused: Bool var body: some View { Composer(model: model, focused: $focused).onAppear { focused = true } } } #endif