Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .claude/rules/ui-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ paths:
- Never put `.accessibilityIdentifier` on a SwiftUI container alone: it replaces every descendant's identifier in that hosting tree. Pair it with `.accessibilityElement(children: .contain)` first. How a UI test queries a leaf control is in `.claude/rules/ui-tests.md`.
- Keep focus, selection, undo, the responder chain and IME working after the change, and keep UI state on the main actor (no `Task.detached` to escape it).
- An API newer than the deployment target (`apple/AGENTS.md`) needs `if #available` and a fallback.
- A view that is AppKit on purpose says why in its type comment (`FavoritesOutlineView`: a SwiftUI `List` cannot draw an emphasized selection under a bare `NSHostingController`). Read it before converting.
- A view that is AppKit on purpose says why in its type comment (`FavoritesOutlineView`: dragging a favorite out and in-place rename). Read it before converting.
1 change: 1 addition & 0 deletions apple/TablePro/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) }
WindowOpener.shared.setCompareSyncPresenter { CompareSyncWindowController.present(prefillSource: $0) }
KeyRepeatFilter.shared.install()
TableClickFocus.shared.install()
RecentTabSwitcherController.installEditorKeyClaim()
let syncSettings = AppSettingsStorage.shared.loadSync()
let passwordSyncExpected = syncSettings.enabled && syncSettings.syncConnections && syncSettings.syncPasswords
Expand Down
107 changes: 107 additions & 0 deletions apple/TablePro/Core/KeyboardHandling/TableClickFocus.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import AppKit

// On macOS 27 a click on a SwiftUI List or Table row leaves the backing table without first
// responder (FB25239926), so the selection draws grey and keys reach the previous responder.
@MainActor
final class TableClickFocus {
static let shared = TableClickFocus()

// What held the keyboard when the press began. A field editor serves every field, so the control it edits counts too.
@MainActor
private struct Holder {
weak var responder: NSResponder?
weak var editedControl: AnyObject?

init(_ responder: NSResponder?) {
self.responder = responder
editedControl = (responder as? NSTextView)?.delegate
}

func isStill(_ current: NSResponder?) -> Bool {
current != nil && current === responder && (current as? NSTextView)?.delegate === editedControl
}
}

private var monitor: Any?
private weak var pendingWindow: NSWindow?
private weak var pendingTable: NSTableView?
private var pendingHolder = Holder(nil)

init() {}

func install() {
guard monitor == nil, #available(macOS 27, *) else { return }
monitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .leftMouseUp]) { nsEvent in
nonisolated(unsafe) let event = nsEvent
MainActor.assumeIsolated { Self.shared.handle(event) }
return nsEvent
}
}

func handle(_ event: NSEvent) {
switch event.type {
case .leftMouseDown: mouseDown(event)
case .leftMouseUp: mouseUp()
default: break
}
}

private func mouseDown(_ event: NSEvent) {
pendingWindow = nil
pendingTable = nil
guard !event.modifierFlags.contains(.control),
let window = event.window,
window.attachedSheet == nil,
NSApp.modalWindow.map({ $0 === window }) ?? true,
let hit = window.contentView?.superview?.hitTest(event.locationInWindow),
!hit.acceptsFirstResponder,
let table = Self.enclosingTable(of: hit),
!Self.runsItsOwnMouseDown(table),
table.acceptsFirstResponder,
!Self.holdsFocus(table, in: window) else { return }
let row = table.row(at: table.convert(event.locationInWindow, from: nil))
// A press on a selected row changes no selection, and its mouse-up can end in a tracking loop the monitor never sees.
if row >= 0, table.selectedRowIndexes.contains(row) {
window.makeFirstResponder(table)
return
}
// Claimed before SwiftUI handles the mouse-up, the click can lose its selection.
pendingWindow = window
pendingTable = table
pendingHolder = Holder(window.firstResponder)
}

