Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .claude/rules/data-grid.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode
## Model

- **`DataGridModel` holds the grid's state** and outlives every mount: column set, row order, selection, sort, value filter, column layout, display formats, find and the edit session. Its owner holds it strongly; the data tab keeps one per tab on `MainContentCoordinator`.
- **The data tab hands its grid a `DataTabGridPresentation` named by the tab**, applied through `applyGridPresentation(_:)`. `onChange` runs the closure of the body from before a tab switch, so a closure that captured the model wrote the incoming tab's configuration into the outgoing tab's model.
- **An owner talks to the model, never to the view.** It implements `DataGridDataSource` and `DataGridActions` in an adapter class and calls `reloadRows()` when its rows were replaced or `apply(_ delta:)` when they changed. The model keeps the selection by identity and sends the mounted view one `DataGridChange`.
- **Rows are `RowID`, columns are `DataGridColumnID`.** `DataGridRowOrder` maps display rows, and `DataGridColumnSet` is the only converter between data index, display position and pane. A bare `Int` is a display position, valid only inside one call: capture the IDs before a popover, a sheet or an `await`.
- **Every edit is one `model.commit(_:actionName:)`** of `DataGridCellEdit`s, taken by IDs when the gesture began. A command over many cells is one call, so one undo step.
Expand Down Expand Up @@ -42,7 +43,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode
- **Wrap Text is per grid, and off is the fixed-pitch table.** `model.wrapsText` is the store's flag on a grid that offers `.wrapText`. The controller answers `tableView(_:heightOfRow:)` only while it is on (`responds(to:)`, then the delegates are assigned again and the tables reloaded), so a grid that never wraps runs none of this. `tableView.rowHeight` stays the one-line height in both modes.
- **A wrapped row's height comes from `display.lineCounts`**, a line count per `RowID` over every column, capped at `DataGridWrapLayout.maximumLines`. It clears with the display cache and whenever `DataGridWrapGeometry` moves (a width, the column set, a font, the Row height, Show Invisible Characters). A row with no count is one line. Rows AppKit shows or holds ready are measured on the main actor as the viewport moves, the prewarm fills the rest, and every count that changes an answer is followed by `noteHeightOfRows` on both panes inside a kept place, never by a reload.
- **In a tall row everything but the value sits on the first line**: the row number, the accessory, the checkbox, a placeholder and the edit field. `DataGridWrapLayout` breaks the value and the renderer draws it, from the text the formatter left with every line break as one LF.
- **Every column stays attached.** Never hide an off-screen column with `NSTableColumn.isHidden`: each write costs O(attached columns). Columns come from each pane's pool, keyed by `DataGridColumnID`, so a re-run of the same result does not flicker (#951).
- **Every column stays attached.** Never hide an off-screen column with `NSTableColumn.isHidden`: each write costs O(attached columns). Columns come from each pane's pool, keyed by `DataGridColumnID`, so a re-run of the same result does not flicker (#951). A pooled column's `dataCell` is a plain `NSCell`: the default text field cell tiles the table on every attach, which made attaching n columns O(n²).
- **Resolve a table column through `DataGridPane.slot(atTableIndex:columns:)` and `tableIndex(forDisplayPosition:columns:)`**, never a fixed index into `tableColumns`: the row-number column sits first and the frozen pane holds a subset.
- **`gridStyleMask` stays empty.** AppKit's vertical grid lines keep a subview per column (518 ms a layout at 500 columns). `DataGridBodyChrome` draws the separators in each row, and the stripes and separators past the last row.
- **Selection takes the theme.** `drawSelection(in:)` fills the whole row in a row selection and the selected columns' span in a cell range: `dataGrid.selection` when emphasized, else `dataGrid.inactiveSelection`. The active cell is an inner stroke in `dataGrid.focusBorder`, 2 pt with focus and 1 pt without, in the selected text color over an emphasized fill. No outline goes round a range.
Expand All @@ -52,7 +53,7 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode

## Header

