Repository Public License
1import SwiftUI23#if os(macOS)4import AppKit5typealias PlatformColor = NSColor6typealias PlatformFont = NSFont7#else8import UIKit9typealias PlatformColor = UIColor10typealias PlatformFont = UIFont11#endif1213/// The native text field of the omnibox. SwiftUI's `TextField` cannot select its content on focus nor report14/// arrow keys reliably while editing, so the platform field is wrapped once here for both systems.15struct OmniboxTextField {16 /// Text while editing.17 @Binding var text: String18 /// Text shown while the field is not being edited (the short address).19 var displayText: String20 var prompt: String21 var isEditing: Bool22 /// Changes when the field must take focus and select everything.23 var focusRequest: Int24 var textColor: Color25 var promptColor: Color26 var tintColor: Color27 var identifier: String28 var onBeginEditing: () -> Void29 var onEndEditing: () -> Void30 var onSubmit: () -> Void31 var onMove: (Int) -> Void32 var onCancel: () -> Void3334 @MainActor35 final class Coordinator: NSObject {36 var parent: OmniboxTextField37 var lastFocusRequest: Int38 var isUpdating = false3940 init(_ parent: OmniboxTextField) {41 self.parent = parent42 self.lastFocusRequest = parent.focusRequest43 }44 }4546 @MainActor func makeCoordinator() -> Coordinator { Coordinator(self) }47}4849#if os(macOS)5051final class OmniboxNSTextField: NSTextField {52 var onFocus: (() -> Void)?5354 override func becomeFirstResponder() -> Bool {55 let became = super.becomeFirstResponder()56 if became { onFocus?() }57 return became58 }59}6061extension OmniboxTextField: NSViewRepresentable {62 func makeNSView(context: Context) -> OmniboxNSTextField {63 let field = OmniboxNSTextField()64 field.isBordered = false65 field.isBezeled = false66 field.drawsBackground = false67 field.focusRingType = .none68 field.lineBreakMode = .byTruncatingTail69 field.usesSingleLineMode = true70 field.cell?.isScrollable = true71 field.cell?.wraps = false72 field.font = .systemFont(ofSize: NSFont.systemFontSize)73 field.delegate = context.coordinator74 field.setAccessibilityIdentifier(identifier)75 field.setAccessibilityLabel(prompt)76 field.setContentHuggingPriority(.defaultLow, for: .horizontal)77 field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)78 field.onFocus = { [weak coordinator = context.coordinator] in79 guard let coordinator, !coordinator.isUpdating else { return }80 coordinator.parent.onBeginEditing()81 }82 return field83 }8485 func updateNSView(_ field: OmniboxNSTextField, context: Context) {86 let coordinator = context.coordinator87 coordinator.parent = self88 coordinator.isUpdating = true89 defer { coordinator.isUpdating = false }90 field.textColor = NSColor(textColor)91 field.placeholderAttributedString = NSAttributedString(92 string: prompt, attributes: [.foregroundColor: NSColor(promptColor), .font: field.font as Any])93 let wanted = isEditing ? text : displayText94 if field.stringValue != wanted { field.stringValue = wanted }95 let editor = field.currentEditor() as? NSTextView96 editor?.insertionPointColor = NSColor(tintColor)97 if focusRequest != coordinator.lastFocusRequest {98 coordinator.lastFocusRequest = focusRequest99 // Deferred: the window may not have laid the field out yet during this update pass.100 DispatchQueue.main.async { [weak field] in101 guard let field, let window = field.window else { return }102 coordinator.isUpdating = true103 if field.currentEditor() == nil { window.makeFirstResponder(field) }104 field.currentEditor()?.selectAll(nil)105 coordinator.isUpdating = false106 }107 } else if !isEditing, editor != nil, field.window?.firstResponder === editor {108 // Editing was cancelled from the model (Escape, navigation): hand focus back to the window.109 DispatchQueue.main.async { [weak field] in110 guard let field, field.currentEditor() != nil else { return }111 field.window?.makeFirstResponder(nil)112 }113 }114 }115}116117extension OmniboxTextField.Coordinator: NSTextFieldDelegate {118 func controlTextDidChange(_ notification: Notification) {119 guard !isUpdating, let field = notification.object as? NSTextField else { return }120 parent.text = field.stringValue121 }122123 func controlTextDidEndEditing(_ notification: Notification) {124 guard !isUpdating else { return }125 parent.onEndEditing()126 }127128 func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {129 switch selector {130 case #selector(NSResponder.moveDown(_:)): parent.onMove(1); return true131 case #selector(NSResponder.moveUp(_:)): parent.onMove(-1); return true132 case #selector(NSResponder.cancelOperation(_:)): parent.onCancel(); return true133 case #selector(NSResponder.insertNewline(_:)): parent.onSubmit(); return true134 default: return false135 }136 }137}138139#else140141final class OmniboxUITextField: UITextField {142 var onMove: ((Int) -> Void)?143 var onCancel: (() -> Void)?144145 override var keyCommands: [UIKeyCommand]? {146 let up = UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(moveUp))147 let down = UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(moveDown))148 let escape = UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(cancelEditing))149 for command in [up, down, escape] { command.wantsPriorityOverSystemBehavior = true }150 return [up, down, escape]151 }152153 @objc private func moveUp() { onMove?(-1) }154 @objc private func moveDown() { onMove?(1) }155 @objc private func cancelEditing() { onCancel?() }156}157158extension OmniboxTextField: UIViewRepresentable {159 func makeUIView(context: Context) -> OmniboxUITextField {160 let field = OmniboxUITextField()161 field.borderStyle = .none162 field.keyboardType = .webSearch163 field.returnKeyType = .go164 field.autocapitalizationType = .none165 field.autocorrectionType = .no166 field.spellCheckingType = .no167 field.smartQuotesType = .no168 field.smartDashesType = .no169 field.clearButtonMode = .whileEditing170 field.enablesReturnKeyAutomatically = false171 field.font = .preferredFont(forTextStyle: .body)172 field.adjustsFontForContentSizeCategory = true173 field.delegate = context.coordinator174 field.accessibilityIdentifier = identifier175 field.accessibilityLabel = prompt176 field.setContentHuggingPriority(.defaultLow, for: .horizontal)177 field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)178 field.addTarget(context.coordinator, action: #selector(Coordinator.textChanged(_:)), for: .editingChanged)179 return field180 }181182 func updateUIView(_ field: OmniboxUITextField, context: Context) {183 let coordinator = context.coordinator184 coordinator.parent = self185 coordinator.isUpdating = true186 defer { coordinator.isUpdating = false }187 field.onMove = onMove188 field.onCancel = onCancel189 field.textColor = UIColor(textColor)190 field.tintColor = UIColor(tintColor)191 field.attributedPlaceholder = NSAttributedString(string: prompt, attributes: [.foregroundColor: UIColor(promptColor)])192 let wanted = isEditing ? text : displayText193 if field.text != wanted { field.text = wanted }194 if focusRequest != coordinator.lastFocusRequest {195 coordinator.lastFocusRequest = focusRequest196 DispatchQueue.main.async { [weak field] in197 guard let field, field.window != nil else { return }198 if !field.isFirstResponder { field.becomeFirstResponder() }199 field.selectAll(nil)200 }201 } else if !isEditing, field.isFirstResponder {202 DispatchQueue.main.async { [weak field] in field?.resignFirstResponder() }203 }204 }205}206207extension OmniboxTextField.Coordinator: UITextFieldDelegate {208 @objc func textChanged(_ field: UITextField) {209 guard !isUpdating else { return }210 parent.text = field.text ?? ""211 }212213 func textFieldDidBeginEditing(_ textField: UITextField) {214 guard !isUpdating else { return }215 if !parent.isEditing { parent.onBeginEditing() }216 }217218 func textFieldDidEndEditing(_ textField: UITextField) {219 guard !isUpdating else { return }220 parent.onEndEditing()221 }222223 func textFieldShouldReturn(_ textField: UITextField) -> Bool {224 parent.onSubmit()225 return false226 }227}228229#endif230