private func mouseUp() {
guard let window = pendingWindow, let table = pendingTable else { return }
let holder = pendingHolder
pendingWindow = nil
pendingTable = nil
DispatchQueue.main.async {
guard table.window === window, !Self.holdsFocus(table, in: window) else { return }
// A focus the click itself moved elsewhere stays; one it left vacant or untouched goes to the table.
let current = window.firstResponder
guard current == nil || current === window || holder.isStill(current) else { return }
window.makeFirstResponder(table)
}
}

// The bug is in tables SwiftUI defines; AppKit's own and the app's subclasses take focus in NSTableView.mouseDown.
private static func runsItsOwnMouseDown(_ table: NSTableView) -> Bool {
let bundle = Bundle(for: type(of: table))
return bundle == Bundle(for: NSTableView.self) || bundle == Bundle.main
}

private static func enclosingTable(of view: NSView) -> NSTableView? {
var current: NSView? = view
while let candidate = current {
if let table = candidate as? NSTableView { return table }
current = candidate.superview
}
return nil
}

private static func holdsFocus(_ table: NSTableView, in window: NSWindow) -> Bool {
guard let responder = window.firstResponder as? NSView else { return false }
return responder === table || responder.isDescendant(of: table)
}
}
36 changes: 36 additions & 0 deletions apple/TablePro/Core/KeyboardHandling/TableCommandKeys.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import AppKit

