diff --git a/.claude/rules/ui-lifecycle.md b/.claude/rules/ui-lifecycle.md index 8b1a3b8df1..ee59e7a7d5 100644 --- a/.claude/rules/ui-lifecycle.md +++ b/.claude/rules/ui-lifecycle.md @@ -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. diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 2d5440c4b5..95e5a815a8 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -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 diff --git a/apple/TablePro/Core/KeyboardHandling/TableClickFocus.swift b/apple/TablePro/Core/KeyboardHandling/TableClickFocus.swift new file mode 100644 index 0000000000..6698777448 --- /dev/null +++ b/apple/TablePro/Core/KeyboardHandling/TableClickFocus.swift @@ -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) + } +} diff --git a/apple/TablePro/Core/KeyboardHandling/TableCommandKeys.swift b/apple/TablePro/Core/KeyboardHandling/TableCommandKeys.swift new file mode 100644 index 0000000000..005a875f03 --- /dev/null +++ b/apple/TablePro/Core/KeyboardHandling/TableCommandKeys.swift @@ -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 + } +} diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift index ac2d1f14aa..d9fc7ad0cd 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift @@ -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) @@ -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) } diff --git a/apple/TablePro/Views/Connection/HostListFieldRow.swift b/apple/TablePro/Views/Connection/HostListFieldRow.swift index f3e910b3d7..6f04a92dd4 100644 --- a/apple/TablePro/Views/Connection/HostListFieldRow.swift +++ b/apple/TablePro/Views/Connection/HostListFieldRow.swift @@ -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 { diff --git a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift index b801aedbe7..c3ea5aa3f7 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift @@ -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 { diff --git a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift index 44ff3ed8b8..182eea6353 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift @@ -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 { diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index 504099bb28..9170061c6a 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -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 { diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift index de8453c88d..791943c252 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift @@ -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: NSViewRepresentable { internal let input: FavoritesOutlineInput @Binding internal var selection: FavoriteSelection? diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 08ec6fb5fd..1c56a97245 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -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], diff --git a/apple/TablePro/Views/Sidebar/SidebarOutlineView.swift b/apple/TablePro/Views/Sidebar/SidebarOutlineView.swift index f8a2384802..e6c9baef02 100644 --- a/apple/TablePro/Views/Sidebar/SidebarOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarOutlineView.swift @@ -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() diff --git a/apple/TablePro/Views/Sidebar/SidebarRootShape.swift b/apple/TablePro/Views/Sidebar/SidebarRootShape.swift index 5ff6935c38..5bc68981d5 100644 --- a/apple/TablePro/Views/Sidebar/SidebarRootShape.swift +++ b/apple/TablePro/Views/Sidebar/SidebarRootShape.swift @@ -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 diff --git a/apple/TableProTests/Core/KeyboardHandling/TableClickFocusTests.swift b/apple/TableProTests/Core/KeyboardHandling/TableClickFocusTests.swift new file mode 100644 index 0000000000..825a3f051b --- /dev/null +++ b/apple/TableProTests/Core/KeyboardHandling/TableClickFocusTests.swift @@ -0,0 +1,273 @@ +import AppKit +import SwiftUI +import Testing + +@testable import TablePro + +@MainActor +struct TableClickFocusTests { + // Stands in for SwiftUI's backing table: defined outside AppKit and the app, it hands a click to the view under it. + private class PassThroughTable: NSTableView { + override func hitTest(_ point: NSPoint) -> NSView? { + let local = convert(point, from: superview) + for rowView in subviews.reversed() { + if let inner = rowView.hitTest(local) { return inner } + } + return super.hitTest(point) + } + } + + private final class RefusingPassThroughTable: PassThroughTable { + override var acceptsFirstResponder: Bool { false } + } + + private final class Tile: NSView {} + + private final class Cells: NSObject, NSTableViewDataSource, NSTableViewDelegate { + let editable: Bool + let tiles: Bool + + init(editable: Bool, tiles: Bool) { + self.editable = editable + self.tiles = tiles + } + + func numberOfRows(in tableView: NSTableView) -> Int { 4 } + + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + if tiles { return Tile(frame: NSRect(x: 0, y: 0, width: 280, height: 24)) } + let cell = NSTableCellView(frame: NSRect(x: 0, y: 0, width: 280, height: 24)) + guard editable else { return cell } + let field = NSTextField(string: "row \(row)") + field.frame = cell.bounds + field.autoresizingMask = [.width, .height] + cell.addSubview(field) + return cell + } + } + + private struct SwiftUIRows: View { + let selection: Set + + var body: some View { + List(selection: .constant(selection)) { + ForEach(0 ..< 4, id: \.self) { Text("row \($0)").tag($0) } + } + } + } + + @MainActor + private struct Stage { + let window: NSWindow + let table: NSTableView + let cells: Cells? + + var fields: [NSTextField] { window.contentView?.subviews.compactMap { $0 as? NSTextField } ?? [] } + + func event(_ type: NSEvent.EventType, row: Int, modifiers: NSEvent.ModifierFlags = []) throws -> NSEvent { + let cell = table.frameOfCell(atColumn: 0, row: row) + let point = table.convert(NSPoint(x: cell.midX, y: cell.midY), to: nil) + let event = try #require(NSEvent.mouseEvent( + with: type, + location: point, + modifierFlags: modifiers, + timestamp: 0, + windowNumber: window.windowNumber, + context: nil, + eventNumber: 0, + clickCount: 1, + pressure: 1 + )) + try #require(event.window === window) + return event + } + + func hitView(atRow row: Int) throws -> NSView { + let point = try event(.leftMouseDown, row: row).locationInWindow + return try #require(window.contentView?.superview?.hitTest(point)) + } + + var tableHoldsFocus: Bool { window.firstResponder === table } + } + + private static let frame = NSRect(x: 0, y: 0, width: 300, height: 220) + + private static func makeWindow(holding list: NSView) -> NSWindow { + let window = NSWindow(contentRect: frame, styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + let content = NSView(frame: frame) + let field = NSTextField(frame: NSRect(x: 0, y: 190, width: 150, height: 24)) + let otherField = NSTextField(frame: NSRect(x: 150, y: 190, width: 150, height: 24)) + list.frame = NSRect(x: 0, y: 0, width: 300, height: 180) + content.addSubview(field) + content.addSubview(otherField) + content.addSubview(list) + window.contentView = content + content.layoutSubtreeIfNeeded() + window.displayIfNeeded() + window.makeFirstResponder(field) + return window + } + + private func stage(_ table: NSTableView, editable: Bool = false, tiles: Bool = false, selectedRow: Int? = nil) -> Stage { + let cells = Cells(editable: editable, tiles: tiles) + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("name")) + column.width = 280 + table.addTableColumn(column) + table.headerView = nil + table.dataSource = cells + table.delegate = cells + let scrollView = NSScrollView() + scrollView.documentView = table + let window = Self.makeWindow(holding: scrollView) + table.reloadData() + if let selectedRow { + table.selectRowIndexes(IndexSet(integer: selectedRow), byExtendingSelection: false) + } + scrollView.layoutSubtreeIfNeeded() + return Stage(window: window, table: table, cells: cells) + } + + private static func stageSwiftUIList(selection: Set = []) -> Stage? { + let host = NSHostingView(rootView: SwiftUIRows(selection: selection)) + let window = makeWindow(holding: host) + guard let table = firstTable(in: host) else { return nil } + return Stage(window: window, table: table, cells: nil) + } + + private static func firstTable(in view: NSView) -> NSTableView? { + if let table = view as? NSTableView { return table } + return view.subviews.lazy.compactMap { firstTable(in: $0) }.first + } + + // The private view tree behind a SwiftUI List differs between OS builds, so this asks the host. + static func swiftUIListHandsClicksToItsCells() -> Bool { + guard let stage = stageSwiftUIList(), let hit = try? stage.hitView(atRow: 1) else { return false } + return hit !== stage.table && hit.isDescendant(of: stage.table) && !hit.acceptsFirstResponder + } + + private func click(row: Int, in stage: Stage, modifiers: NSEvent.ModifierFlags = [], with focus: TableClickFocus) async throws { + focus.handle(try stage.event(.leftMouseDown, row: row, modifiers: modifiers)) + focus.handle(try stage.event(.leftMouseUp, row: row, modifiers: modifiers)) + await drainMainQueue() + } + + @Test("A click on an unselected row gives the table focus once the mouse is up") + func unselectedRowClaimsAfterMouseUp() async throws { + let stage = stage(PassThroughTable()) + let focus = TableClickFocus() + + focus.handle(try stage.event(.leftMouseDown, row: 1)) + #expect(!stage.tableHoldsFocus) + focus.handle(try stage.event(.leftMouseUp, row: 1)) + await drainMainQueue() + + #expect(stage.tableHoldsFocus) + } + + @Test("A press on a selected row gives the table focus at once") + func selectedRowClaimsAtMouseDown() throws { + let stage = stage(PassThroughTable(), selectedRow: 2) + let focus = TableClickFocus() + + focus.handle(try stage.event(.leftMouseDown, row: 2)) + + #expect(stage.tableHoldsFocus) + } + + @Test("A focus the click itself moves to another view stays there") + func focusMovedByTheClickStays() async throws { + let stage = stage(PassThroughTable()) + let focus = TableClickFocus() + let other = try #require(stage.fields.last) + + focus.handle(try stage.event(.leftMouseDown, row: 1)) + stage.window.makeFirstResponder(other) + focus.handle(try stage.event(.leftMouseUp, row: 1)) + await drainMainQueue() + + #expect(!stage.tableHoldsFocus) + #expect((stage.window.firstResponder as? NSTextView)?.delegate === other) + } + + @Test("A focus the click leaves vacant goes to the table") + func vacatedFocusGoesToTheTable() async throws { + let stage = stage(PassThroughTable()) + let focus = TableClickFocus() + + focus.handle(try stage.event(.leftMouseDown, row: 1)) + stage.fields.first?.removeFromSuperview() + focus.handle(try stage.event(.leftMouseUp, row: 1)) + await drainMainQueue() + + #expect(stage.tableHoldsFocus) + } + + @Test("A Control-click opens a menu and leaves focus where it was") + func controlClickLeavesFocus() async throws { + let stage = stage(PassThroughTable()) + + try await click(row: 1, in: stage, modifiers: .control, with: TableClickFocus()) + + #expect(!stage.tableHoldsFocus) + } + + @Test("A click on a text field in a row is left to the field") + func focusableHitViewIsLeftAlone() async throws { + let stage = stage(PassThroughTable(), editable: true) + try #require(try stage.hitView(atRow: 1) is NSTextField) + + try await click(row: 1, in: stage, with: TableClickFocus()) + + #expect(!stage.tableHoldsFocus) + } + + @Test("An AppKit table keeps its own click handling, even where it hands the click to a cell") + func appKitTableIsLeftAlone() throws { + let stage = stage(NSTableView(), tiles: true, selectedRow: 1) + try #require(try stage.hitView(atRow: 1) is Tile) + + TableClickFocus().handle(try stage.event(.leftMouseDown, row: 1)) + + #expect(!stage.tableHoldsFocus) + } + + @Test("A table the app defines is left to its own mouseDown, even where it hands the click to a cell") + func appTableIsLeftAlone() throws { + let stage = stage(WorkspaceRailTableView(frame: .zero), tiles: true, selectedRow: 1) + try #require(try stage.hitView(atRow: 1) is Tile) + + TableClickFocus().handle(try stage.event(.leftMouseDown, row: 1)) + + #expect(!stage.tableHoldsFocus) + } + + @Test("A table that refuses focus keeps refusing it") + func refusingTableIsLeftAlone() async throws { + let stage = stage(RefusingPassThroughTable()) + + try await click(row: 1, in: stage, with: TableClickFocus()) + + #expect(!stage.tableHoldsFocus) + } + + @Test( + "A click on a SwiftUI List row gives the list focus", + .enabled("The host's SwiftUI List keeps clicks on its table") { + await TableClickFocusTests.swiftUIListHandsClicksToItsCells() + } + ) + func swiftUIListRowClaims() async throws { + let stage = try #require(Self.stageSwiftUIList()) + + try await click(row: 1, in: stage, with: TableClickFocus()) + + #expect(stage.tableHoldsFocus) + } + + private func drainMainQueue() async { + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + } +} diff --git a/apple/TableProTests/Core/KeyboardHandling/TableCommandKeyTests.swift b/apple/TableProTests/Core/KeyboardHandling/TableCommandKeyTests.swift new file mode 100644 index 0000000000..8c4f9ec1cc --- /dev/null +++ b/apple/TableProTests/Core/KeyboardHandling/TableCommandKeyTests.swift @@ -0,0 +1,187 @@ +import AppKit +import Testing + +@testable import TablePro + +@MainActor +struct TableCommandKeyTests { + private final class RecordingOutline: SidebarOutlineView { + var commands: [String] = [] + + override func insertNewline(_ sender: Any?) { commands.append("insertNewline") } + override func deleteBackward(_ sender: Any?) { commands.append("deleteBackward") } + override func deleteForward(_ sender: Any?) { commands.append("deleteForward") } + } + + private final class KeyRecordingView: NSView { + var keyDowns = 0 + + override func keyDown(with event: NSEvent) { keyDowns += 1 } + } + + private final class RailController: NSViewController { + var opened = 0 + + override func loadView() { view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)) } + override func insertNewline(_ sender: Any?) { opened += 1 } + } + + private final class Rows: NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate, NSTableViewDataSource { + func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { + item == nil ? 3 : 0 + } + + func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { + "row \(index)" + } + + func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { false } + + func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { + NSTableCellView(frame: NSRect(x: 0, y: 0, width: 200, height: 24)) + } + + func numberOfRows(in tableView: NSTableView) -> Int { 3 } + } + + private enum Key { + case returnKey, enter, delete, forwardDelete, down + + var code: KeyCode { + switch self { + case .returnKey: .return + case .enter: .enter + case .delete: .delete + case .forwardDelete: .forwardDelete + case .down: .downArrow + } + } + + var characters: String { + switch self { + case .returnKey: "\r" + case .enter: "\u{3}" + case .delete: "\u{7F}" + case .forwardDelete: "\u{F728}" + case .down: "\u{F701}" + } + } + } + + private func press(_ key: Key, modifiers: NSEvent.ModifierFlags = [], in table: NSTableView) throws { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: modifiers, + timestamp: 0, + windowNumber: table.window?.windowNumber ?? 0, + context: nil, + characters: key.characters, + charactersIgnoringModifiers: key.characters, + isARepeat: false, + keyCode: key.code.rawValue + )) + table.keyDown(with: event) + } + + private func mount(_ table: Table, in container: NSView, rows: Rows) -> NSWindow { + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("name")) + table.addTableColumn(column) + table.headerView = nil + if let outline = table as? NSOutlineView { + outline.outlineTableColumn = column + outline.dataSource = rows + outline.delegate = rows + } else { + table.dataSource = rows + } + let scrollView = NSScrollView(frame: container.bounds) + scrollView.documentView = table + container.addSubview(scrollView) + let window = NSWindow(contentRect: container.frame, styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = container + table.reloadData() + window.makeFirstResponder(table) + table.selectRowIndexes(IndexSet(integer: 1), byExtendingSelection: false) + return window + } + + @Test("Return and keypad Enter reach insertNewline on the outline") + func returnRunsInsertNewline() throws { + let rows = Rows() + let outline = RecordingOutline() + let window = mount(outline, in: NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)), rows: rows) + + try press(.returnKey, in: outline) + try press(.enter, in: outline) + + #expect(outline.commands == ["insertNewline", "insertNewline"]) + _ = window + } + + @Test("Delete and Forward Delete reach their delete commands") + func deleteRunsDeleteCommands() throws { + let rows = Rows() + let outline = RecordingOutline() + let window = mount(outline, in: NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)), rows: rows) + + try press(.delete, in: outline) + try press(.forwardDelete, in: outline) + + #expect(outline.commands == ["deleteBackward", "deleteForward"]) + _ = window + } + + @Test("A key with a modifier is not turned into a command") + func modifiedKeysStayKeys() throws { + let rows = Rows() + let outline = RecordingOutline() + let window = mount(outline, in: NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)), rows: rows) + + try press(.delete, modifiers: .shift, in: outline) + try press(.returnKey, modifiers: .shift, in: outline) + + #expect(outline.commands.isEmpty) + _ = window + } + + @Test("An arrow key still moves the selection") + func arrowMovesSelection() throws { + let rows = Rows() + let outline = RecordingOutline() + let window = mount(outline, in: NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)), rows: rows) + + try press(.down, in: outline) + + #expect(outline.selectedRow == 2) + #expect(outline.commands.isEmpty) + _ = window + } + + @Test("Return nobody answers keeps travelling up, so a default button can take it") + func unansweredReturnPassesUp() throws { + let rows = Rows() + let outline = SidebarOutlineView() + let container = KeyRecordingView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)) + let window = mount(outline, in: container, rows: rows) + + try press(.returnKey, in: outline) + + #expect(container.keyDowns == 1) + _ = window + } + + @Test("Return on the connections strip reaches its controller") + func railReturnReachesController() throws { + let rows = Rows() + let controller = RailController() + let table = WorkspaceRailTableView(frame: .zero) + let window = mount(table, in: controller.view, rows: rows) + + try press(.returnKey, in: table) + + #expect(controller.opened == 1) + _ = window + } +} diff --git a/apple/TableProUITests/ListClickFocusUITests.swift b/apple/TableProUITests/ListClickFocusUITests.swift new file mode 100644 index 0000000000..5217fa839a --- /dev/null +++ b/apple/TableProUITests/ListClickFocusUITests.swift @@ -0,0 +1,42 @@ +import XCTest + +final class ListClickFocusUITests: UITestCase { + func testClickingASectionGivesTheListTheArrowKeys() throws { + let app = try launchApp() + let welcome = welcomeWindow(in: app) + XCTAssertTrue(welcome.waitToExist(timeout: 10)) + + app.typeShortcut(.newConnection) + let chooser = welcome.sheets.firstMatch + let search = chooser.searchFields["database-type-chooser-search"] + XCTAssertTrue(waitUntilHittable(search, timeout: 10), "New Connection must present the database chooser") + search.click() + search.typeText("SQLite") + let proceed = chooser.buttons["Continue"] + XCTAssertTrue(waitForPredicate(timeout: 10) { proceed.exists && proceed.isEnabled }) + proceed.click() + + let form = window("connection-form", in: app) + XCTAssertTrue(form.waitToExist(timeout: 10), "Choosing SQLite must open the connection form") + let name = form.textFields["connection-form-name"] + XCTAssertTrue(waitUntilHittable(name, timeout: 10)) + name.click() + + let sidebar = form.outlines.containing(.staticText, identifier: "connection-form-section-options").firstMatch + let optionsRow = sidebar.outlineRows.containing(.staticText, identifier: "connection-form-section-options").firstMatch + let options = optionsRow.staticTexts["connection-form-section-options"] + XCTAssertTrue(waitUntilHittable(options, timeout: 10)) + options.click() + XCTAssertTrue(waitForPredicate(timeout: 10) { optionsRow.isSelected }, "Clicking Options must select it") + XCTAssertTrue( + waitForPredicate(timeout: 10) { self.holdsKeyboardFocus(sidebar) }, + "Clicking a section must move the keyboard from the name field to the list" + ) + + app.typeKey(.upArrow, modifierFlags: []) + XCTAssertTrue( + waitForPredicate(timeout: 10) { !optionsRow.isSelected }, + "Up after clicking a section must select the section above it" + ) + } +} diff --git a/apple/TableProUITests/WelcomeConnectionListUITests.swift b/apple/TableProUITests/WelcomeConnectionListUITests.swift index 7509a4fabc..fac7679b2d 100644 --- a/apple/TableProUITests/WelcomeConnectionListUITests.swift +++ b/apple/TableProUITests/WelcomeConnectionListUITests.swift @@ -43,4 +43,20 @@ final class WelcomeConnectionListUITests: UITestCase { "Escape must keep the old name" ) } + + func testReturnOnASelectedConnectionOpensIt() throws { + try seedSQLiteSession([ConnectionSeed(name: "alpha-staging", tabs: [], isOpen: false)]) + let app = try launchApp() + let welcome = welcomeWindow(in: app) + XCTAssertTrue(welcome.waitToExist(timeout: 15)) + let list = welcomeConnectionList(in: welcome) + let row = welcomeConnectionRow(named: "alpha-staging", in: list) + XCTAssertTrue(waitUntilHittable(row, timeout: 15)) + row.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(list) }, "A click must give the list the keyboard") + + app.typeKey(.return, modifierFlags: []) + + XCTAssertTrue(mainWindow(in: app).waitToExist(timeout: 30), "Return must open the selected connection") + } } diff --git a/apple/changelog.d/4175.fixed.1.md b/apple/changelog.d/4175.fixed.1.md new file mode 100644 index 0000000000..3f9427a4ad --- /dev/null +++ b/apple/changelog.d/4175.fixed.1.md @@ -0,0 +1 @@ +Return and Delete on a selected row in the Welcome window, Favorites and the connections strip no longer do nothing. diff --git a/apple/changelog.d/4175.fixed.2.md b/apple/changelog.d/4175.fixed.2.md new file mode 100644 index 0000000000..0168844b6c --- /dev/null +++ b/apple/changelog.d/4175.fixed.2.md @@ -0,0 +1 @@ +The host, attached database and extension lists in the connection form no longer hide the rows that do not fit. diff --git a/apple/changelog.d/4175.fixed.md b/apple/changelog.d/4175.fixed.md new file mode 100644 index 0000000000..e8deb394dd --- /dev/null +++ b/apple/changelog.d/4175.fixed.md @@ -0,0 +1 @@ +On macOS 27, clicking a row in a list or table no longer leaves its selection grey and the arrow keys going elsewhere.