| 1 | #if os(iOS) |
| 2 | import SwiftUI |
| 3 | import UIKit |
| 4 | |
| 5 | /// The keyboard on iPad and iPhone, when a cell is selected. |
| 6 | /// |
| 7 | /// UIKit composes text (a dead key's ´ then e, an input method's かな) only |
| 8 | /// inside a text input that is already first responder when the key goes |
| 9 | /// down; a key press cannot be handed to one afterwards. So the grid keeps |
| 10 | /// this field first responder while a cell is selected, sitting on that cell. |
| 11 | /// Idle, it is invisible and turns arrows, Return, Tab and Delete into grid |
| 12 | /// moves. The first text it receives, typed or composed, starts a cell edit |
| 13 | /// that replaces the cell (Return and F2 keep it), and from then on it is the |
| 14 | /// cell's editor. It brings up no on-screen keyboard: touch editing stays in |
| 15 | /// the formula bar, reached by double-tapping a cell. |
| 16 | struct SheetKeySink: UIViewRepresentable { |
| 17 | let model: SheetModel |
| 18 | /// Bumped to ask for the keyboard (a cell was tapped, the grid appeared). |
| 19 | let focusRequest: Int |
| 20 | let move: (Int, Int) -> Void |
| 21 | func makeUIView(context: Context) -> SinkField { |
| 22 | let field = SinkField() |
| 23 | field.model = model |
| 24 | field.move = move |
| 25 | return field |
| 26 | } |
| 27 | func updateUIView(_ field: SinkField, context: Context) { |
| 28 | field.model = model |
| 29 | field.move = move |
| 30 | field.pageChanged(to: model.page?.Sheet.ID) |
| 31 | field.selectionChanged(to: model.selection.start) |
| 32 | if focusRequest != field.focusRequest { |
| 33 | field.focusRequest = focusRequest |
| 34 | field.claimKeyboard() |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | @MainActor final class SinkField: UITextField { |
| 39 | weak var model: SheetModel? |
| 40 | var move: (Int, Int) -> Void = { _, _ in } |
| 41 | var focusRequest = 0 |
| 42 | /// True once this field holds the cell's edit. |
| 43 | private(set) var typing = false |
| 44 | private var cell: Coordinate? |
| 45 | private var quiet = false |
| 46 | /// Presses handled here, so their ends are not sent on to UIKit either. |
| 47 | private var handled: Set<UIKeyboardHIDUsage> = [] |
| 48 | |
| 49 | override init(frame: CGRect) { |
| 50 | super.init(frame: frame) |
| 51 | inputView = UIView() // no on-screen keyboard: touch edits in the formula bar |
| 52 | inputAssistantItem.leadingBarButtonGroups = [] |
| 53 | inputAssistantItem.trailingBarButtonGroups = [] |
| 54 | autocorrectionType = .no |
| 55 | autocapitalizationType = .none |
| 56 | spellCheckingType = .no |
| 57 | smartQuotesType = .no // a formula's quotes are ASCII |
| 58 | smartDashesType = .no |
| 59 | smartInsertDeleteType = .no |
| 60 | inlinePredictionType = .no |
| 61 | font = .systemFont(ofSize: 13) |
| 62 | borderStyle = .none |
| 63 | accessibilityLabel = sheetsMacString("Cell contents") |
| 64 | addTarget(self, action: #selector(changed), for: .editingChanged) |
| 65 | appearIdle() |
| 66 | } |
| 67 | required init?(coder: NSCoder) { nil } |
| 68 | |
| 69 | /// Idle, the field is invisible and cannot be typed into without a hardware |
| 70 | /// keyboard, so VoiceOver must not land on it: the cell's own button is |
| 71 | /// what it reads. Typing, it is the cell's editor and is announced as one. |
| 72 | private func appearIdle() { |
| 73 | isAccessibilityElement = false |
| 74 | accessibilityElementsHidden = true |
| 75 | textColor = .clear |
| 76 | tintColor = .clear |
| 77 | backgroundColor = .clear |
| 78 | layer.borderWidth = 0 |
| 79 | } |
| 80 | private func appearTyping() { |
| 81 | isAccessibilityElement = true |
| 82 | accessibilityElementsHidden = false |
| 83 | textColor = .label |
| 84 | tintColor = nil |
| 85 | backgroundColor = .systemBackground |
| 86 | layer.borderColor = UIColor.tintColor.cgColor |
| 87 | layer.borderWidth = 2 |
| 88 | } |
| 89 | |
| 90 | func claimKeyboard() { |
| 91 | guard window != nil, !isFirstResponder else { return } |
| 92 | becomeFirstResponder() |
| 93 | } |
| 94 | override func didMoveToWindow() { |
| 95 | super.didMoveToWindow() |
| 96 | if window != nil && focusRequest > 0 { claimKeyboard() } |
| 97 | } |
| 98 | |
| 99 | private var sheet: UInt64? |
| 100 | /// Another sheet opened: no edit of the old one carries over. |
| 101 | func pageChanged(to id: UInt64?) { |
| 102 | guard id != sheet else { return } |
| 103 | sheet = id |
| 104 | if typing || !(text ?? "").isEmpty { reset() } |
| 105 | } |
| 106 | /// A commit, a cancel, or a tap moved the selection: this edit is over. |
| 107 | func selectionChanged(to point: Coordinate) { |
| 108 | guard point != cell else { return } |
| 109 | cell = point |
| 110 | if typing || !(text ?? "").isEmpty { reset() } |
| 111 | } |
| 112 | private func reset() { |
| 113 | quiet = true |
| 114 | if markedTextRange != nil { unmarkText() } |
| 115 | text = "" |
| 116 | quiet = false |
| 117 | typing = false |
| 118 | appearIdle() |
| 119 | } |
| 120 | |
| 121 | /// Typed or composed text, the first of which starts the edit. |
| 122 | @objc private func changed() { |
| 123 | guard !quiet, let model else { return } |
| 124 | let value = text ?? "" |
| 125 | if !typing { |
| 126 | guard model.mayWrite, !model.dirty, !model.opening, !value.isEmpty || markedTextRange != nil else { |
| 127 | if !model.mayWrite { reset() } |
| 128 | return |
| 129 | } |
| 130 | typing = true |
| 131 | appearTyping() |
| 132 | } |
| 133 | model.draft = value |
| 134 | } |
| 135 | /// Every commit ends this edit, including one on the last row or column, |
| 136 | /// where the selection cannot move and so would never reset the field. |
| 137 | private func commit(moveRight: Bool) { |
| 138 | guard let model else { return } |
| 139 | model.commit(moveRight: moveRight) |
| 140 | if !model.dirty { reset() } |
| 141 | } |
| 142 | /// Return or F2 on a selected cell: edit it here, keeping its contents. |
| 143 | private func editInPlace() { |
| 144 | guard let model, model.mayWrite, !model.dirty else { return } |
| 145 | quiet = true |
| 146 | text = model.rawAt(model.selection.start) |
| 147 | quiet = false |
| 148 | typing = true |
| 149 | appearTyping() |
| 150 | } |
| 151 | |
| 152 | // The text input calls a key press arrives as. Each reports the change |
| 153 | // itself rather than relying on .editingChanged alone, which UIKit sends |
| 154 | // for some of these and not others. |
| 155 | override func insertText(_ text: String) { |
| 156 | super.insertText(text) |
| 157 | changed() |
| 158 | } |
| 159 | override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { |
| 160 | super.setMarkedText(markedText, selectedRange: selectedRange) |
| 161 | changed() |
| 162 | } |
| 163 | override func unmarkText() { |
| 164 | super.unmarkText() |
| 165 | changed() |
| 166 | } |
| 167 | override func deleteBackward() { |
| 168 | if typing { super.deleteBackward(); changed(); return } |
| 169 | if let model, model.mayWrite { Task { await model.clear() } } |
| 170 | } |
| 171 | |
| 172 | override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 173 | // An input method's own keys (Return confirms, Escape cancels, arrows |
| 174 | // pick a candidate) are never ours while it is composing. |
| 175 | guard markedTextRange == nil, let key = presses.first?.key, |
| 176 | key.modifierFlags.intersection([.command, .control, .alternate]).isEmpty, |
| 177 | handle(key.keyCode, shift: key.modifierFlags.contains(.shift)) |
| 178 | else { return super.pressesBegan(presses, with: event) } |
| 179 | handled.insert(key.keyCode) |
| 180 | } |
| 181 | /// The grid's keys. Returns false for anything that is text. |
| 182 | func handle(_ code: UIKeyboardHIDUsage, shift: Bool = false) -> Bool { |
| 183 | guard let model else { return false } |
| 184 | switch code { |
| 185 | case .keyboardReturnOrEnter, .keypadEnter: |
| 186 | if typing { commit(moveRight: false) } else { editInPlace() } |
| 187 | case .keyboardTab: |
| 188 | if typing { commit(moveRight: true) } else { move(0, shift ? -1 : 1) } |
| 189 | case .keyboardEscape: |
| 190 | guard typing else { return false } |
| 191 | model.discard(); reset() |
| 192 | case .keyboardF2 where !typing: editInPlace() |
| 193 | case .keyboardUpArrow where !typing: move(-1, 0) |
| 194 | case .keyboardDownArrow where !typing: move(1, 0) |
| 195 | case .keyboardLeftArrow where !typing: move(0, -1) |
| 196 | case .keyboardRightArrow where !typing: move(0, 1) |
| 197 | default: return false |
| 198 | } |
| 199 | return true |
| 200 | } |
| 201 | override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 202 | if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } |
| 203 | super.pressesEnded(presses, with: event) |
| 204 | } |
| 205 | override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| 206 | if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } |
| 207 | super.pressesCancelled(presses, with: event) |
| 208 | } |
| 209 | |
| 210 | /// Idle, Copy, Paste and Select All belong to the grid's commands. |
| 211 | override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { |
| 212 | typing ? super.canPerformAction(action, withSender: sender) : false |
| 213 | } |
| 214 | |
| 215 | override func resignFirstResponder() -> Bool { |
| 216 | let resigned = super.resignFirstResponder() |
| 217 | // Focus went elsewhere (the formula bar, say): the edit, if any, carries |
| 218 | // on there with the same draft. |
| 219 | if resigned && typing { |
| 220 | quiet = true |
| 221 | text = "" |
| 222 | quiet = false |
| 223 | typing = false |
| 224 | appearIdle() |
| 225 | } |
| 226 | return resigned |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | #endif |
| 231 | |