extension NSTableView {
// NSTableView moves the selection itself but passes Return and Delete up as plain key events, so an
// insertNewline(_:) or deleteBackward(_:) on the table or above it never runs unless they go through here.
func interpretCommandKey(_ event: NSEvent) -> Bool {
guard event.modifierFlags.isDisjoint(with: [.command, .shift, .option, .control]),
let command = Self.command(for: event.specialKey),
answersFromHereUp(command) else { return false }
interpretKeyEvents([event])
return true
}

private static func command(for key: NSEvent.SpecialKey?) -> Selector? {
switch key {
case .carriageReturn?, .newline?, .enter?:
return #selector(NSResponder.insertNewline(_:))
case .delete?:
return #selector(NSResponder.deleteBackward(_:))
case .deleteForward?:
return #selector(NSResponder.deleteForward(_:))
default:
return nil
}
}

// A key nobody answers keeps travelling up as a key event, so a sheet's default button still gets Return.
private func answersFromHereUp(_ command: Selector) -> Bool {
var responder: NSResponder? = self
while let current = responder {
if current.responds(to: command) { return true }
responder = current.nextResponder
}
return false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ internal final class WorkspaceRailTableView: NSTableView {
)
}

override internal func keyDown(with event: NSEvent) {
guard !interpretCommandKey(event) else { return }
super.keyDown(with: event)
}

override internal func otherMouseUp(with event: NSEvent) {
guard event.isMiddleButton else {
super.otherMouseUp(with: event)
Expand Down Expand Up @@ -485,8 +490,7 @@ internal final class WorkspaceRailViewController: NSViewController {
commit(row: tableView.clickedRow)
}

/// Return opens the highlighted row, the same contract every AppKit list keeps. `NSTableView`
/// routes it here through the responder chain, so no key handling of the rail's own is needed.
/// Return opens the highlighted row, the same contract every AppKit list keeps.
override func insertNewline(_ sender: Any?) {
commit(row: tableView.selectedRow)
}
Expand Down
3 changes: 2 additions & 1 deletion apple/TablePro/Views/Connection/HostListFieldRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ struct HostListFieldRow: View {
/// The control group brings its own intrinsic height, which is taller than the two
/// hand-sized 20pt buttons this row used to draw.
let buttonBarHeight: CGFloat = 32
return min(rows * rowHeight + buttonBarHeight + 8, 140)
// No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls.
return rows * rowHeight + buttonBarHeight + 8
}

private func bindingForEntry(_ entry: HostEntry) -> Binding<String> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ struct AttachedDatabaseListEditor: View {
private let buttonBarHeight: CGFloat = 32

private var listHeight: CGFloat {
// No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls.
let rows = CGFloat(max(model.rows.count, 2))
return min(rows * rowHeight + buttonBarHeight + 8, 200)
return rows * rowHeight + buttonBarHeight + 8
}

private func nameBinding(for id: UUID) -> Binding<String> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ struct LoadableExtensionListEditor: View {
private let buttonBarHeight: CGFloat = 32

private var listHeight: CGFloat {
// No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls.
let rows = CGFloat(max(model.rows.count, 2))
return min(rows * rowHeight + buttonBarHeight + 8, 200)
return rows * rowHeight + buttonBarHeight + 8
}

private func pathBinding(for id: UUID) -> Binding<String> {
Expand Down
4 changes: 2 additions & 2 deletions apple/TablePro/Views/Settings/AppearanceSettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ internal struct AppearanceSettingsView: View {
}
}

// A List inside a scrolling grouped Form neither scrolls nor takes keyboard focus (measured on
// macOS 27), so the Form keeps its own height and the theme list sits below it.
// A List inside a scrolling grouped Form does not scroll (measured on macOS 27), so the Form
// keeps its own height and the theme list sits below it.
private var settingsForm: some View {
Form {
Section {
Expand Down
9 changes: 3 additions & 6 deletions apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,9 @@ internal struct FavoritesOutlineActions {
internal let performMenuCommand: (FavoritesMenuCommand) -> Void
}

/// The Favorites list as an `NSOutlineView`.
///
/// A SwiftUI `List` here could not draw an emphasized selection or answer an arrow key, because the
/// app hosts it in a bare `NSHostingController` with no SwiftUI scene above it. Rows stay SwiftUI:
/// AppKit publishes `NSTableCellView.backgroundStyle` into the hosted view's environment, so the
/// existing row content keeps working with no emphasis plumbing of its own.
/// The Favorites list as an `NSOutlineView`, for dragging a favorite out and in-place rename.
/// Rows stay SwiftUI: AppKit publishes `NSTableCellView.backgroundStyle` into the hosted view's
/// environment, so the row content needs no emphasis plumbing of its own.
internal struct FavoritesOutlineView<Row: View>: NSViewRepresentable {
internal let input: FavoritesOutlineInput
@Binding internal var selection: FavoriteSelection?
Expand Down
4 changes: 0 additions & 4 deletions apple/TablePro/Views/Sidebar/FavoritesTabView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -329,10 +329,6 @@ internal struct FavoritesTabView: View {
)
}

/// The Favorites list is an `NSOutlineView`. A SwiftUI `List` here drew no emphasized selection
/// and answered no arrow key, because the app hosts it in a bare `NSHostingController` with no
/// SwiftUI scene above it. Rows, menus and actions stay exactly where they were; only the list
/// container changed.
private func favoritesList(
_ items: [FavoriteNode],
databaseGroups: [FavoriteDatabaseGroup],
Expand Down
5 changes: 5 additions & 0 deletions apple/TablePro/Views/Sidebar/SidebarOutlineView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ internal class SidebarOutlineView: NSOutlineView {
super.mouseDown(with: event)
}

override internal func keyDown(with event: NSEvent) {
guard !interpretCommandKey(event) else { return }
super.keyDown(with: event)
}

override internal func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
adoptFirstResponderIfVacant()
Expand Down
9 changes: 2 additions & 7 deletions apple/TablePro/Views/Sidebar/SidebarRootShape.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,8 @@
import Foundation
import TableProPluginKit

/// Which shape the sidebar's object outline takes at its root.
///
/// The three shapes used to be three separate views, two of them SwiftUI `List`s. A `List` hosted in
/// a bare `NSHostingController`, which is what this app has since it runs an AppKit lifecycle with no
/// SwiftUI scene, never answers a key equivalent and never draws an emphasized selection: its
/// backing view does not even respond to `moveDown:`. So all three shapes are one `NSOutlineView`
/// now, and this is the only thing that differs between them.
/// Which shape the sidebar's object outline takes at its root. All three are one `NSOutlineView`;
/// this is the only thing that differs between them.
internal enum SidebarRootShape: Equatable {
/// Object-kind sections: Tables, Views, Procedures and the rest, plus Recent and Redis keys.
case flat
Expand Down
Loading
Loading