oficina / sheets Public

Mac: the first key reaches its cell in a frame or two on any width of sheet

Review #72 delta, finding 6. On wide sheets the first keystroke waited for
the grid: 66 ms at 10 columns, 241 ms at 60 and 790 ms at 200 (median, test
host, main of this branch), against a 1 s type-ahead deadline after which
held keys were dropped. Measured and fixed in three steps:

- The cell editor lived inside SheetCell, and every cell read the grid's
  editing binding, so opening one re-rendered every cell. It now floats
  over the grid (SheetEditorOverlay) and the editing state is its own
  observable that no cell reads (40 / 147 / 460 ms).
- Opening the editor's view still cost a layout of every row's every
  column: rows and the column header are now LazyHStacks, so columns off
  screen are not built at all.
- The scroll-to-selection ran inside the keystroke and laid the grid out:
  it now runs only when the cell is not already in view, and after the
  keystroke (onScrollGeometryChange tracks what is visible).

After: 30 / 31 / 26 ms. The grid is also split into a stateful shell and
an Equatable layout, so the shell's focus changes rebuild nothing.

Held keys are never dropped: if the field has not come a second later the
typed text is handed to the formula bar (fieldNeverCame).

Tests: testFirstKeyReachesTheFieldWithinFramesOnWideSheets (10, 60, 200
columns, median under 50 ms; fails on the old code at 60 and 200),
testHeldKeysAreHandedOnIfTheFieldNeverComes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev af2f41a4ec9b7c70d34c445f637ff92b4ddd72d6 parent b6344bc
5 files changed, +339 −186
  • native/apple/Sources/SheetsKit/SheetCell.swift +57 −38
  • native/apple/Sources/SheetsKit/SheetGrid.swift +249 −144
  • native/apple/Sources/SheetsKit/SheetTable.swift +1 −1
  • native/apple/Sources/SheetsKit/SheetTypeAhead.swift +16 −2
  • native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift +16 −1
