oficina / sheets Public

Native: typing on a cell scrolled out of view brings it back, and never empties it unseen

Review #72 finding 2. The grid is lazy and nothing scrolled the selection
into view, so typing on a selected cell whose row had scrolled away set the
draft to empty and opened an edit with no field; after the type-ahead
expired the next click committed that empty draft over the cell.

Now the selection is scrolled into view when an edit starts and when the
arrows move it (SheetGridScroller: the row first if the lazy stack has not
built it, then the cell). The draft is emptied only at replay, once the
field exists and is about to receive the keys, and an expired type-ahead
closes the edit it opened.

Test: testTypingOnACellScrolledOutOfViewBringsItBack fails without this.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6e73b138b7bdc4bb4899914ef5f45481cc2cb28a parent 1ca9cbd
3 files changed, +73 −9
  • native/apple/Sources/SheetsKit/SheetGrid.swift +38 −8
  • native/apple/Sources/SheetsKit/SheetTypeAhead.swift +13 −1
  • native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift +22 −0
diff --git a/native/apple/Sources/SheetsKit/SheetGrid.swift b/native/apple/Sources/SheetsKit/SheetGrid.swift
index 4e0b30f..ed15841 100644
--- a/native/apple/Sources/SheetsKit/SheetGrid.swift
+++ b/native/apple/Sources/SheetsKit/SheetGrid.swift
@@ -7,6 +7,7 @@ struct SheetGrid: View {
@State private var savingResize = false
@GestureState private var draggingResize = false
@FocusState private var focused: Bool
+ @State private var scroller = SheetGridScroller()
#if os(macOS)
@State private var typeAhead = SheetTypeAhead()
#else
@@ -15,6 +16,7 @@ struct SheetGrid: View {
#endif
var beginEditing: () -> Void = {}
var body: some View {
+ ScrollViewReader { proxy in
ScrollView([.horizontal, .vertical]) {
LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
Section {
@@ -33,9 +35,11 @@ struct SheetGrid: View {
#endif
}
ForEach(0..<model.cols, id: \.self) { col in
- cell(row: row, col: col)
+ cell(row: row, col: col).id(Coordinate(r: row, c: col))
}
}
+ .onAppear { scroller.rows.insert(row) }
+ .onDisappear { scroller.rows.remove(row) }
}
} header: {
HStack(spacing: 0) {
@@ -66,6 +70,8 @@ struct SheetGrid: View {
.overlay(alignment: .topLeading) { keySink }
#endif
}.defaultScrollAnchor(.topLeading)
+ .onAppear { scroller.proxy = proxy }
+ }
.accessibilityLabel("Spreadsheet grid")
.focusable()
.focusEffectDisabled()
@@ -133,7 +139,9 @@ struct SheetGrid: View {
private func handleKey(_ event: NSEvent) -> Bool {
if typeAhead.awaitingField {
if typeAhead.expired || editing == nil {
+ // The field never came: nothing was changed, and nothing stays open.
typeAhead.cancel()
+ editing = nil
} else if event.modifierFlags.intersection([.command, .control]).isEmpty {
typeAhead.hold(event)
return true
@@ -152,11 +160,14 @@ struct SheetGrid: View {
return true
}
guard SheetTypeAhead.startsTyping(event) else { return false }
- // Typing replaces the cell; Return, F2 and double-click keep it.
- model.draft = ""
- typeAhead.begin(with: event)
- edit(model.selection.start)
- if editing == nil { typeAhead.cancel(); model.discard(); return false }
+ // Typing replaces the cell; Return, F2 and double-click keep it. The
+ // cell may be scrolled out of view, where the lazy grid has no field to
+ // open: bring it into view first.
+ let point = model.selection.start
+ scroller.reveal(point)
+ typeAhead.begin(with: event) { [model] in model.draft = "" }
+ edit(point)
+ if editing == nil { typeAhead.cancel(); return false }
return true
}
#endif
@@ -201,8 +212,9 @@ struct SheetGrid: View {
private func move(_ r: Int, _ c: Int) -> KeyPress.Result {
guard editing == nil else { return .ignored }
let p = model.selection.start
- model.select(
- Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c))))
+ let next = Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c)))
+ model.select(next)
+ scroller.reveal(next)
return .handled
}
private func width(_ col: Int) -> Double {
@@ -279,3 +291,21 @@ struct SheetResizePreview {
size = min(2000, max(16, (original + translation).rounded()))
}
}
+
+/// Keeps the selected cell on screen. The grid is lazy: a row scrolled out of
+/// view has no views, so there is no cell to edit until it is scrolled back.
+/// Not observed: rows coming and going must not re-render the grid.
+@MainActor final class SheetGridScroller {
+ var proxy: ScrollViewProxy?
+ var rows = Set<Int>()
+ func reveal(_ point: Coordinate) {
+ guard let proxy else { return }
+ if rows.contains(point.r) {
+ proxy.scrollTo(point)
+ } else {
+ // Bring the row into being, then the cell into view.
+ proxy.scrollTo(point.r)
+ DispatchQueue.main.async { proxy.scrollTo(point) }
+ }
+ }
+}
diff --git a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
index 2b95878..d6c18af 100644
--- a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
+++ b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
@@ -18,6 +18,10 @@ import SwiftUI
/// True from the keystroke that opened the field until it has them all.
private(set) var awaitingField = false
private var deadline: TimeInterval = 0
+ /// Empties the cell's draft. Run only once the field exists and is about to
+ /// receive the keys: a draft emptied for a field that never came would be
+ /// committed by the next click as an empty cell.
+ private var replace: (() -> Void)?
/// Whether a key, pressed on a selected cell, should start replacing it.
/// Anything that is not text (arrows, Return, Tab, Escape, Delete, function
@@ -32,7 +36,8 @@ import SwiftUI
return !CharacterSet.controlCharacters.contains(scalar)
}
- func begin(with event: NSEvent) {
+ func begin(with event: NSEvent, replace: @escaping () -> Void) {
+ self.replace = replace
held = [event]
awaitingField = true
deadline = ProcessInfo.processInfo.systemUptime + 1
@@ -43,6 +48,7 @@ import SwiftUI
func cancel() {
held = []
awaitingField = false
+ replace = nil
}
/// Called once the cell's field is first responder. The replay waits one
@@ -59,6 +65,12 @@ import SwiftUI
let events = held
held = []
awaitingField = false
+ if let replace {
+ self.replace = nil
+ replace()
+ field.stringValue = ""
+ field.currentEditor()?.string = ""
+ }
for (index, event) in events.enumerated() {
guard let editor = field.currentEditor() else {
// Return or Tab ended this edit; what followed starts the next one.
diff --git a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
index 83e2bc7..56f3c61 100644
--- a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
+++ b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
@@ -190,6 +190,28 @@ final class FirstKeystrokeTests: XCTestCase {
XCTAssertLessThan(median, 50)
}
+ /// Review #72, finding 2: a selected cell scrolled out of the lazy grid
+ /// has no field. Typing must bring it into view and type into it, and
+ /// must never empty the draft for a field that does not exist (the next
+ /// click would commit that empty draft over the cell).
+ @MainActor func testTypingOnACellScrolledOutOfViewBringsItBack() async throws {
+ let server = SheetServerFixture()
+ let model = fixtureModel(server, rows: 120, cols: 4)
+ let far = Coordinate(r: 100, c: 0)
+ model.cells[far] = Cell(r: 100, c: 0, raw: "keep me", display: "keep me")
+ let (window, host) = try await host(model)
+ defer { window.orderOut(nil) }
+ model.select(far)
+ key("x", code: 7, window: window)
+ XCTAssertEqual(model.draft, "keep me", "the draft changes only once the cell's field has the keys")
+ try await Task.sleep(for: .milliseconds(400))
+ XCTAssertFalse(editors(host).isEmpty, "the cell was scrolled into view and opened")
+ XCTAssertEqual(model.draft, "x")
+ key("\r", code: 36, window: window)
+ await model.settle()
+ XCTAssertEqual(server.value(100, 0), "x")
+ }
+
@MainActor func testWhichKeysStartTyping() {
func event(_ chars: String, _ ignoring: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, characters: chars, charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)!