| 1 | @testable import BaseKit |
| 2 | import SwiftUI |
| 3 | import XCTest |
| 4 | |
| 5 | /// Paul's bug in Base Mac 0.1.0: Shift Return sent the message. Return |
| 6 | /// sends; Shift and Option Return are a new line at the cursor; an input |
| 7 | /// method's Return is its own. |
| 8 | final class ComposerReturnTests: XCTestCase { |
| 9 | func testWhatReturnDoes() { |
| 10 | XCTAssertEqual(ComposerReturn.action([], composing: false), .send) |
| 11 | XCTAssertEqual(ComposerReturn.action(.shift, composing: false), .newline) |
| 12 | XCTAssertEqual(ComposerReturn.action(.option, composing: false), .newline) |
| 13 | XCTAssertEqual(ComposerReturn.action([.shift, .option], composing: false), .newline) |
| 14 | XCTAssertEqual(ComposerReturn.action(.command, composing: false), .send) |
| 15 | for modifiers: EventModifiers in [[], .shift, .option, .command] { |
| 16 | XCTAssertEqual(ComposerReturn.action(modifiers, composing: true), .pass, "an input method's Return finishes its word") |
| 17 | } |
| 18 | XCTAssertTrue(ComposerReturn.keys.contains(.return)) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | #if os(macOS) |
| 23 | import AppKit |
| 24 | |
| 25 | /// The real composer in a real window, driven by key events as the |
| 26 | /// keyboard sends them. |
| 27 | @MainActor final class ComposerKeyTests: XCTestCase { |
| 28 | private var window: NSWindow! |
| 29 | private var model: AskModel! |
| 30 | private var transport: GatedTransport! |
| 31 | |
| 32 | override func setUp() { |
| 33 | _ = NSApplication.shared |
| 34 | transport = GatedTransport() |
| 35 | model = AskModel(client: BaseClient(transport: transport) {}, schedule: { _, _ in }) |
| 36 | window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 420, height: 300), styleMask: [.titled], backing: .buffered, defer: false) |
| 37 | window.isReleasedWhenClosed = false |
| 38 | window.contentView = NSHostingView(rootView: FocusedComposer(model: model).frame(width: 420)) |
| 39 | window.makeKeyAndOrderFront(nil) |
| 40 | for _ in 0..<40 where editor == nil { RunLoop.main.run(until: Date().addingTimeInterval(0.05)) } |
| 41 | XCTAssertNotNil(editor, "the composer never took the keyboard") |
| 42 | } |
| 43 | |
| 44 | override func tearDown() { window.close() } |
| 45 | |
| 46 | private var editor: NSTextView? { window.firstResponder as? NSTextView } |
| 47 | |
| 48 | private func type(_ text: String, cursor: Int? = nil, selecting length: Int = 0) throws { |
| 49 | let editor = try XCTUnwrap(editor) |
| 50 | editor.insertText(text, replacementRange: NSRange(location: 0, length: (editor.string as NSString).length)) |
| 51 | editor.setSelectedRange(NSRange(location: cursor ?? (text as NSString).length, length: length)) |
| 52 | settle() |
| 53 | XCTAssertEqual(model.text, text) |
| 54 | } |
| 55 | |
| 56 | private func press(_ modifiers: NSEvent.ModifierFlags = [], keyCode: UInt16 = 36, characters: String = "\r") throws { |
| 57 | let event = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: modifiers, timestamp: 0, |
| 58 | windowNumber: window.windowNumber, context: nil, characters: characters, |
| 59 | charactersIgnoringModifiers: characters, isARepeat: false, keyCode: keyCode)) |
| 60 | window.sendEvent(event) |
| 61 | settle() |
| 62 | } |
| 63 | |
| 64 | private func settle() { RunLoop.main.run(until: Date().addingTimeInterval(0.15)) } |
| 65 | private var sent: Bool { !transport.calls.isEmpty } |
| 66 | |
| 67 | func testReturnSends() throws { |
| 68 | try type("What's on tomorrow?") |
| 69 | try press() |
| 70 | XCTAssertTrue(sent, "Return sends") |
| 71 | } |
| 72 | |
| 73 | func testKeypadEnterSends() throws { |
| 74 | try type("What's on tomorrow?") |
| 75 | try press(.numericPad, keyCode: 76, characters: "\u{3}") |
| 76 | XCTAssertTrue(sent, "the keypad's Enter sends") |
| 77 | } |
| 78 | |
| 79 | func testShiftReturnIsANewLineAtTheEnd() throws { |
| 80 | try type("Three things") |
| 81 | try press(.shift) |
| 82 | XCTAssertFalse(sent, "Shift Return sent the message") |
| 83 | XCTAssertEqual(model.text, "Three things\n") |
| 84 | XCTAssertEqual(editor?.selectedRange(), NSRange(location: 13, length: 0)) |
| 85 | } |
| 86 | |
| 87 | func testShiftReturnIsANewLineAtTheCursor() throws { |
| 88 | try type("Flour delivery", cursor: 5) |
| 89 | try press(.shift) |
| 90 | XCTAssertFalse(sent) |
| 91 | XCTAssertEqual(model.text, "Flour\n delivery") |
| 92 | XCTAssertEqual(editor?.selectedRange(), NSRange(location: 6, length: 0), "the cursor follows the new line") |
| 93 | // And typing goes on from there. |
| 94 | editor?.insertText("x", replacementRange: editor!.selectedRange()) |
| 95 | settle() |
| 96 | XCTAssertEqual(model.text, "Flour\nx delivery") |
| 97 | } |
| 98 | |
| 99 | func testShiftReturnReplacesTheSelection() throws { |
| 100 | try type("Flour, then Ana", cursor: 5, selecting: 7) |
| 101 | try press(.shift) |
| 102 | XCTAssertFalse(sent) |
| 103 | XCTAssertEqual(model.text, "Flour\nAna") |
| 104 | } |
| 105 | |
| 106 | func testOptionReturnIsANewLine() throws { |
| 107 | try type("Flour delivery", cursor: 5) |
| 108 | try press(.option) |
| 109 | XCTAssertFalse(sent, "Option Return sent the message") |
| 110 | XCTAssertEqual(model.text, "Flour\n delivery") |
| 111 | } |
| 112 | |
| 113 | /// Return while an input method composes (marked text) finishes the |
| 114 | /// word; nothing is sent until the next Return. |
| 115 | func testReturnWhileComposingDoesNotSend() throws { |
| 116 | try type("Tomorrow ") |
| 117 | let editor = try XCTUnwrap(editor) |
| 118 | editor.setMarkedText("あした", selectedRange: NSRange(location: 3, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) |
| 119 | XCTAssertTrue(editor.hasMarkedText()) |
| 120 | try press() |
| 121 | XCTAssertFalse(sent, "Return while composing sent the message") |
| 122 | XCTAssertFalse(editor.hasMarkedText(), "the composition is finished") |
| 123 | XCTAssertTrue(model.text.hasPrefix("Tomorrow あした"), model.text) |
| 124 | try press() |
| 125 | XCTAssertTrue(sent, "the next Return sends") |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | extension ComposerKeyTests { |
| 130 | /// The menu's Paste (or Paste and Match Style) as AppKit sends it: |
| 131 | /// the item's will- and did-send around the field reading `board`. |
| 132 | private func paste(from board: NSPasteboard, action: Selector = #selector(NSText.paste(_:))) throws { |
| 133 | let editor = try XCTUnwrap(editor) |
| 134 | let item = NSMenuItem(title: "Paste", action: action, keyEquivalent: "v") |
| 135 | let menu = NSMenu(title: "Edit") |
| 136 | menu.addItem(item) |
| 137 | NotificationCenter.default.post(name: NSMenu.willSendActionNotification, object: menu, userInfo: ["MenuItem": item]) |
| 138 | XCTAssertTrue(editor.readSelection(from: board)) |
| 139 | NotificationCenter.default.post(name: NSMenu.didSendActionNotification, object: menu, userInfo: ["MenuItem": item]) |
| 140 | settle() |
| 141 | } |
| 142 | |
| 143 | private func richBoard() -> NSPasteboard { |
| 144 | let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) |
| 145 | board.clearContents() |
| 146 | board.setString("<p>The <b>flour</b> comes <i>Thursday</i>:</p><ul><li>Rye</li><li><a href=\"https://fennel.example/order\">The order</a></li></ul>", forType: .html) |
| 147 | board.setString("The flour comes Thursday:\nRye\nThe order", forType: .string) |
| 148 | return board |
| 149 | } |
| 150 | |
| 151 | /// A rich paste comes in as Markdown at the cursor (2026-11-26), and |
| 152 | /// one Undo takes it all back, in the model too (S1); a plain one is |
| 153 | /// pasted as it is. A pasteboard of the test's own, never the person's. |
| 154 | func testARichPasteIsMarkdown() throws { |
| 155 | let board = richBoard() |
| 156 | defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| 157 | ComposerInput.pasteboard = board |
| 158 | try type("Note: ") |
| 159 | try paste(from: board) |
| 160 | XCTAssertEqual(model.text, "Note: The **flour** comes *Thursday*:\n\n- Rye\n- [The order](https://fennel.example/order)") |
| 161 | XCTAssertEqual(editor?.selectedRange().location, (model.text as NSString).length, "the cursor after the paste") |
| 162 | XCTAssertFalse(sent) |
| 163 | editor?.undoManager?.undo() |
| 164 | settle() |
| 165 | XCTAssertEqual(model.text, "Note: ", "one Undo takes the paste back") |
| 166 | editor?.undoManager?.redo() |
| 167 | settle() |
| 168 | XCTAssertTrue(model.text.contains("**flour**"), "and Redo brings it back") |
| 169 | editor?.undoManager?.undo() |
| 170 | settle() |
| 171 | try press() |
| 172 | XCTAssertEqual(sentText, "Note:", "Return after Undo sends what the field shows") |
| 173 | } |
| 174 | |
| 175 | func testAPlainPasteIsAsCopied() throws { |
| 176 | let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)")) |
| 177 | defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| 178 | ComposerInput.pasteboard = board |
| 179 | board.clearContents() |
| 180 | board.setString("plain *as* copied", forType: .string) |
| 181 | try type("Note: ") |
| 182 | try paste(from: board) |
| 183 | XCTAssertEqual(model.text, "Note: plain *as* copied") |
| 184 | } |
| 185 | |
| 186 | /// Fable's N1: Paste and Match Style, and an insert that is no Paste |
| 187 | /// (dictation, a drop, an input method's word) of the very same text, |
| 188 | /// stay as they are. |
| 189 | func testOnlyPasteIsConverted() throws { |
| 190 | let board = richBoard() |
| 191 | defer { board.releaseGlobally(); ComposerInput.pasteboard = .general } |
| 192 | ComposerInput.pasteboard = board |
| 193 | try type("") |
| 194 | try paste(from: board, action: #selector(NSTextView.pasteAsPlainText(_:))) |
| 195 | XCTAssertEqual(model.text, "The flour comes Thursday:\nRye\nThe order", "Paste and Match Style") |
| 196 | let editor = try XCTUnwrap(editor) |
| 197 | editor.insertText("\nThe flour comes Thursday:\nRye\nThe order", replacementRange: editor.selectedRange()) |
| 198 | settle() |
| 199 | XCTAssertFalse(model.text.contains("**"), model.text) |
| 200 | } |
| 201 | |
| 202 | /// The Paste key is the Edit menu's: it sends the item's will-send, |
| 203 | /// which is what lets a paste be told from other inserts. |
| 204 | func testThePasteKeyIsTheMenus() throws { |
| 205 | final class Target: NSObject { var pasted = false; @objc func paste(_ sender: Any?) { pasted = true } } |
| 206 | let target = Target() |
| 207 | let item = NSMenuItem(title: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v") |
| 208 | item.target = target |
| 209 | let menu = NSMenu(title: "Edit") |
| 210 | menu.addItem(item) |
| 211 | var told: Selector? |
| 212 | let watch = NotificationCenter.default.addObserver(forName: NSMenu.willSendActionNotification, object: menu, queue: nil) { note in |
| 213 | told = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action |
| 214 | } |
| 215 | defer { NotificationCenter.default.removeObserver(watch) } |
| 216 | let key = try XCTUnwrap(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: 0, windowNumber: window.windowNumber, |
| 217 | context: nil, characters: "v", charactersIgnoringModifiers: "v", isARepeat: false, keyCode: 9)) |
| 218 | XCTAssertTrue(menu.performKeyEquivalent(with: key)) |
| 219 | XCTAssertTrue(target.pasted) |
| 220 | XCTAssertEqual(told, #selector(NSText.paste(_:))) |
| 221 | } |
| 222 | |
| 223 | private var sentText: String? { |
| 224 | transport.bodies("/ask/messages").last.flatMap { $0 }.flatMap { URLComponents(string: "?" + String(decoding: $0, as: UTF8.self))?.queryItems?.first { $0.name == "text" }?.value } |
| 225 | } |
| 226 | |
| 227 | /// Fable's S1: Undo in a Mac field told the field and not the model, so |
| 228 | /// Return sent the text that had been taken back. |
| 229 | func testReturnSendsWhatUndoLeft() throws { |
| 230 | try type("Flour") |
| 231 | let editor = try XCTUnwrap(editor) |
| 232 | editor.breakUndoCoalescing() |
| 233 | editor.insertText(" delivery", replacementRange: editor.selectedRange()) |
| 234 | settle() |
| 235 | XCTAssertEqual(model.text, "Flour delivery") |
| 236 | editor.undoManager?.undo() |
| 237 | settle() |
| 238 | XCTAssertEqual(editor.string, "Flour") |
| 239 | XCTAssertEqual(model.text, "Flour", "Undo reaches the model") |
| 240 | editor.undoManager?.redo() |
| 241 | settle() |
| 242 | XCTAssertEqual(model.text, "Flour delivery", "and so does Redo") |
| 243 | editor.undoManager?.undo() |
| 244 | settle() |
| 245 | try press() |
| 246 | XCTAssertEqual(sentText, "Flour", "Return sends what the field shows") |
| 247 | } |
| 248 | |
| 249 | func testUndoingANewLineReachesTheModel() throws { |
| 250 | try type("Flour delivery", cursor: 5) |
| 251 | try press(.shift) |
| 252 | XCTAssertEqual(model.text, "Flour\n delivery") |
| 253 | editor?.undoManager?.undo() |
| 254 | settle() |
| 255 | XCTAssertEqual(model.text, "Flour delivery") |
| 256 | editor?.undoManager?.redo() |
| 257 | settle() |
| 258 | XCTAssertEqual(model.text, "Flour\n delivery") |
| 259 | XCTAssertFalse(sent) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | private struct FocusedComposer: View { |
| 264 | let model: AskModel |
| 265 | @FocusState private var focused: Bool |
| 266 | var body: some View { |
| 267 | Composer(model: model, focused: $focused).onAppear { focused = true } |
| 268 | } |
| 269 | } |
| 270 | #endif |
| 271 | |