diff --git a/native/apple/Sources/SheetsKit/SheetCell.swift b/native/apple/Sources/SheetsKit/SheetCell.swift
index 2807a35..9eac511 100644
--- a/native/apple/Sources/SheetsKit/SheetCell.swift
+++ b/native/apple/Sources/SheetsKit/SheetCell.swift
@@ -3,15 +3,10 @@ import SwiftUI
struct SheetCell: View {
@Bindable var model: SheetModel
let point: Coordinate
- @Binding var editing: Coordinate?
var select: () -> Void
var beginEditing: () -> Void = {}
- var endEditing: () -> Void
var columnWidth: Double? = nil
var rowHeight: Double? = nil
- #if os(macOS)
- var typeAhead: SheetTypeAhead? = nil
- #endif
@Environment(\.colorScheme) private var scheme
private func width(_ col: Int) -> Double { columnWidth ?? model.sizes.cols?[String(col)] ?? 110 }
private func height(_ row: Int) -> Double { rowHeight ?? model.sizes.rows?[String(row)] ?? 32 }
@@ -21,34 +16,9 @@ struct SheetCell: View {
let alignment: Alignment =
style?.a == "center"
? .center : style?.a == "right" || (style?.a == nil && cell?.n == true) ? .trailing : .leading
- return Group {
- #if os(macOS)
- if editing == point {
- // Never disabled by a save: saves are optimistic (SheetWrites.swift),
- // so the field neither greys nor drops focus while one is in flight.
- SheetCellEditor(text: $model.draft, enabled: model.mayWrite,
- label: String(format: sheetsMacString("Edit %@"), point.ref),
- typeAhead: typeAhead,
- commit: { commit(right: $0) }, cancel: {
- model.discard(); endEditing()
- })
- .padding(.horizontal, 5)
- .frame(width: width(point.c), height: height(point.r))
- .background(fill(style))
- .overlay { Rectangle().strokeBorder(Color.accentColor, lineWidth: 2) }
- .accessibilityLabel(String(format: sheetsMacString("Edit %@"), point.ref))
- } else { display(cell, style: style, alignment: alignment) }
- #else
- display(cell, style: style, alignment: alignment)
- #endif
- }
- }
- private func commit(right: Bool) -> Bool {
- guard model.selection.start == point else { return false }
- model.commit(moveRight: right)
- guard !model.dirty else { return false }
- endEditing()
- return true
+ // The editor is not drawn here: it floats over the grid
+ // (SheetEditorOverlay), so opening one re-renders no cell.
+ return display(cell, style: style, alignment: alignment)
}
private func display(_ cell: Cell?, style: CellStyle?, alignment: Alignment) -> some View {
let failed = model.editState(point) == .failed
@@ -71,11 +41,7 @@ struct SheetCell: View {
.accessibilityValue(failed ? sheetsMacString("Not saved") : style?.lc == true ? "Imported colours have low contrast" : "")
.accessibilityAddTraits(model.selection.contains(point) ? .isSelected : [])
}
- private func fill(_ style: CellStyle?) -> Color {
- if let hex = style?.fx { return Color(hex: hex) }
- if let h = style?.fh, let c = style?.fc { return .oklch(scheme == .dark ? 0.30 : 0.92, c, h) }
- return Color.clear
- }
+ private func fill(_ style: CellStyle?) -> Color { cellFill(style, scheme: scheme) }
private func ink(_ style: CellStyle?) -> Color {
if let hex = style?.k { return Color(hex: hex) }
if let h = style?.kh, let c = style?.kc { return .oklch(scheme == .dark ? 0.80 : 0.42, c, h) }
@@ -115,3 +81,56 @@ struct SheetNotSavedMark: View {
}.fill(Color.red).frame(width: 8, height: 8).accessibilityHidden(true)
}
}
+
+func cellFill(_ style: CellStyle?, scheme: ColorScheme) -> Color {
+ if let hex = style?.fx { return Color(hex: hex) }
+ if let h = style?.fh, let c = style?.fc { return .oklch(scheme == .dark ? 0.30 : 0.92, c, h) }
+ return Color.clear
+}
+
+/// Which cell has an open editor. Observed only by the editor overlay and the
+/// selection observer, never by the grid or its cells: opening an editor
+/// re-rendered every cell when this lived in the grid, which on a 200-column
+/// sheet kept the first keystroke from its field for most of a second.
+@MainActor @Observable final class SheetEditingState {
+ var cell: Coordinate?
+}
+
+#if os(macOS)
+/// The cell editor, floating over the grid at the edited cell.
+struct SheetEditorOverlay: View {
+ @Bindable var model: SheetModel
+ let state: SheetEditingState
+ let typeAhead: SheetTypeAhead
+ let frame: (Coordinate) -> CGRect
+ let end: () -> Void
+ @Environment(\.colorScheme) private var scheme
+ var body: some View {
+ if let point = state.cell {
+ let box = frame(point)
+ let style = model.styles[model.displayCell(point)?.f ?? ""]
+ // Never disabled by a save: saves are optimistic (SheetWrites.swift),
+ // so the field neither greys nor drops focus while one is in flight.
+ SheetCellEditor(text: $model.draft, enabled: model.mayWrite,
+ label: String(format: sheetsMacString("Edit %@"), point.ref),
+ typeAhead: typeAhead,
+ commit: { commit(point, right: $0) }, cancel: { model.discard(); end() })
+ .padding(.horizontal, 5)
+ .frame(width: box.width, height: box.height)
+ .background(cellFill(style, scheme: scheme))
+ .background(.background)
+ .overlay { Rectangle().strokeBorder(Color.accentColor, lineWidth: 2) }
+ .accessibilityLabel(String(format: sheetsMacString("Edit %@"), point.ref))
+ .offset(x: box.minX, y: box.minY)
+ .id(point)
+ }
+ }
+ private func commit(_ point: Coordinate, right: Bool) -> Bool {
+ guard model.selection.start == point else { return false }
+ model.commit(moveRight: right)
+ guard !model.dirty else { return false }
+ end()
+ return true
+ }
+}
+#endif
diff --git a/native/apple/Sources/SheetsKit/SheetGrid.swift b/native/apple/Sources/SheetsKit/SheetGrid.swift
index ed15841..a460842 100644
--- a/native/apple/Sources/SheetsKit/SheetGrid.swift
+++ b/native/apple/Sources/SheetsKit/SheetGrid.swift
@@ -1,11 +1,18 @@
import SwiftUI
+/// The grid: state and behaviour here, layout in `SheetGridContent`.
+///
+/// The split is for speed. Anything this view owns that changes (keyboard
+/// focus above all, which moves every time a cell's editor opens or closes)
+/// re-runs this body; if that rebuilt the rows, opening an editor on a
+/// 200-column sheet cost most of a second before the first key reached it.
+/// The content is Equatable on what it actually draws from, so a focus change
+/// re-renders nothing but this thin shell.
struct SheetGrid: View {
@Bindable var model: SheetModel
- @State private var editing: Coordinate?
+ @State private var editState = SheetEditingState()
@State private var resizing: SheetResizePreview?
@State private var savingResize = false
- @GestureState private var draggingResize = false
@FocusState private var focused: Bool
@State private var scroller = SheetGridScroller()
#if os(macOS)
@@ -16,83 +23,25 @@ struct SheetGrid: View {
#endif
var beginEditing: () -> Void = {}
var body: some View {
- ScrollViewReader { proxy in
- ScrollView([.horizontal, .vertical]) {
- LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
- Section {
- ForEach(0..<model.rows, id: \.self) { row in
- HStack(spacing: 0) {
- ZStack(alignment: .bottom) {
- Button { selectRow(row) } label: {
- Text(String(row + 1)).frame(width: 48, height: height(row)).background(.quaternary)
- }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1))
- #if os(macOS)
- resizeHandle(axis: "row", index: row).frame(width: 48, height: 8)
- #else
- Color.clear.frame(width: 48, height: 8)
- .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row))
- .accessibilityHidden(true)
- #endif
- }
- ForEach(0..<model.cols, id: \.self) { col in
- 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) {
- Text("").frame(width: 48, height: 32)
- ForEach(0..<model.cols, id: \.self) { col in
- ZStack(alignment: .trailing) {
- Button { selectColumn(col) } label: {
- Text(Coordinate(r: 0, c: col).ref.dropLast())
- .frame(width: width(col), height: 32)
- .contentShape(.rect)
- }.buttonStyle(.plain)
- .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast())))
- #if os(macOS)
- resizeHandle(axis: "col", index: col).frame(width: 8, height: 32)
- .help(sheetsMacString("Double-click to fit column to contents"))
- #else
- Color.clear.frame(width: 8, height: 32)
- #endif
- }
- #if os(macOS)
- .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } }
- #endif
- }
- }.background(.regularMaterial)
- }
- }
- #if os(iOS)
- .overlay(alignment: .topLeading) { keySink }
- #endif
- }.defaultScrollAnchor(.topLeading)
- .onAppear { scroller.proxy = proxy }
- }
+ content.equatable()
.accessibilityLabel("Spreadsheet grid")
.focusable()
.focusEffectDisabled()
.focused($focused)
- .background { SheetSelectionObserver(model: model, editing: $editing) }
+ .background { SheetSelectionObserver(model: model, state: editState) }
.onChange(of: focused) { _, value in model.gridFocused = value }
.onDisappear { model.gridFocused = false; if !savingResize { resizing = nil } }
- .onChange(of: draggingResize) { _, active in
- if !active, !savingResize { resizing = nil }
- }
.onKeyPress(.leftArrow) { move(0, -1) }
.onKeyPress(.rightArrow) { move(0, 1) }
.onKeyPress(.upArrow) { move(-1, 0) }
.onKeyPress(.downArrow) { move(1, 0) }
.onKeyPress(.delete) {
- guard editing == nil, model.mayWrite else { return .ignored }
+ guard editState.cell == nil, model.mayWrite else { return .ignored }
Task { await model.clear() }
return .handled
}
.onKeyPress(.return) {
- guard editing == nil, model.mayWrite else { return .ignored }
+ guard editState.cell == nil, model.mayWrite else { return .ignored }
edit(model.selection.start)
return .handled
}
@@ -102,46 +51,38 @@ struct SheetGrid: View {
.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)
+ private var content: SheetGridContent {
+ var actions = SheetGridActions(
+ select: select, edit: edit, selectRow: selectRow, selectColumn: selectColumn,
+ endEditing: endEditing, move: { r, c in _ = move(r, c) },
+ canResize: { [model] in model.mayWrite && !model.busy && !model.dirty && !savingResize },
+ resizeChange: resizeChange, resizeFinish: finishResize,
+ resizeCancel: { if !savingResize { resizing = nil } })
+ actions.beginEditing = beginEditing
#if os(macOS)
- return SheetCell(
- model: model, point: point, editing: $editing,
- select: { select(point) },
- beginEditing: { edit(point) },
- endEditing: { editing = nil; typeAhead.cancel(); focused = true },
- columnWidth: width(col), rowHeight: height(row), typeAhead: typeAhead)
+ return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing,
+ typeAhead: typeAhead, actions: actions)
#else
- return SheetCell(
- model: model, point: point, editing: $editing,
- select: { select(point) },
- beginEditing: { edit(point) },
- endEditing: { editing = nil; takeKeyboard() },
- columnWidth: width(col), rowHeight: height(row))
+ return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing,
+ keyboardRequest: keyboardRequest, actions: actions)
#endif
}
+ private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) }
+ private func endEditing() {
+ editState.cell = nil
+ #if os(macOS)
+ typeAhead.cancel()
+ #endif
+ takeKeyboard()
+ }
#if os(macOS)
/// Every key event in this window, before SwiftUI sees it (SheetKeyMonitor).
/// Typing on a selected cell opens its field and hands the keystroke to it
/// whole, so a dead key or an input method composes from the first key.
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
+ if typeAhead.expired || editState.cell == nil {
+ fieldNeverCame()
} else if event.modifierFlags.intersection([.command, .control]).isEmpty {
typeAhead.hold(event)
return true
@@ -151,7 +92,7 @@ struct SheetGrid: View {
}
// The grid has the keyboard, or nothing does: a cell's field has just let
// go of it (SheetCellEditor) and SwiftUI has not handed it back yet.
- guard editing == nil, model.mayWrite, !model.dirty, let window = event.window,
+ guard editState.cell == nil, model.mayWrite, !model.dirty, let window = event.window,
model.gridFocused || window.firstResponder === window,
!(window.firstResponder is NSText)
else { return false }
@@ -161,20 +102,29 @@ struct SheetGrid: View {
}
guard SheetTypeAhead.startsTyping(event) else { 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.
+ // cell may be scrolled out of view: bring it into view too.
let point = model.selection.start
- scroller.reveal(point)
- typeAhead.begin(with: event) { [model] in model.draft = "" }
+ scroller.reveal(point, at: metrics.frame(point))
+ typeAhead.begin(with: event, replace: { [model] in model.draft = "" }, expired: fieldNeverCame)
edit(point)
- if editing == nil { typeAhead.cancel(); return false }
+ if editState.cell == nil { typeAhead.cancel(); return false }
return true
}
+ /// The cell's field did not come up in time. Nothing typed is dropped: the
+ /// held text goes to the formula bar, where the edit carries on.
+ private func fieldNeverCame() {
+ let text = typeAhead.heldText
+ typeAhead.cancel()
+ editState.cell = nil
+ guard !text.isEmpty else { return }
+ model.draft = text
+ beginEditing()
+ }
#endif
private func edit(_ point: Coordinate) {
guard model.mayWrite else { return }
#if os(macOS)
- editing = point
+ editState.cell = point
#else
beginEditing()
#endif
@@ -184,7 +134,7 @@ struct SheetGrid: View {
// spreadsheet does; the save itself no longer holds anything up.
if model.dirty, point != model.selection.start { model.commit(moveRight: nil) }
guard !model.dirty else { return }
- if editing != point { editing = nil }
+ if editState.cell != point { editState.cell = nil }
model.select(point)
takeKeyboard()
}
@@ -197,50 +147,34 @@ struct SheetGrid: View {
}
private func selectRow(_ row: Int) {
guard !model.dirty else { return }
- editing = nil
+ editState.cell = nil
model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref
model.selectRange()
takeKeyboard()
}
private func selectColumn(_ col: Int) {
guard !model.dirty else { return }
- editing = nil
+ editState.cell = nil
model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref
model.selectRange()
takeKeyboard()
}
private func move(_ r: Int, _ c: Int) -> KeyPress.Result {
- guard editing == nil else { return .ignored }
+ guard editState.cell == nil else { return .ignored }
let p = model.selection.start
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)
+ scroller.reveal(next, at: metrics.frame(next))
return .handled
}
- private func width(_ col: Int) -> Double {
- if let resizing, resizing.axis == "col", resizing.index == col { return resizing.size }
- return model.sizes.cols?[String(col)] ?? 110
- }
- private func height(_ row: Int) -> Double {
- if let resizing, resizing.axis == "row", resizing.index == row { return resizing.size }
- return model.sizes.rows?[String(row)] ?? 32
- }
- #if os(macOS)
- private func resizeHandle(axis: String, index: Int) -> some View {
- SheetResizeHandle(vertical: axis == "row",
- canBegin: { model.mayWrite && !model.busy && !model.dirty && !savingResize },
- change: { translation in
- if resizing == nil {
- resizing = SheetResizePreview(axis: axis, index: index,
- original: axis == "col" ? width(index) : height(index))
- }
- resizing?.update(translation: translation)
- }, finish: { finishResize(axis: axis, index: index) },
- cancel: { if !savingResize { resizing = nil } },
- fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil)
-
+ private func resizeChange(axis: String, index: Int, translation: Double) {
+ if resizing == nil {
+ resizing = SheetResizePreview(axis: axis, index: index,
+ original: axis == "col" ? metrics.width(index) : metrics.height(index))
+ }
+ guard resizing?.axis == axis, resizing?.index == index else { return }
+ resizing?.update(translation: translation)
}
- #endif
private func finishResize(axis: String, index: Int) {
guard let preview = resizing, preview.axis == axis, preview.index == index else { return }
savingResize = true
@@ -250,19 +184,179 @@ struct SheetGrid: View {
savingResize = false
}
}
+}
+
+/// What the grid's layout may ask of the grid.
+struct SheetGridActions {
+ var select: (Coordinate) -> Void
+ var edit: (Coordinate) -> Void
+ var selectRow: (Int) -> Void
+ var selectColumn: (Int) -> Void
+ var endEditing: () -> Void
+ var move: (Int, Int) -> Void
+ var canResize: () -> Bool
+ var resizeChange: (_ axis: String, _ index: Int, _ translation: Double) -> Void
+ var resizeFinish: (_ axis: String, _ index: Int) -> Void
+ var resizeCancel: () -> Void
+ var beginEditing: () -> Void = {}
+}
+
+/// Column widths and row heights, with a resize in progress applied.
+struct SheetGridMetrics {
+ let sizes: Sizes
+ let resizing: SheetResizePreview?
+ func width(_ col: Int) -> Double {
+ if let resizing, resizing.axis == "col", resizing.index == col { return resizing.size }
+ return sizes.cols?[String(col)] ?? 110
+ }
+ func height(_ row: Int) -> Double {
+ if let resizing, resizing.axis == "row", resizing.index == row { return resizing.size }
+ return sizes.rows?[String(row)] ?? 32
+ }
+ /// Where a cell sits in the grid's content: after the row header and the
+ /// pinned column header.
+ func frame(_ point: Coordinate) -> CGRect {
+ CGRect(
+ x: 48 + (0..<point.c).reduce(0) { $0 + width($1) },
+ y: 32 + (0..<point.r).reduce(0) { $0 + height($1) },
+ width: width(point.c), height: height(point.r))
+ }
+}
+
+/// The grid's rows, headers and floating editor. Equatable on what it draws
+/// from (the model's observed properties are tracked by SwiftUI as usual), so
+/// the grid's own focus and key state never rebuild it (see SheetGrid).
+struct SheetGridContent: View, Equatable {
+ @Bindable var model: SheetModel
+ let editState: SheetEditingState
+ let scroller: SheetGridScroller
+ let resizing: SheetResizePreview?
+ #if os(macOS)
+ let typeAhead: SheetTypeAhead
+ #else
+ let keyboardRequest: Int
+ #endif
+ let actions: SheetGridActions
+ @GestureState private var draggingResize = false
+
+ nonisolated static func == (a: Self, b: Self) -> Bool {
+ MainActor.assumeIsolated {
+ #if os(macOS)
+ let same = a.typeAhead === b.typeAhead
+ #else
+ let same = a.keyboardRequest == b.keyboardRequest
+ #endif
+ return same && a.model === b.model && a.editState === b.editState && a.scroller === b.scroller
+ && a.resizing == b.resizing
+ }
+ }
+ private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) }
+ private func width(_ col: Int) -> Double { metrics.width(col) }
+ private func height(_ row: Int) -> Double { metrics.height(row) }
+
+ var body: some View {
+ ScrollViewReader { proxy in
+ ScrollView([.horizontal, .vertical]) {
+ LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
+ Section {
+ ForEach(0..<model.rows, id: \.self) { row in
+ LazyHStack(spacing: 0) {
+ ZStack(alignment: .bottom) {
+ Button { actions.selectRow(row) } label: {
+ Text(String(row + 1)).frame(width: 48, height: height(row)).background(.quaternary)
+ }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1))
+ #if os(macOS)
+ resizeHandle(axis: "row", index: row).frame(width: 48, height: 8)
+ #else
+ Color.clear.frame(width: 48, height: 8)
+ .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row))
+ .accessibilityHidden(true)
+ #endif
+ }
+ ForEach(0..<model.cols, id: \.self) { col in
+ cell(row: row, col: col).id(Coordinate(r: row, c: col))
+ }
+ }
+ .onAppear { scroller.rows.insert(row) }
+ .onDisappear { scroller.rows.remove(row) }
+ }
+ } header: {
+ LazyHStack(spacing: 0) {
+ Text("").frame(width: 48, height: 32)
+ ForEach(0..<model.cols, id: \.self) { col in
+ ZStack(alignment: .trailing) {
+ Button { actions.selectColumn(col) } label: {
+ Text(Coordinate(r: 0, c: col).ref.dropLast())
+ .frame(width: width(col), height: 32)
+ .contentShape(.rect)
+ }.buttonStyle(.plain)
+ .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast())))
+ #if os(macOS)
+ resizeHandle(axis: "col", index: col).frame(width: 8, height: 32)
+ .help(sheetsMacString("Double-click to fit column to contents"))
+ #else
+ Color.clear.frame(width: 8, height: 32)
+ #endif
+ }
+ #if os(macOS)
+ .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } }
+ #endif
+ }
+ }.background(.regularMaterial)
+ }
+ }
+ #if os(iOS)
+ .overlay(alignment: .topLeading) { keySink }
+ #else
+ .overlay(alignment: .topLeading) {
+ SheetEditorOverlay(model: model, state: editState, typeAhead: typeAhead,
+ frame: metrics.frame, end: actions.endEditing)
+ }
+ #endif
+ }.defaultScrollAnchor(.topLeading)
+ .onAppear { scroller.proxy = proxy }
+ .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in scroller.visible = rect }
+ }
+ .onChange(of: draggingResize) { _, active in
+ if !active { actions.resizeCancel() }
+ }
+ }
+ #if os(iOS)
+ /// The keyboard's place on the selected cell (SheetKeySink).
+ private var keySink: some View {
+ let box = metrics.frame(model.selection.start)
+ return SheetKeySink(model: model, focusRequest: keyboardRequest, move: actions.move)
+ .frame(width: box.width, height: box.height)
+ .offset(x: box.minX, y: box.minY)
+ .allowsHitTesting(false)
+ }
+ #endif
+ private func cell(row: Int, col: Int) -> some View {
+ let point = Coordinate(r: row, c: col)
+ return SheetCell(
+ model: model, point: point,
+ select: { actions.select(point) },
+ beginEditing: { actions.edit(point) },
+ columnWidth: width(col), rowHeight: height(row))
+ }
+ #if os(macOS)
+ private func resizeHandle(axis: String, index: Int) -> some View {
+ SheetResizeHandle(vertical: axis == "row",
+ canBegin: actions.canResize,
+ change: { translation in actions.resizeChange(axis, index, translation) },
+ finish: { actions.resizeFinish(axis, index) },
+ cancel: actions.resizeCancel,
+ fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil)
+ }
+ #endif
private func resizeGesture(axis: String, index: Int) -> some Gesture {
DragGesture(minimumDistance: 2, coordinateSpace: .global)
.updating($draggingResize) { _, active, _ in active = true }
.onChanged { value in
- guard model.mayWrite, !model.busy, !model.dirty else { return }
- if resizing == nil {
- resizing = SheetResizePreview(axis: axis, index: index,
- original: axis == "col" ? width(index) : height(index))
- }
- guard resizing?.axis == axis, resizing?.index == index else { return }
- resizing?.update(translation: axis == "col" ? value.translation.width : value.translation.height)
+ guard actions.canResize() else { return }
+ actions.resizeChange(axis, index, axis == "col" ? value.translation.width : value.translation.height)
}
- .onEnded { _ in finishResize(axis: axis, index: index) }
+ .onEnded { _ in actions.resizeFinish(axis, index) }
}
}
@@ -270,16 +364,16 @@ struct SheetGrid: View {
/// LazyVStack and every row's view construction.
private struct SheetSelectionObserver: View {
let model: SheetModel
- @Binding var editing: Coordinate?
+ let state: SheetEditingState
var body: some View {
Color.clear.frame(width: 0, height: 0)
.onChange(of: model.selection.start) { _, point in
- if editing != point { editing = nil }
+ if state.cell != point { state.cell = nil }
}
}
}
-struct SheetResizePreview {
+struct SheetResizePreview: Equatable {
let axis: String
let index: Int
let original: Double
@@ -292,13 +386,24 @@ struct SheetResizePreview {
}
}
-/// 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.
+/// Keeps the selected cell on screen. Not observed: scrolling and 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) {
+ /// The scroll view's visible rect, in the content's coordinates.
+ var visible: CGRect?
+ /// Scrolls only when the cell is not already in view (under the pinned
+ /// column header counts as out of view), and never inside the keystroke:
+ /// a scroll lays the grid out, and the first key must not wait for that.
+ func reveal(_ point: Coordinate, at frame: CGRect) {
+ if let visible {
+ let clear = CGRect(x: visible.minX, y: visible.minY + 32, width: visible.width, height: visible.height - 32)
+ if clear.contains(frame) { return }
+ }
+ DispatchQueue.main.async { [weak self] in self?.scroll(to: point) }
+ }
+ private func scroll(to point: Coordinate) {
guard let proxy else { return }
if rows.contains(point.r) {
proxy.scrollTo(point)
diff --git a/native/apple/Sources/SheetsKit/SheetTable.swift b/native/apple/Sources/SheetsKit/SheetTable.swift
index 02ae0d1..e1f759c 100644
--- a/native/apple/Sources/SheetsKit/SheetTable.swift
+++ b/native/apple/Sources/SheetsKit/SheetTable.swift
@@ -22,7 +22,7 @@ struct SheetTable: View {
HStack(spacing: 0) {
Text(String(row.Number)).frame(width: 48)
ForEach(row.Cells, id: \.C) { cell in
- SheetCell(model: model, point: Coordinate(r: cell.R, c: cell.C), editing: .constant(nil), select: { model.select(Coordinate(r: cell.R, c: cell.C)) }, endEditing: {})
+ SheetCell(model: model, point: Coordinate(r: cell.R, c: cell.C), select: { model.select(Coordinate(r: cell.R, c: cell.C)) })
}
}
}
diff --git a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
index 2c1ad84..b561415 100644
--- a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
+++ b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift
@@ -40,14 +40,28 @@ import SwiftUI
return !CharacterSet.controlCharacters.contains(scalar)
}
- func begin(with event: NSEvent, replace: @escaping () -> Void) {
+ private var generation = 0
+ /// `expired` runs if the field has not come a second later; the grid then
+ /// hands what was typed to the formula bar rather than drop it.
+ func begin(with event: NSEvent, replace: @escaping () -> Void, expired: @escaping () -> Void) {
self.replace = replace
held = [event]
awaitingField = true
deadline = ProcessInfo.processInfo.systemUptime + 1
+ generation += 1
+ let current = generation
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
+ guard let self, self.awaitingField, self.generation == current else { return }
+ expired()
+ }
+ }
+ /// The text the held keys carry, for the formula bar if the field never
+ /// comes. A dead key's composition is lost there; its base letter is not.
+ var heldText: String {
+ held.compactMap(\.characters).joined().filter { !$0.unicodeScalars.contains { CharacterSet.controlCharacters.contains($0) } }
}
func hold(_ event: NSEvent) { held.append(event) }
- /// A field that never came (the edit was refused) must not swallow keys.
+ /// A field that never came must not swallow keys.
var expired: Bool { awaitingField && ProcessInfo.processInfo.systemUptime > deadline }
func cancel() {
held = []
diff --git a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
index 0777420..0c62a6e 100644
--- a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
+++ b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
@@ -277,11 +277,26 @@ final class FirstKeystrokeTests: XCTestCase {
}
let median = samples.sorted()[samples.count / 2]
report.append("\(cols) cols: median \(String(format: "%.1f", median)) ms \(samples.map { String(format: "%.0f", $0) })")
- XCTAssertLessThan(median, 100, "\(cols) columns")
+ XCTAssertLessThan(median, 50, "\(cols) columns: one or two frames, whatever the width")
}
print("MEASURE first key to glyph: " + report.joined(separator: "; "))
}
+ /// Held keys are never dropped: if the field does not come, what was typed
+ /// is handed on (to the formula bar) rather than discarded.
+ @MainActor func testHeldKeysAreHandedOnIfTheFieldNeverComes() async throws {
+ func event(_ text: String, _ code: UInt16) -> NSEvent {
+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!
+ }
+ let typeAhead = SheetTypeAhead()
+ var handedOn: String?
+ typeAhead.begin(with: event("x", 7), replace: {}, expired: { handedOn = typeAhead.heldText })
+ typeAhead.hold(event("y", 16))
+ typeAhead.hold(event("\r", 36))
+ try await Task.sleep(for: .milliseconds(1300))
+ XCTAssertEqual(handedOn, "xy", "the typed text, without the Return")
+ }
+
@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)!