oficina / sheets Public

Sheets iOS: a hardware keyboard types into the selected cell from the first key

UIKit composes text (dead keys, input methods) only inside a text input
that is first responder before the key goes down, and a key press cannot
be handed to one afterwards. SheetKeySink keeps an invisible text field on
the selected cell holding the keyboard, with no on-screen keyboard and no
smart quotes; idle it maps arrows/Return/Tab/Delete/F2 to the grid, and
its first text (typed or marked) starts an in-place edit that replaces the
cell. Touch editing stays in the formula bar.

KeySinkTests drive it through the text input calls UIKit makes (insertText,
setMarkedText, unmarkText) on an iPad simulator. The review executable gets
an iOS stub so the package's tests build for a simulator at all.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d3cc31ac171a36dd578855cac2017bf61996ef75 parent c9bdf30
5 files changed, +364 −17
  • native/README.md +5 −1
  • native/apple/Sources/SheetsKit/SheetGrid.swift +29 −16
  • native/apple/Sources/SheetsKit/SheetKeySink.swift +208 −0
  • native/apple/Sources/SheetsReview/Review.swift +6 −0
  • native/apple/Tests/SheetsKitTests/KeySinkTests.swift +116 −0
diff --git a/native/README.md b/native/README.md
index ce37b06..16044cc 100644
--- a/native/README.md
+++ b/native/README.md
@@ -65,7 +65,11 @@ Select a cell, then edit its formula bar, double-click, press Return or F2
(these keep the cell's contents), or just type (this replaces them, as in
Numbers or Excel). The keystroke that starts typing goes to the cell's own
text field, so a dead key (´ then e) or an input method composes from the
-first key. Enter saves and moves down; Tab saves and moves right; Escape
+first key. On iPad and iPhone a hardware keyboard works the same way: while
+a cell is selected an invisible text field sits on it holding the keyboard
+(without raising the on-screen one), so arrows, Return, Tab and Delete move
+and clear, and the first typed or composed text starts the edit in place.
+Touch editing stays in the formula bar (double-tap a cell). Enter saves and moves down; Tab saves and moves right; Escape
discards the focused cell edit. The range field accepts
addresses such as `A1:C10`. Menus provide copy/paste, clear, fill, formatting,
size controls, functions, history, comments, sharing and workbook transfer.
diff --git a/native/apple/Sources/SheetsKit/SheetGrid.swift b/native/apple/Sources/SheetsKit/SheetGrid.swift
index 9a0b34f..4e0b30f 100644
--- a/native/apple/Sources/SheetsKit/SheetGrid.swift
+++ b/native/apple/Sources/SheetsKit/SheetGrid.swift
@@ -9,6 +9,9 @@ struct SheetGrid: View {
@FocusState private var focused: Bool
#if os(macOS)
@State private var typeAhead = SheetTypeAhead()
+ #else
+ /// Bumped to give the keyboard to the cell (SheetKeySink).
+ @State private var keyboardRequest = 0
#endif
var beginEditing: () -> Void = {}
var body: some View {
@@ -59,6 +62,9 @@ struct SheetGrid: View {
}.background(.regularMaterial)
}
}
+ #if os(iOS)
+ .overlay(alignment: .topLeading) { keySink }
+ #endif
}.defaultScrollAnchor(.topLeading)
.accessibilityLabel("Spreadsheet grid")
.focusable()
@@ -87,21 +93,21 @@ struct SheetGrid: View {
#if os(macOS)
.background { SheetKeyMonitor(handle: handleKey) }
#else
- .onKeyPress(characters: .alphanumerics.union(.punctuationCharacters).union(.symbols).union(.whitespaces)) {
- press in
- guard model.mayWrite, !press.characters.contains(where: { $0 == "\t" || $0.isNewline }),
- press.modifiers.intersection([.command, .control, .option]).isEmpty
- else { return .ignored }
- if model.dirty {
- model.draft += press.characters
- } else {
- model.draft = press.characters
- edit(model.selection.start)
- }
- return .handled
- }
+ .onAppear { keyboardRequest += 1 }
#endif
}
+ #if os(iOS)
+ /// The keyboard's place on the selected cell (SheetKeySink).
+ private var keySink: some View {
+ let point = model.selection.start
+ let x = 48 + (0..<point.c).reduce(0) { $0 + width($1) }
+ let y = 32 + (0..<point.r).reduce(0) { $0 + height($1) }
+ return SheetKeySink(model: model, focusRequest: keyboardRequest, move: { r, c in _ = move(r, c) })
+ .frame(width: width(point.c), height: height(point.r))
+ .offset(x: x, y: y)
+ .allowsHitTesting(false)
+ }
+ #endif
private func cell(row: Int, col: Int) -> some View {
let point = Coordinate(r: row, c: col)
#if os(macOS)
@@ -116,7 +122,7 @@ struct SheetGrid: View {
model: model, point: point, editing: $editing,
select: { select(point) },
beginEditing: { edit(point) },
- endEditing: { editing = nil; focused = true },
+ endEditing: { editing = nil; takeKeyboard() },
columnWidth: width(col), rowHeight: height(row))
#endif
}
@@ -169,21 +175,28 @@ struct SheetGrid: View {
guard !model.dirty else { return }
if editing != point { editing = nil }
model.select(point)
+ takeKeyboard()
+ }
+ private func takeKeyboard() {
+ #if os(macOS)
focused = true
+ #else
+ keyboardRequest += 1
+ #endif
}
private func selectRow(_ row: Int) {
guard !model.dirty else { return }
editing = nil
model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref
model.selectRange()
- focused = true
+ takeKeyboard()
}
private func selectColumn(_ col: Int) {
guard !model.dirty else { return }
editing = nil
model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref
model.selectRange()
- focused = true
+ takeKeyboard()
}
private func move(_ r: Int, _ c: Int) -> KeyPress.Result {
guard editing == nil else { return .ignored }
diff --git a/native/apple/Sources/SheetsKit/SheetKeySink.swift b/native/apple/Sources/SheetsKit/SheetKeySink.swift
new file mode 100644
index 0000000..7996e09
--- /dev/null
+++ b/native/apple/Sources/SheetsKit/SheetKeySink.swift
@@ -0,0 +1,208 @@
+#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.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<UIKeyboardHIDUsage> = []
+
+ 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 }
+
+ private func appearIdle() {
+ textColor = .clear
+ tintColor = .clear
+ backgroundColor = .clear
+ layer.borderWidth = 0
+ }
+ private func appearTyping() {
+ 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() }
+ }
+
+ /// 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, !value.isEmpty || markedTextRange != nil else {
+ if !model.mayWrite { reset() }
+ return
+ }
+ typing = true
+ appearTyping()
+ }
+ model.draft = value
+ }
+ /// 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<UIPress>, 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 { model.commit(moveRight: false) } else { editInPlace() }
+ case .keyboardTab:
+ if typing { model.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<UIPress>, 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<UIPress>, 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
diff --git a/native/apple/Sources/SheetsReview/Review.swift b/native/apple/Sources/SheetsReview/Review.swift
index d7b0044..fef122a 100644
--- a/native/apple/Sources/SheetsReview/Review.swift
+++ b/native/apple/Sources/SheetsReview/Review.swift
@@ -1,4 +1,7 @@
// Test-only executable; isolated credentials arrive through stdin, never argv.
+// Mac only. The iOS stub lets the package's tests build for a simulator
+// (xcodebuild test -scheme SheetsNative-Package), where KeySinkTests run.
+#if os(macOS)
import AppKit
import SwiftUI
import RastrilloApple
@@ -61,3 +64,6 @@ import SheetsKit
return false
}
}
+#else
+@main enum Review { static func main() {} }
+#endif
diff --git a/native/apple/Tests/SheetsKitTests/KeySinkTests.swift b/native/apple/Tests/SheetsKitTests/KeySinkTests.swift
new file mode 100644
index 0000000..0a2a4b9
--- /dev/null
+++ b/native/apple/Tests/SheetsKitTests/KeySinkTests.swift
@@ -0,0 +1,116 @@
+#if os(iOS)
+import UIKit
+import XCTest
+@testable import SheetsKit
+
+/// iPad and iPhone with a hardware keyboard (SheetKeySink). The text input
+/// calls below are the ones UIKit makes for a key press: insertText for a
+/// plain key, setMarkedText for a dead key or an input method's composition.
+final class KeySinkTests: XCTestCase {
+ @MainActor private func sink(_ raw: String = "") -> (SheetModel, SheetKeySink.SinkField, UIWindow) {
+ let model = fixtureModel(SheetServerFixture())
+ if !raw.isEmpty { model.cells[Coordinate(r: 0, c: 0)] = Cell(r: 0, c: 0, raw: raw, display: raw) }
+ model.select(Coordinate(r: 0, c: 0))
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 300))
+ let field = SheetKeySink.SinkField()
+ field.model = model
+ field.move = { r, c in
+ let p = model.selection.start
+ model.select(Coordinate(r: max(0, p.r + r), c: max(0, p.c + c)))
+ }
+ field.frame = CGRect(x: 48, y: 32, width: 110, height: 32)
+ window.addSubview(field)
+ window.makeKeyAndVisible()
+ field.selectionChanged(to: model.selection.start)
+ field.focusRequest = 1
+ field.claimKeyboard()
+ return (model, field, window)
+ }
+ private let none = NSRange(location: NSNotFound, length: 0)
+
+ @MainActor func testTheFieldHoldsTheKeyboardWithoutAnOnScreenOne() {
+ let (_, field, window) = sink()
+ defer { window.isHidden = true }
+ XCTAssertTrue(field.isFirstResponder)
+ XCTAssertNotNil(field.inputView, "no on-screen keyboard over the grid")
+ XCTAssertEqual(field.smartQuotesType, .no)
+ XCTAssertFalse(field.typing)
+ }
+
+ @MainActor func testFirstKeyReplacesTheCell() {
+ let (model, field, window) = sink("old")
+ defer { window.isHidden = true }
+ field.insertText("n")
+ XCTAssertTrue(field.typing)
+ XCTAssertEqual(model.draft, "n")
+ field.insertText("ew")
+ XCTAssertEqual(model.draft, "new")
+ XCTAssertTrue(field.handle(.keyboardReturnOrEnter))
+ XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "new")
+ XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 0))
+ field.selectionChanged(to: model.selection.start)
+ XCTAssertFalse(field.typing)
+ XCTAssertEqual(field.text, "")
+ }
+
+ @MainActor func testDeadKeyComposesFromTheFirstKey() {
+ let (model, field, window) = sink("old")
+ defer { window.isHidden = true }
+ field.setMarkedText("´", selectedRange: NSRange(location: 1, length: 0))
+ XCTAssertTrue(field.typing, "a dead key alone starts the edit")
+ field.insertText("é")
+ XCTAssertEqual(field.text, "é")
+ XCTAssertEqual(model.draft, "é")
+ }
+
+ @MainActor func testInputMethodComposesFromTheFirstKey() {
+ let (model, field, window) = sink()
+ defer { window.isHidden = true }
+ field.setMarkedText("k", selectedRange: NSRange(location: 1, length: 0))
+ field.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0))
+ // Return belongs to the input method while it composes.
+ XCTAssertNotNil(field.markedTextRange)
+ field.unmarkText()
+ XCTAssertEqual(model.draft, "か")
+ XCTAssertTrue(field.handle(.keyboardReturnOrEnter))
+ XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "か")
+ }
+
+ @MainActor func testReturnAndF2KeepTheCellEscapeCancels() {
+ let (model, field, window) = sink("old")
+ defer { window.isHidden = true }
+ XCTAssertTrue(field.handle(.keyboardReturnOrEnter))
+ XCTAssertTrue(field.typing)
+ XCTAssertEqual(field.text, "old")
+ field.insertText("!")
+ XCTAssertEqual(model.draft, "old!")
+ XCTAssertTrue(field.handle(.keyboardEscape))
+ XCTAssertFalse(field.typing)
+ XCTAssertEqual(model.draft, "old")
+ XCTAssertFalse(model.dirty)
+ XCTAssertTrue(field.handle(.keyboardF2))
+ XCTAssertEqual(field.text, "old")
+ }
+
+ @MainActor func testIdleKeysMoveTheSelection() {
+ let (model, field, window) = sink()
+ defer { window.isHidden = true }
+ XCTAssertTrue(field.handle(.keyboardDownArrow))
+ XCTAssertTrue(field.handle(.keyboardRightArrow))
+ XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 1))
+ XCTAssertTrue(field.handle(.keyboardTab, shift: true))
+ XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 0))
+ XCTAssertFalse(field.handle(.keyboardA), "letters are text, not commands")
+ }
+
+ @MainActor func testReadOnlySheetsDoNotStartAnEdit() {
+ let (model, field, window) = sink("old")
+ defer { window.isHidden = true }
+ model.page = SheetPage(Sheet: model.page!.Sheet, Rows: 6, Cols: 4, Truncated: false, MayWrite: false,
+ MayComment: false, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil)
+ field.insertText("x")
+ XCTAssertFalse(field.typing)
+ XCTAssertEqual(model.draft, "old")
+ }
+}
+#endif