#if os(iOS) import SwiftUI import UIKit /// The keyboard on iPad and iPhone, when a cell is selected. /// /// UIKit composes text (a dead key's ´ then e, an input method's かな) only /// inside a text input that is already first responder when the key goes /// down; a key press cannot be handed to one afterwards. So the grid keeps /// this field first responder while a cell is selected, sitting on that cell. /// Idle, it is invisible and turns arrows, Return, Tab and Delete into grid /// moves. The first text it receives, typed or composed, starts a cell edit /// that replaces the cell (Return and F2 keep it), and from then on it is the /// cell's editor. It brings up no on-screen keyboard: touch editing stays in /// the formula bar, reached by double-tapping a cell. struct SheetKeySink: UIViewRepresentable { let model: SheetModel /// Bumped to ask for the keyboard (a cell was tapped, the grid appeared). let focusRequest: Int let move: (Int, Int) -> Void func makeUIView(context: Context) -> SinkField { let field = SinkField() field.model = model field.move = move return field } func updateUIView(_ field: SinkField, context: Context) { field.model = model field.move = move field.pageChanged(to: model.page?.Sheet.ID) field.selectionChanged(to: model.selection.start) if focusRequest != field.focusRequest { field.focusRequest = focusRequest field.claimKeyboard() } } @MainActor final class SinkField: UITextField { weak var model: SheetModel? var move: (Int, Int) -> Void = { _, _ in } var focusRequest = 0 /// True once this field holds the cell's edit. private(set) var typing = false private var cell: Coordinate? private var quiet = false /// Presses handled here, so their ends are not sent on to UIKit either. private var handled: Set = [] override init(frame: CGRect) { super.init(frame: frame) inputView = UIView() // no on-screen keyboard: touch edits in the formula bar inputAssistantItem.leadingBarButtonGroups = [] inputAssistantItem.trailingBarButtonGroups = [] autocorrectionType = .no autocapitalizationType = .none spellCheckingType = .no smartQuotesType = .no // a formula's quotes are ASCII smartDashesType = .no smartInsertDeleteType = .no inlinePredictionType = .no font = .systemFont(ofSize: 13) borderStyle = .none accessibilityLabel = sheetsMacString("Cell contents") addTarget(self, action: #selector(changed), for: .editingChanged) appearIdle() } required init?(coder: NSCoder) { nil } /// Idle, the field is invisible and cannot be typed into without a hardware /// keyboard, so VoiceOver must not land on it: the cell's own button is /// what it reads. Typing, it is the cell's editor and is announced as one. private func appearIdle() { isAccessibilityElement = false accessibilityElementsHidden = true textColor = .clear tintColor = .clear backgroundColor = .clear layer.borderWidth = 0 } private func appearTyping() { isAccessibilityElement = true accessibilityElementsHidden = false textColor = .label tintColor = nil backgroundColor = .systemBackground layer.borderColor = UIColor.tintColor.cgColor layer.borderWidth = 2 } func claimKeyboard() { guard window != nil, !isFirstResponder else { return } becomeFirstResponder() } override func didMoveToWindow() { super.didMoveToWindow() if window != nil && focusRequest > 0 { claimKeyboard() } } private var sheet: UInt64? /// Another sheet opened: no edit of the old one carries over. func pageChanged(to id: UInt64?) { guard id != sheet else { return } sheet = id if typing || !(text ?? "").isEmpty { reset() } } /// A commit, a cancel, or a tap moved the selection: this edit is over. func selectionChanged(to point: Coordinate) { guard point != cell else { return } cell = point if typing || !(text ?? "").isEmpty { reset() } } private func reset() { quiet = true if markedTextRange != nil { unmarkText() } text = "" quiet = false typing = false appearIdle() } /// Typed or composed text, the first of which starts the edit. @objc private func changed() { guard !quiet, let model else { return } let value = text ?? "" if !typing { guard model.mayWrite, !model.dirty, !model.opening, !value.isEmpty || markedTextRange != nil else { if !model.mayWrite { reset() } return } typing = true appearTyping() } model.draft = value } /// Every commit ends this edit, including one on the last row or column, /// where the selection cannot move and so would never reset the field. private func commit(moveRight: Bool) { guard let model else { return } model.commit(moveRight: moveRight) if !model.dirty { reset() } } /// Return or F2 on a selected cell: edit it here, keeping its contents. private func editInPlace() { guard let model, model.mayWrite, !model.dirty else { return } quiet = true text = model.rawAt(model.selection.start) quiet = false typing = true appearTyping() } // The text input calls a key press arrives as. Each reports the change // itself rather than relying on .editingChanged alone, which UIKit sends // for some of these and not others. override func insertText(_ text: String) { super.insertText(text) changed() } override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { super.setMarkedText(markedText, selectedRange: selectedRange) changed() } override func unmarkText() { super.unmarkText() changed() } override func deleteBackward() { if typing { super.deleteBackward(); changed(); return } if let model, model.mayWrite { Task { await model.clear() } } } override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { // An input method's own keys (Return confirms, Escape cancels, arrows // pick a candidate) are never ours while it is composing. guard markedTextRange == nil, let key = presses.first?.key, key.modifierFlags.intersection([.command, .control, .alternate]).isEmpty, handle(key.keyCode, shift: key.modifierFlags.contains(.shift)) else { return super.pressesBegan(presses, with: event) } handled.insert(key.keyCode) } /// The grid's keys. Returns false for anything that is text. func handle(_ code: UIKeyboardHIDUsage, shift: Bool = false) -> Bool { guard let model else { return false } switch code { case .keyboardReturnOrEnter, .keypadEnter: if typing { commit(moveRight: false) } else { editInPlace() } case .keyboardTab: if typing { commit(moveRight: true) } else { move(0, shift ? -1 : 1) } case .keyboardEscape: guard typing else { return false } model.discard(); reset() case .keyboardF2 where !typing: editInPlace() case .keyboardUpArrow where !typing: move(-1, 0) case .keyboardDownArrow where !typing: move(1, 0) case .keyboardLeftArrow where !typing: move(0, -1) case .keyboardRightArrow where !typing: move(0, 1) default: return false } return true } override func pressesEnded(_ presses: Set, with event: UIPressesEvent?) { if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } super.pressesEnded(presses, with: event) } override func pressesCancelled(_ presses: Set, with event: UIPressesEvent?) { if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } super.pressesCancelled(presses, with: event) } /// Idle, Copy, Paste and Select All belong to the grid's commands. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { typing ? super.canPerformAction(action, withSender: sender) : false } override func resignFirstResponder() -> Bool { let resigned = super.resignFirstResponder() // Focus went elsewhere (the formula bar, say): the edit, if any, carries // on there with the same draft. if resigned && typing { quiet = true text = "" quiet = false typing = false appearIdle() } return resigned } } } #endif