oficina / sheets Public

Mac: the grid is laid out from exact geometry; columns and rows windowed by hand

Review #72 delta 2, finding 1 (and the pre-existing scroll notes, 6). The
LazyHStack added for speed estimated the widths of columns it had not
built, while the editor, clicks, scrolling and the iOS key field used the
exact widths: content 19957 or 21967 points wide instead of 22048, a click
after scrolling right selected a cell 19 to 32 columns away, the editor
could open off screen, and mixed widths opened pre-scrolled.

A plain HStack is exact but too slow (first key to glyph 34 / 125 / 389 ms
at 10 / 60 / 200 columns). So the columns and rows that exist as views are
windowed by hand from SheetGridMetrics (prefix sums of the exact widths
and heights): a leading and a trailing spacer stand in for what is off
screen, the visible range comes from the scroll geometry and is widened to
blocks of 4 columns and 8 rows, so scrolling re-renders only when a block
edge is crossed. Content size is exact; first key to glyph stays flat at
35 / 37 / 38 ms (median of five after a warm-up, test host).

Scrolling to a cell is now by position from the same geometry (least
scroll, clear of the pinned header and of legacy scroll bars), so a far
cell is revealed where it is, not at the grid's right edge, and custom row
heights no longer drift after a jump.

Tests (GridGeometryTests): exact content size and no pre-scroll with mixed
widths; scroll right with the wheel, click where the geometry says a cell
is, and type: the right cell is selected and the editor sits in it, on
screen; typing on far cells scrolls exactly to them; the least-scroll rule.
The first-key test takes six samples and drops a warm-up.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 61f3bce45d475d4d46daed572ec18a6025961579 parent 186d734
4 files changed, +327 −86
  • native/apple/Sources/SheetsKit/SheetCell.swift +1 −0
  • native/apple/Sources/SheetsKit/SheetGrid.swift +185 −85
  • native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift +3 −1
  • native/apple/Tests/SheetsKitTests/GridGeometryTests.swift +138 −0
