Download this file
| 1 | import AppKit |
| 2 | import EquipoKit |
| 3 | |
| 4 | /// The text belongs to the card, so replacing a row never discards an edit. |
| 5 | @MainActor final class QuestionAnswerField: NSTextField, NSTextFieldDelegate { |
| 6 | private let draft: QuestionAnswerDraft |
| 7 | private let onSubmit: (String) -> Void |
| 8 | |
| 9 | init(draft: QuestionAnswerDraft, onSubmit: @escaping (String) -> Void) { |
| 10 | self.draft = draft; self.onSubmit = onSubmit |
| 11 | super.init(frame: .zero) |
| 12 | stringValue = draft.typedChoice |
| 13 | delegate = self |
| 14 | } |
| 15 | required init?(coder: NSCoder) { fatalError() } |
| 16 | |
| 17 | func controlTextDidChange(_ notification: Notification) { |
| 18 | draft.typedChoice = stringValue |
| 19 | } |
| 20 | func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { |
| 21 | guard selector == #selector(NSResponder.insertNewline(_:)) else { return false } |
| 22 | submit() |
| 23 | return true |
| 24 | } |
| 25 | func submit() { |
| 26 | guard isEnabled else { return } |
| 27 | let text = stringValue.trimmingCharacters(in: .whitespacesAndNewlines) |
| 28 | guard !text.isEmpty else { return } |
| 29 | draft.typedChoice = stringValue |
| 30 | onSubmit(text) |
| 31 | } |
| 32 | } |
| 33 | |