import AppKit import SwiftUI /// The keys the overlays react to, from a text field or a bare key catcher. enum OverlayKey: Equatable { case up, down, commandUp, commandDown, commandLeft, commandRight, enter, escape case commandP /// Maps the text system's commands back to the keys that produced them. init?(selector: Selector) { switch selector { case #selector(NSResponder.moveUp(_:)): self = .up case #selector(NSResponder.moveDown(_:)): self = .down case #selector(NSResponder.moveToBeginningOfDocument(_:)): self = .commandUp case #selector(NSResponder.moveToEndOfDocument(_:)): self = .commandDown case #selector(NSResponder.moveToBeginningOfLine(_:)), #selector(NSResponder.moveToLeftEndOfLine(_:)): self = .commandLeft case #selector(NSResponder.moveToEndOfLine(_:)), #selector(NSResponder.moveToRightEndOfLine(_:)): self = .commandRight case #selector(NSResponder.insertNewline(_:)): self = .enter case #selector(NSResponder.cancelOperation(_:)): self = .escape default: return nil } } /// Maps a raw key event, for overlays without a text field. init?(event: NSEvent) { let command = event.modifierFlags.contains(.command) switch event.keyCode { case 126: self = command ? .commandUp : .up case 125: self = command ? .commandDown : .down case 123 where command: self = .commandLeft case 124 where command: self = .commandRight case 36, 76: self = .enter case 53: self = .escape default: guard command, event.charactersIgnoringModifiers?.lowercased() == "p" else { return nil } self = .commandP } } } /// A borderless single-line field that hands navigation keys to the overlay before the text system sees them. struct OverlayCommandField: NSViewRepresentable { @Binding var text: String var placeholder: String var font: NSFont /// nil selects the whole text on focus, so typing replaces a seeded query. var initialSelection: NSRange? var onKey: (OverlayKey) -> Bool func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSTextField { let field = FocusingTextField() field.isBordered = false field.drawsBackground = false field.focusRingType = .none field.font = font field.textColor = NSColor(hex: 0xF4F5F4) field.placeholderAttributedString = NSAttributedString( string: placeholder, attributes: [.foregroundColor: NSColor(hex: 0x6C7783), .font: font] ) field.stringValue = text field.delegate = context.coordinator field.cell?.isScrollable = true field.cell?.wraps = false field.initialSelection = initialSelection return field } func updateNSView(_ field: NSTextField, context: Context) { context.coordinator.parent = self if field.stringValue != text { field.stringValue = text } } final class Coordinator: NSObject, NSTextFieldDelegate { var parent: OverlayCommandField init(_ parent: OverlayCommandField) { self.parent = parent } func controlTextDidChange(_ note: Notification) { guard let field = note.object as? NSTextField else { return } parent.text = field.stringValue } func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { guard let key = OverlayKey(selector: selector) else { return false } return parent.onKey(key) } } } /// An invisible first responder that forwards the overlay keys and swallows the ones it handles. struct OverlayKeyCatcher: NSViewRepresentable { var onKey: (OverlayKey) -> Bool func makeNSView(context: Context) -> CatcherView { let view = CatcherView() view.onKey = onKey return view } func updateNSView(_ view: CatcherView, context: Context) { view.onKey = onKey } final class CatcherView: NSView { var onKey: (OverlayKey) -> Bool = { _ in false } override var acceptsFirstResponder: Bool { true } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() DispatchQueue.main.async { [weak self] in guard let self, let window = self.window else { return } window.makeFirstResponder(self) } } override func keyDown(with event: NSEvent) { if let key = OverlayKey(event: event), onKey(key) { return } super.keyDown(with: event) } override func performKeyEquivalent(with event: NSEvent) -> Bool { guard window?.firstResponder === self, let key = OverlayKey(event: event) else { return super.performKeyEquivalent(with: event) } return onKey(key) || super.performKeyEquivalent(with: event) } } } /// Takes focus once it is on screen and applies the initial selection. private final class FocusingTextField: NSTextField { var initialSelection: NSRange? private var focused = false override func viewDidMoveToWindow() { super.viewDidMoveToWindow() guard !focused, window != nil else { return } focused = true DispatchQueue.main.async { [weak self] in guard let self, let window = self.window, window.makeFirstResponder(self) else { return } guard let editor = self.currentEditor() as? NSTextView else { return } editor.insertionPointColor = NSColor(hex: 0xE8913A) let length = (self.stringValue as NSString).length editor.selectedRange = self.initialSelection.map { NSRange(location: min($0.location, length), length: min($0.length, length)) } ?? NSRange(location: 0, length: length) } } }