oficina / base Public

Merge fix/composer-shift-enter (Undo reaches the model) into feat/composer-markdown

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

Brings in Fable's S1 fix. ComposerInput is rewritten in the resolution to hold both branches: one start() (when the anchor is made, Fable's N3) watching Undo/Redo, text changes and the menus' Paste; the Mac paste swap now runs only inside a menu Paste (its key or a click), never for Paste and Match Style, typing, an input method's marked text, dictation or drops (Fable's N1), and picks HTML, else RTF, never both (N2). The paste tests drive the menu's notifications and assert the model after Undo.
claude agent, operated by paul@keymail.dev 41a646e500d7d4df94f8bcb9c62ec5318beed61f parent cbb2873parent d811be9
2 files changed, +177 −51
  • native/apple/Sources/BaseKit/Ask/Composer.swift +61 −32
  • native/apple/Tests/BaseKitTests/ComposerTests.swift +116 −19
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index c1eb285..5e6c107 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -38,7 +38,8 @@ public struct Composer: View {
.foregroundStyle(p[.frost])
.lineLimit(1...7)
.focused($focused)
- .background(ComposerAnchor(input: input).allowsHitTesting(false).accessibilityHidden(true))
+ .background(ComposerAnchor(input: input, model: model).allowsHitTesting(false).accessibilityHidden(true))
+ .onChange(of: focused, initial: true) { _, now in input.focused = now }
// A hardware keyboard's Return (and a Mac keypad's Enter), as
// the web's keydown. On a Mac a field's own Return always
// submits, Shift or not, so the field never sees one of these.
@@ -49,8 +50,6 @@ public struct Composer: View {
case .pass: return .ignored
}
}
- // A rich paste comes in as Markdown (ComposerInput.richPaste).
- .onChange(of: focused, initial: true) { _, now in input.focused = now }
#if os(iOS)
// The iPhone's on-screen keyboard: its Send key.
.onSubmit(send)
@@ -102,44 +101,70 @@ enum ComposerReturn: Equatable {
/// first responder of the window the anchor is in, while the field has the
/// keyboard (as it does whenever its key handler runs).
@MainActor final class ComposerInput {
+ weak var model: AskModel?
#if os(macOS)
+ /// Whether the field has the keyboard (its FocusState).
+ var focused = false
weak var anchor: NSView?
/// A Mac field's editor.
var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView }
- /// Whether the field has the keyboard (its FocusState).
- var focused = false
+ var composing: Bool { editor?.hasMarkedText() ?? false }
/// Where pastes come from (tests give their own).
static var pasteboard = NSPasteboard.general
+ private var observers: [NSObjectProtocol] = []
+ /// A menu's Paste (by its key or a click) is being sent.
+ private var pasting = false
private var converting = false
- private var observer: NSObjectProtocol?
- init() {
- observer = NotificationCenter.default.addObserver(forName: NSText.didChangeNotification, object: nil, queue: nil) { [weak self] note in
- // Text changes are posted on the main thread.
- nonisolated(unsafe) let changed = note.object as AnyObject?
- MainActor.assumeIsolated { self?.richPaste(in: changed) }
+ /// Starts watching the field, once its anchor is in a view (never in
+ /// an init: SwiftUI makes a ComposerInput on every pass of a parent's
+ /// body and keeps only the first).
+ func start() {
+ guard observers.isEmpty else { return }
+ let center = NotificationCenter.default
+ // Undo, Redo, text changes and menu actions all post on the main
+ // thread.
+ func watch(_ name: Notification.Name, _ act: @escaping @MainActor (ComposerInput, Notification) -> Void) {
+ observers.append(center.addObserver(forName: name, object: nil, queue: nil) { [weak self] note in
+ nonisolated(unsafe) let note = note
+ MainActor.assumeIsolated { if let self { act(self, note) } }
+ })
+ }
+ watch(.NSUndoManagerDidUndoChange) { $0.undone(by: $1.object as AnyObject?) }
+ watch(.NSUndoManagerDidRedoChange) { $0.undone(by: $1.object as AnyObject?) }
+ watch(NSText.didChangeNotification) { $0.richPaste(in: $1.object as AnyObject?) }
+ watch(NSMenu.willSendActionNotification) { input, note in
+ input.pasting = (note.userInfo?["MenuItem"] as? NSMenuItem)?.action == #selector(NSText.paste(_:))
}
+ watch(NSMenu.didSendActionNotification) { input, _ in input.pasting = false }
}
- isolated deinit { observer.map(NotificationCenter.default.removeObserver) }
+ isolated deinit { observers.forEach(NotificationCenter.default.removeObserver) }
- /// A rich paste (HTML or RTF on the pasteboard) as Markdown. The Mac
- /// field pastes the plain text itself and has no hook before it, so
- /// this follows: when the field's text has just taken the pasteboard's
- /// plain text, ending at the cursor, that is put back as one edit with
- /// the paste (one Undo takes both). Typing, an input method, Undo and
- /// Paste and Match Style are left alone.
+ /// Undo and Redo in a Mac field change the field but never tell it,
+ /// so its binding kept the text taken back, and Send sent that. Told
+ /// here as a typed change is, the field updates the model itself
+ /// (setting the model would push the text back into the field and
+ /// lose Redo).
+ func undone(by manager: AnyObject?) {
+ guard focused, let editor, let manager, manager === editor.undoManager, model?.text != editor.string else { return }
+ editor.didChangeText()
+ }
+
+ /// A rich paste (HTML, or RTF without HTML) as Markdown. The Mac field
+ /// pastes the plain text itself and has no hook before it, so this
+ /// follows, inside the Paste menu action (its key or a click): the
+ /// plain text just pasted, ending at the cursor, is put back as one
+ /// edit with the paste (one Undo takes both). Paste and Match Style,
+ /// typing, an input method, dictation, drops and Undo are never a
+ /// Paste, and are left alone.
func richPaste(in changed: AnyObject?) {
- guard focused, !converting, let editor, changed === editor,
- editor.undoManager?.isUndoing != true, editor.undoManager?.isRedoing != true else { return }
- if let event = NSApp.currentEvent, event.type == .keyDown {
- let keys = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
- guard keys.contains(.command), !keys.isSuperset(of: [.option, .shift]) else { return }
- }
+ guard pasting, focused, !converting, let editor, changed === editor, !editor.hasMarkedText() else { return }
let board = Self.pasteboard
- guard let plain = board.string(forType: .string), !plain.isEmpty else { return }
- let markdown = board.string(forType: .html).flatMap(PasteMarkdown.fromHTML)
- ?? board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF)
+ guard let rich = board.availableType(from: [.html, .rtf]),
+ let plain = board.string(forType: .string), !plain.isEmpty else { return }
+ let markdown = rich == .html ? board.string(forType: .html).flatMap(PasteMarkdown.fromHTML)
+ : board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF)
guard let markdown else { return }
let text = editor.string as NSString, length = (plain as NSString).length
let selection = editor.selectedRange()
@@ -153,7 +178,7 @@ enum ComposerReturn: Equatable {
editor.didChangeText()
editor.breakUndoCoalescing()
}
- var composing: Bool { editor?.hasMarkedText() ?? false }
+
/// A new line in place of the selection, as Option Return in any Mac
/// field: one undoable edit, the cursor after it.
func insertNewline() -> Bool {
@@ -217,16 +242,20 @@ final class ComposerPaste: NSObject, UITextPasteDelegate {
#if os(macOS)
struct ComposerAnchor: NSViewRepresentable {
let input: ComposerInput
- func makeNSView(context: Context) -> NSView { let view = NSView(); input.anchor = view; return view }
- func updateNSView(_ view: NSView, context: Context) { input.anchor = view }
+ let model: AskModel
+ func makeNSView(context: Context) -> NSView {
+ let view = NSView(); input.anchor = view; input.model = model; input.start(); return view
+ }
+ func updateNSView(_ view: NSView, context: Context) { input.anchor = view; input.model = model }
}
#elseif os(iOS)
struct ComposerAnchor: UIViewRepresentable {
let input: ComposerInput
+ let model: AskModel
func makeUIView(context: Context) -> UIView {
- let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; return view
+ let view = UIView(); view.isUserInteractionEnabled = false; input.anchor = view; input.model = model; return view
}
- func updateUIView(_ view: UIView, context: Context) { input.anchor = view }
+ func updateUIView(_ view: UIView, context: Context) { input.anchor = view; input.model = model }
}
#endif
diff --git a/native/apple/Tests/BaseKitTests/ComposerTests.swift b/native/apple/Tests/BaseKitTests/ComposerTests.swift
index d97e14a..1bc8228 100644
--- a/native/apple/Tests/BaseKitTests/ComposerTests.swift
+++ b/native/apple/Tests/BaseKitTests/ComposerTests.swift
@@ -127,39 +127,136 @@ import AppKit
}
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("<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)
+ 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; a plain one is pasted as it is. A
- /// pasteboard of the test's own, never the person's.
+ /// 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)
- board.clearContents()
- 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)
- board.setString("The flour comes Thursday:\nRye\nThe order", forType: .string)
- XCTAssertTrue(editor.readSelection(from: board))
+ editor.insertText("\nThe flour comes Thursday:\nRye\nThe order", replacementRange: editor.selectedRange())
settle()
- 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)
+ 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()
- // (The field's own text: a hosted field's binding misses an Undo
- // here, any Undo, typing's too.)
- XCTAssertEqual(editor.string, "Note: ", "one Undo takes the paste back")
+ XCTAssertEqual(editor.string, "Flour")
+ XCTAssertEqual(model.text, "Flour", "Undo reaches the model")
editor.undoManager?.redo()
settle()
- XCTAssertTrue(editor.string.contains("**flour**"), "and Redo brings it back")
+ XCTAssertEqual(model.text, "Flour delivery", "and so does Redo")
+ editor.undoManager?.undo()
+ settle()
+ try press()
+ XCTAssertEqual(sentText, "Flour", "Return sends what the field shows")
+ }
- board.clearContents()
- board.setString("plain *as* copied", forType: .string)
- editor.setSelectedRange(NSRange(location: (editor.string as NSString).length, length: 0))
- XCTAssertTrue(editor.readSelection(from: board))
+ func testUndoingANewLineReachesTheModel() throws {
+ try type("Flour delivery", cursor: 5)
+ try press(.shift)
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ editor?.undoManager?.undo()
settle()
- XCTAssertTrue(editor.string.hasSuffix("plain *as* copied"), editor.string)
- XCTAssertTrue(model.text.hasSuffix("plain *as* copied"), model.text)
+ XCTAssertEqual(model.text, "Flour delivery")
+ editor?.undoManager?.redo()
+ settle()
+ XCTAssertEqual(model.text, "Flour\n delivery")
+ XCTAssertFalse(sent)
}
}