- **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)` and a `viewWillDraw` that repaints the body on each step of a column drag. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown.
- **AppKit's header behavior in the theme's colors.** `DataGridHeaderView` is a `ThemeTableHeaderView` and every column a `ThemeTableHeaderCell` (`.claude/rules/theme.md`); it adds `menu(for:)`, a `viewWillDraw` that repaints the body on each step of a column drag, and a `resetCursorRects` that adds AppKit's divider rects for the columns on screen only, since AppKit's own pass adds one for every column on every scroll step. AppKit draws the title and the primary sort arrow; the controller sets each header cell's `accessibilitySortDirection`, which AppKit leaves unknown.
- **The model's sort is the source.** `tableView.sortDescriptors` is written from `store.sortState` under `isApplyingSortDescriptors`, because an assignment inside the callback fires it again. A plain click keeps only the clicked key and flips it on a repeat; an Option-click keeps the key AppKit appended (`HeaderSortCycle`). Shift-click reaches no sort callback, and Command-click selects the column.
- **Header text is the column name.** The type, the comment and, while several keys sort, the sort order go in `headerToolTip`; an active value filter adds a funnel symbol attachment to the title, in the header text color.

Expand Down
9 changes: 9 additions & 0 deletions apple/.swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,15 @@ custom_rules:
excluded_match_kinds: [comment, doccomment]
message: "Declare an FSEvents callback as a `nonisolated private static let` of type FSEventStreamCallback and pass that."
severity: error
# The app builds in the Swift 6 mode, where a main-actor @objc getter checks its executor on every call. The editor
# package builds in the Swift 5 mode, so the scope names the app folder alone.
flipped_view_getter_isolation:
name: "Flipped View Getter Isolation"
regex: '^(?![^\n]*\bnonisolated\b)[^\n]*\boverride\b[^\n]*\bvar\s+isFlipped\b'
included: ['.*/apple/TablePro/']
excluded_match_kinds: [comment, doccomment]
message: "isFlipped is a constant AppKit asks in every coordinate conversion: declare it nonisolated."
severity: error
date_formatter_locale:
name: "Fixed-Format Date Formatter Locale"
regex: 'DateFormatter\(\)(?:(?!\.locale\s*=|DateFormatter\(\))[\s\S]){0,800}?\.dateFormat\s*=\s*"(?!(?:[^\n]*\n){0,8}[^\n]*\.locale\s*=)'
Expand Down
11 changes: 9 additions & 2 deletions apple/TablePro/Views/DataGrid/Cells/DataGridBodyChrome.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,18 @@ enum DataGridBodyChrome {
return row.isMultiple(of: 2) ? resolved[.gridBackground] : resolved[.gridAlternateRow]
}

// Opaque whatever the stripe is, because a frozen pane row covers the scrolling rows beneath it.
// Opaque whatever the stripe is, because a frozen pane row covers the scrolling rows beneath it. An even row's
// stripe is the grid background, which is always opaque (`ThemeSlot.requiresOpaque`), so it fills once.
static func fillRowBackground(_ rect: NSRect, row: Int, of tableView: NSTableView, scope: ThemeScope) {
let stripe = stripeColor(forRow: row, of: tableView, scope: scope)
if let stripe, row.isMultiple(of: 2) {
stripe.setFill()
rect.fill()
return
}
tableView.backgroundColor.setFill()
rect.fill()
guard let stripe = stripeColor(forRow: row, of: tableView, scope: scope) else { return }
guard let stripe else { return }
stripe.setFill()
rect.fill(using: .sourceOver)
}
Expand Down
2 changes: 1 addition & 1 deletion apple/TablePro/Views/DataGrid/DataGridContainerView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ final class DataGridContainerView: NSView {
fatalError("init(coder:) has not been implemented")
}

override var isFlipped: Bool { true }
override nonisolated var isFlipped: Bool { true }

override func setFrameSize(_ newSize: NSSize) {
super.setFrameSize(newSize)
Expand Down
81 changes: 81 additions & 0 deletions apple/TablePro/Views/DataGrid/DataGridHeaderView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,85 @@ final class DataGridHeaderView: ThemeTableHeaderView {
bodyFollowsColumnDrag = isDragging
controller?.headerGeometryDidStep(in: paneKind)
}

// Every scroll step drops the cursor rects, and AppKit's pass adds one for every column, asking for the visible
// columns again for each: 75 M instructions a step at 500 columns (measured on macOS 27).
override func resetCursorRects() {
guard let tableView, tableView.userInterfaceLayoutDirection == .leftToRight else {
super.resetCursorRects()
return
}
for resize in DataGridHeaderCursor.resizeRects(in: self, of: tableView) {
addCursorRect(resize.rect, cursor: resize.cursor)
}
}
}

// AppKit's own divider geometry and cursors, measured on macOS 27, for the columns the header shows.
@MainActor
enum DataGridHeaderCursor {
struct Resize: Equatable {
let rect: NSRect
let cursor: NSCursor
}

static let width: CGFloat = 5
static let leadingInset: CGFloat = 3
// The last divider has nothing after it, so AppKit gives it a wider target.
static let lastWidth: CGFloat = 9
static let lastLeadingInset: CGFloat = 5

static func resizeRects(in header: NSTableHeaderView, of tableView: NSTableView) -> [Resize] {
guard tableView.allowsColumnResizing else { return [] }
let visible = header.visibleRect
guard visible.width > 0 else { return [] }
let columns = tableView.tableColumns
let shown = tableView.columnIndexes(in: NSRect(x: visible.minX, y: tableView.bounds.minY, width: visible.width, height: 1))
guard let first = shown.first, let last = shown.last, last < columns.count else { return [] }
// The divider before the first shown column reaches into view.
return (max(first - 1, 0)...last).compactMap { index in
let column = columns[index]
guard !column.isHidden, column.resizingMask.contains(.userResizingMask) else { return nil }
let header = header.headerRect(ofColumn: index)
let isLast = index == columns.count - 1
let rect = NSRect(
x: header.maxX - (isLast ? lastLeadingInset : leadingInset),
y: header.minY,
width: isLast ? lastWidth : width,
height: header.height
)
return Resize(rect: rect, cursor: cursor(for: column))
}
}

private enum Direction {
case left
case right
case both
}

static func cursor(for column: NSTableColumn) -> NSCursor {
if column.width <= column.minWidth {
return resize(.right)
}
if column.width >= column.maxWidth {
return resize(.left)
}
return resize(.both)
}

private static func resize(_ direction: Direction) -> NSCursor {
if #available(macOS 15.0, *) {
switch direction {
case .left: return .columnResize(directions: .left)
case .right: return .columnResize(directions: .right)
case .both: return .columnResize(directions: .all)
}
}
switch direction {
case .left: return .resizeLeft
case .right: return .resizeRight
case .both: return .resizeLeftRight
}
}
}
8 changes: 8 additions & 0 deletions apple/TablePro/Views/DataGrid/DataGridPane.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ final class DataGridPane {
let identifier = NSUserInterfaceItemIdentifier("DataGrid.column.\(id.stringValue)")
let column = NSTableColumn(identifier: identifier)
column.headerCell = ThemeTableHeaderCell()
column.dataCell = Self.undrawnDataCell()
column.minWidth = DataGridMetrics.dataColumnMinWidth
column.maxWidth = DataGridMetrics.dataColumnMaxWidth
column.resizingMask = .userResizingMask
Expand All @@ -119,6 +120,7 @@ final class DataGridPane {
if let rowNumberColumn { return rowNumberColumn }
let column = NSTableColumn(identifier: Self.rowNumberIdentifier)
column.headerCell = ThemeTableHeaderCell()
column.dataCell = Self.undrawnDataCell()
column.title = "#"
column.isEditable = false
column.resizingMask = []
Expand All @@ -129,6 +131,12 @@ final class DataGridPane {
return column
}

// A view-based table never draws it, and the default text field cell tiles the table on every attach, which made
// attaching n columns O(n²) (measured on macOS 27). One per column, since a cell belongs to one control view.
private static func undrawnDataCell() -> NSCell {
NSCell()
}

func forgetColumns(except kept: Set<DataGridColumnID>) {
for (id, column) in columnsByID where !kept.contains(id) {
columnsByID.removeValue(forKey: id)
Expand Down
8 changes: 7 additions & 1 deletion apple/TablePro/Views/DataGrid/DataGridRowView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ final class DataGridRowView: NSTableRowView {

// MARK: - Drawing

// drawBackground(in:) fills with an opaque color whenever both are set. Saying so spares AppKit a color lookup per
// row and the layer its blending.
override var isOpaque: Bool {
controller != nil && gridTable != nil
}

override func drawBackground(in dirtyRect: NSRect) {
guard let controller, let gridTable else {
super.drawBackground(in: dirtyRect)
Expand Down Expand Up @@ -145,7 +151,7 @@ final class DataGridRowView: NSTableRowView {
final class DataGridRowContentView: NSView {
weak var rowView: DataGridRowView?

override var isFlipped: Bool { true }
override nonisolated var isFlipped: Bool { true }
override var allowsVibrancy: Bool { false }

override func isAccessibilityElement() -> Bool { false }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,13 @@ extension DataGridViewController {
// Only an accessory that came or went can move a width, and a wider column can leave the frozen pane with an open editor.
private func columnMetadataDidChange() {
let changed = presenter.refreshColumnPresentations()
if changed.isEmpty {
refreshHeaders()
} else {
if !changed.isEmpty {
suspendFieldEditing(unmounting: true)
reconcileColumns(widening: changed)
resumeFieldEditing()
followRowChangesWithPopovers()
}
refreshHeaders()
redrawVisibleRows()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import AppKit

extension DataGridViewController {
// Builds both panes' column lists from the model. Never culls a column with isHidden: each write costs
// O(attached columns), and seconds at 500 columns with mounted views (probe section 5).
// O(attached columns), and seconds at 500 columns with mounted views (probe section 5). Leaves the header text
// to the caller, which refreshes it once after the sort indicators.
func reconcileColumns(widening changedPresentations: IndexSet = []) {
isRebuildingColumns = true
defer { isRebuildingColumns = false }
Expand Down Expand Up @@ -53,7 +54,6 @@ extension DataGridViewController {
main.forgetColumns(except: ids)
savedWidthIDs = nextSaved
updateFrozenPane()
refreshHeaders()
}

// A width saved before accessories reserved room, and never set by the user, is measured again.
Expand Down
1 change: 1 addition & 0 deletions apple/TablePro/Views/DataGrid/DataGridViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView {
}
if previous.defaultSortDirection != settings.defaultSortDirection {
reconcileColumns()
refreshHeaders()
}
if previous.dateFormat != settings.dateFormat
|| previous.nullDisplay != settings.nullDisplay
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ final class DataGridEditingCellView: NSTableCellView {
layoutField()
}

override var isFlipped: Bool { true }
override nonisolated var isFlipped: Bool { true }

// A selected row's emphasized style would turn the text white on the field's own white background.
override var backgroundStyle: NSView.BackgroundStyle {
Expand Down
2 changes: 1 addition & 1 deletion apple/TablePro/Views/ERDiagram/ERDiagramSceneView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ final class ERDiagramSceneView: NSView, NSMenuItemValidation {
return baked
}

override var isFlipped: Bool { true }
override nonisolated var isFlipped: Bool { true }

override var isOpaque: Bool { false }

Expand Down
35 changes: 35 additions & 0 deletions apple/TablePro/Views/Main/Child/DataTabGrid.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//
// DataTabGrid.swift
// TablePro
//

import SwiftUI

// The data tab's grid. onChange runs the closure of the body from before a tab switch, so it reads only the
// presentation it is handed, which names its tab. Configuration is applied outside the update pass, since the model
// publishes when it changes.
struct DataTabGrid: View {
let coordinator: MainContentCoordinator
let model: DataGridModel
let presentation: DataTabGridPresentation

var body: some View {
DataGridView(model: model)
.id(presentation.tabId)
.frame(maxHeight: .infinity, alignment: .top)
.onAppear {
coordinator.applyGridPresentation(presentation)
focusIfRequested()
}
.onChange(of: presentation) { coordinator.applyGridPresentation($0) }
}

// An explicit open asks for the keyboard; the grid is in its window once this turn ends.
private func focusIfRequested() {
guard coordinator.consumePendingGridFocus() else { return }
let model = model
Task { @MainActor in
model.focus()
}
}
}
30 changes: 5 additions & 25 deletions apple/TablePro/Views/Main/Child/MainEditorContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -824,24 +824,12 @@ struct MainEditorContentView: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
}

// Configuration is applied outside the update pass: the model publishes when it changes.
@ViewBuilder
private func dataGridView(tab: QueryTab) -> some View {
let model = displayedGridModel(for: tab)
let configuration = coordinator.gridConfiguration(for: tab)
let highlightRules = coordinator.highlightRules(for: tab)
DataGridView(model: model)
.id(tab.id)
.frame(maxHeight: .infinity, alignment: .top)
.onAppear {
model.configuration = configuration
focusGridIfRequested(model)
}
.onChange(of: configuration) { model.configuration = $0 }
.onChange(of: highlightRules) { _ in
model.display.cache.clearHighlights()
model.repaintAllRows()
}
DataTabGrid(
coordinator: coordinator,
model: displayedGridModel(for: tab),
presentation: coordinator.gridPresentation(for: tab)
)
}

private func displayedGridModel(for tab: QueryTab) -> DataGridModel {
Expand All @@ -850,14 +838,6 @@ struct MainEditorContentView: View {
return model
}

// An explicit open asks for the keyboard; the grid is in its window once this turn ends.
private func focusGridIfRequested(_ model: DataGridModel) {
guard coordinator.consumePendingGridFocus() else { return }
Task { @MainActor in
model.focus()
}
}

private func resolvedTableRows(for tab: QueryTab) -> TableRows {
coordinator.tabSessionRegistry.existingTableRows(for: tab.id) ?? TableRows()
}
Expand Down
2 changes: 1 addition & 1 deletion apple/TablePro/Views/Main/EditorTabItemView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ internal final class EditorTabItemView: NSView {
fatalError("EditorTabItemView does not support NSCoder init")
}

override internal var isFlipped: Bool { true }
override nonisolated internal var isFlipped: Bool { true }
override internal var mouseDownCanMoveWindow: Bool { false }

// HIG: people expect to act on a tab in an inactive window without bringing it forward first.
Expand Down
Loading
Loading