From 48cea53e0be2d7295ef5cccfb2a7b3f488aef287 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 18 Nov 2026 18:13:46 +0700 Subject: [PATCH 1/4] refactor(macos): rebuild the editor tab bar on AppKit to match the system tab bar --- .../Infrastructure/EditorTabReorder.swift | 2 +- .../EditorTabStripPaneController.swift | 80 +-- ...plitViewController+TabStripAccessory.swift | 120 ++-- .../Infrastructure/WindowManager.swift | 36 +- .../Infrastructure/WorkspacePanes.swift | 9 +- .../Models/Settings/AppSettings.swift | 6 +- .../Views/Main/EditorTabCommands.swift | 33 + .../Main/EditorTabContextMenuBuilder.swift | 131 ++-- .../Views/Main/EditorTabInteractionView.swift | 426 ------------ .../Views/Main/EditorTabItemView.swift | 383 +++++++++++ .../Main/EditorTabReorderCancelMonitor.swift | 96 --- .../Views/Main/EditorTabRunLayout.swift | 188 ++--- .../TablePro/Views/Main/EditorTabStrip.swift | 640 ------------------ .../EditorTabStripAccessoryController.swift | 59 +- .../Main/EditorTabStripInteraction.swift | 217 ------ .../Views/Main/EditorTabStripLayout.swift | 94 +-- .../Views/Main/EditorTabStripSnapshot.swift | 83 +++ .../Views/Main/EditorTabStripSurfaces.swift | 79 +-- .../Views/Main/EditorTabStripView.swift | 609 +++++++++++++++++ .../Views/Settings/GeneralSettingsView.swift | 7 - .../Helpers/EditorTabFixtures.swift | 89 +++ .../EditorTabContextMenuBuilderTests.swift | 56 +- .../Main/EditorTabMiddleClickTests.swift | 219 ++---- .../Views/Main/EditorTabRunLayoutTests.swift | 204 +++--- .../Main/EditorTabStripChromeTests.swift | 230 ++----- .../Main/EditorTabStripInteractionTests.swift | 204 ------ .../Main/EditorTabStripLayoutTests.swift | 12 +- .../Main/EditorTabStripSnapshotTests.swift | 75 ++ .../Main/EditorTabStripSurfacesTests.swift | 170 ++--- .../Main/EditorTabStripTrackThemeTests.swift | 74 +- .../Views/Main/EditorTabStripViewTests.swift | 215 ++++++ .../Main/EditorTabStripWindowDragTests.swift | 45 +- .../EditorTabDetachUITests.swift | 24 + .../EditorTabReorderUITests.swift | 4 +- 34 files changed, 2111 insertions(+), 2808 deletions(-) create mode 100644 apple/TablePro/Views/Main/EditorTabCommands.swift delete mode 100644 apple/TablePro/Views/Main/EditorTabInteractionView.swift create mode 100644 apple/TablePro/Views/Main/EditorTabItemView.swift delete mode 100644 apple/TablePro/Views/Main/EditorTabReorderCancelMonitor.swift delete mode 100644 apple/TablePro/Views/Main/EditorTabStrip.swift delete mode 100644 apple/TablePro/Views/Main/EditorTabStripInteraction.swift create mode 100644 apple/TablePro/Views/Main/EditorTabStripSnapshot.swift create mode 100644 apple/TablePro/Views/Main/EditorTabStripView.swift create mode 100644 apple/TableProTests/Helpers/EditorTabFixtures.swift delete mode 100644 apple/TableProTests/Views/Main/EditorTabStripInteractionTests.swift create mode 100644 apple/TableProTests/Views/Main/EditorTabStripSnapshotTests.swift create mode 100644 apple/TableProTests/Views/Main/EditorTabStripViewTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift index aa52514285..fb1563f680 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabReorder.swift @@ -72,7 +72,7 @@ internal struct EditorTabReorder: Equatable { internal enum EditorTabReorderResolver { /// `location` is measured in the track's *content* space, so it is unaffected by how far the /// track has scrolled. Tabs share the track equally, which is what makes a width enough to - /// place a point; `EditorTabStripLayout.tabWidth(forTrack:count:)` is the one that produced it. + /// place a point; `EditorTabStripLayout.tabWidth(forViewport:count:)` is the one that produced it. internal static func destination( forLocation location: CGFloat, tabWidth: CGFloat, diff --git a/apple/TablePro/Core/Services/Infrastructure/EditorTabStripPaneController.swift b/apple/TablePro/Core/Services/Infrastructure/EditorTabStripPaneController.swift index f36891d56d..01311f2bfe 100644 --- a/apple/TablePro/Core/Services/Infrastructure/EditorTabStripPaneController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/EditorTabStripPaneController.swift @@ -4,64 +4,54 @@ // import AppKit -import SwiftUI +import Combine -/// One connection's tab strip pane: an AppKit view that owns the pointer, wrapped around the -/// SwiftUI view that draws. -/// -/// It is a pane like the other three, built and kept alive per connection, so it carries the same -/// `sizingOptions = []` firewall that stops tab content publishing a minimum width the window's -/// split dividers cannot beat (#1872). -/// -/// The height is published rather than fixed. A wrapped strip is taller than a scrolling one, and -/// `preferredContentSize` is the documented way for a child to tell its parent so; the titlebar -/// accessory grows the band from it, which is what keeps the content below laid out around the -/// strip instead of behind it. @MainActor internal final class EditorTabStripPaneController: NSViewController { - internal let interaction = EditorTabStripInteraction() + internal let stripView = EditorTabStripView() - private let hosting = NSHostingController(rootView: AnyView(Color.clear)) + private var subscriptions: Set = [] + private var execution: TabExecutionObservation? - internal var rootView: AnyView { - get { hosting.rootView } - set { hosting.rootView = newValue } + override internal func loadView() { + view = stripView + preferredContentSize = CGSize(width: 0, height: EditorTabStripLayout.bandHeight) } - override internal func loadView() { - let surface = EditorTabInteractionView(interaction: interaction) - surface.onRowCountChanged = { [weak self] rows in - self?.publishHeight(forRowCount: rows) + internal func bind( + tabManager: QueryTabManager, + execution: TabExecutionObservation, + target: ContainerSwitchTarget?, + commands: EditorTabCommands + ) { + subscriptions.removeAll() + self.execution = execution + stripView.commands = commands + + let refresh = { [weak self, weak tabManager, weak execution] in + guard let self, let tabManager, let execution else { return } + self.stripView.apply(EditorTabStripSnapshot.items( + tabs: tabManager.visibleTabs, + selectedId: tabManager.selectedTab?.id, + target: target, + isBusy: { execution.isBusy($0) } + )) } - view = surface + tabManager.onMainActorChange(refresh).store(in: &subscriptions) + execution.onMainActorChange(refresh).store(in: &subscriptions) + refresh() + } - hosting.sizingOptions = [] - addChild(hosting) - let pane = hosting.view - pane.translatesAutoresizingMaskIntoConstraints = false - surface.addSubview(pane) - NSLayoutConstraint.activate([ - pane.leadingAnchor.constraint(equalTo: surface.leadingAnchor), - pane.trailingAnchor.constraint(equalTo: surface.trailingAnchor), - pane.topAnchor.constraint(equalTo: surface.topAnchor), - pane.bottomAnchor.constraint(equalTo: surface.bottomAnchor), - ]) - publishHeight(forRowCount: 1) + internal func unbind() { + subscriptions.removeAll() + execution = nil + stripView.commands = nil + stripView.apply([]) } - /// Empties the pane the way every other one is emptied, including the explicit layout pass a - /// detached hosting controller needs before SwiftUI will dismantle its tree. internal func teardown() { - interaction.commands = nil - rootView = AnyView(Color.clear) - hosting.view.layoutSubtreeIfNeeded() + unbind() view.removeFromSuperview() removeFromParent() } - - private func publishHeight(forRowCount rows: Int) { - let height = EditorTabStripLayout.bandHeight(forRowCount: rows) - guard preferredContentSize.height != height else { return } - preferredContentSize = CGSize(width: 0, height: height) - } } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift index 06e7a84ac3..a33d14070a 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift @@ -5,14 +5,9 @@ import AppKit import Combine -import SwiftUI internal extension MainSplitViewController { - /// Installed from `TabWindowController.init`, right after the content view controller is - /// assigned, rather than from `viewWillAppear`. A window that joins a tab group without ever - /// being activated never runs its appearance lifecycle, so a band added there would be missing - /// from every background tab until the user clicked it. That is the same shape as the blank - /// window title CLAUDE.md records, and the fix is the same: do it at construction. + // At construction, because a window that joins a tab group without activating never runs its appearance lifecycle. func installTabStripAccessory(on window: NSWindow) { guard !window.titlebarAccessoryViewControllers.contains(where: { $0 === tabStripAccessory }) else { return } tabStripAccessory.setBandVisible(false) @@ -20,10 +15,18 @@ internal extension MainSplitViewController { showSelectedTabStrip() } - /// The strip is built per connection like the other three panes, so a connection the user is - /// not looking at keeps its own strip rather than rebuilding it on every switch. func refreshTabStripPane(of workspace: ConnectionWorkspace) { - workspace.panes.tabStrip.rootView = buildTabStripView(for: workspace) + let pane = workspace.panes.tabStrip + guard let sessionState = workspace.sessionState else { + pane.unbind() + return + } + pane.bind( + tabManager: sessionState.tabManager, + execution: TabExecutionObservation(owner: sessionState.coordinator), + target: workspace.connection.flatMap { PluginManager.shared.containerSwitchTarget(for: $0.type) }, + commands: makeTabCommands(for: workspace, sessionState: sessionState) + ) } func showSelectedTabStrip() { @@ -31,12 +34,7 @@ internal extension MainSplitViewController { applyTabStripVisibility() } - /// Re-arms on every call, which is what makes this safe to drive from anywhere. The first arm - /// a window makes is worthless on its own: it runs from `TabWindowController.init`, before the - /// connection has a session, so the tracking closure reads through a nil `sessionState` and - /// registers a dependency on nothing. Only the call that follows the session coming up sees a - /// real `tabManager` to observe, and there is no single moment in the lifecycle that is - /// reliably that call. + // Re-arms on every call: the first arm runs from `TabWindowController.init`, before the connection has a session. func applyTabStripVisibility() { let tabCount = workspaces.selected?.sessionState?.tabManager.visibleTabs.count ?? 0 tabStripAccessory.setBandVisible( @@ -49,16 +47,7 @@ internal extension MainSplitViewController { armTabStripObservation() } - /// `withObservationTracking` fires once per registration and cannot be cancelled, so something - /// has to re-register and nothing may register twice. `applyTabStripVisibility()` runs on every - /// phase change and every workspace switch, which would otherwise leave a live arm behind each - /// time and wake all of them on the next tab change. An arm is therefore made only when there - /// is none, or when the connection on screen changed and the live one is watching the previous - /// connection's tab manager: `workspaces.selected` is not itself observable, so a switch can - /// never reach the closure on its own. - /// - /// The generation is still carried, because an arm that has already fired cannot be recalled - /// and must fail its own guard rather than act on a window that has moved on. + // The generation is carried because an arm that already fired cannot be recalled and must fail its own guard. private func armTabStripObservation() { let manager = workspaces.selected?.sessionState?.tabManager let identity = manager.map(ObjectIdentifier.init) @@ -69,10 +58,6 @@ internal extension MainSplitViewController { tabStripObservedManager = identity let generation = tabStripObservationGeneration - /// `onMainActorChange` already delivers a turn late, which is what the count needs: - /// the publisher fires before the change lands. It also wakes for any tab mutation - /// rather than only a count change, so the count is compared here. The count is the - /// strip's, which moving to another entry changes without a tab opening or closing. guard let manager = workspaces.selected?.sessionState?.tabManager else { return } var lastCount = manager.visibleTabs.count tabStripObservation = manager.onMainActorChange { [weak self] in @@ -85,45 +70,32 @@ internal extension MainSplitViewController { } } - /// `commandActions` is read at click time rather than captured, because it only exists once - /// the detail pane has appeared and this strip is built alongside that pane, not after it. - /// The workspace is held weakly: it owns the hosting controller these closures live in. - /// - /// The command set is handed to the pane's interaction object rather than to the SwiftUI view, - /// because the view is no longer what receives a press. AppKit owns the pointer over the - /// strip and reaches the app through exactly these closures. - private func buildTabStripView(for workspace: ConnectionWorkspace) -> AnyView { - guard let sessionState = workspace.sessionState else { return AnyView(Color.clear) } - let interaction = workspace.panes.tabStrip.interaction - configure(interaction, for: workspace, sessionState: sessionState) - return AnyView( - EditorTabStrip( - tabManager: sessionState.tabManager, - interaction: interaction, - containerTarget: workspace.connection.flatMap { - PluginManager.shared.containerSwitchTarget(for: $0.type) - }, - execution: TabExecutionObservation(owner: sessionState.coordinator), - onNewTab: { [weak workspace] in - workspace?.sessionState?.coordinator.commandActions?.newTab() - } - ) - ) + private static func tabStripContains(screenPoint: NSPoint) -> Bool { + let number = NSWindow.windowNumber(at: screenPoint, belowWindowWithWindowNumber: 0) + guard let window = NSApp.window(withWindowNumber: number), + let split = window.contentViewController as? MainSplitViewController, + !split.tabStripAccessory.isHidden + else { return false } + let band = split.tabStripAccessory.view + return window.convertToScreen(band.convert(band.bounds, to: nil)).contains(screenPoint) } - private func configure( - _ interaction: EditorTabStripInteraction, + // The workspace is held weakly: it owns the pane these closures live in. + private func makeTabCommands( for workspace: ConnectionWorkspace, sessionState: SessionStateFactory.SessionState - ) { + ) -> EditorTabCommands { let manager = sessionState.tabManager - let target = workspace.connection.flatMap { PluginManager.shared.containerSwitchTarget(for: $0.type) } - interaction.commands = EditorTabCommands( + return EditorTabCommands( + connectionId: workspace.connectionId, activate: { [weak manager] id in guard let manager, manager.selectedTabId != id else { return } TabSwitchTracer.shared.requestSwitch(.tabStrip, to: id) manager.selectedTabId = id }, + newTab: { [weak workspace] in + workspace?.sessionState?.coordinator.commandActions?.newTab() + }, keepOpen: { [weak manager] id in manager?.promotePreviewTab(id: id) if #available(macOS 14.0, *) { @@ -151,9 +123,9 @@ internal extension MainSplitViewController { moveTab: { [weak manager] id, destination in manager?.moveTab(id: id, to: destination) }, canMove: { [weak manager] id, offset in manager?.canMoveTab(id: id, by: offset) ?? false }, moveBy: { [weak manager] id, offset in manager?.moveTab(id: id, by: offset) }, - tearOff: { [weak workspace] id in + tearOff: { [weak workspace] id, dropPoint in guard let connectionId = workspace?.connectionId else { return } - WindowManager.shared.openTabInNewWindow(connectionId: connectionId, tabId: id) + WindowManager.shared.openTabInNewWindow(connectionId: connectionId, tabId: id, droppedAt: dropPoint) }, canTearOff: { [weak workspace] id in guard let workspace, @@ -171,8 +143,12 @@ internal extension MainSplitViewController { .reportedStatus.isConnected == true ) }, - /// The selection is left alone: selecting first would judge the tab against the grid edits - /// of the tab it replaced, which the change manager still holds until the switch lands. + receiveTab: { [weak workspace] id, index in + guard let workspace else { return false } + return WindowManager.shared.moveTab(id, into: workspace, at: index) + }, + isOverTabStrip: { Self.tabStripContains(screenPoint: $0) }, + // The selection is left alone: selecting first would judge the tab against the grid edits it replaced. moveToConnection: { [weak self] id in self?.presentMoveTabPicker(tabId: id) }, @@ -181,27 +157,7 @@ internal extension MainSplitViewController { }, canMoveToConnection: { [weak workspace] id in workspace?.sessionState?.coordinator.canMoveTabToConnection(id) ?? false - }, - /// The resolver's description, not the drawn title: a table tab carries its database - /// and schema there even when the short title is unique, and the tooltip is where a - /// truncated or duplicated name is told apart. - tooltip: { [weak manager] id in - guard let manager, let tab = manager.tabs.first(where: { $0.id == id }) else { return "" } - let description = EditorTabLabelResolver.resolve(tabs: manager.visibleTabs, target: target)[id]? - .description ?? tab.title - guard tab.isPreview else { return description } - return String( - format: String(localized: "%@\nPreview tab. Double-click to keep it open."), - description - ) } ) - /// Seeded here, where the strip is built, rather than from one of its view modifiers. See - /// `EditorTabStripInteraction.adopt(tabIds:overflow:)`; the strip's own `onChange` carries - /// every later change. - interaction.adopt( - tabIds: manager.visibleTabs.map(\.id), - overflow: AppSettingsManager.shared.tabs.overflow - ) } } diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift index d8db9f0d62..c80edce47e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift @@ -230,7 +230,7 @@ internal final class WindowManager { /// payload, so nothing re-opens or re-restores it, and the intent is `.openContent` because /// `.restoreOrDefault` would fill the new window with the whole saved set. @discardableResult - internal func openTabInNewWindow(connectionId: UUID, tabId: UUID) -> Bool { + internal func openTabInNewWindow(connectionId: UUID, tabId: UUID, droppedAt dropPoint: NSPoint? = nil) -> Bool { /// Resolved by which workspace actually holds the tab. After one detach the connection is /// hosted twice, and the singular lookup names an arbitrary one of them: asking it for a /// tab that lives in the other window fails a move the user did ask for. @@ -296,12 +296,46 @@ internal final class WindowManager { /// merge it straight back into the tab group it was asked to leave, which is the trap /// `openStandaloneWindow` already documents. window.tabbingMode = .disallowed + if let dropPoint { + window.setFrameTopLeftPoint(NSPoint(x: dropPoint.x - Self.droppedWindowInset.width, y: dropPoint.y + Self.droppedWindowInset.height)) + } window.makeKeyAndOrderFront(nil) window.tabbingMode = .automatic AppActivationPolicyController.shared.activate(ignoringOtherApps: true) return true } + // Puts the new window's titlebar under the pointer that dropped the tab. + private static let droppedWindowInset = NSSize(width: 120, height: 20) + + // A tab dropped on another window of its connection. Both windows share the session, so only the tab moves. + @discardableResult + internal func moveTab(_ tabId: UUID, into target: ConnectionWorkspace, at index: Int) -> Bool { + guard let origin = workspaces(for: target.connectionId).first(where: { workspace in + workspace !== target && workspace.sessionState?.tabManager.tabs.contains { $0.id == tabId } == true + }), + let sourceState = origin.sessionState, + let targetState = target.sessionState, + let tab = sourceState.tabManager.tabs.first(where: { $0.id == tabId }) + else { return false } + + let moved = sourceState.coordinator.enrichedForPersistence(tab) + if let liveSession = sourceState.coordinator.tabSessionRegistry.session(for: tabId) { + targetState.coordinator.tabSessionRegistry.register(liveSession) + } + sourceState.coordinator.tabSessionRegistry.unregister(id: tabId) + sourceState.tabManager.closeTab(id: tabId) + + targetState.tabManager.adoptTab(moved, claimFocus: true) + targetState.tabManager.moveTab(id: moved.id, to: index) + host(containing: target)?.view.window?.makeKeyAndOrderFront(nil) + return true + } + + private func host(containing workspace: ConnectionWorkspace) -> MainSplitViewController? { + hosts().first { $0.workspaces.workspace(for: workspace.connectionId) === workspace } + } + // MARK: - Move Tab to Connection /// Moves a query tab to another connection, connecting that one when it is not up. The tab diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspacePanes.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspacePanes.swift index 0d5a39eac1..366e3f7be3 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspacePanes.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspacePanes.swift @@ -79,14 +79,7 @@ internal final class WorkspacePanes { internal let agentConversation: NSHostingController internal let sidebar: NSHostingController - /// The editor tab strip. It is a pane like the other three, built and kept alive per - /// connection, even though the window shows it in the titlebar accessory rather than in a - /// split item. Holding it here is what gives it the same `sizingOptions` firewall and the - /// same teardown as everything else the connection owns. - /// - /// It is the one pane that is not a bare hosting controller. AppKit owns the pointer over the - /// strip, so the SwiftUI view is wrapped in the view that owns it; see - /// `EditorTabStripPaneController`. + // Kept per connection like the other panes, though the window shows it in the titlebar accessory. internal let tabStrip: EditorTabStripPaneController /// Written by the one function that produces pane content, and read by the one that decides diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 9d4d1cf751..ac43c890b5 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -351,19 +351,15 @@ struct HistorySettings: Codable, Equatable { struct TabSettings: Codable, Equatable { var enablePreviewTabs: Bool = true - // `scroll` is the system's answer: every tab bar Apple ships keeps one row and scrolls it. - var overflow: EditorTabStripOverflow = .scroll static let `default` = TabSettings() - init(enablePreviewTabs: Bool = true, overflow: EditorTabStripOverflow = .scroll) { + init(enablePreviewTabs: Bool = true) { self.enablePreviewTabs = enablePreviewTabs - self.overflow = overflow } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let fallback = Self.default enablePreviewTabs = container.decodeSetting(.enablePreviewTabs, default: fallback.enablePreviewTabs) - overflow = container.decodeSetting(.overflow, default: fallback.overflow) } } diff --git a/apple/TablePro/Views/Main/EditorTabCommands.swift b/apple/TablePro/Views/Main/EditorTabCommands.swift new file mode 100644 index 0000000000..1eb718bfa9 --- /dev/null +++ b/apple/TablePro/Views/Main/EditorTabCommands.swift @@ -0,0 +1,33 @@ +// +// EditorTabCommands.swift +// TablePro +// + +import AppKit +import Foundation + +internal struct EditorTabCommands { + internal let connectionId: UUID + internal let activate: (UUID) -> Void + internal let newTab: () -> Void + internal let keepOpen: (UUID) -> Void + internal let canKeepOpen: (UUID) -> Bool + internal let isPinned: (UUID) -> Bool + internal let setPinned: (UUID, Bool) -> Void + internal let close: (UUID) -> Void + internal let closeOthers: (UUID) -> Void + internal let canCloseOthers: (UUID) -> Bool + internal let closeAll: () -> Void + internal let canCloseAll: () -> Bool + internal let moveTab: (UUID, Int) -> Void + internal let canMove: (UUID, Int) -> Bool + internal let moveBy: (UUID, Int) -> Void + // The screen point a dragged tab was dropped at, nil when the menu asked. + internal let tearOff: (UUID, NSPoint?) -> Void + internal let canTearOff: (UUID) -> Bool + internal let receiveTab: (UUID, Int) -> Bool + internal let isOverTabStrip: (NSPoint) -> Bool + internal let moveToConnection: (UUID) -> Void + internal let offersMoveToConnection: (UUID) -> Bool + internal let canMoveToConnection: (UUID) -> Bool +} diff --git a/apple/TablePro/Views/Main/EditorTabContextMenuBuilder.swift b/apple/TablePro/Views/Main/EditorTabContextMenuBuilder.swift index 7f92c9203f..3a265e9143 100644 --- a/apple/TablePro/Views/Main/EditorTabContextMenuBuilder.swift +++ b/apple/TablePro/Views/Main/EditorTabContextMenuBuilder.swift @@ -5,83 +5,84 @@ import AppKit -/// The tab's contextual menu, built in AppKit because AppKit now owns the press. -/// -/// The strip keeps its SwiftUI `.contextMenu` as well, and the two never both fire: a right-click -/// resolves through `NSView.menu(for:)` on the view that owns the press, and the SwiftUI menu is -/// left as the route VoiceOver and Full Keyboard Access already take to the same commands. @MainActor internal enum EditorTabContextMenuBuilder { + private struct Command { + let title: String + var isEnabled = true + var startsGroup = false + let action: () -> Void + } + internal static func menu(for tabId: UUID, commands: EditorTabCommands) -> NSMenu { let menu = NSMenu() menu.autoenablesItems = false - - append( - menu, - title: String(localized: "Keep Open"), - isEnabled: commands.canKeepOpen(tabId) - ) { commands.keepOpen(tabId) } - - let isPinned = commands.isPinned(tabId) - append(menu, title: pinTitle(isPinned: isPinned)) { commands.setPinned(tabId, !isPinned) } - - menu.addItem(.separator()) - - append(menu, title: String(localized: "Close Tab")) { commands.close(tabId) } - append( - menu, - title: String(localized: "Close Other Tabs"), - isEnabled: commands.canCloseOthers(tabId) - ) { commands.closeOthers(tabId) } - append( - menu, - title: String(localized: "Close All Tabs"), - isEnabled: commands.canCloseAll() - ) { commands.closeAll() } - - menu.addItem(.separator()) - - append( - menu, - title: String(localized: "Move Tab Left"), - isEnabled: commands.canMove(tabId, -1) - ) { commands.moveBy(tabId, -1) } - append( - menu, - title: String(localized: "Move Tab Right"), - isEnabled: commands.canMove(tabId, 1) - ) { commands.moveBy(tabId, 1) } - - menu.addItem(.separator()) - - append( - menu, - title: String(localized: "Move Tab to New Window"), - isEnabled: commands.canTearOff(tabId) - ) { commands.tearOff(tabId) } - - /// Hidden rather than dimmed on a tab that can never move, as the HIG asks of context menus. - if commands.offersMoveToConnection(tabId) { - append( - menu, - title: String(localized: "Move Tab to Connection…"), - isEnabled: commands.canMoveToConnection(tabId) - ) { commands.moveToConnection(tabId) } + for command in entries(for: tabId, commands: commands) { + if command.startsGroup { + menu.addItem(.separator()) + } + menu.addItem(ClosureMenuTarget.item( + title: command.title, + isEnabled: command.isEnabled, + action: command.action + )) } - return menu } + // The rotor lists only what would do something, the same commands the menu offers. + internal static func accessibilityActions( + for tabId: UUID, + commands: EditorTabCommands + ) -> [NSAccessibilityCustomAction] { + entries(for: tabId, commands: commands).filter(\.isEnabled).map { command in + let action = command.action + return NSAccessibilityCustomAction(name: command.title) { + action() + return true + } + } + } + internal static func pinTitle(isPinned: Bool) -> String { isPinned ? String(localized: "Unpin Tab") : String(localized: "Pin Tab") } - private static func append( - _ menu: NSMenu, - title: String, - isEnabled: Bool = true, - action: @escaping () -> Void - ) { - menu.addItem(ClosureMenuTarget.item(title: title, isEnabled: isEnabled, action: action)) + private static func entries(for tabId: UUID, commands: EditorTabCommands) -> [Command] { + let isPinned = commands.isPinned(tabId) + var entries = [ + Command(title: String(localized: "Keep Open"), isEnabled: commands.canKeepOpen(tabId)) { + commands.keepOpen(tabId) + }, + Command(title: pinTitle(isPinned: isPinned)) { commands.setPinned(tabId, !isPinned) }, + Command(title: String(localized: "Close Tab"), startsGroup: true) { commands.close(tabId) }, + Command(title: String(localized: "Close Other Tabs"), isEnabled: commands.canCloseOthers(tabId)) { + commands.closeOthers(tabId) + }, + Command(title: String(localized: "Close All Tabs"), isEnabled: commands.canCloseAll()) { + commands.closeAll() + }, + Command( + title: String(localized: "Move Tab Left"), + isEnabled: commands.canMove(tabId, -1), + startsGroup: true + ) { commands.moveBy(tabId, -1) }, + Command(title: String(localized: "Move Tab Right"), isEnabled: commands.canMove(tabId, 1)) { + commands.moveBy(tabId, 1) + }, + Command( + title: String(localized: "Move Tab to New Window"), + isEnabled: commands.canTearOff(tabId), + startsGroup: true + ) { commands.tearOff(tabId, nil) }, + ] + // Hidden rather than dimmed on a tab that can never move, as the HIG asks of context menus. + if commands.offersMoveToConnection(tabId) { + entries.append(Command( + title: String(localized: "Move Tab to Connection…"), + isEnabled: commands.canMoveToConnection(tabId) + ) { commands.moveToConnection(tabId) }) + } + return entries } } diff --git a/apple/TablePro/Views/Main/EditorTabInteractionView.swift b/apple/TablePro/Views/Main/EditorTabInteractionView.swift deleted file mode 100644 index eff508f767..0000000000 --- a/apple/TablePro/Views/Main/EditorTabInteractionView.swift +++ /dev/null @@ -1,426 +0,0 @@ -// -// EditorTabInteractionView.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// The single owner of pointer input over the editor tab strip. -/// -/// It is the strip's superview rather than a view laid over it, which is what keeps the SwiftUI -/// tabs where accessibility already finds them: a view mounted *over* the track covers every tab in -/// the accessibility tree however little it draws, measured, which is why the Escape monitor this -/// replaces had to be a background. A parent adds no sibling and shadows nothing. -/// -/// Two things follow from owning the press outright. `mouseDownCanMoveWindow` is false, so AppKit's -/// titlebar window drag can never take a gesture that started on a tab, at any position, on any -/// machine. And the click, the reorder and the tear-off are told apart inside one AppKit tracking -/// loop rather than by SwiftUI arbitrating between a `Button`, a `ScrollView` and a `DragGesture`, -/// which is what made a plain one-place drag do nothing about one time in seven. -/// -/// The loop is the shape AppKit controls have always used: `nextEvent(matching:)` with periodic -/// events mixed in, which is the documented way to keep autoscrolling while the pointer is held -/// still at the edge of the track. -@MainActor -internal final class EditorTabInteractionView: NSView { - internal let interaction: EditorTabStripInteraction - - /// Told to the pane controller, which publishes it as the band's height. A wrapped strip is - /// taller, and the titlebar accessory has to grow with it or the extra rows are drawn behind - /// the content. - internal var onRowCountChanged: ((Int) -> Void)? - - private var isResolvingAccessibilityHit = false - private var hoverTrackingArea: NSTrackingArea? - private var lastActivatedTabId: UUID? - private var middleClickTabId: UUID? - - internal init(interaction: EditorTabStripInteraction) { - self.interaction = interaction - super.init(frame: .zero) - /// Every path that re-lays the run reports through here, not just this view's own layout. - /// A tab opened or closed while the strip is wrapped can cross a row boundary, and that - /// change arrives on the interaction rather than on a layout pass. - interaction.onRowCountChanged = { [weak self] rows in - self?.onRowCountChanged?(rows) - self?.needsLayout = true - } - } - - @available(*, unavailable) - internal required init?(coder: NSCoder) { - fatalError("EditorTabInteractionView does not support NSCoder init") - } - - /// The run layout, the SwiftUI drawing and this view's hit testing all measure y downward, so - /// none of the three has to flip the other two. - override internal var isFlipped: Bool { true } - - /// The strip never drags the window. The band around it keeps AppKit's default, so the empty - /// chrome either side of the track still moves the window the way Finder's tab bar does. - override internal var mouseDownCanMoveWindow: Bool { false } - - override internal func isAccessibilityElement() -> Bool { false } - - // MARK: - Geometry - - /// The track's viewport, which is everything the pointer owns. The new-tab button sits outside - /// it and stays an ordinary SwiftUI button. - internal var trackRect: CGRect { - let trailing = EditorTabStripLayout.stripInset - + EditorTabStripLayout.newTabButtonSize - + EditorTabStripLayout.trackSpacing - let width = max(bounds.width - EditorTabStripLayout.stripInset - trailing, 0) - return CGRect( - x: EditorTabStripLayout.stripInset, - y: 0, - width: width, - height: EditorTabStripLayout.trackHeight(forRowCount: interaction.run.rowCount) - ) - } - - private var viewportRect: CGRect { - trackRect.insetBy(dx: EditorTabStripLayout.trackPadding, dy: EditorTabStripLayout.trackPadding) - } - - private func contentPoint(from event: NSEvent) -> CGPoint { - contentPoint(fromViewPoint: convert(event.locationInWindow, from: nil)) - } - - private func contentPoint(fromViewPoint point: CGPoint) -> CGPoint { - CGPoint( - x: point.x - viewportRect.minX + interaction.contentOffset, - y: point.y - viewportRect.minY - ) - } - - override internal func layout() { - super.layout() - rebuildRun() - refreshHoverTracking() - } - - /// Re-measures the run. The row count reaches the pane controller from the interaction, which - /// is the one place every rebuild goes through. - internal func rebuildRun() { - interaction.updateRun(trackWidth: trackRect.width, count: interaction.tabIds.count) - interaction.clampContentOffset() - } - - // MARK: - Hit testing - - /// Claims the track and nothing else, so a press on a tab is this view's and a press on the - /// new-tab button, on the band's insets or on the chrome below the track is not. - /// - /// The claim is for the pointer alone. Accessibility resolves a screen point through this same - /// method, so claiming it unconditionally answered "the strip" for every tab and took all of - /// them out of reach of VoiceOver, Switch Control, Voice Control and XCUITest at once: this - /// view publishes nothing, so there was no element under a tab to speak, press or click. That - /// shipped in #2571 and turned the whole UI suite red from the commit that merged it. - override internal func hitTest(_ point: NSPoint) -> NSView? { - guard !isResolvingAccessibilityHit else { return super.hitTest(point) } - let local = convert(point, from: superview) - guard trackRect.contains(local) else { return super.hitTest(point) } - return self - } - - /// Answers from the SwiftUI tree, which is where the tabs publish themselves. - /// - /// The subviews are asked directly rather than through `super`, which will not walk into them - /// from a receiver that is not itself an accessibility element: lifting the pointer's claim and - /// deferring to `super` left every tab unreachable exactly as before. The point arrives in - /// screen coordinates and is passed on unchanged, because that is what the children expect too. - override internal func accessibilityHitTest(_ point: NSPoint) -> Any? { - isResolvingAccessibilityHit = true - defer { isResolvingAccessibilityHit = false } - for subview in subviews.reversed() { - if let hit = subview.accessibilityHitTest(point) { return hit } - } - return super.accessibilityHitTest(point) - } - - /// A point outside the viewport names no tab, however a scrolled run would translate it. The - /// content offset moves the run under a fixed viewport, so without this the track's own two - /// points of padding, and any point the pointer reaches past the track, resolve to whichever - /// tab the offset happens to put there: a tab clipped off the leading edge, or one hidden - /// behind the new-tab button. - private func tabIndex(atViewPoint point: CGPoint) -> Int? { - guard viewportRect.contains(point) else { return nil } - return EditorTabRunLayoutBuilder.index(at: contentPoint(fromViewPoint: point), in: interaction.run) - } - - private func tabId(at index: Int) -> UUID? { - let ids = interaction.displayedIds - guard ids.indices.contains(index) else { return nil } - return ids[index] - } - - private func isCloseButton(_ point: CGPoint, forTabAt index: Int) -> Bool { - guard let placement = interaction.run.placement(at: index) else { return false } - return EditorTabRunLayoutBuilder.closeButtonRect(in: placement.frame) - .contains(contentPoint(fromViewPoint: point)) - } - - // MARK: - Hover - - private func refreshHoverTracking() { - if let hoverTrackingArea { removeTrackingArea(hoverTrackingArea) } - let area = NSTrackingArea( - rect: trackRect, - options: [.activeInKeyWindow, .mouseEnteredAndExited, .mouseMoved], - owner: self - ) - addTrackingArea(area) - hoverTrackingArea = area - } - - override internal func mouseMoved(with event: NSEvent) { - updateHover(at: convert(event.locationInWindow, from: nil)) - } - - override internal func mouseExited(with event: NSEvent) { - interaction.setHovered(nil) - } - - private func updateHover(at point: CGPoint) { - guard let index = tabIndex(atViewPoint: point), let id = tabId(at: index) else { - interaction.setHovered(nil) - toolTip = nil - return - } - interaction.setHovered(id, overCloseButton: isCloseButton(point, forTabAt: index)) - toolTip = interaction.commands?.tooltip(id) - } - - // MARK: - Scrolling - - /// The track scrolls itself, because the view that owns the press owns the wheel too. A - /// wrapped run never overflows, so it ignores this. - override internal func scrollWheel(with event: NSEvent) { - let delta = abs(event.scrollingDeltaX) >= abs(event.scrollingDeltaY) - ? event.scrollingDeltaX - : event.scrollingDeltaY - guard delta != 0 else { return } - interaction.scroll(by: -delta) - /// The run moved under a pointer that did not, so the tab it is over, its close target and - /// the tooltip all changed. Without this the close affordance is drawn on one tab while a - /// click in that slot hits another. - updateHover(at: convert(event.locationInWindow, from: nil)) - } - - // MARK: - Contextual menu - - override internal func menu(for event: NSEvent) -> NSMenu? { - let point = convert(event.locationInWindow, from: nil) - guard let index = tabIndex(atViewPoint: point), let id = tabId(at: index), - let commands = interaction.commands - else { return nil } - return EditorTabContextMenuBuilder.menu(for: id, commands: commands) - } - - // MARK: - Middle click - - /// Middle-click closes the tab under the pointer, the gesture every browser and Xcode answer - /// and the one the connections strip already answers here. AppKit routes no action for the - /// wheel button, so the tab is resolved from the click point the way `menu(for:)` resolves one. - /// - /// The press is remembered and the close committed on release, which is the contract every - /// AppKit button keeps and the one `trackCloseButton` already keeps for the tab's own close - /// button: releasing anywhere else lets a user change their mind. What decides is the release's - /// location, never the view under it, because AppKit sends the release to whichever view took - /// the press however far the pointer has travelled since. Measured on a titlebar accessory, - /// which is where this strip lives. - override internal func otherMouseDown(with event: NSEvent) { - guard event.isMiddleButton else { - super.otherMouseDown(with: event) - return - } - beginMiddleClick(atViewPoint: convert(event.locationInWindow, from: nil)) - } - - override internal func otherMouseUp(with event: NSEvent) { - guard event.isMiddleButton, middleClickTabId != nil else { - super.otherMouseUp(with: event) - return - } - endMiddleClick(atViewPoint: convert(event.locationInWindow, from: nil)) - } - - internal func beginMiddleClick(atViewPoint point: CGPoint) { - middleClickTabId = tabIndex(atViewPoint: point).flatMap { tabId(at: $0) } - } - - /// Closes only when the release still lands on the tab the press did. A tab that closed under - /// the pointer meanwhile leaves a different id in its slot, so the gesture finds nothing and - /// takes the tab that replaced it nowhere. - internal func endMiddleClick(atViewPoint point: CGPoint) { - guard let pressedId = middleClickTabId else { return } - middleClickTabId = nil - guard let index = tabIndex(atViewPoint: point), tabId(at: index) == pressedId else { return } - interaction.commands?.close(pressedId) - } - - // MARK: - Tracking - - override internal func mouseDown(with event: NSEvent) { - let start = convert(event.locationInWindow, from: nil) - guard let index = tabIndex(atViewPoint: start), let pressedId = tabId(at: index) else { return } - - if isCloseButton(start, forTabAt: index) { - trackCloseButton(startingAt: start, tabId: pressedId) - return - } - - activate(pressedId, click: EditorTabClick(event: event)) - trackDrag(startingAt: start, tabId: pressedId) - } - - /// A press on the close button commits only if the pointer is still on it when the button comes - /// up, which is what every AppKit button does and what lets a user change their mind. - private func trackCloseButton(startingAt start: CGPoint, tabId: UUID) { - guard let window else { return } - var isInside = true - while let next = window.nextEvent(matching: [.leftMouseDragged, .leftMouseUp]) { - let point = convert(next.locationInWindow, from: nil) - if next.type == .leftMouseUp { - if isInside, let index = interaction.displayedIds.firstIndex(of: tabId), - isCloseButton(point, forTabAt: index) { - interaction.commands?.close(tabId) - } - return - } - guard let index = interaction.displayedIds.firstIndex(of: tabId) else { return } - isInside = isCloseButton(point, forTabAt: index) - } - } - - private func trackDrag(startingAt start: CGPoint, tabId: UUID) { - guard let window else { return } - var gesture: EditorTabGesture? - NSEvent.startPeriodicEvents(afterDelay: 0.08, withPeriod: 0.02) - defer { NSEvent.stopPeriodicEvents() } - - var latest = start - while let next = window.nextEvent(matching: [.leftMouseDragged, .leftMouseUp, .keyDown, .periodic]) { - switch next.type { - case .keyDown where next.keyCode == KeyCode.escape.rawValue: - interaction.clearReorder() - consumeRemainingDrag(in: window) - return - case .keyDown: - /// Every key-down matches the mask, and taking one out of the queue without - /// dispatching it would swallow `Cmd+W`, `Cmd+T` and the tab-switch shortcuts for - /// as long as the button is held. The reorder already survives a tab opening or - /// closing under it, so the commands stay live. - NSApp.sendEvent(next) - case .leftMouseUp: - /// The release carries a location of its own, and a fast drag can cross a - /// neighbour's midpoint between the last drag sample and it. Resolving from - /// `latest` alone commits the order the pointer had a frame ago, which is the - /// short-move-or-nothing this change exists to remove. - latest = convert(next.locationInWindow, from: nil) - gesture = resolveGesture(gesture, from: start, to: latest, tabId: tabId) - if gesture == .reorder { applyReorder(at: latest, tabId: tabId) } - finishDrag(gesture, tabId: tabId) - return - case .periodic: - guard gesture == .reorder else { continue } - autoscroll(towards: latest) - applyReorder(at: latest, tabId: tabId) - case .leftMouseDragged: - latest = convert(next.locationInWindow, from: nil) - gesture = resolveGesture(gesture, from: start, to: latest, tabId: tabId) - guard gesture == .reorder else { continue } - autoscroll(towards: latest) - applyReorder(at: latest, tabId: tabId) - default: - continue - } - } - } - - /// A press becomes a reorder once it travels the distance AppKit uses to tell a click from a - /// drag, and a tear-off once it leaves the band by more than a tab's height again. A gesture - /// never goes back to being a click. - private func resolveGesture( - _ current: EditorTabGesture?, - from start: CGPoint, - to point: CGPoint, - tabId: UUID - ) -> EditorTabGesture? { - if canTearOff(tabId), abs(point.y - start.y) >= EditorTabStripLayout.tearOffThreshold { - interaction.markTearingOff(tabId) - return .tearOff - } - if current == .tearOff { - interaction.markTearingOff(nil) - } - guard current == .reorder || hypot(point.x - start.x, point.y - start.y) >= EditorTabStripLayout.reorderThreshold - else { return current } - interaction.beginReorder(of: tabId) - return .reorder - } - - private func canTearOff(_ tabId: UUID) -> Bool { - interaction.commands?.canTearOff(tabId) ?? false - } - - private func applyReorder(at point: CGPoint, tabId: UUID) { - let location = EditorTabRunLayoutBuilder.linearLocation( - of: contentPoint(fromViewPoint: point), - in: interaction.run - ) - withMotion(.easeInOut(duration: 0.18)) { - interaction.updateReorder(toLinearLocation: location) - } - } - - /// Scrolls the track while the pointer is held near either edge, so a tab can be dragged to a - /// place that is not currently on screen. Without it a reorder stops at the viewport and the - /// tabs a user opened first, the ones #2438 is about, cannot be reached at all. - private func autoscroll(towards point: CGPoint) { - guard interaction.overflow == .scroll else { return } - let leadingEdge = viewportRect.minX + EditorTabStripLayout.autoscrollMargin - let trailingEdge = viewportRect.maxX - EditorTabStripLayout.autoscrollMargin - if point.x < leadingEdge { - interaction.scroll(by: -EditorTabStripLayout.autoscrollStep) - } else if point.x > trailingEdge { - interaction.scroll(by: EditorTabStripLayout.autoscrollStep) - } - } - - private func finishDrag(_ gesture: EditorTabGesture?, tabId: UUID) { - switch gesture { - case .tearOff: - interaction.markTearingOff(nil) - interaction.clearReorder() - interaction.commands?.tearOff(tabId) - case .reorder: - interaction.commitReorder() - default: - interaction.clearReorder() - } - } - - /// Escape abandons the drag, and the pointer is still down. Swallowing the rest of the gesture - /// is what keeps the release from starting a fresh one. - private func consumeRemainingDrag(in window: NSWindow) { - while let next = window.nextEvent(matching: [.leftMouseDragged, .leftMouseUp]) { - if next.type == .leftMouseUp { return } - } - } - - private func activate(_ tabId: UUID, click: EditorTabClick?) { - guard let commands = interaction.commands else { return } - let activation = EditorTabActivationResolver.resolve( - click: click, - tabId: tabId, - lastActivatedTabId: lastActivatedTabId - ) - lastActivatedTabId = tabId - commands.activate(tabId) - guard activation == .selectAndKeep else { return } - commands.keepOpen(tabId) - } -} diff --git a/apple/TablePro/Views/Main/EditorTabItemView.swift b/apple/TablePro/Views/Main/EditorTabItemView.swift new file mode 100644 index 0000000000..f4ceef2bcb --- /dev/null +++ b/apple/TablePro/Views/Main/EditorTabItemView.swift @@ -0,0 +1,383 @@ +// +// EditorTabItemView.swift +// TablePro +// + +import AppKit + +extension NSPasteboard.PasteboardType { + internal static let editorTab = NSPasteboard.PasteboardType("com.TablePro.editor-tab") +} + +// AppKit on purpose: a tab is a drag source, a key view and a tab button element, none of which a hosted view can be here. +@MainActor +internal final class EditorTabItemView: NSView { + internal private(set) var item: EditorTabItem + internal weak var strip: EditorTabStripView? + + internal var showsLeadingSeparator = false { + didSet { if showsLeadingSeparator != oldValue { needsDisplay = true } } + } + + internal var isHovered = false { + didSet { + guard isHovered != oldValue else { return } + updateCloseButton() + needsDisplay = true + } + } + + internal var isWindowActive = true { + didSet { + guard isWindowActive != oldValue else { return } + updateCloseButton() + updateTitle() + needsDisplay = true + } + } + + internal let closeButton: NSButton + internal let titleField = NSTextField(labelWithString: "") + private let pinView = NSImageView() + private let statusView = NSImageView() + private let spinner = NSProgressIndicator() + private var pressLocation: NSPoint? + private var middlePressed = false + + internal init(item: EditorTabItem) { + self.item = item + closeButton = NSButton() + super.init(frame: .zero) + wantsLayer = true + layerContentsRedrawPolicy = .onSetNeedsDisplay + configureSubviews() + apply(item) + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("EditorTabItemView does not support NSCoder init") + } + + override 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. + override internal func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + internal func apply(_ newItem: EditorTabItem) { + item = newItem + toolTip = newItem.tooltip + pinView.isHidden = !newItem.isPinned + updateTitle() + updateStatus() + updateCloseButton() + needsDisplay = true + needsLayout = true + } + + private func configureSubviews() { + titleField.lineBreakMode = .byTruncatingTail + titleField.maximumNumberOfLines = 1 + titleField.cell?.usesSingleLineMode = true + titleField.setAccessibilityElement(false) + addSubview(titleField) + + let pinConfiguration = NSImage.SymbolConfiguration(pointSize: EditorTabStripLayout.pinGlyphSize, weight: .regular) + pinView.image = NSImage(systemSymbolName: "pin.fill", accessibilityDescription: nil)? + .withSymbolConfiguration(pinConfiguration) + pinView.contentTintColor = .secondaryLabelColor + pinView.setAccessibilityElement(false) + addSubview(pinView) + + statusView.setAccessibilityElement(false) + addSubview(statusView) + + spinner.style = .spinning + spinner.controlSize = .mini + spinner.isDisplayedWhenStopped = false + spinner.setAccessibilityElement(false) + addSubview(spinner) + + let closeConfiguration = NSImage.SymbolConfiguration( + pointSize: EditorTabStripLayout.closeGlyphSize, + weight: .semibold + ) + closeButton.image = NSImage( + systemSymbolName: "xmark", + accessibilityDescription: String(localized: "Close Tab") + )?.withSymbolConfiguration(closeConfiguration) + closeButton.imagePosition = .imageOnly + closeButton.bezelStyle = .circular + closeButton.controlSize = .mini + closeButton.showsBorderOnlyWhileMouseInside = true + closeButton.contentTintColor = .secondaryLabelColor + closeButton.target = self + closeButton.action = #selector(closeClicked) + closeButton.toolTip = String(localized: "Close Tab") + closeButton.setAccessibilityLabel(String(localized: "Close Tab")) + closeButton.isHidden = true + addSubview(closeButton) + } + + private func updateTitle() { + titleField.stringValue = item.title + titleField.font = item.isPreview ? Self.previewFont : Self.titleFont + titleField.textColor = titleColor + pinView.contentTintColor = titleColor + } + + private var titleColor: NSColor { + guard isWindowActive else { + return item.isSelected ? .secondaryLabelColor : .tertiaryLabelColor + } + return item.isSelected ? .labelColor : .secondaryLabelColor + } + + private func updateStatus() { + switch item.status { + case .idle: + statusView.isHidden = true + spinner.stopAnimation(nil) + case .running: + statusView.isHidden = true + spinner.startAnimation(nil) + case .finished: + spinner.stopAnimation(nil) + showStatus(symbol: "checkmark.circle.fill", color: .controlAccentColor) + case .failed: + spinner.stopAnimation(nil) + showStatus(symbol: "exclamationmark.triangle.fill", color: .systemRed) + } + } + + private func showStatus(symbol: String, color: NSColor) { + let configuration = NSImage.SymbolConfiguration(pointSize: EditorTabStripLayout.statusGlyphSize, weight: .regular) + .applying(NSImage.SymbolConfiguration(hierarchicalColor: color)) + statusView.image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)? + .withSymbolConfiguration(configuration) + statusView.isHidden = false + } + + // The system bar shows the close button only under the pointer, on the selected tab too. + private func updateCloseButton() { + closeButton.isHidden = !(isHovered && isWindowActive) || bounds.width < EditorTabStripLayout.minimumContentWidth + } + + override internal func layout() { + super.layout() + let metrics = EditorTabStripLayout.self + let hasRoom = bounds.width >= metrics.minimumContentWidth + titleField.isHidden = !hasRoom + pinView.isHidden = !hasRoom || !item.isPinned + spinner.isHidden = !hasRoom + statusView.isHidden = !hasRoom || item.status == .idle || item.status == .running + updateCloseButton() + guard hasRoom else { return } + + let slot = metrics.accessoryWidth + let midY = bounds.midY + closeButton.frame = CGRect(x: metrics.accessoryInset, y: midY - slot / 2, width: slot, height: slot) + let statusFrame = CGRect( + x: bounds.maxX - metrics.accessoryInset - slot, + y: midY - slot / 2, + width: slot, + height: slot + ) + statusView.frame = statusFrame + spinner.frame = statusFrame + + let inset = metrics.accessoryInset + slot + metrics.pinSpacing + let available = max(bounds.width - inset * 2, 0) + let pinWidth = item.isPinned ? metrics.pinGlyphSize + metrics.pinSpacing : 0 + let textSize = titleField.sizeThatFits(NSSize(width: CGFloat.greatestFiniteMagnitude, height: bounds.height)) + let textWidth = min(ceil(textSize.width), max(available - pinWidth, 0)) + let textHeight = ceil(textSize.height) + let startX = bounds.midX - (pinWidth + textWidth) / 2 + pinView.frame = CGRect( + x: startX, + y: midY - metrics.pinGlyphSize / 2, + width: metrics.pinGlyphSize, + height: metrics.pinGlyphSize + ) + titleField.frame = CGRect(x: startX + pinWidth, y: midY - textHeight / 2, width: textWidth, height: textHeight) + } + + override internal func draw(_ dirtyRect: NSRect) { + let metrics = EditorTabStripLayout.self + if showsLeadingSeparator { + EditorTabStripPalette.separatorColor.setFill() + NSRect( + x: 0, + y: bounds.midY - metrics.separatorHeight / 2, + width: metrics.separatorWidth, + height: metrics.separatorHeight + ).fill() + } + if item.isSelected { + EditorTabStripPalette.selectedColor.setFill() + capsule(in: bounds).fill() + EditorTabStripPalette.selectionEdgeColor.setStroke() + let edge = capsule(in: bounds.insetBy(dx: metrics.hairline / 2, dy: metrics.hairline / 2)) + edge.lineWidth = metrics.hairline + edge.stroke() + } else if isHovered, isWindowActive { + EditorTabStripPalette.hoverColor.setFill() + capsule(in: bounds).fill() + } + } + + private func capsule(in rect: NSRect) -> NSBezierPath { + let radius = rect.height / 2 + return NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) + } + + internal func dragImage() -> NSImage { + let image = NSImage(size: bounds.size) + guard let bitmap = bitmapImageRepForCachingDisplay(in: bounds) else { return image } + cacheDisplay(in: bounds, to: bitmap) + image.addRepresentation(bitmap) + return image + } + + @objc + private func closeClicked() { + strip?.commands?.close(item.id) + } + + // MARK: - Pointer + + override internal func hitTest(_ point: NSPoint) -> NSView? { + let local = convert(point, from: superview) + guard bounds.contains(local) else { return nil } + if !closeButton.isHidden, closeButton.frame.contains(local) { return closeButton } + return self + } + + override internal func mouseDown(with event: NSEvent) { + pressLocation = convert(event.locationInWindow, from: nil) + strip?.activate(item.id, click: EditorTabClick(event: event)) + } + + override internal func mouseDragged(with event: NSEvent) { + guard let start = pressLocation else { return } + let point = convert(event.locationInWindow, from: nil) + guard hypot(point.x - start.x, point.y - start.y) >= EditorTabStripLayout.dragThreshold else { return } + pressLocation = nil + strip?.beginDrag(of: self, with: event) + } + + override internal func mouseUp(with event: NSEvent) { + pressLocation = nil + } + + override internal func otherMouseDown(with event: NSEvent) { + guard event.isMiddleButton else { + super.otherMouseDown(with: event) + return + } + middlePressed = true + } + + override internal func otherMouseUp(with event: NSEvent) { + guard event.isMiddleButton, middlePressed else { + super.otherMouseUp(with: event) + return + } + endMiddleClick(atViewPoint: convert(event.locationInWindow, from: nil)) + } + + internal func beginMiddleClick() { + middlePressed = true + } + + // AppKit sends the release to the view that took the press, wherever the pointer went. + internal func endMiddleClick(atViewPoint point: NSPoint) { + guard middlePressed else { return } + middlePressed = false + guard bounds.contains(point) else { return } + strip?.commands?.close(item.id) + } + + override internal func menu(for event: NSEvent) -> NSMenu? { + guard let commands = strip?.commands else { return nil } + return EditorTabContextMenuBuilder.menu(for: item.id, commands: commands) + } + + // MARK: - Keyboard + + override internal var acceptsFirstResponder: Bool { NSApp.isFullKeyboardAccessEnabled } + override internal var canBecomeKeyView: Bool { NSApp.isFullKeyboardAccessEnabled } + override internal var focusRingMaskBounds: NSRect { bounds } + + override internal func drawFocusRingMask() { + capsule(in: bounds).fill() + } + + override internal func keyDown(with event: NSEvent) { + switch event.specialKey { + case .leftArrow: + strip?.moveFocus(from: self, by: -1) + case .rightArrow: + strip?.moveFocus(from: self, by: 1) + case .carriageReturn, .enter: + strip?.commands?.activate(item.id) + default: + guard event.charactersIgnoringModifiers == " " else { + super.keyDown(with: event) + return + } + strip?.commands?.activate(item.id) + } + } + + // MARK: - Accessibility + + override internal func isAccessibilityElement() -> Bool { true } + override internal func accessibilityRole() -> NSAccessibility.Role? { .radioButton } + override internal func accessibilitySubrole() -> NSAccessibility.Subrole? { .tabButtonSubrole } + override internal func accessibilityLabel() -> String? { item.title } + override internal func accessibilityIdentifier() -> String { "editor-tab" } + override internal func accessibilityValue() -> Any? { NSNumber(value: item.isSelected) } + override internal func accessibilityValueDescription() -> String? { item.accessibilityDescription } + override internal func isAccessibilitySelected() -> Bool { item.isSelected } + + override internal func accessibilityPerformPress() -> Bool { + strip?.commands?.activate(item.id) + return strip?.commands != nil + } + + override internal func accessibilityPerformShowMenu() -> Bool { + guard let commands = strip?.commands else { return false } + let menu = EditorTabContextMenuBuilder.menu(for: item.id, commands: commands) + menu.popUp(positioning: nil, at: NSPoint(x: bounds.minX, y: bounds.maxY), in: self) + return true + } + + override internal func accessibilityCustomActions() -> [NSAccessibilityCustomAction]? { + guard let commands = strip?.commands else { return nil } + return EditorTabContextMenuBuilder.accessibilityActions(for: item.id, commands: commands) + } + + private static let titleFont = NSFont.systemFont(ofSize: EditorTabStripLayout.fontSize) + private static let previewFont = NSFontManager.shared.convert(titleFont, toHaveTrait: .italicFontMask) +} + +extension EditorTabItemView: NSDraggingSource { + internal func draggingSession( + _ session: NSDraggingSession, + sourceOperationMaskFor context: NSDraggingContext + ) -> NSDragOperation { + context == .withinApplication ? .move : [] + } + + internal func ignoreModifierKeys(for session: NSDraggingSession) -> Bool { true } + + internal func draggingSession( + _ session: NSDraggingSession, + endedAt screenPoint: NSPoint, + operation: NSDragOperation + ) { + strip?.dragDidEnd(of: self, at: screenPoint, operation: operation) + } +} diff --git a/apple/TablePro/Views/Main/EditorTabReorderCancelMonitor.swift b/apple/TablePro/Views/Main/EditorTabReorderCancelMonitor.swift deleted file mode 100644 index 7bd69ca69f..0000000000 --- a/apple/TablePro/Views/Main/EditorTabReorderCancelMonitor.swift +++ /dev/null @@ -1,96 +0,0 @@ -// -// EditorTabReorderCancelMonitor.swift -// TablePro -// - -import AppKit -import SwiftUI - -/// Owns the Escape key while a tab reorder is in flight, and nothing else. -/// -/// It exists because the monitor needs a lifetime and `EditorTabStrip` is a value with no `deinit`. -/// Every local monitor in this app is owned by a reference type that installs and removes it -/// (`InlineSuggestionManager`, `CellOverlayBase`, `QuickSwitcherPanelView`); a `View` cannot be, -/// so the representable's coordinator is. -/// -/// It draws nothing, takes no clicks and publishes nothing to accessibility. That is not -/// decoration: a view mounted over the track covers every tab in the accessibility tree however -/// little it draws and however it hit-tests, measured, so XCUITest found no tab hittable at all. -/// It is mounted as a background for the same reason. -internal struct EditorTabReorderCancelMonitor: NSViewRepresentable { - internal let isReordering: Bool - internal let onCancel: () -> Void - - internal func makeNSView(context: Context) -> NSView { - InertView() - } - - internal func updateNSView(_ nsView: NSView, context: Context) { - context.coordinator.onCancel = onCancel - context.coordinator.setCancelMonitorActive(isReordering) - } - - internal func makeCoordinator() -> Coordinator { - Coordinator(onCancel: onCancel) - } - - /// SwiftUI tears the representable down here and nowhere else, so this is where a monitor that - /// outlives its drag would otherwise leak. - internal static func dismantleNSView(_ nsView: NSView, coordinator: Coordinator) { - coordinator.setCancelMonitorActive(false) - } - - @MainActor - internal final class Coordinator { - internal var onCancel: () -> Void - private var cancelMonitor: Any? - - internal init(onCancel: @escaping () -> Void) { - self.onCancel = onCancel - } - - /// No `deinit`: `NSEvent.removeMonitor` is main-actor work and a `deinit` is not isolated, - /// so the release would have to hop and might never run. The monitor is bounded from the - /// other end instead. It exists only while a reorder is in flight, and every exit from that - /// state, a commit, an Escape, a tab closing, the pane going away, comes back through - /// `updateNSView` with `isReordering` false. `dismantleNSView` is the backstop for the view - /// itself being destroyed mid-drag. - internal func setCancelMonitorActive(_ isActive: Bool) { - guard isActive != (cancelMonitor != nil) else { return } - if isActive { - install() - } else { - remove() - } - } - - /// Escape is swallowed while a reorder is in flight, so the key that abandons the drag does - /// not also close a sheet or clear a search field behind it. - private func install() { - cancelMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] nsEvent in - nonisolated(unsafe) let event = nsEvent - let handled = MainActor.assumeIsolated { () -> Bool in - guard let self, event.keyCode == KeyCode.escape.rawValue else { return false } - self.onCancel() - return true - } - return handled ? nil : nsEvent - } - } - - private func remove() { - guard let cancelMonitor else { return } - NSEvent.removeMonitor(cancelMonitor) - self.cancelMonitor = nil - } - } -} - -/// Present so the coordinator has a lifetime, and invisible to everything else. -internal final class InertView: NSView { - override internal func hitTest(_ point: NSPoint) -> NSView? { nil } - - override internal func isAccessibilityElement() -> Bool { false } - - override internal func accessibilityChildren() -> [Any]? { nil } -} diff --git a/apple/TablePro/Views/Main/EditorTabRunLayout.swift b/apple/TablePro/Views/Main/EditorTabRunLayout.swift index 3bf4173095..a663c8585d 100644 --- a/apple/TablePro/Views/Main/EditorTabRunLayout.swift +++ b/apple/TablePro/Views/Main/EditorTabRunLayout.swift @@ -5,141 +5,97 @@ import CoreGraphics import Foundation -import SwiftUI -/// What the strip does once the tabs stop fitting. -/// -/// `scroll` is the system's answer and stays the default: every tab bar Apple ships, in Finder, -/// Safari and Terminal, keeps one row and scrolls it. `rows` is offered because a tab bar that -/// scrolls hides the tabs a user opened first, which is the complaint #2438 was filed about, and -/// it is opt-in for the same reason. -internal enum EditorTabStripOverflow: String, CaseIterable, Codable, Sendable { - case scroll - case rows - - internal var displayName: String { - switch self { - case .scroll: return String(localized: "Scroll them") - case .rows: return String(localized: "Wrap onto more rows") - } - } -} - -/// Where one tab sits in the run, in the track's content space. -internal struct EditorTabPlacement: Equatable { - internal let index: Int - internal let row: Int - internal let frame: CGRect -} - -/// The whole run of tabs: where each one sits, how many rows it took, and how big the content is. -/// -/// This is the single source of geometry for the strip. The AppKit view that owns the pointer -/// hit-tests against it, the reorder resolves against it, and SwiftUI draws from it, so a tab the -/// user can see, a tab the pointer can hit and a tab the drag can target are the same rectangle by -/// construction rather than by three views agreeing. internal struct EditorTabRunLayout: Equatable { - internal let placements: [EditorTabPlacement] + internal let viewportWidth: CGFloat + internal let count: Int internal let tabWidth: CGFloat - internal let tabsPerRow: Int - internal let rowCount: Int - internal let contentSize: CGSize - internal static let empty = EditorTabRunLayout( - placements: [], - tabWidth: 0, - tabsPerRow: 1, - rowCount: 1, - contentSize: .zero - ) + internal init(viewportWidth: CGFloat, count: Int) { + self.viewportWidth = max(viewportWidth, 0) + self.count = max(count, 0) + tabWidth = EditorTabStripLayout.tabWidth(forViewport: self.viewportWidth, count: self.count) + } - internal func placement(at index: Int) -> EditorTabPlacement? { - placements.first { $0.index == index } + internal var contentWidth: CGFloat { + tabWidth * CGFloat(count) } -} -/// The pure geometry of the run, kept apart from both the AppKit view and the SwiftUI one. -internal enum EditorTabRunLayoutBuilder { - /// Lays the run out inside a track of `width`. - /// - /// `scroll` keeps one row and lets the content run past the viewport. `rows` fits as many tabs - /// per row as `minimumTabWidth` allows and wraps, so the content never runs wider than the - /// track and no tab is ever off screen. - internal static func run( - forTrack width: CGFloat, - count: Int, - overflow: EditorTabStripOverflow - ) -> EditorTabRunLayout { - guard count > 0, width > 0 else { return .empty } + internal var maximumOffset: CGFloat { + max(contentWidth - viewportWidth, 0) + } - let usable = max(width - EditorTabStripLayout.trackPadding * 2, 0) - let perRow = tabsPerRow(usable: usable, count: count, overflow: overflow) - let rows = Int(ceil(Double(count) / Double(max(perRow, 1)))) - let tabWidth = overflow == .scroll - ? EditorTabStripLayout.tabWidth(forTrack: width, count: count) - : usable / CGFloat(max(perRow, 1)) + // The system bar narrows the tabs past either edge, which is what says more tabs are there. + private var collapseZone: CGFloat { + min(tabWidth * 2, viewportWidth / 3) + } + + internal func clamped(offset: CGFloat) -> CGFloat { + min(max(offset, 0), maximumOffset) + } - let placements = (0 ..< count).map { index -> EditorTabPlacement in - let row = index / max(perRow, 1) - let column = index % max(perRow, 1) - return EditorTabPlacement( - index: index, - row: row, - frame: CGRect( - x: CGFloat(column) * tabWidth, - y: CGFloat(row) * EditorTabStripLayout.rowStride, - width: tabWidth, - height: EditorTabStripLayout.tabHeight - ) + // In content coordinates, the space the scroll view's document is laid out in. + internal func frames(offset: CGFloat) -> [CGRect] { + let origin = clamped(offset: offset) + return (0 ..< count).map { index in + let minX = position(ofSlotEdge: index, offset: origin) + let maxX = position(ofSlotEdge: index + 1, offset: origin) + return CGRect( + x: minX, + y: 0, + width: maxX - minX, + height: EditorTabStripLayout.tabHeight ) } + } - return EditorTabRunLayout( - placements: placements, - tabWidth: tabWidth, - tabsPerRow: max(perRow, 1), - rowCount: max(rows, 1), - contentSize: CGSize( - width: overflow == .scroll ? tabWidth * CGFloat(count) : usable, - height: CGFloat(max(rows, 1)) * EditorTabStripLayout.rowStride - - EditorTabStripLayout.rowSpacing - ) - ) + // Where a point on the drawn run falls among the uniform slots a reorder resolves against. + internal func slotLocation(ofContentX x: CGFloat, offset: CGFloat) -> CGFloat { + let frames = frames(offset: offset) + guard let first = frames.first, x > first.minX else { return 0 } + guard let index = frames.firstIndex(where: { x < $0.maxX }) else { return contentWidth } + let frame = frames[index] + let fraction = frame.width > 0 ? (x - frame.minX) / frame.width : 0 + return (CGFloat(index) + fraction) * tabWidth } - private static func tabsPerRow(usable: CGFloat, count: Int, overflow: EditorTabStripOverflow) -> Int { - guard overflow == .rows else { return count } - let fitting = Int(floor(usable / EditorTabStripLayout.minimumTabWidth)) - return max(min(fitting, count), 1) + // The offset that shows a tab at full width, or the current one when it already does. + internal func revealOffset(forTabAt index: Int, from offset: CGFloat) -> CGFloat { + guard (0 ..< count).contains(index), maximumOffset > 0 else { return 0 } + let origin = clamped(offset: offset) + let minX = CGFloat(index) * tabWidth + let maxX = minX + tabWidth + if minX - origin < collapseZone { + return clamped(offset: minX - collapseZone) + } + if maxX - origin > viewportWidth - collapseZone { + return clamped(offset: maxX - viewportWidth + collapseZone) + } + return origin } - /// The tab a point in content space lands on, or nil for the gaps a wrapped last row leaves. - internal static func index(at point: CGPoint, in run: EditorTabRunLayout) -> Int? { - run.placements.first { $0.frame.contains(point) }?.index + private func position(ofSlotEdge edge: Int, offset: CGFloat) -> CGFloat { + let visible = collapsed(CGFloat(edge) * tabWidth - offset, offset: offset) + return (visible + offset).rounded() } - /// The close button's target, which the pointer owner needs because the button is drawn by - /// SwiftUI but no longer clicked through it. - internal static func closeButtonRect(in frame: CGRect) -> CGRect { - CGRect( - x: frame.minX + EditorTabStripLayout.accessoryInset, - y: frame.midY - EditorTabStripLayout.accessoryWidth / 2, - width: EditorTabStripLayout.accessoryWidth, - height: EditorTabStripLayout.accessoryWidth - ) + private func collapsed(_ x: CGFloat, offset: CGFloat) -> CGFloat { + let leading = min(offset, collapseZone) + if x < leading { + return leading - compressed(leading - x, into: leading, farthest: leading + offset) + } + let trailing = min(maximumOffset - offset, collapseZone) + let edge = viewportWidth - trailing + if x > edge { + return edge + compressed(x - edge, into: trailing, farthest: contentWidth - offset - edge) + } + return x } - /// Flattens a point in the run onto the single axis the reorder resolves along. - /// - /// One row is already that axis. A wrapped run is not, so a point is projected onto the run it - /// would have been had it never wrapped: the row it is over contributes a whole row of tabs, - /// and the offset inside the row contributes the rest. The reorder rule then stays the one - /// rule, with its midpoint hysteresis, rather than growing a second one for rows. - internal static func linearLocation(of point: CGPoint, in run: EditorTabRunLayout) -> CGFloat { - guard run.tabWidth > 0 else { return 0 } - guard run.rowCount > 1 else { return point.x } - let row = min(max(Int(floor(point.y / EditorTabStripLayout.rowStride)), 0), run.rowCount - 1) - let clampedX = min(max(point.x, 0), run.tabWidth * CGFloat(run.tabsPerRow)) - return CGFloat(row * run.tabsPerRow) * run.tabWidth + clampedX + // Starts at full scale, so no tab is drawn wider than its slot, and lands the farthest tab on the viewport's edge. + private func compressed(_ distance: CGFloat, into zone: CGFloat, farthest: CGFloat) -> CGFloat { + guard zone > 0, farthest > zone else { return min(distance, zone) } + let scale = zone * farthest / (farthest - zone) + return scale * distance / (distance + scale) } } diff --git a/apple/TablePro/Views/Main/EditorTabStrip.swift b/apple/TablePro/Views/Main/EditorTabStrip.swift deleted file mode 100644 index da6a9ffbf6..0000000000 --- a/apple/TablePro/Views/Main/EditorTabStrip.swift +++ /dev/null @@ -1,640 +0,0 @@ -// -// EditorTabStrip.swift -// TablePro -// - -import SwiftUI - -/// The editor tabs for one connection, drawn to the geometry of `NSTabBar`, the private control -/// the system's own window tab bar is built from. Native window tabs cannot express this: a window -/// belongs to exactly one tab group and a group's bar shows every window in it, so one window -/// hosting several connections could only ever show all of their tabs interleaved. -/// -/// The band is a titlebar accessory rather than a row in the content stack, so this view draws -/// only what sits inside it: a filled track pinned to the band's top edge, and a new-tab button -/// outside the track. `EditorTabStripAccessoryController` owns the band itself. -/// -/// The track carries a surface, which is the whole difference between a tab bar and three loose -/// pills. Without one the selected tab is a lone pane of glass over the content background, and -/// glass draws itself there as a control floating above content, with the drop shadow to match: -/// the tab ended up ringed in shadow where the system rings it in light. The two capsules are -/// concentric at their ends, the selected one inset two points inside the track, which is why it -/// never overruns the track's curve. -/// -/// The track and the selected tab are opaque fills, and only the new-tab button is -/// glass. A selection cannot be drawn in glass, because glass takes its colour from whatever is -/// behind the window and a selection has to mean the same thing over every wallpaper. Measured -/// across twenty arrangements on macOS 27, every glass surface nested in, beside, or unioned with -/// another one rendered *darker* than its track in light appearance, and the pair that shipped -/// inverted again whenever the window lost key. That is also what Apple asks for: "avoid applying -/// the material to both layers. Instead, use fills, transparency, and vibrancy for the top -/// elements" (WWDC25 session 219). The band is already the system's glass, so these fills are the -/// top layer on it rather than a second pane of it. -internal struct EditorTabStrip: View { - @ObservedObject internal var tabManager: QueryTabManager - /// The pointer's owner. AppKit measures the run and drives every press; this view draws what - /// that produced. Nothing here reads a mouse. - @ObservedObject internal var interaction: EditorTabStripInteraction - /// The dimension this engine's tabs are anchored to, so a label can name the container it - /// shares a title with. Resolved by the window, because a view has no business asking the - /// plugin registry what kind of container a connection has. - internal let containerTarget: ContainerSwitchTarget? - /// Which tabs are running something. Observed rather than pushed in, so a claim opening or - /// settling redraws this strip the same way it redraws the result pane. A tab that is not the - /// selected one has no status bar on screen, and its progress used to show as the window-wide - /// spinner in the centre of the toolbar. - @ObservedObject internal var execution: TabExecutionObservation - internal let onNewTab: () -> Void - /// Left unset by the app, which reads the two accessibility settings instead. A test sets it, - /// because glass does not rasterise. - internal var surfaceStyle: EditorTabStripSurfaceStyle? - - /// Read here rather than pushed in at build time, so changing the preference re-lays every - /// open strip at once instead of the next time an unrelated pane happens to rebuild. - @ObservedObject private var settings = AppSettingsManager.shared - - @Environment(\.controlActiveState) private var controlActiveState - @Environment(\.colorSchemeContrast) private var colorSchemeContrast - @Environment(\.accessibilityReduceTransparency) private var reduceTransparency - - internal var body: some View { - glassContainer { - HStack(spacing: EditorTabStripLayout.trackSpacing) { - track - EditorTabStripNewButton( - action: onNewTab, - isWindowActive: isWindowActive, - prefersSolidSurfaces: prefersSolidSurfaces - ) - .frame(height: EditorTabStripLayout.trackHeight) - } - .frame(height: trackHeight, alignment: .top) - } - .padding(.horizontal, EditorTabStripLayout.stripInset) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - /// A closed tab leaves its id behind, and the tab that slides into its place would - /// otherwise light up under a pointer that never moved onto it. The initial list is seeded - /// where the strip is built, so these two carry changes only. - .onChange(of: tabManager.visibleTabs.map(\.id)) { ids in - interaction.dropClosedTabs(keeping: ids) - } - .onChange(of: settings.tabs.overflow) { style in - interaction.overflow = style - } - /// Cmd+1..9, opening a table from the sidebar and closing a tab can all land on a tab that - /// is scrolled out of sight, so the selection pulls itself into view. - .onChange(of: tabManager.selectedTabId) { newValue in - guard let newValue else { return } - withMotion(.easeOut(duration: 0.15)) { - interaction.revealTab(id: newValue) - } - } - // A pin moves tabs without changing the selection, so the selected one can slide out of view. - .onChange(of: tabManager.visibleTabs.filter { $0.isPinned }.map(\.id)) { _ in - interaction.dropClosedTabs(keeping: tabManager.visibleTabs.map(\.id)) - guard let selected = tabManager.selectedTab?.id else { return } - withMotion(.easeOut(duration: 0.15)) { - interaction.revealTab(id: selected) - } - } - .accessibilityElement(children: .contain) - .accessibilityLabel(Text("Editor Tabs")) - .modifier(TabBarAccessibilityTrait()) - } - - private var trackHeight: CGFloat { - EditorTabStripLayout.trackHeight(forRowCount: interaction.run.rowCount) - } - - /// One container for every glass element in the strip. Glass cannot sample glass across - /// containers, so the track, the selected tab and the new-tab button light inconsistently - /// when they are not grouped, and the button sits only four points from the track's edge. - /// - /// `spacing` stays at zero. It is the proximity at which the container starts *merging* - /// neighbouring shapes into one, and the new-tab button flowing into the track is not wanted. - /// Note that grouping is not free: the container raises the glass it holds above the rest of - /// its content, which is why every control the tabs draw has to live inside its own glass - /// rather than beside it. - @ViewBuilder - private func glassContainer(@ViewBuilder content: () -> some View) -> some View { - if #available(macOS 26.0, *) { - GlassEffectContainer(spacing: 0) { content() } - } else { - content() - } - } - - /// The tabs, each drawn at the rectangle `EditorTabRunLayout` gave it, shifted by however far - /// the track has scrolled. There is no `ScrollView` here on purpose: the view that owns the - /// press owns the wheel and the autoscroll too, so one object decides where a tab is and the - /// drawing follows it rather than the two agreeing by construction. - private var track: some View { - /// The run and the list are read once, together, and the placement is handed to each item - /// rather than looked up again inside the `ForEach`, whose closures SwiftUI evaluates - /// lazily. One paint is then measured against one run: a tab drawn from a list the run was - /// not built for has no rectangle, and is drawn nowhere. - let run = interaction.run - let tabs = displayedTabs - return ZStack(alignment: .topLeading) { - ForEach(Array(tabs.enumerated()), id: \.element.id) { index, tab in - item(for: tab, at: index, in: tabs, placement: run.placement(at: index), label: labels[tab.id]) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - /// Clipped to the same shape the track is drawn as, so a tab scrolled under a rounded end - /// is cut by that curve instead of squaring it off. A capsule only stays right for one - /// row: its radius is half the height, so a wrapped track would curve away most of the - /// first row's close target while the pointer still hit-tests the whole rectangle. - .clipShape(EditorTabStripLayout.trackShape(forRowCount: run.rowCount)) - .padding(EditorTabStripLayout.trackPadding) - .frame(height: trackHeight) - .trackSurface(rowCount: run.rowCount) - } - - private var displayedTabs: [QueryTab] { - let byId = Dictionary(tabManager.visibleTabs.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) - return interaction.displayedIds.compactMap { byId[$0] } - } - - private var labels: [UUID: EditorTabLabelResolver.Label] { - EditorTabLabelResolver.resolve(tabs: displayedTabs, target: containerTarget) - } - - @ViewBuilder - private func item( - for tab: QueryTab, - at index: Int, - in tabs: [QueryTab], - placement: EditorTabPlacement?, - label: EditorTabLabelResolver.Label? - ) -> some View { - if let placement { - EditorTabStripItem( - tab: tab, - label: label ?? EditorTabLabelResolver.Label(text: tab.title, description: tab.title), - isSelected: tabManager.selectedTab?.id == tab.id, - isHovered: interaction.hoveredTabId == tab.id, - isCloseHovered: interaction.hoveredCloseTabId == tab.id, - isWindowActive: isWindowActive, - showsLeadingSeparator: EditorTabStripLayout.showsSeparator( - before: index, - tabIds: tabs.map(\.id), - selectedId: tabManager.selectedTab?.id, - hoveredId: interaction.hoveredTabId, - isReordering: interaction.reorder != nil - ), - position: index + 1, - count: tabs.count, - isBusy: execution.isBusy(tab.id), - commands: interaction.commands - ) - .opacity(opacity(of: tab)) - .frame(width: placement.frame.width, height: placement.frame.height) - .offset( - x: placement.frame.minX - interaction.contentOffset, - y: placement.frame.minY - ) - } - } - - /// The dragged tab fades enough to read as lifted out of the strip, and a tab being torn off - /// fades further so the gesture says what it is about to do before the mouse comes up. - private func opacity(of tab: QueryTab) -> CGFloat { - if interaction.tearingOffTabId == tab.id { return EditorTabStripLayout.tearingOffOpacity } - return interaction.reorder?.draggedId == tab.id ? EditorTabStripLayout.draggingOpacity : 1 - } - - private var isWindowActive: Bool { - controlActiveState != .inactive - } - - /// Read only by the new-tab button now, which is the one surface still allowed to be glass. - private var prefersSolidSurfaces: Bool { - if let surfaceStyle { return surfaceStyle == .solid } - return EditorTabStripEmphasis.prefersSolidSurfaces( - reduceTransparency: reduceTransparency, - contrast: colorSchemeContrast - ) - } -} - -private struct EditorTabStripItem: View { - let tab: QueryTab - let label: EditorTabLabelResolver.Label - let isSelected: Bool - let isHovered: Bool - let isCloseHovered: Bool - let isWindowActive: Bool - let showsLeadingSeparator: Bool - let position: Int - let count: Int - let isBusy: Bool - /// The same command set the pointer's owner drives. The controls below never receive a mouse - /// event any more, and exist for the keyboard, Full Keyboard Access and VoiceOver, which reach - /// them without one. - let commands: EditorTabCommands? - - var body: some View { - ZStack { - if showsLeadingSeparator { - HStack { - Rectangle() - .fill(EditorTabStripPalette.separator) - .frame( - width: EditorTabStripLayout.hairline, - height: EditorTabStripLayout.separatorHeight - ) - Spacer() - } - } - - surface - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .contentShape(Rectangle()) - .contextMenu { - /// The double-click that keeps a tab is an editor idiom rather than a system one, so - /// it needs a command beside it: a gesture with no menu equivalent cannot be found by - /// a user who does not already expect it, and cannot be performed at all by VoiceOver. - Button(String(localized: "Keep Open")) { commands?.keepOpen(tab.id) } - .disabled(!canKeepOpen) - Button(pinTitle) { commands?.setPinned(tab.id, !tab.isPinned) } - Divider() - Button(String(localized: "Close Tab")) { commands?.close(tab.id) } - Button(String(localized: "Close Other Tabs")) { commands?.closeOthers(tab.id) } - .disabled(!canCloseOthers) - Button(String(localized: "Close All Tabs")) { commands?.closeAll() } - .disabled(!canCloseAll) - Divider() - /// Dragging is the usual way to reorder, and it is also the only way that needs a - /// pointer. These give the same reordering to the keyboard and to VoiceOver, which - /// reaches a context menu but cannot perform a drag. - Button(String(localized: "Move Tab Left")) { commands?.moveBy(tab.id, -1) } - .disabled(!canMoveLeft) - Button(String(localized: "Move Tab Right")) { commands?.moveBy(tab.id, 1) } - .disabled(!canMoveRight) - Divider() - Button(String(localized: "Move Tab to New Window")) { commands?.tearOff(tab.id) } - .disabled(!canTearOff) - if offersMoveToConnection { - Button(String(localized: "Move Tab to Connection…")) { commands?.moveToConnection(tab.id) } - .disabled(!canMoveToConnection) - } - } - .accessibilityElement(children: .combine) - .accessibilityAddTraits(.isButton) - .accessibilityIdentifier("editor-tab") - .accessibilityLabel(Text(label.text)) - .accessibilityValue(Text(positionDescription)) - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityAction(named: Text("Close Tab")) { commands?.close(tab.id) } - /// Offered only where it does something, so the actions rotor matches the contextual menu - /// rather than announcing a command that silently does nothing on a tab already kept. - .accessibilityActions { - if canKeepOpen { - Button(String(localized: "Keep Open")) { commands?.keepOpen(tab.id) } - } - Button(pinTitle) { commands?.setPinned(tab.id, !tab.isPinned) } - if offersMoveToConnection, canMoveToConnection { - Button(String(localized: "Move Tab to Connection")) { commands?.moveToConnection(tab.id) } - } - } - .accessibilityAction(named: Text("Move Tab Left")) { if canMoveLeft { commands?.moveBy(tab.id, -1) } } - .accessibilityAction(named: Text("Move Tab Right")) { if canMoveRight { commands?.moveBy(tab.id, 1) } } - .accessibilityAction(named: Text("Move Tab to New Window")) { if canTearOff { commands?.tearOff(tab.id) } } - } - - /// Everything the tab draws lives inside the glass, never over it. A `GlassEffectContainer` - /// raises the glass it holds above the rest of that container's content, so a sibling drawn - /// earlier in a `ZStack`, or an overlay attached outside, is painted over rather than under: - /// the title first measured dimmer than every unselected one, and the close button vanished - /// from the selected tab entirely. - /// - /// The two controls are siblings rather than nested, because a button inside another button's - /// label never receives the click. - private var surface: some View { - ZStack { - Button { commands?.activate(tab.id) } label: { title } - .buttonStyle(.plain) - - HStack(spacing: 0) { - closeButton - Spacer(minLength: 0) - } - .padding(.leading, EditorTabStripLayout.accessoryInset) - } - .tabSurface( - isSelected: isSelected, - isHovered: isHovered, - isWindowActive: isWindowActive - ) - } - - /// A spacer holds each end so the title stays optically centred. The close button sits in the - /// leading one as a sibling overlay rather than inside this label, because a button nested in - /// a button never receives the click. - private var title: some View { - HStack(spacing: 0) { - Color.clear - .frame(width: EditorTabStripLayout.accessoryWidth) - HStack(spacing: EditorTabStripLayout.pinSpacing) { - if tab.isPinned { - Image(systemName: "pin.fill") - .font(.system(size: EditorTabStripLayout.pinGlyphSize)) - .foregroundStyle(titleColor) - .accessibilityHidden(true) - } - Text(label.text) - .lineLimit(1) - .truncationMode(.tail) - .italic(tab.isPreview) - .font(.system(size: EditorTabStripLayout.fontSize)) - .foregroundStyle(titleColor) - } - .frame(maxWidth: .infinity) - unseenIndicator - .frame(width: EditorTabStripLayout.accessoryWidth) - } - .padding(.horizontal, EditorTabStripLayout.accessoryInset) - .frame(maxWidth: .infinity, maxHeight: .infinity) - /// The whole tab is the target, not the glyphs. A `Button` hit-tests the shape its label - /// draws, and this label is a short run of text between two clear spacers, so without a - /// shape of its own everything either side of a title like "Album" stops selecting the - /// tab: roughly 55pt of dead zone at each end of a 184pt tab. - .contentShape(Rectangle()) - } - - // The trailing slot is reserved, so nothing reflows. Running outranks the unseen mark, and shows on the selected tab too. - @ViewBuilder - private var unseenIndicator: some View { - if isBusy { - ProgressView() - .controlSize(.mini) - .accessibilityHidden(true) - } else if let outcome = tab.execution.unseenOutcome, !isSelected { - Image(systemName: outcome == .failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill") - .font(.system(size: EditorTabStripLayout.unseenGlyphSize)) - .symbolRenderingMode(.hierarchical) - .foregroundStyle(outcome == .failed ? Color.red : Color.accentColor) - .accessibilityHidden(true) - } else { - Color.clear - } - } - - private var canKeepOpen: Bool { - commands?.canKeepOpen(tab.id) ?? false - } - - private var canTearOff: Bool { - commands?.canTearOff(tab.id) ?? false - } - - private var pinTitle: String { - EditorTabContextMenuBuilder.pinTitle(isPinned: tab.isPinned) - } - - private var canCloseOthers: Bool { - commands?.canCloseOthers(tab.id) ?? false - } - - private var canCloseAll: Bool { - commands?.canCloseAll() ?? false - } - - private var offersMoveToConnection: Bool { - commands?.offersMoveToConnection(tab.id) ?? false - } - - private var canMoveToConnection: Bool { - commands?.canMoveToConnection(tab.id) ?? false - } - - private var canMoveLeft: Bool { - commands?.canMove(tab.id, -1) ?? false - } - - private var canMoveRight: Bool { - commands?.canMove(tab.id, 1) ?? false - } - - /// Carries the preview state, because the italic title cannot: an assistive technology is told - /// the string, never the face it is set in, and the HIG asks that no interface rely on a single - /// method to convey a change in state. - private var positionDescription: String { - var description = String(format: String(localized: "%1$d of %2$d"), position, count) - if tab.isPinned { - description = String(format: String(localized: "%@, pinned"), description) - } - if tab.isPreview { - description = String(format: String(localized: "%@, preview tab"), description) - } - if isBusy { - return String(format: String(localized: "%@, running"), description) - } - guard let outcome = tab.execution.unseenOutcome, !isSelected else { return description } - guard outcome == .failed else { return String(format: String(localized: "%@, finished"), description) } - return String(format: String(localized: "%@, failed"), description) - } - - /// The system draws both labels in the same face at the same size and separates them by colour - /// alone; measuring its bar shows identical glyph advances for a selected and an unselected - /// title, so weight carries no meaning here. - private var titleColor: Color { - guard isWindowActive else { - return Color(nsColor: isSelected ? .secondaryLabelColor : .tertiaryLabelColor) - } - return Color(nsColor: isSelected ? .labelColor : .secondaryLabelColor) - } - - /// Shown for the tab in front at all times, and for any tab the pointer is over, so closing - /// the visible tab never needs a hunt for its button. - @ViewBuilder - private var closeButton: some View { - if isSelected || (isHovered && isWindowActive) { - EditorTabStripCloseButton( - action: { commands?.close(tab.id) }, - isHovering: isCloseHovered, - isWindowActive: isWindowActive - ) - } else { - Color.clear - } - } -} - -private struct EditorTabStripCloseButton: View { - let action: () -> Void - /// Driven by the view that owns the pointer, because this button no longer receives a mouse - /// event of its own. - let isHovering: Bool - let isWindowActive: Bool - - var body: some View { - Button(action: action) { - Image(systemName: "xmark") - .font(.system(size: 9, weight: .semibold)) - .foregroundStyle(Color(nsColor: isWindowActive ? .secondaryLabelColor : .tertiaryLabelColor)) - .frame( - width: EditorTabStripLayout.accessoryWidth, - height: EditorTabStripLayout.accessoryWidth - ) - .contentShape(Circle()) - } - .buttonStyle(EditorTabStripCloseButtonStyle(isHovering: isHovering)) - .accessibilityLabel(Text("Close Tab")) - } -} - -private struct EditorTabStripCloseButtonStyle: ButtonStyle { - let isHovering: Bool - - func makeBody(configuration: Configuration) -> some View { - configuration.label - .background( - Circle().fill(fill(isPressed: configuration.isPressed)) - ) - } - - private func fill(isPressed: Bool) -> Color { - if isPressed { return Color(nsColor: .tertiaryFill) } - return isHovering ? Color(nsColor: .quaternaryFill) : .clear - } -} - -private struct EditorTabStripNewButton: View { - let action: () -> Void - let isWindowActive: Bool - let prefersSolidSurfaces: Bool - - @Environment(\.colorScheme) private var colorScheme - - var body: some View { - Button(action: action) { - Image(systemName: "plus") - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(Color(nsColor: isWindowActive ? .secondaryLabelColor : .tertiaryLabelColor)) - .frame( - width: EditorTabStripLayout.newTabButtonSize, - height: EditorTabStripLayout.newTabButtonSize - ) - .contentShape(Circle()) - } - .buttonStyle(.plain) - .newTabSurface(isLightAppearance: colorScheme == .light, prefersSolidSurfaces: prefersSolidSurfaces) - .help(Text("New Tab")) - .accessibilityLabel(Text("New Tab")) - } -} - -/// Opaque over the system window, so the track stays below the selected tab whatever is behind the window. Over a -/// themed window it is a translucent system fill, since the color behind it is then the theme's and known. -internal struct EditorTabStripTrackSurface: ViewModifier { - /// Whether the window color is the theme's changes with an edit in place, which does not rebuild the strip. - @ObservedObject private var themeEngine = ThemeEngine.shared - @Environment(\.colorSchemeContrast) private var contrast - - internal let rowCount: Int - - internal func body(content: Content) -> some View { - let shape = EditorTabStripLayout.trackShape(forRowCount: rowCount) - let isOverThemedBackdrop = EditorTabStripPalette.isOverThemedBackdrop(highContrast: contrast == .increased) - return content.background( - shape - .fill(EditorTabStripPalette.trackFill(overThemedBackdrop: isOverThemedBackdrop)) - .overlay( - shape - .stroke( - EditorTabStripPalette.trackEdge, - lineWidth: EditorTabStripLayout.hairline - ) - ) - ) - } -} - -private extension View { - func trackSurface(rowCount: Int) -> some View { - modifier(EditorTabStripTrackSurface(rowCount: rowCount)) - } - - /// The selected tab is the one pane of glass the system raises out of the track. An unselected - /// tab is not inert either: hovering fills it so the pointer has something to land on, and a - /// background window shows neither. - @ViewBuilder - func tabSurface( - isSelected: Bool, - isHovered: Bool, - isWindowActive: Bool - ) -> some View { - if isSelected { - selectedTabSurface() - } else if isHovered, isWindowActive { - background(EditorTabStripLayout.tabShape.fill(EditorTabStripPalette.hoverFill)) - } else { - self - } - } - - /// A fill and a rim, which is how the system draws a raised segment. A vertical section - /// through a selected segment reads track 236, rim 215, highlight 255, body 242: the fill - /// carries six levels and the edge carries twenty-one. Only the fill was drawn here before, - /// which is why the selection read as flat even at the distance the system uses. - /// - /// `controlBackgroundColor` is not the fill: it matches the window background exactly in dark, - /// so the raised tab would read as a hole punched in its own track. - /// - /// The fill does not step down for a background window. Reaching for the track's own - /// `unemphasizedSelectedContentBackgroundColor` there left the two identical, so a background - /// window showed no selected tab at all. The system keeps its selected tab drawn there; only - /// the labels step down, which they already do in `titleColor`. - func selectedTabSurface() -> some View { - background( - EditorTabStripLayout.tabShape - .fill(EditorTabStripPalette.selectedFill) - .overlay( - EditorTabStripLayout.tabShape - .strokeBorder( - EditorTabStripPalette.selectionEdge, - lineWidth: EditorTabStripLayout.hairline - ) - ) - ) - } - - /// The one genuine press target in the strip, so this is where interactive glass belongs. - /// The tab capsule does not take it: the tab a click lands on is an unselected one, which - /// carries no glass to respond. - /// - /// It keeps the untinted material on purpose. The button sits outside the track, so it belongs - /// at the height of the chrome rather than recessed into a channel it is not in. - @ViewBuilder - func newTabSurface(isLightAppearance: Bool, prefersSolidSurfaces: Bool) -> some View { - if #available(macOS 26.0, *), !prefersSolidSurfaces { - glassEffect(.regular.interactive(), in: Circle()) - } else { - background( - Circle() - .fill(Color(nsColor: .controlColor)) - .shadow( - color: Color(nsColor: .shadowColor).opacity(isLightAppearance ? 0.12 : 0), - radius: isLightAppearance ? 1 : 0, - y: isLightAppearance ? 0.5 : 0 - ) - ) - } - } -} - -/// `AccessibilityTraits.isTabBar` is macOS 14. Without it VoiceOver announces the strip as a -/// plain container; the label and the per-tab elements are unchanged. -private struct TabBarAccessibilityTrait: ViewModifier { - @ViewBuilder - func body(content: Content) -> some View { - if #available(macOS 14.0, *) { - content.accessibilityAddTraits(.isTabBar) - } else { - content - } - } -} diff --git a/apple/TablePro/Views/Main/EditorTabStripAccessoryController.swift b/apple/TablePro/Views/Main/EditorTabStripAccessoryController.swift index b13c047ef4..662a0c1b94 100644 --- a/apple/TablePro/Views/Main/EditorTabStripAccessoryController.swift +++ b/apple/TablePro/Views/Main/EditorTabStripAccessoryController.swift @@ -5,42 +5,16 @@ import AppKit -/// The window chrome band that holds the editor tab strip, in the same place the system puts its -/// own: a bottom titlebar accessory, flush under the toolbar. -/// -/// This is not a styling choice. A runtime probe of `NSTabBar`, the private control Finder's tab -/// bar is built from, shows it hosted in exactly this way, and AppKit gives the placement two -/// things a content-view mount cannot have. The accessory is inset past a `.sidebar` split item -/// automatically, so the band starts where the content pane starts rather than at the window edge, -/// with no sidebar-width tracking of our own. And the window's `contentLayoutRect` shrinks by the -/// band, so the content below is laid out around it instead of being pushed by a stack. -/// -/// Three properties have to be set together or the band misbehaves in ways that only show up in -/// one state. `automaticallyAdjustsSize` defaults to true and would resize the view to the -/// system's standard accessory height, discarding ours. `fullScreenMinHeight` defaults to zero, -/// and the header is explicit that zero "will fully hide the view when the menu bar is hidden", so -/// leaving it would make the tab strip vanish in full screen. `layoutAttribute` must be `.bottom` -/// for either of the other two to apply at all. +// A bottom titlebar accessory is where the system hosts its own tab bar, and AppKit insets it past the sidebar. @MainActor internal final class EditorTabStripAccessoryController: NSTitlebarAccessoryViewController { - /// The strip belongs to one connection, the accessory belongs to the window, and a window - /// hosts several connections. The band therefore shows the selected workspace's own strip the - /// same way the split items show its panes, so every other connection's strip stays built. private let paneHost = WorkspacePaneHost() - /// The band's height, which follows the strip. A wrapped strip is taller than a scrolling one, - /// and the accessory has to grow with it or the extra rows are drawn behind the content - /// instead of the window's `contentLayoutRect` making room for them. - /// - /// It is the view's own frame height, never a constraint. - /// `NSTitlebarAccessoryViewController` places its view itself and observes that height for - /// changes, which is what the width comment below already says. - private var bandHeight = EditorTabStripLayout.bandHeight - internal init() { super.init(nibName: nil, bundle: nil) layoutAttribute = .bottom automaticallyAdjustsSize = false + // Zero would hide the strip whenever full screen hides the menu bar. fullScreenMinHeight = EditorTabStripLayout.bandHeight } @@ -49,8 +23,6 @@ internal final class EditorTabStripAccessoryController: NSTitlebarAccessoryViewC fatalError("EditorTabStripAccessoryController does not support NSCoder init") } - /// The width is a placeholder AppKit replaces with the pane's; only the height is ours, and - /// `NSTitlebarAccessoryViewController` observes it for changes. override internal func loadView() { let band = NSView(frame: NSRect(x: 0, y: 0, width: 1, height: EditorTabStripLayout.bandHeight)) view = band @@ -69,34 +41,9 @@ internal final class EditorTabStripAccessoryController: NSTitlebarAccessoryViewC internal func show(_ controller: NSViewController?) { paneHost.show(controller) - applyBandHeight(paneHost.preferredContentSize.height) - } - - /// The strip publishes its height through `preferredContentSize`, the documented way for a - /// child to ask its parent for room, and `WorkspacePaneHost` passes it on from the pane it is - /// showing. Anything at or below zero means the pane has nothing to say yet, so the band keeps - /// the single-row height it was built with. - override internal func preferredContentSizeDidChange(for viewController: NSViewController) { - super.preferredContentSizeDidChange(for: viewController) - guard viewController === paneHost else { return } - applyBandHeight(viewController.preferredContentSize.height) - } - - private func applyBandHeight(_ height: CGFloat) { - let resolved = height > 0 ? height : EditorTabStripLayout.bandHeight - guard bandHeight != resolved else { return } - bandHeight = resolved - fullScreenMinHeight = resolved - view.frame.size.height = resolved } - /// `hidden` collapses the band to zero height without taking it off the window, which is what - /// keeps a connection's strip built while the window shows a pane that has no tabs to list. - /// - /// The band collapses under whatever had keyboard focus, so focus is let go on the way down. - /// Closing the second-to-last tab from the strip is enough to reach this: the button that was - /// clicked is inside the band that is now zero points tall, and a first responder in a view - /// with no size leaves Full Keyboard Access tabbing out of somewhere invisible. + // Collapsing keeps every connection's strip built while the window shows a pane with no tabs. internal func setBandVisible(_ isVisible: Bool) { guard isHidden == isVisible else { return } if !isVisible { resignFirstResponderInsideBand() } diff --git a/apple/TablePro/Views/Main/EditorTabStripInteraction.swift b/apple/TablePro/Views/Main/EditorTabStripInteraction.swift deleted file mode 100644 index 08163be1d0..0000000000 --- a/apple/TablePro/Views/Main/EditorTabStripInteraction.swift +++ /dev/null @@ -1,217 +0,0 @@ -// -// EditorTabStripInteraction.swift -// TablePro -// - -import AppKit -import Combine -import Foundation - -/// What a press on the strip turned out to be. -internal enum EditorTabGesture: Equatable { - case click(count: Int) - case reorder - case tearOff -} - -/// The one piece of state the strip's two halves share: AppKit owns the pointer and writes here, -/// SwiftUI reads it and draws. -/// -/// The split exists because the two jobs have different owners on macOS. Which control receives a -/// press inside a titlebar accessory was previously decided by SwiftUI gesture arbitration between -/// a `Button`, a `ScrollView` and a `DragGesture`, with AppKit's own window drag as a fourth -/// claimant, and the winner depended on timing: measured on this strip, a plain one-place drag did -/// nothing about one time in seven, and the four UI tests covering it have never passed CI. A -/// press has exactly one owner now, and it is `EditorTabInteractionView`. -/// -/// Geometry lives here rather than in the SwiftUI layout for the same reason. The tab a user sees, -/// the tab the pointer hits and the tab a drag targets are one rectangle out of -/// `EditorTabRunLayout`, so they cannot disagree. -@MainActor -internal final class EditorTabStripInteraction: ObservableObject { - /// The run the strip draws, measured by the view that owns the pointer. - @Published internal private(set) var run: EditorTabRunLayout = .empty - /// How far the track has scrolled, in points. Always zero when the run wraps, because a - /// wrapped run never overflows. - @Published internal private(set) var contentOffset: CGFloat = 0 - @Published internal private(set) var hoveredTabId: UUID? - /// Set while the pointer is over a tab's close button, because the button no longer receives - /// the mouse and cannot light itself. - @Published internal private(set) var hoveredCloseTabId: UUID? - /// The reorder in flight, holding both the order the strip draws and the order it came from. - /// The manager is not written until the pointer comes up, so an abandoned drag leaves nothing - /// behind and Escape is just dropping this value. - @Published internal private(set) var reorder: EditorTabReorder? - @Published internal private(set) var tearingOffTabId: UUID? - /// The track's visible width, measured by the view that owns the pointer. SwiftUI reads it so - /// a reveal and a clamp use the same number the pointer does. - internal private(set) var viewportWidth: CGFloat = 0 - /// The last width the pointer's owner measured, kept so a tab opening or closing can re-lay - /// the run without waiting for AppKit to schedule another layout pass. - private var trackWidth: CGFloat = 0 - - internal var overflow: EditorTabStripOverflow = .scroll { - didSet { - guard overflow != oldValue else { return } - contentOffset = 0 - updateRun(trackWidth: trackWidth, count: tabIds.count) - } - } - - /// Rebuilt on every render, because the closures reach through the workspace to a coordinator - /// that only exists once the detail pane has appeared. - @Published internal var commands: EditorTabCommands? - - @Published internal var tabIds: [UUID] = [] - - /// Raised whenever a rebuild changes how many rows the run takes, from any path. The band's - /// height follows it, and a tab opened or closed while the strip is wrapped can cross a row - /// boundary without any layout pass having run. - @Published internal var onRowCountChanged: ((Int) -> Void)? - @Published private var reportedRowCount = 1 - - /// The order the strip draws: the reorder's while one is in flight, the manager's otherwise. - internal var displayedIds: [UUID] { - reorder?.order ?? tabIds - } - - internal func updateRun(trackWidth: CGFloat, count: Int) { - self.trackWidth = trackWidth - viewportWidth = max(trackWidth - EditorTabStripLayout.trackPadding * 2, 0) - let rebuilt = EditorTabRunLayoutBuilder.run( - forTrack: trackWidth, - count: count, - overflow: overflow - ) - guard rebuilt != run else { return } - run = rebuilt - clampContentOffset() - guard run.rowCount != reportedRowCount else { return } - reportedRowCount = run.rowCount - onRowCountChanged?(run.rowCount) - } - - internal func setHovered(_ id: UUID?, overCloseButton: Bool = false) { - if hoveredTabId != id { hoveredTabId = id } - let close = overCloseButton ? id : nil - if hoveredCloseTabId != close { hoveredCloseTabId = close } - } - - internal func scroll(by delta: CGFloat) { - guard overflow == .scroll else { return } - contentOffset += delta - clampContentOffset() - } - - internal func clampContentOffset() { - let maximum = max(run.contentSize.width - viewportWidth, 0) - contentOffset = min(max(contentOffset, 0), maximum) - } - - /// Brings a tab fully into the viewport, which is what a selection made from the keyboard, the - /// sidebar or a closed neighbour needs. - internal func revealTab(id: UUID) { - guard overflow == .scroll, viewportWidth > 0 else { return } - guard let index = displayedIds.firstIndex(of: id), let placement = run.placement(at: index) else { return } - if placement.frame.minX < contentOffset { - contentOffset = placement.frame.minX - } else if placement.frame.maxX > contentOffset + viewportWidth { - contentOffset = placement.frame.maxX - viewportWidth - } - clampContentOffset() - } - - internal func beginReorder(of id: UUID) { - guard reorder == nil else { return } - let pinnedIds = Set(tabIds.filter { commands?.isPinned($0) ?? false }) - reorder = EditorTabReorder(draggedId: id, order: tabIds, pinnedIds: pinnedIds) - } - - /// Moves the dragged tab as the pointer passes each neighbour's centre. Returns true when the - /// order changed, so the caller can animate only then. - @discardableResult - internal func updateReorder(toLinearLocation location: CGFloat) -> Bool { - guard var live = reorder, let currentIndex = live.destinationIndex else { return false } - let destination = EditorTabReorderResolver.settledDestination( - forLocation: location, - tabWidth: run.tabWidth, - currentIndex: currentIndex, - count: live.order.count - ) - guard let destination else { return false } - live.move(to: destination) - guard live != reorder else { return false } - reorder = live - return true - } - - internal func markTearingOff(_ id: UUID?) { - guard tearingOffTabId != id else { return } - tearingOffTabId = id - } - - /// Writes the order to the manager once, on release, or not at all when nothing moved. - internal func commitReorder() { - defer { clearReorder() } - guard let reorder, reorder.movedFromOriginal, let destination = reorder.destinationIndex else { return } - commands?.moveTab(reorder.draggedId, destination) - } - - internal func clearReorder() { - reorder = nil - tearingOffTabId = nil - } - - /// Takes the tab list and the overflow style from the model that owns them. - /// - /// The run `EditorTabInteractionView.layout()` measures is built from `tabIds`, so the list has - /// to arrive from whoever builds the strip rather than from one of its view modifiers: a band - /// is installed hidden and has no appearance to wait for, and a run measured against a list - /// that is still empty divides the whole track among the tabs it knew about, leaving the rest - /// without a placement. A tab with no placement is drawn nowhere. - internal func adopt(tabIds ids: [UUID], overflow style: EditorTabStripOverflow) { - overflow = style - dropClosedTabs(keeping: ids) - } - - /// A tab that closed under the pointer leaves both orders, and the drag ends outright when the - /// tab being dragged is the one that went. - internal func dropClosedTabs(keeping ids: [UUID]) { - tabIds = ids - updateRun(trackWidth: trackWidth, count: ids.count) - guard var live = reorder else { return } - guard live.removingClosedTabs(keeping: ids), Set(live.order) == Set(ids) else { - clearReorder() - return - } - reorder = live - } -} - -/// Everything the strip can ask the app to do, in one place, so the AppKit view that owns the -/// pointer never reaches into a view model of its own. -internal struct EditorTabCommands { - internal let activate: (UUID) -> Void - internal let keepOpen: (UUID) -> Void - internal let canKeepOpen: (UUID) -> Bool - internal let isPinned: (UUID) -> Bool - internal let setPinned: (UUID, Bool) -> Void - internal let close: (UUID) -> Void - internal let closeOthers: (UUID) -> Void - internal let canCloseOthers: (UUID) -> Bool - internal let closeAll: () -> Void - internal let canCloseAll: () -> Bool - internal let moveTab: (UUID, Int) -> Void - internal let canMove: (UUID, Int) -> Bool - internal let moveBy: (UUID, Int) -> Void - internal let tearOff: (UUID) -> Void - internal let canTearOff: (UUID) -> Bool - internal let moveToConnection: (UUID) -> Void - /// Whether the tab's kind can ever move, which decides whether the item is shown at all. - internal let offersMoveToConnection: (UUID) -> Bool - /// Whether it can move right now, which decides whether the shown item is dimmed. - internal let canMoveToConnection: (UUID) -> Bool - /// The pointer's owner sets the view's tooltip from this, because the tab's own `.help` never - /// sees a mouse now. - internal let tooltip: (UUID) -> String -} diff --git a/apple/TablePro/Views/Main/EditorTabStripLayout.swift b/apple/TablePro/Views/Main/EditorTabStripLayout.swift index 1f712426c8..152b57cb09 100644 --- a/apple/TablePro/Views/Main/EditorTabStripLayout.swift +++ b/apple/TablePro/Views/Main/EditorTabStripLayout.swift @@ -5,18 +5,10 @@ import CoreGraphics import Foundation -import SwiftUI +import QuartzCore -/// The geometry and visibility rules of the editor tab strip, kept apart from the view so they -/// can be tested. Every number here was measured off `NSTabBar`, the private control the system's -/// own window tab bar is built from, rather than designed: a runtime probe of its view tree on -/// macOS 27 gives a 36pt titlebar accessory holding a 28pt bar, whose track is inset 8pt, then 4pt -/// of gap, then a 28pt new-tab button, then 8pt to the trailing edge. +// Measured off the system's own window tab bar on macOS 27. internal enum EditorTabStripLayout { - internal static let unseenGlyphSize: CGFloat = 10 - - /// The titlebar accessory's own height. The track is pinned to its top edge, flush against the - /// toolbar, and what remains below is the clearance the system leaves before the content. internal static let bandHeight: CGFloat = 36 internal static let trackHeight: CGFloat = 28 internal static let tabHeight: CGFloat = 24 @@ -26,86 +18,38 @@ internal enum EditorTabStripLayout { internal static let newTabButtonSize: CGFloat = 28 internal static let minimumTabWidth: CGFloat = 120 internal static let separatorHeight: CGFloat = 16 + internal static let separatorWidth: CGFloat = 1 + internal static let hairline: CGFloat = 0.5 + internal static let accessoryWidth: CGFloat = 16 internal static let accessoryInset: CGFloat = 5 internal static let fontSize: CGFloat = 11 internal static let pinGlyphSize: CGFloat = 9 internal static let pinSpacing: CGFloat = 3 + internal static let statusGlyphSize: CGFloat = 10 + internal static let closeGlyphSize: CGFloat = 9 + internal static let newTabGlyphSize: CGFloat = 12 - /// One device pixel on the 2x displays this chrome is drawn for, which is what the system uses - /// for both the track's edge and the rule between two tabs. - internal static let hairline: CGFloat = 0.5 - - internal static var bandBottomClearance: CGFloat { bandHeight - trackHeight } - - /// The gap between two wrapped rows, and the pitch that follows from it. - internal static let rowSpacing: CGFloat = 2 - internal static var rowStride: CGFloat { tabHeight + rowSpacing } - - /// A wrapped strip grows the track and the band with it, so the content below is laid out - /// around the taller band rather than behind it. One row resolves to the measured numbers. - internal static func trackHeight(forRowCount rows: Int) -> CGFloat { - trackHeight + CGFloat(max(rows, 1) - 1) * rowStride - } + // Below this a collapsed tab has no room for anything but its edge. + internal static let minimumContentWidth: CGFloat = 44 - internal static func bandHeight(forRowCount rows: Int) -> CGFloat { - bandHeight + CGFloat(max(rows, 1) - 1) * rowStride - } + // The HIG's distance for showing a drag image. + internal static let dragThreshold: CGFloat = 3 - /// How close to the viewport's edge the pointer has to come before a reorder starts scrolling - /// the track under it. One tab's minimum width would swallow the whole viewport on a narrow - /// window, so this is a fixed band, the same shape `NSView.autoscroll(with:)` applies. internal static let autoscrollMargin: CGFloat = 24 internal static let autoscrollStep: CGFloat = 12 - /// How far the pointer has to leave the strip before a reorder becomes a tear-off. Measured - /// against the band rather than the tab, so a drag that stays in the chrome is still a reorder. - internal static let tearOffThreshold: CGFloat = 44 - - /// Fully rounded, because that is what the system's own tab bar is: the runtime - /// probe reports `cornerRadius = 12` on each 24pt `NSGlassEffectView` tab, which is exactly - /// half its height, and a corner fit of the 28pt track lands at 12 to 14pt. An in-content - /// `NSSegmentedControl` is the shallower shape, `(height - 4) / 4`, but that is a different - /// control in a different place; this strip is the titlebar tab bar. - internal static var trackShape: Capsule { Capsule(style: .continuous) } - internal static var tabShape: Capsule { Capsule(style: .continuous) } - - /// A capsule is only the system's shape while the track is one row tall. Its radius is half - /// the height, so a wrapped track would round away most of the first and last rows rather - /// than its ends, and the close button drawn in that corner would disappear under the curve - /// while the pointer still hit-tests the full rectangle. Past one row the corner holds at the - /// radius a single row would have had. - internal static func trackShape(forRowCount rows: Int) -> AnyShape { - guard rows > 1 else { return AnyShape(trackShape) } - return AnyShape(RoundedRectangle(cornerRadius: trackHeight / 2, style: .continuous)) + // The system bar settles an opened or closed tab along this curve. + internal static let motionDuration: TimeInterval = 0.32 + internal static var motionTiming: CAMediaTimingFunction { + CAMediaTimingFunction(controlPoints: 0.22, 0.9, 0.3, 1) } - /// Tabs share the track equally, and stop shrinking at a width that still fits a name so a - /// long list scrolls instead of collapsing into slivers. The system staggers widths slightly - /// by an undocumented rule; an equal share is within a couple of points of it. - internal static func tabWidth(forTrack width: CGFloat, count: Int) -> CGFloat { - let usable = width - trackPadding * 2 - let divisor = CGFloat(max(count, 1)) - return max(usable / divisor, minimumTabWidth) + internal static func tabWidth(forViewport width: CGFloat, count: Int) -> CGFloat { + guard count > 0 else { return minimumTabWidth } + return max(width / CGFloat(count), minimumTabWidth) } - /// How far a tab fades while it is the one being dragged. Enough to read as lifted out of the - /// strip, not so far that its title stops being legible on the way past its neighbours. - internal static let draggingOpacity: CGFloat = 0.45 - - /// A tab being torn off fades further than one being reordered, so the gesture says which of - /// the two it is before the pointer comes up. - internal static let tearingOffOpacity: CGFloat = 0.2 - - /// How far the pointer travels before a press on a tab becomes a reorder rather than a click. - /// The same distance AppKit uses to tell a click from a drag, so a hand that shifts a point or - /// two while clicking still selects the tab. - internal static let reorderThreshold: CGFloat = 4 - - /// A separator is drawn at the leading edge of a tab only when both it and its leading - /// neighbour are plain and untouched. A line against the raised capsule reads as a seam in - /// it, and one against a hovered tab fights that tab's fill. Two tabs therefore never show - /// one, because one of them is always selected. internal static func showsSeparator( before index: Int, tabIds: [UUID], diff --git a/apple/TablePro/Views/Main/EditorTabStripSnapshot.swift b/apple/TablePro/Views/Main/EditorTabStripSnapshot.swift new file mode 100644 index 0000000000..3f75225ae3 --- /dev/null +++ b/apple/TablePro/Views/Main/EditorTabStripSnapshot.swift @@ -0,0 +1,83 @@ +// +// EditorTabStripSnapshot.swift +// TablePro +// + +import Foundation + +internal enum EditorTabStatus: Equatable { + case idle + case running + case finished + case failed +} + +internal struct EditorTabItem: Equatable, Identifiable { + internal let id: UUID + internal let title: String + internal let tooltip: String + internal let isSelected: Bool + internal let isPinned: Bool + internal let isPreview: Bool + internal let status: EditorTabStatus + internal let position: Int + internal let count: Int + + // An assistive technology is told the string, never the italic face a preview is set in. + internal var accessibilityDescription: String { + var description = String(format: String(localized: "%1$d of %2$d"), position, count) + if isPinned { + description = String(format: String(localized: "%@, pinned"), description) + } + if isPreview { + description = String(format: String(localized: "%@, preview tab"), description) + } + switch status { + case .idle: + return description + case .running: + return String(format: String(localized: "%@, running"), description) + case .finished: + return String(format: String(localized: "%@, finished"), description) + case .failed: + return String(format: String(localized: "%@, failed"), description) + } + } +} + +internal enum EditorTabStripSnapshot { + internal static func items( + tabs: [QueryTab], + selectedId: UUID?, + target: ContainerSwitchTarget?, + isBusy: (UUID) -> Bool + ) -> [EditorTabItem] { + let labels = EditorTabLabelResolver.resolve(tabs: tabs, target: target) + return tabs.enumerated().map { index, tab in + let label = labels[tab.id] + let isSelected = tab.id == selectedId + return EditorTabItem( + id: tab.id, + title: label?.text ?? tab.title, + tooltip: tooltip(description: label?.description ?? tab.title, isPreview: tab.isPreview), + isSelected: isSelected, + isPinned: tab.isPinned, + isPreview: tab.isPreview, + status: status(of: tab, isSelected: isSelected, isBusy: isBusy(tab.id)), + position: index + 1, + count: tabs.count + ) + } + } + + private static func tooltip(description: String, isPreview: Bool) -> String { + guard isPreview else { return description } + return String(format: String(localized: "%@\nPreview tab. Double-click to keep it open."), description) + } + + private static func status(of tab: QueryTab, isSelected: Bool, isBusy: Bool) -> EditorTabStatus { + if isBusy { return .running } + guard !isSelected, let outcome = tab.execution.unseenOutcome else { return .idle } + return outcome == .failed ? .failed : .finished + } +} diff --git a/apple/TablePro/Views/Main/EditorTabStripSurfaces.swift b/apple/TablePro/Views/Main/EditorTabStripSurfaces.swift index e2f8557f89..672ebef479 100644 --- a/apple/TablePro/Views/Main/EditorTabStripSurfaces.swift +++ b/apple/TablePro/Views/Main/EditorTabStripSurfaces.swift @@ -3,21 +3,9 @@ // TablePro // -import SwiftUI +import AppKit -/// The strip's surfaces. -/// -/// Every value is a semantic `NSColor`, so the light appearance inverts with the system instead of -/// needing a second hand-tuned palette, and so nothing here has to be retuned when Apple moves a -/// tone. The pair was checked against the system's own tab bar rather than chosen: `NSTabBar` -/// measures a track of rgb(232) and a selected tab of rgb(253) in light, and rgb(71) and rgb(74) -/// in dark. These resolve to rgb(220) and rgb(255) in light, and rgb(70) and rgb(116) in dark. internal enum EditorTabStripPalette { - internal static func trackFill(overThemedBackdrop: Bool) -> Color { - Color(nsColor: trackColor(overThemedBackdrop: overThemedBackdrop)) - } - - /// The track sits in the titlebar, which shows the theme's window color only where `ThemeWindowBackdrop` sets it. internal static var followsWindowBackdrop: Bool { ThemeWindowBackdrop.canReachChrome } @@ -27,10 +15,7 @@ internal enum EditorTabStripPalette { followsWindowBackdrop && ThemeBackdropState.isThemed(highContrast: highContrast) } - /// The system track measures rgb(220) light and rgb(70) dark against `NSTabBar`'s rgb(232) and rgb(71). Over a - /// themed window that opaque gray cuts a slab into the theme, while the window color itself leaves the selected - /// tab a step of 1.00 to 1.08 under a light theme. A translucent system fill keeps the theme's hue and a step of - /// 1.19 to 1.29 in light and 2.1 in dark, the closest of the system fills to the unthemed 1.37 and 2.02. + // Over a themed window an opaque gray cuts a slab into the theme, so the track takes a translucent system fill. internal static func trackColor(overThemedBackdrop: Bool) -> NSColor { let native = NSColor.unemphasizedSelectedContentBackgroundColor guard overThemedBackdrop else { return native } @@ -38,61 +23,15 @@ internal enum EditorTabStripPalette { return native } - /// Opaque white in light, and white at alpha 0.247 in dark. That asymmetry is the whole reason - /// the selection cannot invert: in light it is the ceiling, so no track can rise above it, and - /// in dark it composites *over* whatever the track resolved to, so it always lifts. The step - /// is a property of the colour rather than of a tuned distance. - internal static var selectedFill: Color { Color(nsColor: .controlColor) } + // Opaque white in light and translucent white in dark, so the selection always sits above the track. + internal static var selectedColor: NSColor { .controlColor } - /// Half the weight of a separator. `separatorColor` was twice the measured edge and read as a - /// drawn outline rather than the lit rim the system puts there. - /// - /// `quinaryLabel`, not `quinaryLabelColor`. The two spellings swap places between toolchains: - /// the Xcode 27 beta deprecates this one in favour of `quinaryLabelColor`, and Xcode 26.4, the - /// one CI builds with, rejects `quinaryLabelColor` outright as renamed to this. Take the - /// spelling CI accepts and ignore the beta's deprecation hint. - internal static var trackEdge: Color { Color(nsColor: .quinaryLabel) } + // `quinaryLabel`, not `quinaryLabelColor`: Xcode 26.4 on CI rejects the newer spelling. + internal static var trackEdgeColor: NSColor { .quinaryLabel } - /// The system darkens a hovered tab rather than lightening it, in light appearance: a rendered - /// `NSTabBar` measures rgb(220) under the pointer against a rgb(232) track, and this resolves - /// to rgb(210) against rgb(220). The direction is deliberate and matches, so it is left alone. - internal static var hoverFill: Color { Color(nsColor: .tertiaryFill) } + internal static var hoverColor: NSColor { .tertiaryFill } - internal static var separator: Color { Color(nsColor: .separatorColor) } - - /// The rim is the other half of how the system draws a raised tab, and the half this strip was - /// missing. A vertical section through a selected segment reads track 236, rim 215, highlight - /// 255, body 242: the fill carries six levels and the edge carries twenty-one. Only the fill - /// was drawn here before, which is why the selection read as flat. - internal static var selectionEdge: Color { Color(nsColor: .separatorColor) } -} + internal static var separatorColor: NSColor { .separatorColor } -/// Which of the two surface sets the strip draws. -/// -/// The app resolves this from the environment. A test pins it, because a `glassEffect` cannot be -/// rasterised at all: `cacheDisplay` comes back with an empty bitmap for the entire hosting view, -/// the strip's own titles and close button included, not merely for the glass. -internal enum EditorTabStripSurfaceStyle { - case glass - case solid -} - -/// Whether the strip may use Liquid Glass at all. -/// -/// Only the new-tab button asks any more. The track and the selected tab are opaque, because a -/// selection drawn in glass cannot hold its own sign: measured across twenty -/// arrangements on macOS 27, every glass surface nested in, beside, or unioned with another one -/// rendered *darker* than its track in light appearance, and the shipped pair inverted again when -/// the window lost key. Glass takes its colour from whatever is behind the window, and a selection -/// has to mean the same thing over every wallpaper. -/// -/// The rule itself belongs to `SolidSurfacePreference`, which the six views that reach both -/// settings through `themeMaterial` also use. -internal enum EditorTabStripEmphasis { - internal static func prefersSolidSurfaces( - reduceTransparency: Bool, - contrast: ColorSchemeContrast - ) -> Bool { - SolidSurfacePreference.prefersSolid(reduceTransparency: reduceTransparency, contrast: contrast) - } + internal static var selectionEdgeColor: NSColor { .separatorColor } } diff --git a/apple/TablePro/Views/Main/EditorTabStripView.swift b/apple/TablePro/Views/Main/EditorTabStripView.swift new file mode 100644 index 0000000000..a5d998745b --- /dev/null +++ b/apple/TablePro/Views/Main/EditorTabStripView.swift @@ -0,0 +1,609 @@ +// +// EditorTabStripView.swift +// TablePro +// + +import AppKit +import Combine + +// AppKit on purpose: the scroll view, the drag session and the tab group element are what the system bar is built from. +@MainActor +internal final class EditorTabStripView: NSView { + internal var commands: EditorTabCommands? + + internal private(set) var items: [EditorTabItem] = [] + internal private(set) var run = EditorTabRunLayout(viewportWidth: 0, count: 0) + internal private(set) var reorder: EditorTabReorder? + internal private(set) var hoveredId: UUID? + + internal let newTabButton = NSButton() + internal let scrollView = EditorTabScrollView() + + private let track = EditorTabTrackView() + private let document = EditorTabDocumentView() + private var itemViews: [UUID: EditorTabItemView] = [:] + private var lastActivatedId: UUID? + private var dragHasLeftStrip = false + private var dragWasCancelled = false + private var dragCancelMonitor: Any? + private var incomingIndex: Int? + private var hoverArea: NSTrackingArea? + private var laidOutWidth: CGFloat = 0 + private var windowSubscriptions: Set = [] + private var chromeSubscriptions: Set = [] + + override internal init(frame frameRect: NSRect) { + super.init(frame: frameRect) + configure() + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("EditorTabStripView does not support NSCoder init") + } + + override internal var isFlipped: Bool { true } + + private func configure() { + addSubview(track) + + // A scroll view in the titlebar would otherwise inset its content for the titlebar it sits in. + scrollView.automaticallyAdjustsContentInsets = false + scrollView.contentInsets = NSEdgeInsetsZero + scrollView.drawsBackground = false + scrollView.contentView.drawsBackground = false + scrollView.hasHorizontalScroller = false + scrollView.hasVerticalScroller = false + scrollView.horizontalScrollElasticity = .automatic + scrollView.verticalScrollElasticity = .none + scrollView.documentView = document + scrollView.wantsLayer = true + scrollView.layer?.cornerRadius = EditorTabStripLayout.tabHeight / 2 + scrollView.layer?.cornerCurve = .continuous + scrollView.layer?.masksToBounds = true + scrollView.contentView.postsBoundsChangedNotifications = true + addSubview(scrollView) + + let symbol = NSImage.SymbolConfiguration(pointSize: EditorTabStripLayout.newTabGlyphSize, weight: .medium) + newTabButton.image = NSImage(systemSymbolName: "plus", accessibilityDescription: String(localized: "New Tab"))? + .withSymbolConfiguration(symbol) + newTabButton.imagePosition = .imageOnly + newTabButton.target = self + newTabButton.action = #selector(newTabClicked) + newTabButton.toolTip = String(localized: "New Tab") + newTabButton.setAccessibilityLabel(String(localized: "New Tab")) + if #available(macOS 26.0, *) { + newTabButton.bezelStyle = .glass + newTabButton.borderShape = .circle + } else { + newTabButton.bezelStyle = .circular + } + addSubview(newTabButton) + + registerForDraggedTypes([.editorTab]) + + NotificationCenter.default.addObserver( + self, + selector: #selector(clipBoundsChanged), + name: NSView.boundsDidChangeNotification, + object: scrollView.contentView + ) + AppEvents.shared.themeChanged + .receive(on: RunLoop.main) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.track.needsDisplay = true } + } + .store(in: &chromeSubscriptions) + NSWorkspace.shared.notificationCenter + .publisher(for: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification) + .receive(on: RunLoop.main) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.track.needsDisplay = true } + } + .store(in: &chromeSubscriptions) + } + + private var canAnimate: Bool { + window?.isVisible == true && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion + } + + // MARK: - Content + + internal func apply(_ newItems: [EditorTabItem]) { + guard newItems != items else { return } + let previousIds = items.map(\.id) + let previousSelection = items.first(where: \.isSelected)?.id + items = newItems + + let liveIds = Set(newItems.map(\.id)) + for (id, view) in itemViews where !liveIds.contains(id) { + view.removeFromSuperview() + itemViews[id] = nil + } + if hoveredId.map({ !liveIds.contains($0) }) == true { hoveredId = nil } + reconcileReorder(keeping: newItems.map(\.id)) + + var inserted: Set = [] + for item in newItems { + if let view = itemViews[item.id] { + view.apply(item) + } else { + let view = EditorTabItemView(item: item) + view.strip = self + view.isWindowActive = isWindowKey + document.addSubview(view) + itemViews[item.id] = view + inserted.insert(item.id) + } + } + + let structureChanged = previousIds != newItems.map(\.id) + layoutTabs(animated: structureChanged && !previousIds.isEmpty, inserted: inserted) + + let selection = newItems.first(where: \.isSelected)?.id + if let selection, selection != previousSelection || structureChanged { + reveal(selection, animated: true) + } + } + + private func reconcileReorder(keeping ids: [UUID]) { + guard var live = reorder else { return } + guard live.removingClosedTabs(keeping: ids), Set(live.order) == Set(ids) else { + reorder = nil + return + } + reorder = live + } + + // The order the strip draws: nil marks the slot a tab arriving from another window will take. + private var slots: [UUID?] { + var ids: [UUID?] = reorder?.order ?? items.map(\.id) + if dragHasLeftStrip, let dragged = reorder?.draggedId { + ids.removeAll { $0 == dragged } + } + if let incomingIndex { + ids.insert(nil, at: min(incomingIndex, ids.count)) + } + return ids + } + + // MARK: - Layout + + override internal func layout() { + super.layout() + let metrics = EditorTabStripLayout.self + let buttonX = bounds.width - metrics.stripInset - metrics.newTabButtonSize + newTabButton.frame = CGRect(x: buttonX, y: 0, width: metrics.newTabButtonSize, height: metrics.trackHeight) + let trackFrame = CGRect( + x: metrics.stripInset, + y: 0, + width: max(buttonX - metrics.trackSpacing - metrics.stripInset, 0), + height: metrics.trackHeight + ) + track.frame = trackFrame + scrollView.frame = trackFrame.insetBy(dx: metrics.trackPadding, dy: metrics.trackPadding) + layoutTabs(animated: false) + refreshHoverArea() + + // The band is built collapsed, so the selection can only be revealed once it has a width. + guard scrollView.bounds.width != laidOutWidth else { return } + laidOutWidth = scrollView.bounds.width + if let selection = items.first(where: \.isSelected)?.id { + reveal(selection, animated: false) + } + } + + private func layoutTabs(animated: Bool, inserted: Set = []) { + let slots = slots + run = EditorTabRunLayout(viewportWidth: scrollView.bounds.width, count: slots.count) + document.setFrameSize(NSSize( + width: max(run.contentWidth, scrollView.bounds.width), + height: EditorTabStripLayout.tabHeight + )) + let frames = run.frames(offset: scrollView.contentView.bounds.minX) + let shouldAnimate = animated && canAnimate + + let place = { + for (index, slot) in slots.enumerated() { + guard let id = slot, let view = self.itemViews[id] else { continue } + if shouldAnimate, inserted.contains(id) { + view.frame = CGRect(x: frames[index].minX, y: 0, width: 0, height: frames[index].height) + } + if shouldAnimate { + view.animator().frame = frames[index] + } else { + view.frame = frames[index] + } + } + } + updateSeparators() + + guard shouldAnimate else { + place() + return + } + NSAnimationContext.runAnimationGroup { context in + context.duration = EditorTabStripLayout.motionDuration + context.timingFunction = EditorTabStripLayout.motionTiming + place() + } + } + + private func updateSeparators() { + let ids = slots.compactMap { $0 } + let selectedId = items.first(where: \.isSelected)?.id + for (index, id) in ids.enumerated() { + itemViews[id]?.showsLeadingSeparator = EditorTabStripLayout.showsSeparator( + before: index, + tabIds: ids, + selectedId: selectedId, + hoveredId: hoveredId, + isReordering: reorder != nil + ) + } + } + + @objc + private func clipBoundsChanged() { + guard run.maximumOffset > 0 else { return } + layoutTabs(animated: false) + updateHover() + } + + internal func reveal(_ id: UUID, animated: Bool) { + guard scrollView.bounds.width > 0, let index = slots.firstIndex(of: id) else { return } + let clip = scrollView.contentView + let target = run.revealOffset(forTabAt: index, from: clip.bounds.minX) + guard target != clip.bounds.minX else { return } + let origin = NSPoint(x: target, y: clip.bounds.minY) + if animated, canAnimate { + NSAnimationContext.runAnimationGroup { context in + context.duration = EditorTabStripLayout.motionDuration + context.timingFunction = EditorTabStripLayout.motionTiming + clip.animator().setBoundsOrigin(origin) + } + } else { + clip.setBoundsOrigin(origin) + } + scrollView.reflectScrolledClipView(clip) + } + + // MARK: - Activation + + internal func activate(_ id: UUID, click: EditorTabClick?) { + guard let commands else { return } + let activation = EditorTabActivationResolver.resolve( + click: click, + tabId: id, + lastActivatedTabId: lastActivatedId + ) + lastActivatedId = id + commands.activate(id) + if activation == .selectAndKeep { + commands.keepOpen(id) + } + } + + @objc + private func newTabClicked() { + commands?.newTab() + } + + internal func moveFocus(from view: EditorTabItemView, by offset: Int) { + guard let index = items.firstIndex(where: { $0.id == view.item.id }) else { return } + let target = index + offset + guard items.indices.contains(target), let next = itemViews[items[target].id] else { return } + reveal(next.item.id, animated: true) + window?.makeFirstResponder(next) + } + + internal func itemView(for id: UUID) -> EditorTabItemView? { + itemViews[id] + } + + // MARK: - Hover and window state + + private func refreshHoverArea() { + if let hoverArea { removeTrackingArea(hoverArea) } + let area = NSTrackingArea( + rect: scrollView.frame, + options: [.activeInKeyWindow, .mouseEnteredAndExited, .mouseMoved], + owner: self + ) + addTrackingArea(area) + hoverArea = area + } + + override internal func mouseEntered(with event: NSEvent) { updateHover() } + override internal func mouseMoved(with event: NSEvent) { updateHover() } + override internal func mouseExited(with event: NSEvent) { setHovered(nil) } + + // The run moves under a pointer that did not, so scrolling has to ask again as well. + private func updateHover() { + guard let window, window.isKeyWindow, reorder == nil else { + setHovered(nil) + return + } + let point = document.convert(window.mouseLocationOutsideOfEventStream, from: nil) + let inside = scrollView.contentView.convert(window.mouseLocationOutsideOfEventStream, from: nil) + guard scrollView.contentView.bounds.contains(inside) else { + setHovered(nil) + return + } + setHovered(itemViews.values.first { $0.frame.contains(point) }?.item.id) + } + + private func setHovered(_ id: UUID?) { + guard hoveredId != id else { return } + if let hoveredId { itemViews[hoveredId]?.isHovered = false } + hoveredId = id + if let id { itemViews[id]?.isHovered = true } + updateSeparators() + } + + private var isWindowKey: Bool { + window?.isKeyWindow ?? false + } + + override internal func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + windowSubscriptions.removeAll() + updateWindowState() + guard let window else { return } + for name in [NSWindow.didBecomeKeyNotification, NSWindow.didResignKeyNotification] { + NotificationCenter.default.publisher(for: name, object: window) + .receive(on: RunLoop.main) + .sink { [weak self] _ in + MainActor.assumeIsolated { self?.updateWindowState() } + } + .store(in: &windowSubscriptions) + } + } + + private func updateWindowState() { + let isKey = isWindowKey + itemViews.values.forEach { $0.isWindowActive = isKey } + newTabButton.contentTintColor = isKey ? .secondaryLabelColor : .tertiaryLabelColor + if !isKey { setHovered(nil) } + } + + override internal func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + track.needsDisplay = true + itemViews.values.forEach { $0.needsDisplay = true } + } + + // MARK: - Dragging out + + internal func beginDrag(of view: EditorTabItemView, with event: NSEvent) { + guard let commands else { return } + let id = view.item.id + setHovered(nil) + + let pasteboardItem = NSPasteboardItem() + pasteboardItem.setString(id.uuidString, forType: .editorTab) + let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem) + draggingItem.setDraggingFrame(view.bounds, contents: view.dragImage()) + + let session = view.beginDraggingSession(with: [draggingItem], event: event, source: view) + session.draggingFormation = .none + // A tab that will open its own window where it lands has nowhere to slide back to. + session.animatesToStartingPositionsOnCancelOrFail = !commands.canTearOff(id) + + let pinned = Set(items.filter(\.isPinned).map(\.id)) + reorder = EditorTabReorder(draggedId: id, order: items.map(\.id), pinnedIds: pinned) + dragHasLeftStrip = false + view.alphaValue = 0 + layoutTabs(animated: false) + watchForDragCancel() + } + + // A drag session reports Escape and a release on empty space the same way, so the key is latched as it arrives. + private func watchForDragCancel() { + dragWasCancelled = false + dragCancelMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in + let isEscape = event.keyCode == KeyCode.escape.rawValue + MainActor.assumeIsolated { + if isEscape { self?.dragWasCancelled = true } + } + return event + } + } + + private func stopWatchingForDragCancel() { + guard let dragCancelMonitor else { return } + NSEvent.removeMonitor(dragCancelMonitor) + self.dragCancelMonitor = nil + } + + internal func dragDidEnd(of view: EditorTabItemView, at screenPoint: NSPoint, operation: NSDragOperation) { + let id = view.item.id + let wasCancelled = dragWasCancelled || NSEvent.pressedMouseButtons & 1 != 0 + stopWatchingForDragCancel() + reorder = nil + dragHasLeftStrip = false + view.alphaValue = 1 + layoutTabs(animated: true) + + guard let commands, EditorTabDragEnding.opensNewWindow( + operation: operation, + wasCancelled: wasCancelled, + isOverTabStrip: commands.isOverTabStrip(screenPoint), + canTearOff: commands.canTearOff(id) + ) else { return } + commands.tearOff(id, screenPoint) + } + + // MARK: - Dragging in + + override internal func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { + draggingUpdated(sender) + } + + override internal func wantsPeriodicDraggingUpdates() -> Bool { true } + + override internal func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { + guard let source = sender.draggingSource as? EditorTabItemView else { return [] } + let isOwnTab = source.strip === self + guard isOwnTab || accepts(source) else { return [] } + autoscroll(towards: sender.draggingLocation) + let location = run.slotLocation( + ofContentX: document.convert(sender.draggingLocation, from: nil).x, + offset: scrollView.contentView.bounds.minX + ) + if isOwnTab { + updateReorder(toLocation: location) + } else { + updateIncoming(toLocation: location) + } + return .move + } + + override internal func draggingExited(_ sender: NSDraggingInfo?) { + guard let source = sender?.draggingSource as? EditorTabItemView else { return } + if source.strip === self { + dragHasLeftStrip = true + } else { + incomingIndex = nil + } + layoutTabs(animated: true) + } + + override internal func performDragOperation(_ sender: NSDraggingInfo) -> Bool { + guard let source = sender.draggingSource as? EditorTabItemView, let commands else { return false } + if source.strip === self { + guard let reorder, reorder.movedFromOriginal, let destination = reorder.destinationIndex else { + return true + } + // The manager publishes a turn later, and the tab must not slide back in the meantime. + let byId = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) + items = reorder.order.compactMap { byId[$0] } + commands.moveTab(reorder.draggedId, destination) + return true + } + defer { + incomingIndex = nil + layoutTabs(animated: true) + } + guard accepts(source), let index = incomingIndex else { return false } + return commands.receiveTab(source.item.id, index) + } + + private func accepts(_ source: EditorTabItemView) -> Bool { + guard let commands, let sourceCommands = source.strip?.commands else { return false } + return sourceCommands.connectionId == commands.connectionId && sourceCommands.canTearOff(source.item.id) + } + + private func updateReorder(toLocation location: CGFloat) { + guard var live = reorder, let current = live.destinationIndex else { return } + let wasOutside = dragHasLeftStrip + dragHasLeftStrip = false + if let destination = EditorTabReorderResolver.settledDestination( + forLocation: location, + tabWidth: run.tabWidth, + currentIndex: current, + count: live.order.count + ) { + live.move(to: destination) + } + guard live != reorder || wasOutside else { return } + reorder = live + layoutTabs(animated: true) + } + + private func updateIncoming(toLocation location: CGFloat) { + guard run.tabWidth > 0 else { return } + // Before the gap opens the pointer picks the nearest boundary, after it the slot it is over. + let index = incomingIndex == nil + ? min(Int((location / run.tabWidth).rounded()), items.count) + : EditorTabReorderResolver.destination(forLocation: location, tabWidth: run.tabWidth, count: run.count) + guard index != incomingIndex else { return } + incomingIndex = index + layoutTabs(animated: true) + } + + private func autoscroll(towards windowPoint: NSPoint) { + guard run.maximumOffset > 0 else { return } + let clip = scrollView.contentView + let point = clip.convert(windowPoint, from: nil) + var offset = clip.bounds.minX + if point.x < clip.bounds.minX + EditorTabStripLayout.autoscrollMargin { + offset -= EditorTabStripLayout.autoscrollStep + } else if point.x > clip.bounds.maxX - EditorTabStripLayout.autoscrollMargin { + offset += EditorTabStripLayout.autoscrollStep + } + let target = run.clamped(offset: offset) + guard target != clip.bounds.minX else { return } + clip.setBoundsOrigin(NSPoint(x: target, y: clip.bounds.minY)) + scrollView.reflectScrolledClipView(clip) + } + + // MARK: - Accessibility + + override internal func isAccessibilityElement() -> Bool { true } + override internal func accessibilityRole() -> NSAccessibility.Role? { .tabGroup } + override internal func accessibilityLabel() -> String? { String(localized: "Editor Tabs") } + + override internal func accessibilityTabs() -> [Any]? { + items.compactMap { itemViews[$0.id] } + } +} + +internal enum EditorTabDragEnding { + internal static func opensNewWindow( + operation: NSDragOperation, + wasCancelled: Bool, + isOverTabStrip: Bool, + canTearOff: Bool + ) -> Bool { + operation.isEmpty && !wasCancelled && !isOverTabStrip && canTearOff + } +} + +internal final class EditorTabDocumentView: NSView { + override internal var isFlipped: Bool { true } + override internal var mouseDownCanMoveWindow: Bool { false } +} + +internal final class EditorTabScrollView: NSScrollView { + override internal var mouseDownCanMoveWindow: Bool { false } + + // A wheel mouse only reports the vertical axis, and this view only scrolls along the other one. + override internal func scrollWheel(with event: NSEvent) { + guard event.phase.isEmpty, event.momentumPhase.isEmpty, + abs(event.scrollingDeltaY) > abs(event.scrollingDeltaX) + else { + super.scrollWheel(with: event) + return + } + let clip = contentView + let maximum = max((documentView?.frame.width ?? 0) - clip.bounds.width, 0) + let target = min(max(clip.bounds.minX - event.scrollingDeltaY, 0), maximum) + clip.setBoundsOrigin(NSPoint(x: target, y: clip.bounds.minY)) + reflectScrolledClipView(clip) + } +} + +@MainActor +internal final class EditorTabTrackView: NSView { + override internal var isFlipped: Bool { true } + override internal var mouseDownCanMoveWindow: Bool { false } + + override internal func draw(_ dirtyRect: NSRect) { + let radius = bounds.height / 2 + let highContrast = NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast + let themed = EditorTabStripPalette.isOverThemedBackdrop(highContrast: highContrast) + EditorTabStripPalette.trackColor(overThemedBackdrop: themed).setFill() + NSBezierPath(roundedRect: bounds, xRadius: radius, yRadius: radius).fill() + + let hairline = EditorTabStripLayout.hairline + let edge = NSBezierPath( + roundedRect: bounds.insetBy(dx: hairline / 2, dy: hairline / 2), + xRadius: radius, + yRadius: radius + ) + edge.lineWidth = hairline + EditorTabStripPalette.trackEdgeColor.setStroke() + edge.stroke() + } +} diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index dd574ad3db..4647f9378d 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -51,13 +51,6 @@ struct GeneralSettingsView: View { Section("Tabs") { Toggle("Enable preview tabs", isOn: $tabSettings.enablePreviewTabs) .help("Single-clicking a table opens a temporary tab that gets replaced on next click.") - - Picker("When tabs stop fitting:", selection: $tabSettings.overflow) { - ForEach(EditorTabStripOverflow.allCases, id: \.self) { style in - Text(style.displayName).tag(style) - } - } - .help("Scrolling keeps one row of tabs, the way every macOS tab bar does. Rows wraps them so nothing is off screen.") } Section("Sidebar") { diff --git a/apple/TableProTests/Helpers/EditorTabFixtures.swift b/apple/TableProTests/Helpers/EditorTabFixtures.swift new file mode 100644 index 0000000000..a9000e10ca --- /dev/null +++ b/apple/TableProTests/Helpers/EditorTabFixtures.swift @@ -0,0 +1,89 @@ +// +// EditorTabFixtures.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro + +@MainActor +internal final class EditorTabCommandRecorder { + var activated: [UUID] = [] + var kept: [UUID] = [] + var closed: [UUID] = [] + var movedToConnection: [UUID] = [] + var pinned: [(UUID, Bool)] = [] + var tornOff: [(UUID, NSPoint?)] = [] + var newTabCount = 0 +} + +extension EditorTabCommands { + @MainActor + internal static func stub( + recorder: EditorTabCommandRecorder = EditorTabCommandRecorder(), + connectionId: UUID = UUID(), + isPinned: Bool = false, + canCloseOthers: Bool = true, + canCloseAll: Bool = true, + canTearOff: Bool = true, + offersMoveToConnection: Bool = false, + canMoveToConnection: Bool = false + ) -> EditorTabCommands { + EditorTabCommands( + connectionId: connectionId, + activate: { recorder.activated.append($0) }, + newTab: { recorder.newTabCount += 1 }, + keepOpen: { recorder.kept.append($0) }, + canKeepOpen: { _ in false }, + isPinned: { _ in isPinned }, + setPinned: { recorder.pinned.append(($0, $1)) }, + close: { recorder.closed.append($0) }, + closeOthers: { _ in }, + canCloseOthers: { _ in canCloseOthers }, + closeAll: {}, + canCloseAll: { canCloseAll }, + moveTab: { _, _ in }, + canMove: { _, _ in true }, + moveBy: { _, _ in }, + tearOff: { recorder.tornOff.append(($0, $1)) }, + canTearOff: { _ in canTearOff }, + receiveTab: { _, _ in true }, + isOverTabStrip: { _ in false }, + moveToConnection: { recorder.movedToConnection.append($0) }, + offersMoveToConnection: { _ in offersMoveToConnection }, + canMoveToConnection: { _ in canMoveToConnection } + ) + } +} + +extension EditorTabItem { + internal static func sample( + id: UUID = UUID(), + title: String = "Album", + isSelected: Bool = false, + isPinned: Bool = false, + isPreview: Bool = false, + status: EditorTabStatus = .idle, + position: Int = 1, + count: Int = 1 + ) -> EditorTabItem { + EditorTabItem( + id: id, + title: title, + tooltip: title, + isSelected: isSelected, + isPinned: isPinned, + isPreview: isPreview, + status: status, + position: position, + count: count + ) + } + + internal static func samples(titles: [String], selected: Int? = 0) -> [EditorTabItem] { + titles.enumerated().map { index, title in + sample(title: title, isSelected: index == selected, position: index + 1, count: titles.count) + } + } +} diff --git a/apple/TableProTests/Views/Main/EditorTabContextMenuBuilderTests.swift b/apple/TableProTests/Views/Main/EditorTabContextMenuBuilderTests.swift index fa8439b2ef..3ade2158bf 100644 --- a/apple/TableProTests/Views/Main/EditorTabContextMenuBuilderTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabContextMenuBuilderTests.swift @@ -9,49 +9,45 @@ import Testing @MainActor struct EditorTabContextMenuBuilderTests { - private final class Recorder { - var moved: [UUID] = [] - var pinned: [(UUID, Bool)] = [] - } - private static let moveTitle = String(localized: "Move Tab to Connection…") private static let newWindowTitle = String(localized: "Move Tab to New Window") private func commands( offers: Bool, can: Bool, - recorder: Recorder = Recorder(), + recorder: EditorTabCommandRecorder = EditorTabCommandRecorder(), pinned: Bool = false, canCloseOthers: Bool = true, canCloseAll: Bool = true ) -> EditorTabCommands { - EditorTabCommands( - activate: { _ in }, - keepOpen: { _ in }, - canKeepOpen: { _ in false }, - isPinned: { _ in pinned }, - setPinned: { recorder.pinned.append(($0, $1)) }, - close: { _ in }, - closeOthers: { _ in }, - canCloseOthers: { _ in canCloseOthers }, - closeAll: {}, - canCloseAll: { canCloseAll }, - moveTab: { _, _ in }, - canMove: { _, _ in true }, - moveBy: { _, _ in }, - tearOff: { _ in }, - canTearOff: { _ in true }, - moveToConnection: { recorder.moved.append($0) }, - offersMoveToConnection: { _ in offers }, - canMoveToConnection: { _ in can }, - tooltip: { _ in "" } + .stub( + recorder: recorder, + isPinned: pinned, + canCloseOthers: canCloseOthers, + canCloseAll: canCloseAll, + offersMoveToConnection: offers, + canMoveToConnection: can ) } + @Test("Move Tab to New Window from the menu names no drop point") + func menuTearOffHasNoDropPoint() throws { + let tabId = UUID() + let recorder = EditorTabCommandRecorder() + let menu = EditorTabContextMenuBuilder.menu(for: tabId, commands: commands(offers: false, can: false, recorder: recorder)) + let item = try #require(menu.items.first { $0.title == Self.newWindowTitle }) + + (item.target as? ClosureMenuTarget)?.fire() + + #expect(recorder.tornOff.count == 1) + #expect(recorder.tornOff.first?.0 == tabId) + #expect(recorder.tornOff.first?.1 == nil) + } + @Test("A movable query tab offers Move Tab to Connection right after Move Tab to New Window") func queryTabOffersTheMove() throws { let tabId = UUID() - let recorder = Recorder() + let recorder = EditorTabCommandRecorder() let menu = EditorTabContextMenuBuilder.menu(for: tabId, commands: commands(offers: true, can: true, recorder: recorder)) let titles = menu.items.map(\.title) @@ -62,7 +58,7 @@ struct EditorTabContextMenuBuilderTests { let item = menu.items[move] #expect(item.isEnabled) (item.target as? ClosureMenuTarget)?.fire() - #expect(recorder.moved == [tabId]) + #expect(recorder.movedToConnection == [tabId]) } @Test("A query tab that cannot move now shows the item dimmed") @@ -86,7 +82,7 @@ struct EditorTabContextMenuBuilderTests { @Test("An unpinned tab offers Pin Tab right after Keep Open, and choosing it pins that tab") func unpinnedTabOffersPin() throws { let tabId = UUID() - let recorder = Recorder() + let recorder = EditorTabCommandRecorder() let menu = EditorTabContextMenuBuilder.menu( for: tabId, commands: commands(offers: false, can: false, recorder: recorder) @@ -105,7 +101,7 @@ struct EditorTabContextMenuBuilderTests { @Test("A pinned tab offers Unpin Tab, and choosing it unpins") func pinnedTabOffersUnpin() throws { - let recorder = Recorder() + let recorder = EditorTabCommandRecorder() let menu = EditorTabContextMenuBuilder.menu( for: UUID(), commands: commands(offers: false, can: false, recorder: recorder, pinned: true) diff --git a/apple/TableProTests/Views/Main/EditorTabMiddleClickTests.swift b/apple/TableProTests/Views/Main/EditorTabMiddleClickTests.swift index c4c01087e4..9f93661672 100644 --- a/apple/TableProTests/Views/Main/EditorTabMiddleClickTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabMiddleClickTests.swift @@ -10,212 +10,75 @@ import Testing @testable import TablePro -/// Middle-clicking a tab closes it, resolved against the same run layout the pointer already -/// hit-tests every other gesture with. -/// -/// The gesture is driven through the view's own view-point entry points rather than through -/// synthesized events, because `NSEvent.mouseEvent(with:…)` cannot carry a button number: -/// measured, it reports 0 for `.otherMouseDown` and `.otherMouseUp` whatever else it is given, and -/// the only factory that reports 2 is `NSEvent(cgEvent:)`, whose location is a screen point. The -/// button half of the contract is covered on its own below. +// `NSEvent.mouseEvent(with:…)` cannot carry a button number, so the gesture is driven through the view's entry points. @MainActor struct EditorTabMiddleClickTests { - /// Chosen so the track measures the 604pt the strip's other tests use: the view gives up - /// `stripInset` at the leading edge and the new-tab button plus its spacing at the trailing. - private static let viewWidth: CGFloat = 652 - private static let tabCount = 3 - - private final class Recorder { - var closed: [UUID] = [] + private func makeTab() -> (EditorTabItemView, EditorTabStripView, EditorTabCommandRecorder) { + let recorder = EditorTabCommandRecorder() + let strip = EditorTabStripView(frame: NSRect(x: 0, y: 0, width: 652, height: EditorTabStripLayout.bandHeight)) + strip.commands = .stub(recorder: recorder) + let item = EditorTabItem.sample() + strip.apply([item]) + strip.layoutSubtreeIfNeeded() + let view = strip.itemView(for: item.id) ?? EditorTabItemView(item: item) + return (view, strip, recorder) } - private func makeView( - tabCount: Int = Self.tabCount, - recorder: Recorder = Recorder() - ) -> (EditorTabInteractionView, [UUID], Recorder) { - let ids = (0 ..< tabCount).map { _ in UUID() } - let interaction = EditorTabStripInteraction() - interaction.commands = EditorTabCommands( - activate: { _ in }, - keepOpen: { _ in }, - canKeepOpen: { _ in false }, - isPinned: { _ in false }, - setPinned: { _, _ in }, - close: { recorder.closed.append($0) }, - closeOthers: { _ in }, - canCloseOthers: { _ in true }, - closeAll: {}, - canCloseAll: { true }, - moveTab: { _, _ in }, - canMove: { _, _ in true }, - moveBy: { _, _ in }, - tearOff: { _ in }, - canTearOff: { _ in false }, - moveToConnection: { _ in }, - offersMoveToConnection: { _ in false }, - canMoveToConnection: { _ in false }, - tooltip: { _ in "" } - ) - interaction.dropClosedTabs(keeping: ids) - - let view = EditorTabInteractionView(interaction: interaction) - view.frame = CGRect(x: 0, y: 0, width: Self.viewWidth, height: EditorTabStripLayout.bandHeight) - view.rebuildRun() - return (view, ids, recorder) - } - - /// The view point that lands on a given point of the run's content space, which is where the - /// placements live. The two differ by the track's insets and by however far the run has - /// scrolled, so a test that hardcodes the insets alone is only right at offset zero. - private func viewPoint(ofContent point: CGPoint, in view: EditorTabInteractionView) -> CGPoint { - CGPoint( - x: point.x - view.interaction.contentOffset - + EditorTabStripLayout.stripInset + EditorTabStripLayout.trackPadding, - y: point.y + EditorTabStripLayout.trackPadding - ) - } - - /// The centre of a tab, in the view's own flipped coordinates, built from the run the view just - /// measured so the test and the code agree by construction rather than by arithmetic. - private func centre(ofTabAt index: Int, in view: EditorTabInteractionView) throws -> CGPoint { - let placement = try #require(view.interaction.run.placement(at: index)) - return viewPoint(ofContent: CGPoint(x: placement.frame.midX, y: placement.frame.midY), in: view) + private func centre(of view: NSView) -> NSPoint { + NSPoint(x: view.bounds.midX, y: view.bounds.midY) } @Test("A middle-click on a tab closes it") - func middleClickClosesTheTab() throws { - let (view, ids, recorder) = makeView() - let point = try centre(ofTabAt: 1, in: view) + func middleClickClosesTheTab() { + let (view, strip, recorder) = makeTab() - view.beginMiddleClick(atViewPoint: point) - view.endMiddleClick(atViewPoint: point) + view.beginMiddleClick() + view.endMiddleClick(atViewPoint: centre(of: view)) - #expect(recorder.closed == [ids[1]]) + #expect(recorder.closed == [view.item.id]) + withExtendedLifetime(strip) {} } - /// The tab's own close button is drawn inside the tab, so a middle-click over it is still a - /// middle-click on that tab and must not take the left button's path. - @Test("A middle-click over the close button closes the same tab") - func middleClickOverTheCloseButtonClosesTheTab() throws { - let (view, ids, recorder) = makeView() - let placement = try #require(view.interaction.run.placement(at: 2)) - let button = EditorTabRunLayoutBuilder.closeButtonRect(in: placement.frame) - let point = CGPoint( - x: button.midX + EditorTabStripLayout.stripInset + EditorTabStripLayout.trackPadding, - y: button.midY + EditorTabStripLayout.trackPadding - ) + @Test("Releasing off the tab closes nothing") + func releasingOffTheTabClosesNothing() { + let (view, strip, recorder) = makeTab() - view.beginMiddleClick(atViewPoint: point) - view.endMiddleClick(atViewPoint: point) - - #expect(recorder.closed == [ids[2]]) - } - - /// The same contract the close button keeps: the release has to land where the press did, so a - /// user who changes their mind can slide off and let go. - @Test("Releasing on another tab closes nothing") - func releasingOnAnotherTabClosesNothing() throws { - let (view, _, recorder) = makeView() - - view.beginMiddleClick(atViewPoint: try centre(ofTabAt: 0, in: view)) - view.endMiddleClick(atViewPoint: try centre(ofTabAt: 2, in: view)) + view.beginMiddleClick() + view.endMiddleClick(atViewPoint: NSPoint(x: view.bounds.maxX + 40, y: view.bounds.midY)) #expect(recorder.closed.isEmpty) + withExtendedLifetime(strip) {} } - @Test("Releasing off the strip closes nothing") - func releasingOffTheStripClosesNothing() throws { - let (view, _, recorder) = makeView() + @Test("A release without a press closes nothing") + func releaseWithoutAPressClosesNothing() { + let (view, strip, recorder) = makeTab() - view.beginMiddleClick(atViewPoint: try centre(ofTabAt: 0, in: view)) - view.endMiddleClick(atViewPoint: CGPoint(x: Self.viewWidth - 4, y: 200)) + view.endMiddleClick(atViewPoint: centre(of: view)) #expect(recorder.closed.isEmpty) + withExtendedLifetime(strip) {} } - @Test("A press that missed every tab closes nothing") - func pressOffATabClosesNothing() throws { - let (view, _, recorder) = makeView() - - view.beginMiddleClick(atViewPoint: CGPoint(x: 2, y: 2)) - view.endMiddleClick(atViewPoint: try centre(ofTabAt: 1, in: view)) - - #expect(recorder.closed.isEmpty) - } - - /// The press is spent on release. Without that the strip would keep closing the same tab every - /// time the button came up, which is what a mouse with a sticky wheel button would produce. @Test("A second release without a second press closes nothing") - func secondReleaseClosesNothing() throws { - let (view, ids, recorder) = makeView() - let point = try centre(ofTabAt: 1, in: view) - - view.beginMiddleClick(atViewPoint: point) - view.endMiddleClick(atViewPoint: point) - view.endMiddleClick(atViewPoint: point) - - #expect(recorder.closed == [ids[1]]) - } - - /// A tab that went while the button was held leaves a different id in its slot, so the gesture - /// finds nothing rather than closing whichever tab slid under the pointer. - @Test("A tab closed under the pointer takes nothing with it") - func tabClosedUnderThePointerTakesNothingWithIt() throws { - let (view, ids, recorder) = makeView() - let point = try centre(ofTabAt: 2, in: view) - - view.beginMiddleClick(atViewPoint: point) - view.interaction.dropClosedTabs(keeping: [ids[0], ids[1]]) - view.rebuildRun() - view.endMiddleClick(atViewPoint: point) - - #expect(recorder.closed.isEmpty) - } - - /// The run scrolls under a fixed viewport, so a point outside the viewport still translates - /// into content coordinates, and those land on whichever tab the offset happens to have put - /// there. The track's own two points of padding are the nearest such point: pressing them on a - /// scrolled strip resolved to a tab clipped off the leading edge and closed it. - @Test("A press in the track padding of a scrolled strip closes nothing") - func pressInTheTrackPaddingClosesNothing() throws { - let (view, _, recorder) = makeView(tabCount: 12) - view.interaction.scroll(by: 10_000) - #expect(view.interaction.contentOffset > 0) - let padding = CGPoint(x: EditorTabStripLayout.stripInset + 1, y: EditorTabStripLayout.trackPadding + 12) - - view.beginMiddleClick(atViewPoint: padding) - view.endMiddleClick(atViewPoint: padding) - - #expect(recorder.closed.isEmpty) - } + func secondReleaseClosesNothing() { + let (view, strip, recorder) = makeTab() - /// AppKit hands the release to whichever view took the press however far the pointer has - /// travelled, so the release arrives here with a location this view does not own. A tab - /// straddling the leading edge is the case where the press and the release resolve to the same - /// tab across that boundary, which is the one a same-tab check alone cannot catch. - @Test("A release in the track padding of a scrolled strip closes nothing") - func releaseInTheTrackPaddingClosesNothing() throws { - let (view, _, recorder) = makeView(tabCount: 12) - view.interaction.scroll(by: 150) - let press = try centre(ofTabAt: 1, in: view) - let padding = CGPoint(x: EditorTabStripLayout.stripInset + 1, y: press.y) + view.beginMiddleClick() + view.endMiddleClick(atViewPoint: centre(of: view)) + view.endMiddleClick(atViewPoint: centre(of: view)) - view.beginMiddleClick(atViewPoint: press) - view.endMiddleClick(atViewPoint: padding) - - #expect(recorder.closed.isEmpty) + #expect(recorder.closed == [view.item.id]) + withExtendedLifetime(strip) {} } - /// The override reads the button before anything else, so the side buttons of a five-button - /// mouse pass straight through to whoever else wants them. @Test("A release from another button closes nothing") func releaseFromAnotherButtonClosesNothing() throws { - let (view, _, recorder) = makeView() - let point = try centre(ofTabAt: 1, in: view) + let (view, strip, recorder) = makeTab() let event = try #require( NSEvent.mouseEvent( with: .otherMouseUp, - location: point, + location: centre(of: view), modifierFlags: [], timestamp: 0, windowNumber: 0, @@ -226,16 +89,16 @@ struct EditorTabMiddleClickTests { ) ) - view.beginMiddleClick(atViewPoint: point) + view.beginMiddleClick() view.otherMouseUp(with: event) #expect(event.isMiddleButton == false) #expect(recorder.closed.isEmpty) + withExtendedLifetime(strip) {} } } -/// `buttonNumber` is the only thing that tells the wheel button from the side buttons, and -/// `NSEvent(cgEvent:)` is the one factory that can carry it into a test. +// `NSEvent(cgEvent:)` is the one factory that can carry a button number into a test. struct NSEventMouseButtonTests { private func press(_ button: CGMouseButton) throws -> NSEvent { let cgEvent = try #require( diff --git a/apple/TableProTests/Views/Main/EditorTabRunLayoutTests.swift b/apple/TableProTests/Views/Main/EditorTabRunLayoutTests.swift index 414f92b2b1..f351704252 100644 --- a/apple/TableProTests/Views/Main/EditorTabRunLayoutTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabRunLayoutTests.swift @@ -5,128 +5,148 @@ import CoreGraphics import Foundation -import Testing - @testable import TablePro +import Testing struct EditorTabRunLayoutTests { - private static let trackWidth: CGFloat = 604 + private static let minimum = EditorTabStripLayout.minimumTabWidth - @Test("Tabs that fit share the track in one row") - func fittingTabsShareOneRow() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 3, overflow: .scroll) + @Test("Tabs that fit share the viewport equally and do not scroll") + func tabsThatFitShareTheViewport() { + let run = EditorTabRunLayout(viewportWidth: 1_180, count: 4) - #expect(run.rowCount == 1) - #expect(run.placements.count == 3) - #expect(run.tabWidth == 200) - #expect(run.placements.map(\.frame.minX) == [0, 200, 400]) - #expect(run.placements.allSatisfy { $0.row == 0 }) + #expect(run.tabWidth == 295) + #expect(run.contentWidth == 1_180) + #expect(run.maximumOffset == 0) + #expect(run.frames(offset: 0).map(\.width) == [295, 295, 295, 295]) } - @Test("Scrolling keeps one row and lets the content run past the track") - func scrollingKeepsOneRow() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 12, overflow: .scroll) + @Test("Tabs stop shrinking at the minimum and the content runs past the viewport") + func crowdedTabsScroll() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 10) - #expect(run.rowCount == 1) - #expect(run.tabWidth == EditorTabStripLayout.minimumTabWidth) - #expect(run.contentSize.width == EditorTabStripLayout.minimumTabWidth * 12) - #expect(run.contentSize.width > Self.trackWidth) + #expect(run.tabWidth == Self.minimum) + #expect(run.contentWidth == Self.minimum * 10) + #expect(run.maximumOffset == Self.minimum * 10 - 600) } - /// The whole point of the wrapped run: nothing is off screen, so a tab opened first is still - /// reachable however many followed it. - @Test("Wrapping never runs wider than the track") - func wrappingNeverOverflows() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 12, overflow: .rows) + @Test("An empty run has no frames and nowhere to scroll") + func emptyRun() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 0) - #expect(run.tabsPerRow == 5) - #expect(run.rowCount == 3) - #expect(run.contentSize.width <= Self.trackWidth) - #expect(run.placements.map(\.row) == [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]) + #expect(run.frames(offset: 0).isEmpty) + #expect(run.maximumOffset == 0) } - @Test("A wrapped run stacks its rows by the row stride") - func wrappedRowsStack() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 7, overflow: .rows) - let second = run.placement(at: 5) + @Test("Neighbouring tabs share an edge at every offset", arguments: [0, 137, 480, 1_000] as [CGFloat]) + func tabsLeaveNoGaps(offset: CGFloat) { + let frames = EditorTabRunLayout(viewportWidth: 600, count: 14).frames(offset: offset) - #expect(second?.row == 1) - #expect(second?.frame.minY == EditorTabStripLayout.rowStride) - #expect(second?.frame.minX == 0) + for (leading, trailing) in zip(frames, frames.dropFirst()) { + #expect(leading.maxX == trailing.minX) + } } - /// A narrow window still shows one tab per row rather than dividing by zero. - @Test("A track narrower than one tab keeps a single column") - func narrowTrackKeepsOneColumn() { - let run = EditorTabRunLayoutBuilder.run(forTrack: 40, count: 4, overflow: .rows) + @Test("Every tab stays inside the viewport while the run scrolls", arguments: [0, 137, 480, 1_080] as [CGFloat]) + func tabsStayInsideTheViewport(offset: CGFloat) { + let run = EditorTabRunLayout(viewportWidth: 600, count: 14) + let origin = run.clamped(offset: offset) - #expect(run.tabsPerRow == 1) - #expect(run.rowCount == 4) + for frame in run.frames(offset: offset) { + #expect(frame.minX >= origin - 1) + #expect(frame.maxX <= origin + 600 + 1) + } } - @Test("An empty run is empty rather than a single zero-width tab") - func emptyRun() { - #expect(EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 0, overflow: .scroll) == .empty) - #expect(EditorTabRunLayoutBuilder.run(forTrack: 0, count: 4, overflow: .scroll) == .empty) + @Test("Tabs past the trailing edge narrow as they get further away") + func trailingTabsCollapse() { + let widths = EditorTabRunLayout(viewportWidth: 1_180, count: 20).frames(offset: 0).map(\.width) + + #expect(widths.prefix(6).allSatisfy { $0 == Self.minimum }) + #expect(widths.allSatisfy { $0 <= Self.minimum }) + // Edges land on whole points, so two far tabs can differ by one point either way. + let collapsing = Array(widths.dropFirst(7)) + for (nearer, further) in zip(collapsing, collapsing.dropFirst()) { + #expect(further <= nearer + 1) + } + #expect(widths.last ?? Self.minimum < Self.minimum / 2) } - @Test("A point inside a tab resolves to it, and the gap after a wrapped last row to nothing") - func hitTesting() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 6, overflow: .rows) - - #expect(EditorTabRunLayoutBuilder.index(at: CGPoint(x: 10, y: 10), in: run) == 0) - #expect(EditorTabRunLayoutBuilder.index(at: CGPoint(x: 130, y: 10), in: run) == 1) - #expect( - EditorTabRunLayoutBuilder.index( - at: CGPoint(x: 400, y: EditorTabStripLayout.rowStride + 10), - in: run - ) == nil - ) + @Test("Collapsed tabs fill the viewport up to its edge", arguments: [16, 40, 120]) + func collapsedTabsReachTheEdge(count: Int) { + let run = EditorTabRunLayout(viewportWidth: 1_180, count: count) + + #expect(run.frames(offset: 0).last?.maxX == 1_180) + + let end = run.maximumOffset + #expect(run.frames(offset: end).first?.minX == end) } - @Test("The close button sits in the tab's leading accessory slot") - func closeButtonRect() throws { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 3, overflow: .scroll) - let placement = try #require(run.placement(at: 1)) - let rect = EditorTabRunLayoutBuilder.closeButtonRect(in: placement.frame) + @Test("A point on a collapsed tab resolves to that tab's slot") + func collapsedTabResolvesToItsSlot() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 10) + let frames = run.frames(offset: 0) - #expect(rect.minX == 200 + EditorTabStripLayout.accessoryInset) - #expect(rect.width == EditorTabStripLayout.accessoryWidth) - #expect(rect.midY == EditorTabStripLayout.tabHeight / 2) + for index in frames.indices where frames[index].width > 1 { + let location = run.slotLocation(ofContentX: frames[index].midX, offset: 0) + #expect(Int(location / run.tabWidth) == index, "tab \(index) resolved to \(location)") + } } - /// One row is already the axis the reorder resolves along, so it is passed through untouched. - @Test("A single row projects onto its own x") - func singleRowLinearLocation() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 3, overflow: .scroll) + @Test("Slots match the drawn run where nothing is collapsed") + func uniformRunMapsToItself() { + let run = EditorTabRunLayout(viewportWidth: 1_200, count: 4) - #expect(EditorTabRunLayoutBuilder.linearLocation(of: CGPoint(x: 250, y: 5), in: run) == 250) + #expect(run.slotLocation(ofContentX: 450, offset: 0) == 450) } - /// A wrapped run is projected onto the run it would have been unwrapped, so the reorder keeps - /// one rule with its midpoint hysteresis rather than growing a second one for rows. - @Test("A wrapped row contributes a whole row of tabs to the location") - func wrappedLinearLocation() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 12, overflow: .rows) - let secondRow = CGPoint(x: 30, y: EditorTabStripLayout.rowStride + 5) - - #expect( - EditorTabRunLayoutBuilder.linearLocation(of: secondRow, in: run) - == run.tabWidth * CGFloat(run.tabsPerRow) + 30 - ) + @Test("A point past either end resolves to that end of the run") + func pointsPastTheEndsClamp() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 10) + + #expect(run.slotLocation(ofContentX: -20, offset: 0) == 0) + #expect(run.slotLocation(ofContentX: 5_000, offset: 0) == run.contentWidth) + } + + @Test("The first tab is full width at the start and the last one at the end") + func edgesAreFullWidthAtTheirEnds() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 14) + + #expect(run.frames(offset: 0).first?.width == Self.minimum) + #expect(run.frames(offset: run.maximumOffset).last?.width == Self.minimum) } - /// A drag that leaves the strip above or below still resolves against the nearest row rather - /// than jumping to the start of the run. - @Test("A point above or below the run clamps to the first and last rows") - func clampedRows() { - let run = EditorTabRunLayoutBuilder.run(forTrack: Self.trackWidth, count: 12, overflow: .rows) - let rowWidth = run.tabWidth * CGFloat(run.tabsPerRow) - - #expect(EditorTabRunLayoutBuilder.linearLocation(of: CGPoint(x: 10, y: -200), in: run) == 10) - #expect( - EditorTabRunLayoutBuilder.linearLocation(of: CGPoint(x: 10, y: 5_000), in: run) - == rowWidth * 2 + 10 - ) + @Test("An elastic overscroll lays out as the nearest real offset") + func overscrollClamps() { + let run = EditorTabRunLayout(viewportWidth: 600, count: 14) + + #expect(run.frames(offset: -40) == run.frames(offset: 0)) + #expect(run.frames(offset: run.maximumOffset + 40) == run.frames(offset: run.maximumOffset)) + } + + @Test("Revealing a tab shows it at full width from either side", arguments: [0, 5, 13]) + func revealShowsTheTab(index: Int) { + let run = EditorTabRunLayout(viewportWidth: 800, count: 14) + + for start in [0, run.maximumOffset / 2, run.maximumOffset] { + let offset = run.revealOffset(forTabAt: index, from: start) + #expect(run.frames(offset: offset)[index].width == Self.minimum) + } + } + + @Test("A tab already showing does not move the run") + func revealLeavesAVisibleTabAlone() { + let run = EditorTabRunLayout(viewportWidth: 1_200, count: 14) + let offset = run.maximumOffset / 2 + let index = Int((offset + 600) / run.tabWidth) + + #expect(run.revealOffset(forTabAt: index, from: offset) == offset) + } + + @Test("A run that fits never scrolls to reveal") + func revealOnARunThatFits() { + let run = EditorTabRunLayout(viewportWidth: 1_200, count: 4) + + #expect(run.revealOffset(forTabAt: 3, from: 0) == 0) } } diff --git a/apple/TableProTests/Views/Main/EditorTabStripChromeTests.swift b/apple/TableProTests/Views/Main/EditorTabStripChromeTests.swift index a1ed50c125..9b6de2b61b 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripChromeTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripChromeTests.swift @@ -4,147 +4,61 @@ // import AppKit -import SwiftUI import Testing @testable import TablePro -/// What this suite can and cannot see is decided by Liquid Glass, not by the strip. -/// -/// Glass is composited by the window server rather than drawn into a view's own context, so -/// `cacheDisplay`, `layer.render` and `dataWithPDF` all come back with zero non-transparent pixels -/// for it. Once the glass carries a tint that goes further: the bitmap is empty for the *whole* -/// hosting view, the strip's own titles and close button included, and every measurement below -/// reads exactly zero. Measured, and it is why this suite pins the surface style rather than -/// letting the strip choose. -/// -/// So the strip is rendered here as `.solid`, which is what macOS 14 and 15 draw and what anyone -/// with Increase Contrast or Reduce Transparency on draws at any version. That half had no -/// coverage at all until it shipped a background window with no selected tab. The glass half is -/// checked by comparing the running app against the system's own tab bar, which is where the -/// geometry in `EditorTabStripLayout` came from too. -/// -/// What these tests guard is everything drawn *on* the surface: the titles, the separators and the -/// close button. That is the half that broke twice. A `GlassEffectContainer` raises the glass it -/// holds above the container's other content, so the first two attempts at this strip painted the -/// glass over the selected tab's own title and then over its close button, leaving a tab whose -/// label was dimmer than its neighbours' and which had no visible way to close it. @MainActor struct EditorTabStripChromeTests { private static let width: CGFloat = 600 private static let margin: CGFloat = 20 - private static let tabCount = 3 private static let bandHeight = EditorTabStripLayout.bandHeight - private static var totalHeight: CGFloat { bandHeight + margin * 2 } - /// The row the titles and the close button sit on. - private static var contentRows: [CGFloat] { - let centre = margin + EditorTabStripLayout.trackHeight / 2 - return Array(stride(from: centre - 4, through: centre + 4, by: 1)) - } - + private static var trackRow: CGFloat { margin + EditorTabStripLayout.trackHeight / 2 } + private static var contentRows: [CGFloat] { Array(stride(from: trackRow - 4, through: trackRow + 4, by: 1)) } private static var backdropRows: [CGFloat] { [margin / 2, totalHeight - margin / 2] } - private static var trackWidth: CGFloat { - width - EditorTabStripLayout.stripInset * 2 - - EditorTabStripLayout.newTabButtonSize - EditorTabStripLayout.trackSpacing + private static var viewportWidth: CGFloat { + width - EditorTabStripLayout.stripInset * 2 - EditorTabStripLayout.newTabButtonSize + - EditorTabStripLayout.trackSpacing - EditorTabStripLayout.trackPadding * 2 } - private static var tabWidth: CGFloat { - EditorTabStripLayout.tabWidth(forTrack: trackWidth, count: tabCount) - } + private static var tabWidth: CGFloat { viewportWidth / 3 } private static func tabOrigin(_ index: Int) -> CGFloat { EditorTabStripLayout.stripInset + EditorTabStripLayout.trackPadding + tabWidth * CGFloat(index) } - /// The close button sits `accessoryInset` in from its tab's leading edge and is - /// `accessoryWidth` across. - private static func closeGlyphColumns(ofTabAt index: Int) -> [CGFloat] { - let leading = tabOrigin(index) + EditorTabStripLayout.accessoryInset - return Array(stride(from: leading, to: leading + EditorTabStripLayout.accessoryWidth, by: 1)) - } - - /// Between the close-button box and the title, so the sample lands on the tab's own surface - /// and on no glyph. - private static func surfaceColumns(ofTabAt index: Int) -> [CGFloat] { - let leading = tabOrigin(index) + EditorTabStripLayout.accessoryInset - + EditorTabStripLayout.accessoryWidth + 4 - return [leading] - } + private static func surfaceColumn(ofTabAt index: Int) -> CGFloat { tabOrigin(index) + 14 } - /// The middle of a tab, where its title is centred and no accessory reaches. private static func titleColumns(ofTabAt index: Int) -> [CGFloat] { let centre = tabOrigin(index) + tabWidth / 2 - return Array(stride(from: centre - 40, through: centre + 40, by: 2)) - } - - private func makeHost( - appearance: NSAppearance.Name, - activeState: ControlActiveState = .inactive - ) -> NSView { - let manager = QueryTabManager() - manager.tabs = ["Album", "Artist", "Customer"].map { QueryTab(title: $0) } - manager.selectedTabId = manager.tabs.first?.id - - /// AppKit measures the run in the app, so the harness seeds it: this rasterises the strip - /// without the view that owns the pointer, and the tabs have to know where they are. - let interaction = EditorTabStripInteraction() - interaction.dropClosedTabs(keeping: manager.tabs.map(\.id)) - interaction.updateRun(trackWidth: Self.trackWidth, count: manager.tabs.count) - - let strip = EditorTabStrip( - tabManager: manager, - interaction: interaction, - containerTarget: nil, - execution: TabExecutionObservation(owner: nil), - onNewTab: {}, - surfaceStyle: .solid - ) - - let content = ZStack { - Color(nsColor: .windowBackgroundColor) - VStack(spacing: 0) { - Color.clear.frame(height: Self.margin) - strip.frame(height: Self.bandHeight) - Color.clear.frame(height: Self.margin) - } - } - .frame(width: Self.width, height: Self.totalHeight) - .environment(\.controlActiveState, activeState) - - let host = NSHostingView(rootView: AnyView(content)) - host.frame = NSRect(x: 0, y: 0, width: Self.width, height: Self.totalHeight) - - let window = NSWindow( - contentRect: host.frame, - styleMask: [.titled], - backing: .buffered, - defer: false - ) + return Array(stride(from: centre - 30, through: centre + 30, by: 2)) + } + + private func makeHost(appearance: NSAppearance.Name, isActive: Bool = false) -> (NSView, EditorTabStripView) { + let frame = NSRect(x: 0, y: 0, width: Self.width, height: Self.totalHeight) + let host = NSView(frame: frame) + let strip = EditorTabStripView(frame: NSRect( + x: 0, + y: Self.margin, + width: Self.width, + height: Self.bandHeight + )) + host.addSubview(strip) + + let window = NSWindow(contentRect: frame, styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false window.appearance = NSAppearance(named: appearance) window.contentView = host - settle(window) - return host - } - /// Laying the hosting view's own subtree out is enough here. Spinning the run loop instead - /// would let another suite's queued main-actor work run in the middle of this one. - private func settle(_ window: NSWindow) { + strip.commands = .stub() + strip.apply(EditorTabItem.samples(titles: ["Album", "Artist", "Customer"])) + strip.items.forEach { strip.itemView(for: $0.id)?.isWindowActive = isActive } window.layoutIfNeeded() - window.contentView?.layoutSubtreeIfNeeded() - } - - /// The colour the band is supposed to sit on, resolved independently of the bitmap. Every - /// comparison below is anchored to it so that an empty or all-black rasterisation cannot - /// satisfy the assertions by agreeing with itself. - private func windowBackgroundBrightness(for appearance: NSAppearance.Name) -> CGFloat { - var brightness: CGFloat = 0 - NSAppearance(named: appearance)?.performAsCurrentDrawingAppearance { - brightness = NSColor.windowBackgroundColor.usingColorSpace(.deviceRGB)?.brightnessComponent ?? 0 - } - return brightness + host.layoutSubtreeIfNeeded() + return (host, strip) } private func brightness(of view: NSView, rows: [CGFloat], columns: [CGFloat]) -> [CGFloat] { @@ -160,43 +74,39 @@ struct EditorTabStripChromeTests { } } - /// Ink, as distance from the surface the glyphs are drawn on, so the same assertion holds in - /// light where a label is darker than its background and in dark where it is lighter. private func inkContrast(of view: NSView, columns: [CGFloat]) -> CGFloat { let samples = brightness(of: view, rows: Self.contentRows, columns: columns) guard let low = samples.min(), let high = samples.max() else { return 0 } return high - low } - @Test( - "The selected tab's close button is drawn on its glass, not buried under it", - arguments: [NSAppearance.Name.aqua, .darkAqua] - ) - func selectedTabShowsItsCloseButton(appearance: NSAppearance.Name) { - let host = makeHost(appearance: appearance) + @Test("The selected tab shows its close button only under the pointer, as the system bar does") + func closeButtonFollowsThePointer() throws { + let (_, strip) = makeHost(appearance: .aqua, isActive: true) + let selected = try #require(strip.itemView(for: strip.items[0].id)) - let onSelected = inkContrast(of: host, columns: Self.closeGlyphColumns(ofTabAt: 0)) - let onPlain = inkContrast(of: host, columns: Self.closeGlyphColumns(ofTabAt: 2)) + #expect(selected.closeButton.isHidden) - /// A drawn glyph puts light pixels next to dark ones inside a box that is otherwise one - /// flat surface, so the spread is what proves it is there. - #expect(onSelected > 0.1) + selected.isHovered = true + #expect(!selected.closeButton.isHidden) - /// The same box on a tab that is neither selected nor hovered carries no button, which is - /// what stops a stray highlight anywhere in the strip from satisfying the check above. - #expect(onPlain < 0.05) + selected.isHovered = false + #expect(selected.closeButton.isHidden) } - /// The selected title is `labelColor` and the rest are `secondaryLabelColor`, so the selected - /// one always stands further from whatever it is drawn on. It went the other way when the - /// glass was painting over it, and the difference was large: the selected title measured a - /// peak of 121 against 166 for its neighbours, on a surface of 86. - @Test( - "The selected tab's title reads stronger than its neighbours, not weaker", - arguments: [NSAppearance.Name.aqua, .darkAqua] - ) + @Test("A background window shows no close button under the pointer") + func backgroundWindowHidesTheCloseButton() throws { + let (_, strip) = makeHost(appearance: .aqua, isActive: false) + let selected = try #require(strip.itemView(for: strip.items[0].id)) + + selected.isHovered = true + + #expect(selected.closeButton.isHidden) + } + + @Test("The selected tab's title reads stronger than its neighbours", arguments: [NSAppearance.Name.aqua, .darkAqua]) func selectedTitleOutreadsTheOthers(appearance: NSAppearance.Name) { - let host = makeHost(appearance: appearance) + let (host, _) = makeHost(appearance: appearance) let selected = inkContrast(of: host, columns: Self.titleColumns(ofTabAt: 0)) let unselected = inkContrast(of: host, columns: Self.titleColumns(ofTabAt: 2)) @@ -206,52 +116,32 @@ struct EditorTabStripChromeTests { #expect(selected > unselected) } - /// The bug this pins: the selected capsule used to be filled with the track's own - /// `unemphasizedSelectedContentBackgroundColor` whenever the window was not in front, and both - /// resolve opaque, so a background window on macOS 14 and 15 showed no selected tab at all. - /// The shadow that was meant to cover for it was drawn in light alone and clipped away by the - /// track's own 24pt capsule. - /// - /// Sampled away from the title and the close button, and in both window states, because the - /// state that broke is the one this suite renders by default. @Test( "The selected tab's surface stands clear of the track in either window state", - arguments: [NSAppearance.Name.aqua, .darkAqua], [ControlActiveState.key, .inactive] + arguments: [NSAppearance.Name.aqua, .darkAqua], [true, false] ) - func selectedSurfaceStandsClearOfTheTrack(appearance: NSAppearance.Name, activeState: ControlActiveState) { - let host = makeHost(appearance: appearance, activeState: activeState) + func selectedSurfaceStandsClearOfTheTrack(appearance: NSAppearance.Name, isActive: Bool) throws { + let (host, _) = makeHost(appearance: appearance, isActive: isActive) - let row = Self.margin + EditorTabStripLayout.trackHeight / 2 - let selected = brightness(of: host, rows: [row], columns: Self.surfaceColumns(ofTabAt: 0)) - let plain = brightness(of: host, rows: [row], columns: Self.surfaceColumns(ofTabAt: 2)) + let selected = brightness(of: host, rows: [Self.trackRow], columns: [Self.surfaceColumn(ofTabAt: 0)]) + let plain = brightness(of: host, rows: [Self.trackRow], columns: [Self.surfaceColumn(ofTabAt: 2)]) - guard let selectedTone = selected.first, let plainTone = plain.first else { - Issue.record("The strip did not rasterise") - return - } + let selectedTone = try #require(selected.first) + let plainTone = try #require(plain.first) #expect(abs(selectedTone - plainTone) > 0.05) } - /// The band is 36pt and only its top 28 carry the track, so the strip must not paint the - /// clearance the system leaves between the tab bar and the content below it. @Test("The band leaves its bottom clearance to the window", arguments: [NSAppearance.Name.aqua, .darkAqua]) - func clearanceBelowTrackIsUnpainted(appearance: NSAppearance.Name) { - let host = makeHost(appearance: appearance) - + func clearanceBelowTrackIsUnpainted(appearance: NSAppearance.Name) throws { + let (host, _) = makeHost(appearance: appearance) let clearanceRow = Self.margin + EditorTabStripLayout.trackHeight - + EditorTabStripLayout.bandBottomClearance / 2 + + (EditorTabStripLayout.bandHeight - EditorTabStripLayout.trackHeight) / 2 let columns = Self.titleColumns(ofTabAt: 1) let backdrop = brightness(of: host, rows: Self.backdropRows, columns: columns) let clearance = brightness(of: host, rows: [clearanceRow], columns: columns) - guard let reference = backdrop.first else { - Issue.record("The strip did not rasterise") - return - } - /// Without this the two comparisons below would hold on a bitmap that rendered nothing at - /// all, because both sides would be reading the same blank. - #expect(abs(reference - windowBackgroundBrightness(for: appearance)) < 0.01) + let reference = try #require(backdrop.first) #expect(!clearance.isEmpty) #expect(clearance.allSatisfy { abs($0 - reference) < 0.005 }) } diff --git a/apple/TableProTests/Views/Main/EditorTabStripInteractionTests.swift b/apple/TableProTests/Views/Main/EditorTabStripInteractionTests.swift deleted file mode 100644 index 15f41010f6..0000000000 --- a/apple/TableProTests/Views/Main/EditorTabStripInteractionTests.swift +++ /dev/null @@ -1,204 +0,0 @@ -// -// EditorTabStripInteractionTests.swift -// TableProTests -// - -import CoreGraphics -import Foundation -import Testing - -@testable import TablePro - -@MainActor -struct EditorTabStripInteractionTests { - private static let trackWidth: CGFloat = 604 - - /// Records what the strip asked the app to do, so a reorder can be checked for reaching the - /// tab manager exactly once and only on release. - private final class Recorder { - var moves: [(UUID, Int)] = [] - var activated: [UUID] = [] - var closed: [UUID] = [] - } - - private func makeInteraction( - tabCount: Int, - overflow: EditorTabStripOverflow = .scroll, - recorder: Recorder = Recorder() - ) -> (EditorTabStripInteraction, [UUID], Recorder) { - let ids = (0 ..< tabCount).map { _ in UUID() } - let interaction = EditorTabStripInteraction() - interaction.overflow = overflow - interaction.commands = EditorTabCommands( - activate: { recorder.activated.append($0) }, - keepOpen: { _ in }, - canKeepOpen: { _ in false }, - isPinned: { _ in false }, - setPinned: { _, _ in }, - close: { recorder.closed.append($0) }, - closeOthers: { _ in }, - canCloseOthers: { _ in true }, - closeAll: {}, - canCloseAll: { true }, - moveTab: { recorder.moves.append(($0, $1)) }, - canMove: { _, _ in true }, - moveBy: { _, _ in }, - tearOff: { _ in }, - canTearOff: { _ in false }, - moveToConnection: { _ in }, - offersMoveToConnection: { _ in false }, - canMoveToConnection: { _ in false }, - tooltip: { _ in "" } - ) - interaction.dropClosedTabs(keeping: ids) - interaction.updateRun(trackWidth: Self.trackWidth, count: tabCount) - return (interaction, ids, recorder) - } - - /// `EditorTabStrip` draws a tab only where the run has a placement for its index, so a run - /// measured against a shorter list than the strip draws leaves the last tabs nowhere while the - /// rest share the whole track between them. The list used to arrive from the view's own - /// lifecycle, after the first layout pass had already measured a run for no tabs at all. - @Test("Adopting the model's tabs completes the run measured before any tab was known") - func adoptingAfterAnEmptyMeasurementCompletesTheRun() { - let ids = (0 ..< 5).map { _ in UUID() } - let interaction = EditorTabStripInteraction() - - interaction.updateRun(trackWidth: Self.trackWidth, count: 0) - #expect(interaction.run.placements.isEmpty) - - interaction.adopt(tabIds: ids, overflow: .scroll) - - #expect(interaction.displayedIds == ids) - #expect(interaction.run.placements.count == ids.count) - #expect(ids.indices.allSatisfy { interaction.run.placement(at: $0) != nil }) - } - - /// The style has to be in place for the same measurement, or a user who wraps their tabs gets - /// one paint of the scrolling geometry and a band sized for a row count the run never had. - @Test("Adopting carries the overflow style into the same run") - func adoptingCarriesTheOverflowStyle() { - let ids = (0 ..< 12).map { _ in UUID() } - let interaction = EditorTabStripInteraction() - - interaction.updateRun(trackWidth: Self.trackWidth, count: 0) - interaction.adopt(tabIds: ids, overflow: .rows) - - #expect(interaction.overflow == .rows) - #expect(interaction.run.rowCount > 1) - #expect(interaction.run.contentSize.width <= Self.trackWidth) - } - - @Test("A reorder draws from its own order and leaves the manager alone until release") - func reorderIsNotCommittedUntilRelease() { - let (interaction, ids, recorder) = makeInteraction(tabCount: 4) - - interaction.beginReorder(of: ids[0]) - interaction.updateReorder(toLinearLocation: interaction.run.tabWidth * 2.5) - - #expect(interaction.displayedIds != ids) - #expect(recorder.moves.isEmpty) - - interaction.commitReorder() - - #expect(recorder.moves.count == 1) - #expect(recorder.moves.first?.0 == ids[0]) - #expect(recorder.moves.first?.1 == 2) - #expect(interaction.reorder == nil) - } - - /// Escape drops the value the drag was building, and the manager was never written, so there - /// is nothing to undo. - @Test("A cancelled reorder writes nothing and puts the order back") - func cancelledReorderWritesNothing() { - let (interaction, ids, recorder) = makeInteraction(tabCount: 4) - - interaction.beginReorder(of: ids[0]) - interaction.updateReorder(toLinearLocation: interaction.run.tabWidth * 2.5) - interaction.clearReorder() - - #expect(recorder.moves.isEmpty) - #expect(interaction.displayedIds == ids) - } - - @Test("A reorder that ends where it started writes nothing") - func unmovedReorderWritesNothing() { - let (interaction, ids, recorder) = makeInteraction(tabCount: 4) - - interaction.beginReorder(of: ids[1]) - interaction.commitReorder() - - #expect(recorder.moves.isEmpty) - } - - /// The pointer and the keyboard are independent streams, so `Cmd+W` can close the tab that is - /// mid-drag. A stale id must not reach the commit and put back a tab that is gone. - @Test("Closing the dragged tab ends the drag") - func closingTheDraggedTabEndsTheDrag() { - let (interaction, ids, recorder) = makeInteraction(tabCount: 4) - - interaction.beginReorder(of: ids[0]) - interaction.dropClosedTabs(keeping: Array(ids.dropFirst())) - - #expect(interaction.reorder == nil) - interaction.commitReorder() - #expect(recorder.moves.isEmpty) - } - - @Test("Closing another tab keeps the drag alive without it") - func closingAnotherTabKeepsTheDrag() { - let (interaction, ids, _) = makeInteraction(tabCount: 4) - - interaction.beginReorder(of: ids[0]) - interaction.dropClosedTabs(keeping: [ids[0], ids[1], ids[3]]) - - #expect(interaction.reorder != nil) - #expect(interaction.displayedIds.count == 3) - } - - @Test("The track scrolls only as far as the content runs") - func scrollingClampsToTheContent() { - let (interaction, _, _) = makeInteraction(tabCount: 12) - let maximum = interaction.run.contentSize.width - interaction.viewportWidth - - interaction.scroll(by: 10_000) - #expect(interaction.contentOffset == maximum) - - interaction.scroll(by: -10_000) - #expect(interaction.contentOffset == 0) - } - - /// A wrapped run never overflows, so there is nothing to scroll and the wheel is inert. - @Test("A wrapped run does not scroll") - func wrappedRunDoesNotScroll() { - let (interaction, _, _) = makeInteraction(tabCount: 12, overflow: .rows) - - interaction.scroll(by: 500) - - #expect(interaction.contentOffset == 0) - } - - @Test("Revealing a tab scrolls it fully into the viewport from either side") - func revealScrollsFromEitherSide() { - let (interaction, ids, _) = makeInteraction(tabCount: 12) - - interaction.revealTab(id: ids[11]) - let placement = interaction.run.placement(at: 11) - #expect(interaction.contentOffset == (placement?.frame.maxX ?? 0) - interaction.viewportWidth) - - interaction.revealTab(id: ids[0]) - #expect(interaction.contentOffset == 0) - } - - @Test("Switching to rows drops the scroll offset the run no longer has") - func switchingToRowsResetsTheOffset() { - let (interaction, _, _) = makeInteraction(tabCount: 12) - interaction.scroll(by: 400) - #expect(interaction.contentOffset > 0) - - interaction.overflow = .rows - - #expect(interaction.contentOffset == 0) - #expect(interaction.run.rowCount > 1) - } -} diff --git a/apple/TableProTests/Views/Main/EditorTabStripLayoutTests.swift b/apple/TableProTests/Views/Main/EditorTabStripLayoutTests.swift index 3738247159..748fb1b204 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripLayoutTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripLayoutTests.swift @@ -5,22 +5,22 @@ import Testing struct EditorTabStripLayoutTests { private static let ids = (0..<5).map { _ in UUID() } - @Test("Tabs share the track equally once each share clears the minimum") + @Test("Tabs share the viewport equally once each share clears the minimum") func equalShare() { - let width = EditorTabStripLayout.tabWidth(forTrack: 604, count: 4) + let width = EditorTabStripLayout.tabWidth(forViewport: 600, count: 4) #expect(width == 150) } - @Test("A crowded track stops shrinking at the minimum, so the strip scrolls instead") + @Test("A crowded viewport stops shrinking at the minimum, so the strip scrolls instead") func minimumWidthFloor() { - let width = EditorTabStripLayout.tabWidth(forTrack: 404, count: 20) + let width = EditorTabStripLayout.tabWidth(forViewport: 400, count: 20) #expect(width == EditorTabStripLayout.minimumTabWidth) } @Test("An empty tab list does not divide by zero") func emptyList() { - let width = EditorTabStripLayout.tabWidth(forTrack: 404, count: 0) - #expect(width == 400) + let width = EditorTabStripLayout.tabWidth(forViewport: 400, count: 0) + #expect(width == EditorTabStripLayout.minimumTabWidth) } @Test("No separator leads the first tab") diff --git a/apple/TableProTests/Views/Main/EditorTabStripSnapshotTests.swift b/apple/TableProTests/Views/Main/EditorTabStripSnapshotTests.swift new file mode 100644 index 0000000000..b6c2248a24 --- /dev/null +++ b/apple/TableProTests/Views/Main/EditorTabStripSnapshotTests.swift @@ -0,0 +1,75 @@ +// +// EditorTabStripSnapshotTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct EditorTabStripSnapshotTests { + private func items( + _ tabs: [QueryTab], + selected: UUID? = nil, + busy: Set = [] + ) -> [EditorTabItem] { + EditorTabStripSnapshot.items(tabs: tabs, selectedId: selected, target: nil, isBusy: { busy.contains($0) }) + } + + private func tab(_ title: String, outcome: TabUnseenOutcome? = nil) -> QueryTab { + var tab = QueryTab(title: title) + tab.execution.unseenOutcome = outcome + return tab + } + + @Test("Items keep the tab order and know their position") + func itemsKeepOrder() { + let tabs = [tab("Album"), tab("Artist")] + let result = items(tabs, selected: tabs[1].id) + + #expect(result.map(\.title) == ["Album", "Artist"]) + #expect(result.map(\.position) == [1, 2]) + #expect(result.allSatisfy { $0.count == 2 }) + #expect(result.map(\.isSelected) == [false, true]) + } + + @Test("A running tab reports running, selected or not") + func runningOutranksEverything() { + let running = tab("Album", outcome: .failed) + let result = items([running], selected: running.id, busy: [running.id]) + + #expect(result.first?.status == .running) + } + + @Test("An unseen outcome shows only on a tab that is not selected") + func unseenOutcomeNeedsABackgroundTab() { + let failed = tab("Album", outcome: .failed) + let finished = tab("Artist", outcome: .succeeded) + + let background = items([failed, finished]) + #expect(background.map(\.status) == [.failed, .finished]) + + let foreground = items([failed, finished], selected: failed.id) + #expect(foreground.first?.status == .idle) + } + + @Test("A preview tab's tooltip says how to keep it") + func previewTooltip() { + var preview = tab("Album") + preview.isPreview = true + + #expect(items([preview]).first?.tooltip.contains("Album") == true) + #expect(items([preview]).first?.tooltip != items([tab("Album")]).first?.tooltip) + } + + @Test("Accessibility hears the states the drawing shows") + func accessibilityDescribesState() { + let item = EditorTabItem.sample(isPinned: true, isPreview: true, status: .running, position: 2, count: 3) + let description = item.accessibilityDescription + + #expect(description.contains("2")) + #expect(description.contains("3")) + #expect(description != EditorTabItem.sample(position: 2, count: 3).accessibilityDescription) + } +} diff --git a/apple/TableProTests/Views/Main/EditorTabStripSurfacesTests.swift b/apple/TableProTests/Views/Main/EditorTabStripSurfacesTests.swift index fb448cbd59..f4a6921e0a 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripSurfacesTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripSurfacesTests.swift @@ -2,43 +2,29 @@ // EditorTabStripSurfacesTests.swift // TableProTests // -// What these pin is the one property the selection rests on: that it can never resolve at or -// below the track, over the system window or a themed one. It used to be a pair of Liquid Glass -// tints, whose step was a function of the wallpaper behind the window and inverted outright on -// macOS 27 (#2439). -// import AppKit import Foundation -import SwiftUI @testable import TablePro import Testing @MainActor struct EditorTabStripSurfacesTests { - /// The two appearances that can actually be instantiated, and no more. - /// - /// This list used to carry `.accessibilityHighContrastAqua` and its dark twin as well, which - /// covered nothing: those constants carry the raw values "NSAppearanceNameAccessibilityAqua" - /// and "NSAppearanceNameAccessibilityDarkAqua", and `NSAppearance(named:)` resolves both back - /// to plain Aqua and DarkAqua, which `NSAppearance.currentDrawing().name` confirms from inside - /// the block. So the suite ran the same two appearances twice and reported four. - /// - /// Spelling the real names out does not rescue it either: "NSAppearanceNameAccessibilityHigh- - /// ContrastAqua" instantiates in a plain process and returns nil in the test host, so the - /// cases fail rather than cover anything. Increase Contrast is a system setting, not an - /// appearance to borrow, which is why the app reads it through `colorSchemeContrast` and why - /// `solidSurfacesAnswerBothSettings` below is where that contract is pinned. - nonisolated private static let appearances: [NSAppearance.Name] = [ - .aqua, - .darkAqua, + nonisolated private static let appearances: [NSAppearance.Name] = [.aqua, .darkAqua] + + // Window colors a theme draws behind the strip: Solarized Light, GitHub Light, plain white and Dracula. + nonisolated private static let themedBackdrops: [(NSAppearance.Name, String)] = [ + (.aqua, "#FDF6E3"), + (.aqua, "#F6F8FA"), + (.aqua, "#FFFFFF"), + (.darkAqua, "#282A36"), ] - /// `NSColor.relativeLuminance` drops the alpha component, so a translucent fill has to be laid - /// over what it covers before it can be measured at all. `controlColor` is white at a quarter - /// alpha in dark, which reads as pure white until it is composited. - private func composite(_ source: Color, over destination: NSColor) -> NSColor { - guard let top = NSColor(source).usingColorSpace(.sRGB), + private static let systemTrack = EditorTabStripPalette.trackColor(overThemedBackdrop: false) + + // `relativeLuminance` drops alpha, so a translucent fill is laid over what it covers before it is measured. + private func composite(_ source: NSColor, over destination: NSColor) -> NSColor { + guard let top = source.usingColorSpace(.sRGB), let bottom = destination.usingColorSpace(.sRGB) else { return destination } let alpha = top.alphaComponent @@ -56,123 +42,64 @@ struct EditorTabStripSurfacesTests { return (max(first, second) + 0.05) / (min(first, second) + 0.05) } - /// The track over a window that keeps its system color. - private static let systemTrack = EditorTabStripPalette.trackFill(overThemedBackdrop: false) - - /// Window colors a theme draws behind the strip: Solarized Light, GitHub Light, plain white and Dracula. - nonisolated private static let themedBackdrops: [(NSAppearance.Name, String)] = [ - (.aqua, "#FDF6E3"), - (.aqua, "#F6F8FA"), - (.aqua, "#FFFFFF"), - (.darkAqua, "#282A36"), - ] - private func resolve(_ appearance: NSAppearance.Name, _ body: () -> T) -> T? { var result: T? NSAppearance(named: appearance)?.performAsCurrentDrawingAppearance { result = body() } return result } - // MARK: - The opaque surfaces - - /// The bug this suite exists for. `selectedFill` used to be the track's own - /// `unemphasizedSelectedContentBackgroundColor` whenever the window was not in front, and both - /// resolve opaque, so the selected capsule and the track it sat in were the same pixel. - @Test( - "The opaque selected fill is never the track's own colour", - arguments: EditorTabStripSurfacesTests.appearances - ) - func selectedFillIsNotTheTrackFill(appearance: NSAppearance.Name) { + @Test("The selected fill is never the track's own colour", arguments: EditorTabStripSurfacesTests.appearances) + func selectedFillIsNotTheTrackFill(appearance: NSAppearance.Name) throws { let pair = resolve(appearance) { ( - NSColor(Self.systemTrack).usingColorSpace(.sRGB), - NSColor(EditorTabStripPalette.selectedFill).usingColorSpace(.sRGB) + Self.systemTrack.usingColorSpace(.sRGB), + EditorTabStripPalette.selectedColor.usingColorSpace(.sRGB) ) } - guard let track = pair?.0, let selected = pair?.1 else { - Issue.record("The strip's opaque fills did not resolve") - return - } - /// Compared on resolved components rather than with `==`, which answers how a colour was - /// built rather than what it draws. - #expect( - track.redComponent != selected.redComponent - || track.alphaComponent != selected.alphaComponent - ) + let track = try #require(pair?.0) + let selected = try #require(pair?.1) + #expect(track.redComponent != selected.redComponent || track.alphaComponent != selected.alphaComponent) } - @Test( - "The opaque selected tab stands clear of the track it sits in", - arguments: EditorTabStripSurfacesTests.appearances - ) - func opaqueSelectionStandsClearOfTheTrack(appearance: NSAppearance.Name) { + @Test("The selected tab stands clear of the track it sits in", arguments: EditorTabStripSurfacesTests.appearances) + func selectionStandsClearOfTheTrack(appearance: NSAppearance.Name) throws { let measured = resolve(appearance) { () -> CGFloat in let track = self.composite(Self.systemTrack, over: .windowBackgroundColor) - let selected = self.composite(EditorTabStripPalette.selectedFill, over: track) + let selected = self.composite(EditorTabStripPalette.selectedColor, over: track) return self.contrast(selected, track) } - guard let measured else { - Issue.record("The strip's opaque fills did not resolve") - return - } - /// The system's own tab bar measures 1.161 to 1 in light and 1.098 to 1 in dark. The opaque - /// path carries far more than that, 1.371 and 1.991, because it is what the strip falls - /// back to when the user has asked for Increase Contrast or Reduce Transparency. - #expect(measured > 1.25) + #expect(try #require(measured) > 1.25) } - // MARK: - The selection can never invert - - /// The defect behind #2439, expressed as the property that prevents it. In light appearance - /// `controlColor` is opaque white, so it is the ceiling and no track can rise above it; in - /// dark it is white at alpha 0.247, so it composites *over* whatever the track resolved to and - /// always lifts. Either way the selected tab is lighter than its track, by construction rather - /// than by a tuned distance. The Liquid Glass tints it replaced had neither guarantee. - @Test( - "The selected fill can never resolve at or below the track", - arguments: EditorTabStripSurfacesTests.appearances - ) - func selectionNeverInverts(appearance: NSAppearance.Name) { + @Test("The selected fill can never resolve at or below the track", arguments: EditorTabStripSurfacesTests.appearances) + func selectionNeverInverts(appearance: NSAppearance.Name) throws { let measured = resolve(appearance) { () -> (CGFloat, CGFloat) in let track = self.composite(Self.systemTrack, over: .windowBackgroundColor) - let selected = self.composite(EditorTabStripPalette.selectedFill, over: track) + let selected = self.composite(EditorTabStripPalette.selectedColor, over: track) return (track.relativeLuminance, selected.relativeLuminance) } - guard let measured else { - Issue.record("The strip's fills did not resolve") - return - } - #expect(measured.1 > measured.0) + let values = try #require(measured) + #expect(values.1 > values.0) } - /// A hovered tab has to stay a hint. The system darkens one in light appearance rather than - /// lightening it, so hover and selection travel in opposite directions and the only thing - /// worth pinning is that hover never travels further. @Test( "A hovered tab never moves further from the track than the selected one", arguments: EditorTabStripSurfacesTests.appearances ) - func hoverNeverOutreadsTheSelection(appearance: NSAppearance.Name) { + func hoverNeverOutreadsTheSelection(appearance: NSAppearance.Name) throws { let measured = resolve(appearance) { () -> (CGFloat, CGFloat) in let track = self.composite(Self.systemTrack, over: .windowBackgroundColor) - let hovered = self.composite(EditorTabStripPalette.hoverFill, over: track) - let selected = self.composite(EditorTabStripPalette.selectedFill, over: track) + let hovered = self.composite(EditorTabStripPalette.hoverColor, over: track) + let selected = self.composite(EditorTabStripPalette.selectedColor, over: track) return ( abs(hovered.relativeLuminance - track.relativeLuminance), abs(selected.relativeLuminance - track.relativeLuminance) ) } - guard let measured else { - Issue.record("The strip's fills did not resolve") - return - } - #expect(measured.0 < measured.1) + let values = try #require(measured) + #expect(values.0 < values.1) } - /// The tab is inset inside the track by the padding on every side, so the two capsules stay - /// concentric at their ends and the selected one never overruns the track's curve. Both are - /// fully rounded, which is what the system's own tab bar draws: its runtime view tree reports - /// `cornerRadius = 12` on each 24pt tab, exactly half the height. @Test("The tab is inset inside the track on every side") func tabIsInsetInsideTheTrack() { #expect( @@ -182,38 +109,21 @@ struct EditorTabStripSurfacesTests { #expect(EditorTabStripLayout.trackHeight < EditorTabStripLayout.bandHeight) } - // MARK: - Over a themed window - - /// The window color itself was the track here before, which left the selected tab a step of 1.00 to - /// 1.08 under a light theme. The system's own tab bar measures 1.161 in light. @Test( "Over a themed window the selected tab keeps a step above the track", arguments: EditorTabStripSurfacesTests.themedBackdrops ) - func selectionStandsClearOverAThemedWindow(appearance: NSAppearance.Name, windowHex: String) { + func selectionStandsClearOverAThemedWindow(appearance: NSAppearance.Name, windowHex: String) throws { let measured = resolve(appearance) { () -> (CGFloat, CGFloat, CGFloat) in let track = self.composite( - EditorTabStripPalette.trackFill(overThemedBackdrop: true), + EditorTabStripPalette.trackColor(overThemedBackdrop: true), over: HexColor.color(windowHex) ) - let selected = self.composite(EditorTabStripPalette.selectedFill, over: track) + let selected = self.composite(EditorTabStripPalette.selectedColor, over: track) return (self.contrast(selected, track), track.relativeLuminance, selected.relativeLuminance) } - guard let measured else { - Issue.record("The strip's fills did not resolve") - return - } - #expect(measured.0 > 1.16, "step \(measured.0) over \(windowHex)") - #expect(measured.2 > measured.1) - } - - // MARK: - Leaving glass behind - - @Test("Either accessibility setting alone takes the strip off glass") - func solidSurfacesAnswerBothSettings() { - #expect(!EditorTabStripEmphasis.prefersSolidSurfaces(reduceTransparency: false, contrast: .standard)) - #expect(EditorTabStripEmphasis.prefersSolidSurfaces(reduceTransparency: true, contrast: .standard)) - #expect(EditorTabStripEmphasis.prefersSolidSurfaces(reduceTransparency: false, contrast: .increased)) - #expect(EditorTabStripEmphasis.prefersSolidSurfaces(reduceTransparency: true, contrast: .increased)) + let values = try #require(measured) + #expect(values.0 > 1.16, "step \(values.0) over \(windowHex)") + #expect(values.2 > values.1) } } diff --git a/apple/TableProTests/Views/Main/EditorTabStripTrackThemeTests.swift b/apple/TableProTests/Views/Main/EditorTabStripTrackThemeTests.swift index 2e23c211a7..b45127fa0f 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripTrackThemeTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripTrackThemeTests.swift @@ -4,26 +4,21 @@ // import AppKit -import SwiftUI @testable import TablePro import TableProTheme import Testing @MainActor struct EditorTabStripTrackThemeTests { - private func resolved(_ color: Color, in name: NSAppearance.Name) throws -> NSColor { + private func resolved(_ color: NSColor, in name: NSAppearance.Name) throws -> NSColor { let appearance = try #require(NSAppearance(named: name)) var result: NSColor? appearance.performAsCurrentDrawingAppearance { - result = NSColor(color).usingColorSpace(.sRGB) + result = color.usingColorSpace(.sRGB) } return try #require(result) } - private func native(in name: NSAppearance.Name) throws -> NSColor { - try resolved(Color(nsColor: .unemphasizedSelectedContentBackgroundColor), in: name) - } - private var isOverThemedBackdrop: Bool { EditorTabStripPalette.isOverThemedBackdrop(highContrast: false) } @@ -33,8 +28,9 @@ struct EditorTabStripTrackThemeTests { try ThemeTestFixture.adopting(.builtIn, appearance: .dark) { #expect(!isOverThemedBackdrop) for name in [NSAppearance.Name.aqua, .darkAqua] { - let track = try resolved(EditorTabStripPalette.trackFill(overThemedBackdrop: isOverThemedBackdrop), in: name) - #expect(ThemeTestFixture.matches(track, try native(in: name)), "\(name.rawValue) drew \(track)") + let track = try resolved(EditorTabStripPalette.trackColor(overThemedBackdrop: isOverThemedBackdrop), in: name) + let native = try resolved(.unemphasizedSelectedContentBackgroundColor, in: name) + #expect(ThemeTestFixture.matches(track, native), "\(name.rawValue) drew \(track)") } } } @@ -51,8 +47,8 @@ struct EditorTabStripTrackThemeTests { func themedTrackIsATranslucentSystemFill() throws { guard #available(macOS 14.0, *) else { return } for name in [NSAppearance.Name.aqua, .darkAqua] { - let track = try resolved(EditorTabStripPalette.trackFill(overThemedBackdrop: true), in: name) - let fill = try resolved(Color(nsColor: .secondarySystemFill), in: name) + let track = try resolved(EditorTabStripPalette.trackColor(overThemedBackdrop: true), in: name) + let fill = try resolved(.secondarySystemFill, in: name) #expect(ThemeTestFixture.matches(track, fill), "\(name.rawValue) drew \(track)") #expect(track.alphaComponent < 0.5, "\(name.rawValue) drew \(track)") } @@ -65,32 +61,6 @@ struct EditorTabStripTrackThemeTests { #expect(EditorTabStripPalette.followsWindowBackdrop == expected) } - /// Never ordered front and never closed: `close()` on a test window over-releases it. - @Test("The track moves exactly when a content window's backdrop takes the theme") - func trackMatchesTheWindowBackdrop() throws { - let windowTheme = try ThemeTestFixture.pair([.windowBackdrop: ThemeTestFixture.windowHex], on: .dark) - let editorTheme = try ThemeTestFixture.pair([.editorBackground: ThemeTestFixture.editorHex], on: .dark) - try ThemeTestFixture.adopting(.builtIn, appearance: .dark) { - for theme in [ThemePair.builtIn, windowTheme, editorTheme] { - ThemeTestFixture.adopt(theme, appearance: .dark) - let window = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: 120, height: 40), - styleMask: [.titled], - backing: .buffered, - defer: true - ) - window.isReleasedWhenClosed = false - window.appearance = NSAppearance(named: .darkAqua) - let original = window.backgroundColor - let backdrop = ThemeWindowBackdrop(window: window) - let windowThemed = window.backgroundColor !== original - - #expect(windowThemed == isOverThemedBackdrop, "\(theme.dark.id): window themed \(windowThemed)") - withExtendedLifetime(backdrop) {} - } - } - } - @Test("Editor and grid colors leave the track alone") func contentSlotsLeaveTheTrackAlone() throws { try ThemeTestFixture.adopting([ @@ -101,31 +71,21 @@ struct EditorTabStripTrackThemeTests { } } - @Test("A theme change repaints a track already on screen") - func trackRepaintsOnThemeChange() throws { - let track = Self.host(Color.clear.modifier(EditorTabStripTrackSurface(rowCount: 1))) + @Test("The track draws the current theme each time it paints") + func trackDrawsTheCurrentTheme() throws { + let track = EditorTabTrackView(frame: NSRect(x: 0, y: 0, width: 120, height: 40)) + track.appearance = NSAppearance(named: .darkAqua) try ThemeTestFixture.adopting(.builtIn, appearance: .dark) { let before = try Self.center(of: track) - let system = try Self.center(of: Self.host(Color(nsColor: .unemphasizedSelectedContentBackgroundColor))) - #expect(ThemeTestFixture.matches(before, system), "default drew \(before), system \(system)") - try ThemeTestFixture.adopt([.windowBackdrop: ThemeTestFixture.windowHex], appearance: .dark) let after = try Self.center(of: track) - let expected = try Self.center(of: Self.host( - Color(nsColor: EditorTabStripPalette.trackColor(overThemedBackdrop: EditorTabStripPalette.followsWindowBackdrop)) - )) - #expect(ThemeTestFixture.matches(after, expected), "themed drew \(after), expected \(expected)") + #expect(ThemeTestFixture.matches(before, after) != EditorTabStripPalette.followsWindowBackdrop) } } - private static func host(_ view: some View) -> NSHostingView { - ThemeTestFixture.hostingView(view, size: NSSize(width: 120, height: 40)) - } - - private static func center(of host: NSHostingView) throws -> NSColor { - host.layoutSubtreeIfNeeded() - let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds)) - host.cacheDisplay(in: host.bounds, to: bitmap) + private static func center(of view: NSView) throws -> NSColor { + let bitmap = try #require(view.bitmapImageRepForCachingDisplay(in: view.bounds)) + view.cacheDisplay(in: view.bounds, to: bitmap) let color = try #require(bitmap.colorAt(x: bitmap.pixelsWide / 2, y: bitmap.pixelsHigh / 2)) return try #require(color.usingColorSpace(.sRGB)) } @@ -133,8 +93,8 @@ struct EditorTabStripTrackThemeTests { @Test("The selected tab stays the system's own fill under a theme") func selectedTabStaysSystem() throws { try ThemeTestFixture.adopting([.windowBackdrop: ThemeTestFixture.windowHex], appearance: .dark) { - let selected = try resolved(EditorTabStripPalette.selectedFill, in: .darkAqua) - let system = try resolved(Color(nsColor: .controlColor), in: .darkAqua) + let selected = try resolved(EditorTabStripPalette.selectedColor, in: .darkAqua) + let system = try resolved(.controlColor, in: .darkAqua) #expect(ThemeTestFixture.matches(selected, system)) } } diff --git a/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift b/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift new file mode 100644 index 0000000000..f1bbd22b20 --- /dev/null +++ b/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift @@ -0,0 +1,215 @@ +// +// EditorTabStripViewTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct EditorTabStripViewTests { + private static let size = NSSize(width: 652, height: EditorTabStripLayout.bandHeight) + + private func makeStrip( + titles: [String] = ["Album", "Artist", "Customer"], + width: CGFloat = Self.size.width, + recorder: EditorTabCommandRecorder = EditorTabCommandRecorder() + ) -> (EditorTabStripView, NSWindow) { + let window = NSWindow( + contentRect: NSRect(origin: .zero, size: NSSize(width: width, height: Self.size.height)), + styleMask: [.borderless], + backing: .buffered, + defer: true + ) + window.isReleasedWhenClosed = false + let strip = EditorTabStripView(frame: NSRect(origin: .zero, size: window.frame.size)) + strip.commands = .stub(recorder: recorder) + window.contentView = strip + strip.apply(EditorTabItem.samples(titles: titles)) + strip.layoutSubtreeIfNeeded() + return (strip, window) + } + + private func views(of strip: EditorTabStripView) -> [EditorTabItemView] { + strip.items.compactMap { strip.itemView(for: $0.id) } + } + + @Test("Every item gets a view, laid out in order across the track") + func viewsFollowTheItems() { + let (strip, window) = makeStrip() + defer { window.orderOut(nil) } + + let minXs = views(of: strip).map(\.frame.minX) + #expect(minXs.count == 3) + #expect(minXs == minXs.sorted()) + #expect(views(of: strip).allSatisfy { $0.frame.width == strip.run.tabWidth }) + } + + @Test("A title with room is drawn whole") + func titleWithRoomIsNotTruncated() throws { + let (strip, window) = makeStrip(titles: ["beta_invites", "beta_testers", "license_jobs", "licenses"], width: 1_200) + defer { window.orderOut(nil) } + + for item in strip.items { + let view = try #require(strip.itemView(for: item.id)) + view.layoutSubtreeIfNeeded() + let needed = ceil(view.titleField.attributedStringValue.size().width) + #expect(view.titleField.frame.width >= needed, "\(item.title) got \(view.titleField.frame.width) of \(needed)") + } + } + + @Test("A closed tab's view leaves and the others take its share") + func closedTabLeaves() { + let (strip, window) = makeStrip() + defer { window.orderOut(nil) } + let closed = strip.items[1].id + let width = strip.run.tabWidth + + strip.apply(strip.items.filter { $0.id != closed }) + + #expect(strip.itemView(for: closed) == nil) + #expect(strip.run.tabWidth > width) + } + + @Test("A title change reaches the existing view") + func updatedItemKeepsItsView() { + let (strip, window) = makeStrip() + defer { window.orderOut(nil) } + let id = strip.items[0].id + let view = strip.itemView(for: id) + + strip.apply([.sample(id: id, title: "Renamed", isSelected: true)] + strip.items.dropFirst()) + + #expect(strip.itemView(for: id) === view) + #expect(view?.item.title == "Renamed") + } + + @Test("Selecting a tab past the edge scrolls it to full width") + func selectionIsRevealed() { + let titles = (0 ..< 14).map { "table_\($0)" } + let (strip, window) = makeStrip(titles: titles) + defer { window.orderOut(nil) } + + let last = EditorTabItem.sample( + id: strip.items[13].id, + title: "table_13", + isSelected: true, + position: 14, + count: 14 + ) + var items = strip.items.map { + EditorTabItem.sample(id: $0.id, title: $0.title, position: $0.position, count: $0.count) + } + items[13] = last + strip.apply(items) + strip.reveal(last.id, animated: false) + strip.layoutSubtreeIfNeeded() + + #expect(strip.scrollView.contentView.bounds.minX > 0) + #expect(strip.itemView(for: last.id)?.frame.width == EditorTabStripLayout.minimumTabWidth) + } + + @Test("A second click on the tab the first one activated keeps it open") + func doubleClickKeepsTheTab() { + let recorder = EditorTabCommandRecorder() + let (strip, window) = makeStrip(recorder: recorder) + defer { window.orderOut(nil) } + let id = strip.items[1].id + + strip.activate(id, click: EditorTabClick(clickCount: 1, hasModifiers: false)) + strip.activate(id, click: EditorTabClick(clickCount: 2, hasModifiers: false)) + + #expect(recorder.activated == [id, id]) + #expect(recorder.kept == [id]) + } + + @Test("A double-click straddling two tabs keeps neither") + func doubleClickAcrossTabsKeepsNothing() { + let recorder = EditorTabCommandRecorder() + let (strip, window) = makeStrip(recorder: recorder) + defer { window.orderOut(nil) } + + strip.activate(strip.items[0].id, click: EditorTabClick(clickCount: 1, hasModifiers: false)) + strip.activate(strip.items[1].id, click: EditorTabClick(clickCount: 2, hasModifiers: false)) + + #expect(recorder.kept.isEmpty) + } + + @Test("Only a tab released on empty space opens a window") + func dragEndingOpensAWindowOnlyOnARelease() { + func opens( + operation: NSDragOperation = [], + cancelled: Bool = false, + overStrip: Bool = false, + canTearOff: Bool = true + ) -> Bool { + EditorTabDragEnding.opensNewWindow( + operation: operation, + wasCancelled: cancelled, + isOverTabStrip: overStrip, + canTearOff: canTearOff + ) + } + + #expect(opens()) + #expect(!opens(operation: .move)) + #expect(!opens(cancelled: true)) + #expect(!opens(overStrip: true)) + #expect(!opens(canTearOff: false)) + } + + @Test("The new tab button runs the command") + func newTabButton() { + let recorder = EditorTabCommandRecorder() + let (strip, window) = makeStrip(recorder: recorder) + defer { window.orderOut(nil) } + + strip.newTabButton.performClick(nil) + + #expect(recorder.newTabCount == 1) + } + + @Test("The strip is a tab group and each tab a selected or unselected tab button") + func accessibilityRoles() throws { + let (strip, window) = makeStrip() + defer { window.orderOut(nil) } + let selected = try #require(strip.itemView(for: strip.items[0].id)) + let other = try #require(strip.itemView(for: strip.items[1].id)) + + #expect(strip.accessibilityRole() == .tabGroup) + #expect(strip.accessibilityTabs()?.count == 3) + #expect(selected.accessibilityRole() == .radioButton) + #expect(selected.accessibilitySubrole() == .tabButtonSubrole) + #expect(selected.accessibilityIdentifier() == "editor-tab") + #expect(selected.accessibilityLabel() == "Album") + #expect(selected.isAccessibilitySelected()) + #expect(selected.accessibilityValue() as? NSNumber == 1) + #expect(!other.isAccessibilitySelected()) + #expect(other.accessibilityValue() as? NSNumber == 0) + } + + @Test("Pressing a tab through accessibility selects it") + func accessibilityPress() throws { + let recorder = EditorTabCommandRecorder() + let (strip, window) = makeStrip(recorder: recorder) + defer { window.orderOut(nil) } + let id = strip.items[2].id + + #expect(try #require(strip.itemView(for: id)).accessibilityPerformPress()) + #expect(recorder.activated == [id]) + } + + @Test("The menu's enabled commands are offered to assistive technology") + func accessibilityActionsFollowTheMenu() throws { + let (strip, window) = makeStrip() + defer { window.orderOut(nil) } + let view = try #require(strip.itemView(for: strip.items[0].id)) + + let names = view.accessibilityCustomActions()?.map(\.name) ?? [] + #expect(names.contains(String(localized: "Close Tab"))) + #expect(names.contains(String(localized: "Pin Tab"))) + #expect(!names.contains(String(localized: "Keep Open"))) + } +} diff --git a/apple/TableProTests/Views/Main/EditorTabStripWindowDragTests.swift b/apple/TableProTests/Views/Main/EditorTabStripWindowDragTests.swift index d16d50e3d8..78e2a3efdf 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripWindowDragTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripWindowDragTests.swift @@ -11,21 +11,20 @@ import Testing @MainActor struct EditorTabStripWindowDragTests { - private static let tabCount = 3 - @Test("A press anywhere on a tab reaches a view that never moves the window") func pressOnATabNeverMovesTheWindow() throws { let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_200, height: 800)) defer { fixture.tearDown() } - let strip = try showStrip(in: fixture) - - #expect(strip.interaction.displayedIds.count == Self.tabCount) - for index in strip.interaction.displayedIds.indices { - let placement = try #require(strip.interaction.run.placement(at: index)) - for x in [placement.frame.minX + 1, placement.frame.midX, placement.frame.maxX - 1] { - let hit = viewUnderPress(atContent: CGPoint(x: x, y: placement.frame.midY), of: strip, in: fixture) - #expect(hit === strip, "Tab \(index) at \(x) reached \(String(describing: hit))") - #expect(hit?.mouseDownCanMoveWindow == false, "Tab \(index) at \(x) can move the window") + let strip = showStrip(in: fixture) + + #expect(strip.items.count == 3) + for item in strip.items { + let view = try #require(strip.itemView(for: item.id)) + for x in [view.bounds.minX + 1, view.bounds.midX, view.bounds.maxX - 1] { + let point = view.convert(NSPoint(x: x, y: view.bounds.midY), to: nil) + let hit = fixture.themeFrame?.hitTest(point) + #expect(hit === view, "\(item.title) at \(x) reached \(String(describing: hit))") + #expect(hit?.mouseDownCanMoveWindow == false, "\(item.title) at \(x) can move the window") } } } @@ -34,7 +33,7 @@ struct EditorTabStripWindowDragTests { func titlebarStillMovesTheWindow() throws { let fixture = try OffscreenConnectionWindow(size: CGSize(width: 1_200, height: 800)) defer { fixture.tearDown() } - let strip = try showStrip(in: fixture) + let strip = showStrip(in: fixture) let point = CGPoint(x: fixture.window.frame.width / 2, y: fixture.window.frame.height - 2) let hit = try #require(fixture.themeFrame?.hitTest(point)) @@ -42,25 +41,13 @@ struct EditorTabStripWindowDragTests { #expect(hit.mouseDownCanMoveWindow, "\(hit) takes the press from the window") } - private func showStrip(in fixture: OffscreenConnectionWindow) throws -> EditorTabInteractionView { + private func showStrip(in fixture: OffscreenConnectionWindow) -> EditorTabStripView { let pane = fixture.workspace.panes.tabStrip - let strip = try #require(pane.view as? EditorTabInteractionView) - pane.interaction.adopt(tabIds: (0 ..< Self.tabCount).map { _ in UUID() }, overflow: .scroll) + pane.stripView.commands = .stub() + pane.stripView.apply(EditorTabItem.samples(titles: ["Album", "Artist", "Customer"])) fixture.split.tabStripAccessory.setBandVisible(true) fixture.window.layoutIfNeeded() - return strip - } - - private func viewUnderPress( - atContent point: CGPoint, - of strip: EditorTabInteractionView, - in fixture: OffscreenConnectionWindow - ) -> NSView? { - let local = CGPoint( - x: point.x - strip.interaction.contentOffset - + EditorTabStripLayout.stripInset + EditorTabStripLayout.trackPadding, - y: point.y + EditorTabStripLayout.trackPadding - ) - return fixture.themeFrame?.hitTest(strip.convert(local, to: nil)) + pane.stripView.layoutSubtreeIfNeeded() + return pane.stripView } } diff --git a/apple/TableProUITests/EditorTabDetachUITests.swift b/apple/TableProUITests/EditorTabDetachUITests.swift index 8403e03e9d..f111d3d6dd 100644 --- a/apple/TableProUITests/EditorTabDetachUITests.swift +++ b/apple/TableProUITests/EditorTabDetachUITests.swift @@ -3,6 +3,30 @@ import XCTest // Once one connection is hosted by two windows, the tab must not be lost from both, and the shared // session must not go down with whichever window closes first. final class EditorTabDetachUITests: UITestCase { + func testDraggingATabOutOfTheStripOpensItInItsOwnWindow() throws { + let tables = ["album", "artist", "genre"] + let launch = try launchWithFixture([ConnectionSeed(tabs: tables.map { SeededTab.table($0) })]) + let app = launch.app + let window = launch.window + + XCTAssertTrue( + waitForPredicate(timeout: 20) { self.editorTabTitles(in: window) == tables }, + "The strip must restore a tab per table, got \(editorTabTitles(in: window))" + ) + let dragged = editorTabs(titled: "genre", in: window).firstMatch + XCTAssertTrue(waitUntilHittable(dragged, timeout: 20), "The dragged tab must be hittable") + + dragged.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) + .click(forDuration: 0.02, thenDragTo: window.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6))) + + let windows = app.children(matching: .window) + XCTAssertTrue(waitForPredicate(timeout: 20) { windows.count == 2 }, "The drop must open a second window") + XCTAssertTrue( + windows.matching(NSPredicate(format: "title CONTAINS %@", "genre")).firstMatch.waitToExist(timeout: 20), + "A window must be titled for the dragged tab" + ) + } + func testADetachedTabWorksInItsOwnWindowAndTheOriginalKeepsWorking() throws { let tables = ["album", "artist", "genre"] let launch = try launchWithFixture([ConnectionSeed(tabs: tables.map { SeededTab.table($0) })]) diff --git a/apple/TableProUITests/EditorTabReorderUITests.swift b/apple/TableProUITests/EditorTabReorderUITests.swift index 8beb4e625b..f019ca8fec 100644 --- a/apple/TableProUITests/EditorTabReorderUITests.swift +++ b/apple/TableProUITests/EditorTabReorderUITests.swift @@ -1,8 +1,8 @@ import XCTest // The strip lives in a titlebar accessory, so AppKit's own window drag claims every press on a tab -// unless `EditorTabInteractionView` refuses `mouseDownCanMoveWindow`. Checking the order alone would -// pass with the window sliding across the screen (#2438). +// unless `EditorTabItemView` refuses `mouseDownCanMoveWindow`. Checking the order alone would pass +// with the window sliding across the screen (#2438). final class EditorTabReorderUITests: UITestCase { func testDraggingATabReordersTheStripWithoutMovingTheWindow() throws { let tables = ["album", "artist", "genre"] From 210856056a917a52c3da00d15662b3ccba5d5294 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 18 Nov 2026 18:14:28 +0700 Subject: [PATCH 2/4] docs(changelog): add the editor tab bar fragments --- apple/changelog.d/4323.added.md | 1 + apple/changelog.d/4323.changed.md | 1 + apple/changelog.d/4323.removed.md | 1 + 3 files changed, 3 insertions(+) create mode 100644 apple/changelog.d/4323.added.md create mode 100644 apple/changelog.d/4323.changed.md create mode 100644 apple/changelog.d/4323.removed.md diff --git a/apple/changelog.d/4323.added.md b/apple/changelog.d/4323.added.md new file mode 100644 index 0000000000..f31e103c0d --- /dev/null +++ b/apple/changelog.d/4323.added.md @@ -0,0 +1 @@ +Drag an editor tab onto another window of the same connection to move it there. diff --git a/apple/changelog.d/4323.changed.md b/apple/changelog.d/4323.changed.md new file mode 100644 index 0000000000..9fa5513703 --- /dev/null +++ b/apple/changelog.d/4323.changed.md @@ -0,0 +1 @@ +The editor tab bar now scrolls, animates and drags like the macOS tab bar. diff --git a/apple/changelog.d/4323.removed.md b/apple/changelog.d/4323.removed.md new file mode 100644 index 0000000000..d9663f22e6 --- /dev/null +++ b/apple/changelog.d/4323.removed.md @@ -0,0 +1 @@ +Removed the setting that wrapped editor tabs onto more rows. From 4e145eaf9ba77ee045538afd0dbc90f32457b6cd Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 18 Nov 2026 20:04:43 +0700 Subject: [PATCH 3/4] fix(macos): keep the tab strip's scroll view finite while its band is narrow --- apple/TablePro/Views/Main/EditorTabStripView.swift | 8 +++++++- .../Views/Main/EditorTabStripViewTests.swift | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/Main/EditorTabStripView.swift b/apple/TablePro/Views/Main/EditorTabStripView.swift index a5d998745b..6ac9f1d2b8 100644 --- a/apple/TablePro/Views/Main/EditorTabStripView.swift +++ b/apple/TablePro/Views/Main/EditorTabStripView.swift @@ -181,7 +181,13 @@ internal final class EditorTabStripView: NSView { height: metrics.trackHeight ) track.frame = trackFrame - scrollView.frame = trackFrame.insetBy(dx: metrics.trackPadding, dy: metrics.trackPadding) + // Not `insetBy`: the band starts 1pt wide, and insetting an empty rect returns the null rect at infinity. + scrollView.frame = CGRect( + x: trackFrame.minX + metrics.trackPadding, + y: metrics.trackPadding, + width: max(trackFrame.width - metrics.trackPadding * 2, 0), + height: metrics.tabHeight + ) layoutTabs(animated: false) refreshHoverArea() diff --git a/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift b/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift index f1bbd22b20..971fbfb2bf 100644 --- a/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift +++ b/apple/TableProTests/Views/Main/EditorTabStripViewTests.swift @@ -47,6 +47,20 @@ struct EditorTabStripViewTests { #expect(views(of: strip).allSatisfy { $0.frame.width == strip.run.tabWidth }) } + @Test("A band too narrow for the track keeps finite geometry", arguments: [0, 1, 40] as [CGFloat]) + func narrowBandKeepsFiniteGeometry(width: CGFloat) { + let (strip, window) = makeStrip(width: max(width, 1)) + defer { window.orderOut(nil) } + + strip.setFrameSize(NSSize(width: width, height: Self.size.height)) + strip.layoutSubtreeIfNeeded() + + #expect(strip.scrollView.frame.minX.isFinite) + #expect(strip.scrollView.frame.minY.isFinite) + #expect(strip.scrollView.frame.width == 0) + #expect(strip.items.allSatisfy { strip.itemView(for: $0.id)?.frame.minX.isFinite == true }) + } + @Test("A title with room is drawn whole") func titleWithRoomIsNotTruncated() throws { let (strip, window) = makeStrip(titles: ["beta_invites", "beta_testers", "license_jobs", "licenses"], width: 1_200) From e789876a3ae170f90bff1e613924b01926319c8c Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Wed, 18 Nov 2026 22:33:37 +0700 Subject: [PATCH 4/4] fix(macos): let a table tab move to its own window while its automatic reads run --- ...plitViewController+TabStripAccessory.swift | 3 +- .../Infrastructure/WindowManager.swift | 14 +- .../MainContentCoordinator+QueryTasks.swift | 38 ++++ ...inContentCoordinator+WindowLifecycle.swift | 8 +- .../Views/Main/EditorTabDetachLoadTests.swift | 175 ++++++++++++++++++ .../EditorTabDetachUITests.swift | 15 +- 6 files changed, 241 insertions(+), 12 deletions(-) create mode 100644 apple/TableProTests/Views/Main/EditorTabDetachLoadTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift index a33d14070a..fe3cdf9201 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+TabStripAccessory.swift @@ -136,8 +136,7 @@ internal extension MainSplitViewController { tabType: tab.tabType, tabCount: sessionState.tabManager.tabs.count, hasUnsavedWork: sessionState.coordinator.hasUnsavedWork(forTab: id), - // Not `isExecuting`: Fetch All and an exact row count run on the tab without claiming it. - isBusy: sessionState.coordinator.tabExecution.isBusy(id) || tab.pagination.isBusy, + isBusy: sessionState.coordinator.holdsWorkThatCannotMove(tab), // Not the driver handle, which stays installed through a reconnect and after the monitor gives up. isConnected: DatabaseManager.shared.activeSessions[workspace.connectionId]? .reportedStatus.isConnected == true diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift index c80edce47e..c34e456c1e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift @@ -238,10 +238,12 @@ internal final class WindowManager { workspace.sessionState?.tabManager.tabs.contains { $0.id == tabId } ?? false }), let sourceState = origin.sessionState, - let tab = sourceState.tabManager.tabs.first(where: { $0.id == tabId }), let connection = DatabaseManager.shared.activeSessions[connectionId]?.connection else { return false } + let needsMetadataAndCount = sourceState.coordinator.abandonAutomaticTableReads(of: tabId) + guard let tab = sourceState.tabManager.tabs.first(where: { $0.id == tabId }) else { return false } + let payload = EditorTabPayload( connectionId: connectionId, tabType: tab.tabType, @@ -281,6 +283,8 @@ internal final class WindowManager { /// next window opened for this connection adopt a session state holding a tab that /// never left its old window. SessionStateFactory.removePending(for: payload.id) + sourceState.coordinator.lazyLoadCurrentTabIfNeeded() + if needsMetadataAndCount { sourceState.coordinator.resumeTableMetadataAndCount(of: tab) } return false } @@ -289,6 +293,7 @@ internal final class WindowManager { /// neither prompts nor clears anything from disk. sourceState.coordinator.tabSessionRegistry.unregister(id: tabId) sourceState.tabManager.closeTab(id: tabId) + if needsMetadataAndCount { state.coordinator.resumeTableMetadataAndCount(of: moved) } (window.contentViewController as? MainSplitViewController)?.hostsDetachedTab = true @@ -315,10 +320,12 @@ internal final class WindowManager { workspace !== target && workspace.sessionState?.tabManager.tabs.contains { $0.id == tabId } == true }), let sourceState = origin.sessionState, - let targetState = target.sessionState, - let tab = sourceState.tabManager.tabs.first(where: { $0.id == tabId }) + let targetState = target.sessionState else { return false } + let needsMetadataAndCount = sourceState.coordinator.abandonAutomaticTableReads(of: tabId) + guard let tab = sourceState.tabManager.tabs.first(where: { $0.id == tabId }) else { return false } + let moved = sourceState.coordinator.enrichedForPersistence(tab) if let liveSession = sourceState.coordinator.tabSessionRegistry.session(for: tabId) { targetState.coordinator.tabSessionRegistry.register(liveSession) @@ -328,6 +335,7 @@ internal final class WindowManager { targetState.tabManager.adoptTab(moved, claimFocus: true) targetState.tabManager.moveTab(id: moved.id, to: index) + if needsMetadataAndCount { targetState.coordinator.resumeTableMetadataAndCount(of: moved) } host(containing: target)?.view.window?.makeKeyAndOrderFront(nil) return true } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryTasks.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryTasks.swift index e3cfd3d489..24b59cffb2 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryTasks.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryTasks.swift @@ -84,6 +84,44 @@ extension MainContentCoordinator { cancelQueryTask(for: tabId, delivery: .background) } + // The reads opening a table starts by itself: a moved tab drops them and the window it lands in reads the table again. + private func holdsOnlyAutomaticTableReads(_ tab: QueryTab) -> Bool { + guard tab.tabType == .table, !tab.pagination.isCountingExact, !tab.pagination.isLoadingMore else { return false } + guard hasLoadedTableRows(tab) else { return true } + return !tabExecution.isBusy(tab.id) && !tab.pagination.isLoading + } + + // Not `isExecuting`: Fetch All and an exact row count run on the tab without claiming it. + internal func holdsWorkThatCannotMove(_ tab: QueryTab) -> Bool { + guard tabExecution.isBusy(tab.id) || tab.pagination.isBusy else { return false } + return !holdsOnlyAutomaticTableReads(tab) + } + + // Answers whether the rows had landed, which leaves only their keys and row count for the destination to fetch. + internal func abandonAutomaticTableReads(of tabId: UUID) -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), + tabExecution.isBusy(tabId) || tab.pagination.isBusy, + holdsOnlyAutomaticTableReads(tab) + else { return false } + let rowsLanded = hasLoadedTableRows(tab) + supersedeExecution(for: tabId) + tabManager.mutate(tabId: tabId) { $0.pagination.isLoading = false } + return rowsLanded + } + + // Not a reload: reading the rows again would drop what the user has selected or edited since they landed. + internal func resumeTableMetadataAndCount(of tab: QueryTab) { + guard let tableName = tab.tableContext.tableName, let scope = scope(for: tab) else { return } + let isView = tab.tableContext.knowsView(named: tableName) + tabManager.mutate(tabId: tab.id) { $0.pagination.isCountPending = true } + launchPhase2Work( + tableName: tableName, + tabId: tab.id, + connectionType: connection.type, + schemaTask: startSchemaFetch(tableName, uncached: true, isView: isView, scope: scope) + ) + } + /// What Stop and `Cmd+.` do, on the tab the user is looking at and on nothing else. /// /// The driver cancel goes out inline, because the user is waiting on it, and the claim ends in diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+WindowLifecycle.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+WindowLifecycle.swift index da40de84c0..7a068c10db 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+WindowLifecycle.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+WindowLifecycle.swift @@ -210,13 +210,15 @@ extension MainContentCoordinator { guard tab.execution.errorMessage == nil else { return false } guard !tab.content.query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false } - let hasLoaded = tab.execution.lastExecutedAt != nil - || !tabSessionRegistry.tableRows(for: tab.id).rows.isEmpty - guard !hasLoaded || tabSessionRegistry.isStale(tab.id) else { return false } + guard !hasLoadedTableRows(tab) || tabSessionRegistry.isStale(tab.id) else { return false } return !holdsUnsavedWork(tab) } + func hasLoadedTableRows(_ tab: QueryTab) -> Bool { + tab.execution.lastExecutedAt != nil || !tabSessionRegistry.tableRows(for: tab.id).rows.isEmpty + } + private func clearAbandonedExecutingFlagIfNeeded(for tab: QueryTab) { guard tabExecution.isExecuting(tab.id), !queryTasks.hasTask(for: tab.id) else { return } TableLoadTracer.shared.anomaly( diff --git a/apple/TableProTests/Views/Main/EditorTabDetachLoadTests.swift b/apple/TableProTests/Views/Main/EditorTabDetachLoadTests.swift new file mode 100644 index 0000000000..5ed15dd700 --- /dev/null +++ b/apple/TableProTests/Views/Main/EditorTabDetachLoadTests.swift @@ -0,0 +1,175 @@ +// +// EditorTabDetachLoadTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct EditorTabDetachLoadTests { + private func tableTab() -> QueryTab { + QueryTab(title: "genre", query: "SELECT * FROM genre", tabType: .table, tableName: "genre") + } + + private func queryTab() -> QueryTab { + QueryTab(title: "Query", query: "SELECT 1", tabType: .query) + } + + private func loadedTableTab(in fixture: CoordinatorFixture, pagination: (inout PaginationState) -> Void) -> QueryTab { + var tab = tableTab() + tab.execution.lastExecutedAt = Date() + pagination(&tab.pagination) + return fixture.addTab(tab, rows: TestFixtures.makeTableRows()) + } + + @Test("A table on its first load can move") + func firstLoadCanMove() { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(tableTab()) + + _ = fixture.coordinator.tabExecution.claim(tab.id) + + #expect(!fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A table waiting only on its automatic row count can move") + func automaticCountCanMove() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isCountPending = true } + + #expect(!fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A table reloading the rows it shows stays") + func reloadStays() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isCountPending = true } + + _ = fixture.coordinator.tabExecution.claim(tab.id) + + #expect(fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A count the user asked for stays") + func exactCountStays() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isCountingExact = true } + + #expect(fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A table loading more rows stays") + func loadMoreStays() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isLoadingMore = true } + + #expect(fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A running query stays") + func runningQueryStays() { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(queryTab()) + + _ = fixture.coordinator.tabExecution.claim(tab.id) + + #expect(fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("An idle tab holds nothing back") + func idleTabCanMove() { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(queryTab()) + + #expect(!fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("A count the user started on a table that never loaded stays") + func exactCountOnAnUnloadedTableStays() { + let fixture = CoordinatorFixture() + var tab = tableTab() + tab.pagination.isCountingExact = true + fixture.addTab(tab) + + #expect(fixture.coordinator.holdsWorkThatCannotMove(tab)) + } + + @Test("Abandoning a first load frees the tab and discards the late result") + func abandonedFirstLoadFreesTheTab() throws { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(tableTab()) + let claim = fixture.coordinator.tabExecution.claim(tab.id) + fixture.tabManager.mutate(tabId: tab.id) { $0.pagination.isLoading = true } + + let rowsLanded = fixture.coordinator.abandonAutomaticTableReads(of: tab.id) + + #expect(!rowsLanded) + #expect(!fixture.coordinator.tabExecution.isBusy(tab.id)) + let moved = try #require(fixture.tabManager.tabs.first { $0.id == tab.id }) + #expect(!moved.pagination.isBusy) + #expect(fixture.coordinator.canAutoLoadTableTab(moved)) + let applied = fixture.coordinator.tabExecution.settle(claim) + #expect(!applied) + } + + @Test("A table moved before its keys and count arrive keeps its rows and asks for the rest") + func abandonedPhaseTwoKeepsTheRows() throws { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isCountPending = true } + + let rowsLanded = fixture.coordinator.abandonAutomaticTableReads(of: tab.id) + + #expect(rowsLanded) + let moved = try #require(fixture.tabManager.tabs.first { $0.id == tab.id }) + #expect(!moved.pagination.isBusy) + #expect(!fixture.coordinator.canAutoLoadTableTab(moved)) + #expect(fixture.coordinator.tabSessionRegistry.tableRows(for: tab.id).rows.count == 3) + } + + @Test("The destination marks the total pending while it fetches the keys and count") + func resumeMarksTheCountPending() throws { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { _ in } + + fixture.coordinator.resumeTableMetadataAndCount(of: tab) + + let resumed = try #require(fixture.tabManager.tabs.first { $0.id == tab.id }) + #expect(resumed.pagination.isCountPending) + } + + @Test("A settled table has nothing to give up") + func settledTableGivesUpNothing() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { _ in } + + let rowsLanded = fixture.coordinator.abandonAutomaticTableReads(of: tab.id) + + #expect(!rowsLanded) + } + + @Test("A reload is never abandoned") + func abandonLeavesAReloadRunning() { + let fixture = CoordinatorFixture() + let tab = loadedTableTab(in: fixture) { $0.isCountPending = true } + let claim = fixture.coordinator.tabExecution.claim(tab.id) + + let rowsLanded = fixture.coordinator.abandonAutomaticTableReads(of: tab.id) + + #expect(!rowsLanded) + #expect(fixture.coordinator.tabExecution.isCurrent(claim)) + } + + @Test("A running query is never abandoned") + func abandonLeavesAQueryRunning() { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(queryTab()) + let claim = fixture.coordinator.tabExecution.claim(tab.id) + + let rowsLanded = fixture.coordinator.abandonAutomaticTableReads(of: tab.id) + + #expect(!rowsLanded) + #expect(fixture.coordinator.tabExecution.isCurrent(claim)) + } +} diff --git a/apple/TableProUITests/EditorTabDetachUITests.swift b/apple/TableProUITests/EditorTabDetachUITests.swift index f111d3d6dd..75c0cf1457 100644 --- a/apple/TableProUITests/EditorTabDetachUITests.swift +++ b/apple/TableProUITests/EditorTabDetachUITests.swift @@ -16,14 +16,21 @@ final class EditorTabDetachUITests: UITestCase { let dragged = editorTabs(titled: "genre", in: window).firstMatch XCTAssertTrue(waitUntilHittable(dragged, timeout: 20), "The dragged tab must be hittable") - dragged.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - .click(forDuration: 0.02, thenDragTo: window.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6))) + // Fast enough to land while the table the press opened is still loading. + dragged.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click( + forDuration: 0.02, + thenDragTo: window.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.6)), + withVelocity: XCUIGestureVelocity(rawValue: 6_000), + thenHoldForDuration: 0 + ) let windows = app.children(matching: .window) XCTAssertTrue(waitForPredicate(timeout: 20) { windows.count == 2 }, "The drop must open a second window") + let detached = windows.matching(NSPredicate(format: "title CONTAINS %@", "genre")).firstMatch + XCTAssertTrue(detached.waitToExist(timeout: 20), "A window must be titled for the dragged tab") XCTAssertTrue( - windows.matching(NSPredicate(format: "title CONTAINS %@", "genre")).firstMatch.waitToExist(timeout: 20), - "A window must be titled for the dragged tab" + gridCell(showing: "Rock", in: dataGrid(in: detached)).waitToExist(timeout: 20), + "The new window must load the table the drop interrupted" ) }