diff --git a/native/apple/Sources/SheetsKit/SheetCell.swift b/native/apple/Sources/SheetsKit/SheetCell.swift
index 9eac511..63683d7 100644
--- a/native/apple/Sources/SheetsKit/SheetCell.swift
+++ b/native/apple/Sources/SheetsKit/SheetCell.swift
@@ -101,6 +101,7 @@ func cellFill(_ style: CellStyle?, scheme: ColorScheme) -> Color {
struct SheetEditorOverlay: View {
@Bindable var model: SheetModel
let state: SheetEditingState
+ let window: SheetGridWindow
let typeAhead: SheetTypeAhead
let frame: (Coordinate) -> CGRect
let end: () -> Void
diff --git a/native/apple/Sources/SheetsKit/SheetGrid.swift b/native/apple/Sources/SheetsKit/SheetGrid.swift
index c694df9..75ca358 100644
--- a/native/apple/Sources/SheetsKit/SheetGrid.swift
+++ b/native/apple/Sources/SheetsKit/SheetGrid.swift
@@ -15,6 +15,7 @@ struct SheetGrid: View {
@State private var savingResize = false
@FocusState private var focused: Bool
@State private var scroller = SheetGridScroller()
+ @State private var gridWindow = SheetGridWindow()
#if os(macOS)
@State private var typeAhead = SheetTypeAhead()
#else
@@ -60,14 +61,16 @@ struct SheetGrid: View {
resizeCancel: { if !savingResize { resizing = nil } })
actions.beginEditing = beginEditing
#if os(macOS)
- return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing,
+ return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing,
typeAhead: typeAhead, actions: actions)
#else
- return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing,
+ return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing,
keyboardRequest: keyboardRequest, actions: actions)
#endif
}
- private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) }
+ private var metrics: SheetGridMetrics {
+ SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols)
+ }
private func endEditing() {
editState.cell = nil
#if os(macOS)
@@ -202,26 +205,87 @@ struct SheetGridActions {
var beginEditing: () -> Void = {}
}
-/// Column widths and row heights, with a resize in progress applied.
+/// Column widths and row heights, with a resize in progress applied: the one
+/// geometry the grid is laid out from, and that the editor, the keyboard field,
+/// scrolling and the windowing below all read. Nothing is estimated.
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
+ let rows: Int
+ let cols: Int
+ /// Leading edge of each column (and the total width last), from 0.
+ let colStarts: [Double]
+ let rowStarts: [Double]
+ init(sizes: Sizes, resizing: SheetResizePreview?, rows: Int, cols: Int) {
+ self.sizes = sizes; self.resizing = resizing; self.rows = rows; self.cols = cols
+ func width(_ c: Int) -> Double {
+ if let resizing, resizing.axis == "col", resizing.index == c { return resizing.size }
+ return sizes.cols?[String(c)] ?? 110
+ }
+ func height(_ r: Int) -> Double {
+ if let resizing, resizing.axis == "row", resizing.index == r { return resizing.size }
+ return sizes.rows?[String(r)] ?? 32
+ }
+ var x: [Double] = [0]; x.reserveCapacity(cols + 1)
+ for c in 0..<cols { x.append(x[c] + width(c)) }
+ var y: [Double] = [0]; y.reserveCapacity(rows + 1)
+ for r in 0..<rows { y.append(y[r] + height(r)) }
+ colStarts = x; rowStarts = y
}
+ static let rowHeader = 48.0
+ static let colHeader = 32.0
+ func width(_ col: Int) -> Double { col < cols ? colStarts[col + 1] - colStarts[col] : 110 }
+ func height(_ row: Int) -> Double { row < rows ? rowStarts[row + 1] - rowStarts[row] : 32 }
+ var cellsWidth: Double { colStarts[cols] }
+ var cellsHeight: Double { rowStarts[rows] }
/// 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) },
+ let c = min(point.c, cols), r = min(point.r, rows)
+ return CGRect(x: Self.rowHeader + colStarts[c], y: Self.colHeader + rowStarts[r],
width: width(point.c), height: height(point.r))
}
+ /// The columns and rows a visible rect (content coordinates) touches,
+ /// widened to whole blocks (4 columns, 8 rows), so scrolling re-renders the
+ /// grid only every few columns or rows, never every pixel. Blocks are kept
+ /// small: every cell built is a cell opening an editor has to lay out.
+ func window(for visible: CGRect) -> (cols: Range<Int>, rows: Range<Int>) {
+ func span(_ starts: [Double], _ count: Int, _ lo: Double, _ hi: Double, block: Int) -> Range<Int> {
+ guard count > 0 else { return 0..<0 }
+ // First index whose far edge is past lo; last whose near edge is before hi.
+ var first = 0, low = 0, high = count
+ while low < high { let mid = (low + high) / 2; if starts[mid + 1] <= lo { low = mid + 1 } else { high = mid } }
+ first = low
+ low = first; high = count
+ while low < high { let mid = (low + high) / 2; if starts[mid] < hi { low = mid + 1 } else { high = mid } }
+ let last = max(first, low - 1)
+ let start = first / block * block
+ let end = min(count, (last / block + 1) * block)
+ return start..<max(start, end)
+ }
+ return (
+ span(colStarts, cols, visible.minX - Self.rowHeader, visible.maxX - Self.rowHeader, block: 4),
+ span(rowStarts, rows, visible.minY - Self.colHeader, visible.maxY - Self.colHeader, block: 8))
+ }
+}
+
+/// Which columns and rows exist as views. Only the grid's layout reads the
+/// ranges, and they change only when scrolling crosses a block.
+@MainActor @Observable final class SheetGridWindow {
+ var cols: Range<Int> = 0..<8
+ var rows: Range<Int> = 0..<24
+ /// The top of the area below the pinned column header, in content
+ /// coordinates: the editor is clipped to it. Read only while editing.
+ var clipTop: Double = SheetGridMetrics.colHeader
+ @ObservationIgnored var visible = CGRect(x: 0, y: 0, width: 800, height: 700)
+ func update(_ visible: CGRect, _ metrics: SheetGridMetrics) {
+ self.visible = visible
+ let next = metrics.window(for: visible)
+ if next.cols != cols { cols = next.cols }
+ if next.rows != rows { rows = next.rows }
+ let top = visible.minY + SheetGridMetrics.colHeader
+ if top != clipTop { clipTop = top }
+ }
}
/// The grid's rows, headers and floating editor. Equatable on what it draws
@@ -231,6 +295,7 @@ struct SheetGridContent: View, Equatable {
@Bindable var model: SheetModel
let editState: SheetEditingState
let scroller: SheetGridScroller
+ let window: SheetGridWindow
let resizing: SheetResizePreview?
#if os(macOS)
let typeAhead: SheetTypeAhead
@@ -248,61 +313,45 @@ struct SheetGridContent: View, Equatable {
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
+ && a.window === b.window && 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) }
+ private var metrics: SheetGridMetrics {
+ SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols)
+ }
+ @State private var position = ScrollPosition()
+ // Columns and rows are windowed by hand from the exact metrics: a leading
+ // and a trailing spacer stand in for what is off screen. (A LazyHStack
+ // estimated the widths of columns it had not built, so its layout and the
+ // exact geometry the editor and clicks use disagreed by whole columns.)
var body: some View {
- ScrollViewReader { proxy in
+ let m = metrics
+ let cols = Array(window.cols.clamped(to: 0..<m.cols))
+ let rows = Array(window.rows.clamped(to: 0..<m.rows))
+ let lead = m.colStarts[cols.first ?? 0]
+ let trail = m.cellsWidth - m.colStarts[cols.last.map { $0 + 1 } ?? 0]
ScrollView([.horizontal, .vertical]) {
- LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
+ LazyVStack(alignment: .leading, 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))
+ VStack(alignment: .leading, spacing: 0) {
+ Color.clear.frame(width: 1, height: m.rowStarts[rows.first ?? 0])
+ ForEach(rows, id: \.self) { row in
+ HStack(spacing: 0) {
+ rowHeader(row, m)
+ Color.clear.frame(width: lead, height: m.height(row))
+ ForEach(cols, id: \.self) { col in cell(row: row, col: col, m) }
+ Color.clear.frame(width: trail, height: m.height(row))
}
}
- .onAppear { scroller.rows.insert(row) }
- .onDisappear { scroller.rows.remove(row) }
+ Color.clear.frame(width: 1, height: m.cellsHeight - m.rowStarts[rows.last.map { $0 + 1 } ?? 0])
}
} 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
- }
+ HStack(spacing: 0) {
+ Text("").frame(width: SheetGridMetrics.rowHeader, height: SheetGridMetrics.colHeader)
+ Color.clear.frame(width: lead, height: SheetGridMetrics.colHeader)
+ ForEach(cols, id: \.self) { col in columnHeader(col, m) }
+ Color.clear.frame(width: trail, height: SheetGridMetrics.colHeader)
}.background(.regularMaterial)
}
}
@@ -310,18 +359,60 @@ struct SheetGridContent: View, Equatable {
.overlay(alignment: .topLeading) { keySink }
#else
.overlay(alignment: .topLeading) {
- SheetEditorOverlay(model: model, state: editState, typeAhead: typeAhead,
- frame: metrics.frame, end: actions.endEditing)
+ SheetEditorOverlay(model: model, state: editState, window: window, typeAhead: typeAhead,
+ frame: m.frame, end: actions.endEditing)
}
#endif
- }.defaultScrollAnchor(.topLeading)
- .onAppear { scroller.proxy = proxy }
- .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in scroller.visible = rect }
+ }
+ .defaultScrollAnchor(.topLeading)
+ .scrollPosition($position)
+ .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in
+ scroller.visible = SheetGridScroller.usable(rect)
+ window.update(rect, metrics)
+ }
+ // New sizes or a resize in progress move every edge after them.
+ .onChange(of: m.colStarts + m.rowStarts) { window.update(window.visible, metrics) }
+ .onAppear {
+ scroller.scrollTo = { point in position.scrollTo(point: point) }
+ window.update(window.visible, m)
}
.onChange(of: draggingResize) { _, active in
if !active { actions.resizeCancel() }
}
}
+ private func rowHeader(_ row: Int, _ m: SheetGridMetrics) -> some View {
+ ZStack(alignment: .bottom) {
+ Button { actions.selectRow(row) } label: {
+ Text(String(row + 1)).frame(width: SheetGridMetrics.rowHeader, height: m.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: SheetGridMetrics.rowHeader, height: 8)
+ #else
+ Color.clear.frame(width: SheetGridMetrics.rowHeader, height: 8)
+ .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row))
+ .accessibilityHidden(true)
+ #endif
+ }
+ }
+ private func columnHeader(_ col: Int, _ m: SheetGridMetrics) -> some View {
+ ZStack(alignment: .trailing) {
+ Button { actions.selectColumn(col) } label: {
+ Text(Coordinate(r: 0, c: col).ref.dropLast())
+ .frame(width: m.width(col), height: SheetGridMetrics.colHeader)
+ .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: SheetGridMetrics.colHeader)
+ .help(sheetsMacString("Double-click to fit column to contents"))
+ #else
+ Color.clear.frame(width: 8, height: SheetGridMetrics.colHeader)
+ #endif
+ }
+ #if os(macOS)
+ .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } }
+ #endif
+ }
#if os(iOS)
/// The keyboard's place on the selected cell (SheetKeySink).
private var keySink: some View {
@@ -332,13 +423,13 @@ struct SheetGridContent: View, Equatable {
.allowsHitTesting(false)
}
#endif
- private func cell(row: Int, col: Int) -> some View {
+ private func cell(row: Int, col: Int, _ m: SheetGridMetrics) -> 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))
+ columnWidth: m.width(col), rowHeight: m.height(row))
}
#if os(macOS)
private func resizeHandle(axis: String, index: Int) -> some View {
@@ -389,31 +480,40 @@ struct SheetResizePreview: Equatable {
}
}
-/// Keeps the selected cell on screen. Not observed: scrolling and rows coming
-/// and going must not re-render the grid.
+/// Keeps the selected cell on screen. Not observed: scrolling must not
+/// re-render the grid.
@MainActor final class SheetGridScroller {
- var proxy: ScrollViewProxy?
- var rows = Set<Int>()
+ var scrollTo: ((CGPoint) -> Void)?
/// 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.
+ /// It scrolls just far enough, to the cell's exact place.
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)
- } else {
- // Bring the row into being, then the cell into view.
- proxy.scrollTo(point.r)
- DispatchQueue.main.async { proxy.scrollTo(point) }
- }
+ guard let visible, let target = Self.offset(showing: frame, in: visible) else { return }
+ DispatchQueue.main.async { [weak self] in self?.scrollTo?(target) }
+ }
+ /// The part of the visible rect not under scroll bars. The scroll geometry
+ /// counts the area under them; with legacy (always shown) scroll bars on
+ /// the Mac, a cell revealed into that strip would be hidden by them.
+ static func usable(_ rect: CGRect) -> CGRect {
+ #if os(macOS)
+ guard NSScroller.preferredScrollerStyle == .legacy else { return rect }
+ let bar = NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy)
+ return CGRect(x: rect.minX, y: rect.minY, width: rect.width - bar, height: rect.height - bar)
+ #else
+ return rect
+ #endif
+ }
+ /// The content offset that brings `frame` into view with the least scroll,
+ /// or nil when it is in view already.
+ static func offset(showing frame: CGRect, in visible: CGRect) -> CGPoint? {
+ let top = SheetGridMetrics.colHeader
+ var x = visible.minX, y = visible.minY
+ if frame.minX < visible.minX { x = frame.minX } else if frame.maxX > visible.maxX { x = frame.maxX - visible.width }
+ if frame.minY < visible.minY + top { y = frame.minY - top } else if frame.maxY > visible.maxY { y = frame.maxY - visible.height }
+ let target = CGPoint(x: max(0, x), y: max(0, y))
+ return target == visible.origin ? nil : target
}
}
diff --git a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
index e088163..95200cf 100644
--- a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
+++ b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift
@@ -260,7 +260,8 @@ final class FirstKeystrokeTests: XCTestCase {
var report: [String] = []
for cols in [10, 60, 200] {
var samples: [Double] = []
- for attempt in 0..<4 {
+ // Six tries, the first a warm-up: a busy machine stalls one now and then.
+ for attempt in 0..<6 {
let model = fixtureModel(SheetServerFixture(), rows: 120, cols: cols)
let (window, _) = try await host(model)
let point = Coordinate(r: 1 + attempt, c: 1)
@@ -275,6 +276,7 @@ final class FirstKeystrokeTests: XCTestCase {
XCTAssertEqual(model.draft, "x", "\(cols) columns: the key never arrived")
window.orderOut(nil)
}
+ samples.removeFirst()
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, 50, "\(cols) columns: one or two frames, whatever the width")
diff --git a/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift b/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift
new file mode 100644
index 0000000..b60f26d
--- /dev/null
+++ b/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift
@@ -0,0 +1,138 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+import XCTest
+import RastrilloApple
+@testable import SheetsKit
+
+/// Review #72, the column windowing: the grid is laid out from exact column
+/// widths and row heights (SheetGridMetrics), and the editor, clicks and
+/// scrolling all use the same numbers. A LazyHStack estimated the widths of
+/// columns it had not built, so after scrolling right a click selected a cell
+/// columns away from the one under the pointer, and the editor opened off
+/// screen. These scroll, click where the geometry says a cell is, and type.
+final class GridGeometryTests: XCTestCase {
+ /// 60 columns of 40, 300 and 110 points, and rows of 60 and 32.
+ @MainActor private func mixedModel() -> SheetModel {
+ let model = fixtureModel(SheetServerFixture(), rows: 120, cols: 60)
+ var cols: [String: Double] = [:], rows: [String: Double] = [:]
+ for c in 0..<60 where c % 3 != 2 { cols[String(c)] = c % 3 == 0 ? 40 : 300 }
+ for r in stride(from: 0, to: 120, by: 4) { rows[String(r)] = 60 }
+ model.sizes = Sizes(cols: cols, rows: rows)
+ return model
+ }
+ @MainActor private func metrics(_ model: SheetModel) -> SheetGridMetrics {
+ SheetGridMetrics(sizes: model.sizes, resizing: nil, rows: model.rows, cols: model.cols)
+ }
+ @MainActor private func open(_ model: SheetModel) async throws -> (NSWindow, NSView, NSScrollView) {
+ let host = NSHostingView(rootView: SheetGrid(model: model))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false)
+ window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate()
+ try await Task.sleep(for: .milliseconds(300))
+ func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) }
+ let scroll = try XCTUnwrap(scrolls(host).first)
+ return (window, host, scroll)
+ }
+ @MainActor private func wheel(_ window: NSWindow, dx: Int32, dy: Int32 = 0) {
+ let event = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0)!
+ let screen = window.convertPoint(toScreen: NSPoint(x: 320, y: 200))
+ event.location = CGPoint(x: screen.x, y: (NSScreen.screens.first?.frame.height ?? 0) - screen.y)
+ window.sendEvent(NSEvent(cgEvent: event)!)
+ }
+ /// A content rect (the grid's coordinates) in window coordinates, now.
+ @MainActor private func onScreen(_ frame: CGRect, _ scroll: NSScrollView, _ window: NSWindow) -> CGRect {
+ let visible = scroll.contentView.bounds
+ let height = window.contentView!.bounds.height
+ return CGRect(x: frame.minX - visible.minX, y: height - (frame.maxY - visible.minY), width: frame.width, height: frame.height)
+ }
+ @MainActor private func click(_ point: CGPoint, _ window: NSWindow) {
+ for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] {
+ window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)!)
+ }
+ }
+ @MainActor private func key(_ text: String, _ code: UInt16, _ window: NSWindow) {
+ NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!)
+ }
+ @MainActor private func editorRect(_ host: NSView) -> CGRect? {
+ func find(_ v: NSView) -> NSView? { v is SheetCellEditor.CellTextField ? v : v.subviews.lazy.compactMap(find).first }
+ return find(host).map { $0.convert($0.bounds, to: nil) }
+ }
+ /// The editor's field sits inside its cell (inset by its padding) and on screen.
+ @MainActor private func assertEditor(at cell: CGRect, _ host: NSView, _ scroll: NSScrollView, file: StaticString = #filePath, line: UInt = #line) {
+ guard let field = editorRect(host) else { return XCTFail("no editor", file: file, line: line) }
+ XCTAssertTrue(cell.insetBy(dx: -1, dy: -1).contains(field), "editor \(field) is not in its cell \(cell)", file: file, line: line)
+ XCTAssertTrue(scroll.frame.contains(field), "editor \(field) is off screen", file: file, line: line)
+ }
+
+ @MainActor func testTheContentIsExactlyAsWideAndTallAsTheCells() async throws {
+ let model = mixedModel()
+ let (window, _, scroll) = try await open(model)
+ defer { window.orderOut(nil) }
+ let m = metrics(model)
+ let document = try XCTUnwrap(scroll.documentView).frame.size
+ XCTAssertEqual(document.width, SheetGridMetrics.rowHeader + m.cellsWidth, accuracy: 0.5)
+ XCTAssertEqual(document.height, SheetGridMetrics.colHeader + m.cellsHeight, accuracy: 0.5)
+ XCTAssertEqual(scroll.contentView.bounds.origin, .zero, "mixed widths opened pre-scrolled")
+ }
+
+ @MainActor func testClickAfterScrollingRightSelectsTheCellUnderThePointer() async throws {
+ let model = mixedModel()
+ let (window, host, scroll) = try await open(model)
+ defer { window.orderOut(nil) }
+ let m = metrics(model)
+ for distance: Int32 in [-4000, -3000] {
+ wheel(window, dx: distance)
+ try await Task.sleep(for: .milliseconds(300))
+ let visible = scroll.contentView.bounds
+ XCTAssertGreaterThan(visible.minX, 1000, "the grid scrolled right")
+ // A cell fully in view, by the exact geometry.
+ let row = 6
+ let col = try XCTUnwrap((0..<60).first { c in
+ let f = m.frame(Coordinate(r: row, c: c))
+ return f.minX >= visible.minX + 10 && f.maxX <= visible.maxX - 10
+ })
+ let target = Coordinate(r: row, c: col)
+ let cell = onScreen(m.frame(target), scroll, window)
+ click(CGPoint(x: cell.midX, y: cell.midY), window)
+ try await Task.sleep(for: .milliseconds(150))
+ XCTAssertEqual(model.selection.start, target, "the click selected a different cell from the one under it")
+ key("q", 12, window)
+ try await Task.sleep(for: .milliseconds(200))
+ XCTAssertEqual(model.draft, "q")
+ assertEditor(at: cell, host, scroll)
+ key("\u{1b}", 53, window)
+ try await Task.sleep(for: .milliseconds(100))
+ }
+ }
+
+ @MainActor func testTypingOnAFarCellScrollsExactlyToIt() async throws {
+ let model = mixedModel()
+ let (window, host, scroll) = try await open(model)
+ defer { window.orderOut(nil) }
+ let m = metrics(model)
+ for target in [Coordinate(r: 90, c: 50), Coordinate(r: 3, c: 1), Coordinate(r: 61, c: 33)] {
+ model.select(target)
+ key("z", 6, window)
+ try await Task.sleep(for: .milliseconds(400))
+ let frame = m.frame(target)
+ let visible = scroll.contentView.bounds
+ let clear = CGRect(x: visible.minX, y: visible.minY + SheetGridMetrics.colHeader,
+ width: visible.width, height: visible.height - SheetGridMetrics.colHeader)
+ XCTAssertTrue(clear.insetBy(dx: -1, dy: -1).contains(frame), "\(target.ref) at \(frame) not in view \(visible)")
+ XCTAssertEqual(model.draft, "z")
+ assertEditor(at: onScreen(frame, scroll, window), host, scroll)
+ key("\u{1b}", 53, window)
+ try await Task.sleep(for: .milliseconds(100))
+ }
+ }
+
+ @MainActor func testTheLeastScrollThatShowsACell() {
+ let visible = CGRect(x: 1000, y: 500, width: 600, height: 400)
+ XCTAssertNil(SheetGridScroller.offset(showing: CGRect(x: 1100, y: 600, width: 100, height: 30), in: visible))
+ XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 3000, y: 600, width: 100, height: 30), in: visible),
+ CGPoint(x: 2500, y: 500), "far right: its right edge at the view's, not the grid's last column")
+ XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 200, y: 510, width: 100, height: 30), in: visible),
+ CGPoint(x: 200, y: 478), "up and left: clear of the pinned column header")
+ }
+}
+#endif