From 49f909c1a261054a9b82d54262a8a75849fcb225 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:10:55 +0700 Subject: [PATCH 1/5] perf(welcome): own the toolbar and search in AppKit --- .../ViewModels/WelcomeViewModel.swift | 62 ++- .../IntegrationsActivityLogPane.swift | 2 +- .../Views/Welcome/WelcomeLibraryPane.swift | 133 +----- .../Welcome/WelcomeSplitViewController.swift | 56 ++- .../Views/Welcome/WelcomeTagFilterBar.swift | 177 ++++++++ .../Views/Welcome/WelcomeToolbar.swift | 332 ++++++++++++++ .../Welcome/WelcomeWindowController.swift | 31 +- .../ViewModels/WelcomeViewModelTests.swift | 12 +- .../Views/Welcome/WelcomeToolbarTests.swift | 417 +++++++++++++++--- .../WelcomeConnectionListUITests.swift | 42 ++ 10 files changed, 1011 insertions(+), 253 deletions(-) create mode 100644 apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift create mode 100644 apple/TablePro/Views/Welcome/WelcomeToolbar.swift diff --git a/apple/TablePro/ViewModels/WelcomeViewModel.swift b/apple/TablePro/ViewModels/WelcomeViewModel.swift index febdf34864..42a3b88144 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel.swift @@ -16,10 +16,14 @@ internal struct WelcomeNewGroupRequest: Hashable { internal let movingConnectionIds: [UUID] } -internal struct WelcomeTagToken: Identifiable, Hashable { - internal let id: UUID - internal let name: String - internal let color: ConnectionColor +internal struct WelcomeTagFilter: Equatable { + // In the order they were turned on; a tag missing from storage still filters but has nothing to show. + internal var tags: [ConnectionTag] = [] + internal var tagCount = 0 + internal var match: LibraryTagMatch = .any + + internal var isActive: Bool { tagCount > 0 } + internal var offersMatch: Bool { tagCount > 1 } } enum WelcomeActiveSheet: Identifiable { @@ -95,12 +99,13 @@ final class WelcomeViewModel: ObservableObject { // MARK: - Query @Published var searchText = "" { didSet { scheduleRebuild(previous: oldValue) } } - @Published var searchTokens: [WelcomeTagToken] = [] { - didSet { if searchTokens != oldValue { rebuildOutline() } } + @Published var tagFilterIds: [UUID] = [] { + didSet { if tagFilterIds != oldValue { rebuildOutline() } } } @Published var tagMatch: LibraryTagMatch = .any { didSet { if tagMatch != oldValue { rebuildOutline() } } } + @Published private(set) var tagFilter = WelcomeTagFilter() // MARK: - Outline @@ -206,17 +211,34 @@ final class WelcomeViewModel: ObservableObject { return tags.filter { usedIds.contains($0.id) } } - var suggestedTokens: [WelcomeTagToken] { - let chosen = Set(searchTokens.map(\.id)) - return availableTags.filter { !chosen.contains($0.id) }.map(Self.token(for:)) + func tagSuggestions(matching text: String) -> [ConnectionTag] { + let term = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !term.isEmpty else { return [] } + let active = Set(tagFilterIds) + return availableTags.filter { !active.contains($0.id) && $0.name.localizedCaseInsensitiveContains(term) } } - static func token(for tag: ConnectionTag) -> WelcomeTagToken { - WelcomeTagToken(id: tag.id, name: tag.name, color: tag.color) + func setTagFilter(_ tagId: UUID, isOn: Bool) { + if isOn { + guard !tagFilterIds.contains(tagId) else { return } + tagFilterIds.append(tagId) + } else { + tagFilterIds.removeAll { $0 == tagId } + } + } + + // The typed text only led to the tag, so it goes once the tag filters instead. + func applyTagSuggestion(_ tagId: UUID) { + searchText = "" + setTagFilter(tagId, isOn: true) + } + + func clearTagFilters() { + tagFilterIds.removeAll() } var query: LibraryQuery { - LibraryQuery(text: searchText, tagIds: Set(searchTokens.map(\.id)), tagMatch: tagMatch) + LibraryQuery(text: searchText, tagIds: Set(tagFilterIds), tagMatch: tagMatch) } var isFiltering: Bool { @@ -257,7 +279,7 @@ final class WelcomeViewModel: ObservableObject { hasAnyConnection: hasAnyConnection, hasVisibleContent: !outline.isEmpty, searchText: query.trimmedText, - isTagFiltered: !searchTokens.isEmpty + isTagFiltered: !tagFilterIds.isEmpty )) } @@ -286,6 +308,14 @@ final class WelcomeViewModel: ObservableObject { groupConnectionCounts = Self.groupCounts(in: outline) let visible = visibleRowIds() selection = selection.filter { visible.contains($0) } + let filter = WelcomeTagFilter( + tags: tagFilterIds.compactMap { tagsById[$0] }, + tagCount: tagFilterIds.count, + match: tagMatch + ) + if filter != tagFilter { + tagFilter = filter + } outlineRevision += 1 } @@ -350,9 +380,9 @@ final class WelcomeViewModel: ObservableObject { return false } let usedTagIds = Set(connections.flatMap(\.tagIds)) - let keptTokens = searchTokens.filter { usedTagIds.contains($0.id) } - guard keptTokens.count == searchTokens.count else { - searchTokens = keptTokens + let keptTagIds = tagFilterIds.filter { usedTagIds.contains($0) } + guard keptTagIds.count == tagFilterIds.count else { + tagFilterIds = keptTagIds return false } return true diff --git a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift index 427480ed39..6d4f0d08af 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift @@ -133,7 +133,7 @@ struct IntegrationsActivityLogPane: View { } label: { Label(String(localized: "Filters"), systemImage: ToolbarSymbols.filter(isActive: hasActiveFilters)) } - // A toolbar-hosted Menu otherwise publishes "chevron.pulldown" from its label (see WelcomeViewOptionsMenu). + // A toolbar-hosted Menu otherwise publishes "chevron.pulldown" from its label. .accessibilityLabel(String(localized: "Filters")) .help(String(localized: "Filter activity")) } diff --git a/apple/TablePro/Views/Welcome/WelcomeLibraryPane.swift b/apple/TablePro/Views/Welcome/WelcomeLibraryPane.swift index c1cf09d6ec..9110cae2f3 100644 --- a/apple/TablePro/Views/Welcome/WelcomeLibraryPane.swift +++ b/apple/TablePro/Views/Welcome/WelcomeLibraryPane.swift @@ -3,44 +3,21 @@ // TablePro // -import AppKit import SwiftUI -import TableProConnectionLibrary +// No `.toolbar` or `.searchable` here: bridged into the window they cost the first frame about 100 ms. internal struct WelcomeLibraryPane: View { @ObservedObject var viewModel: WelcomeViewModel var body: some View { content .frame(maxWidth: .infinity, maxHeight: .infinity) - .searchable( - text: $viewModel.searchText, - tokens: $viewModel.searchTokens, - suggestedTokens: suggestedTokens, - placement: .toolbar, - prompt: Text("Search Connections") - ) { token in - Label(token.name, systemImage: "tag") - } - .onSubmit(of: .search) { - viewModel.focusList(selectFirstRow: true) - } - .toolbar { - WelcomeLibraryToolbar(viewModel: viewModel) - } .onAppear { viewModel.setUp() } .modifier(WelcomePresentations(vm: viewModel) { viewModel.focusList() }) } - private var suggestedTokens: Binding<[WelcomeTagToken]> { - Binding( - get: { viewModel.suggestedTokens }, - set: { _ in } - ) - } - @ViewBuilder private var content: some View { switch viewModel.listState { @@ -64,114 +41,8 @@ internal struct WelcomeLibraryPane: View { title: String(localized: "No Matching Connections"), description: String(localized: "No connections have the selected tags."), actionTitle: String(localized: "Clear Filters"), - action: { viewModel.searchTokens.removeAll() } + action: { viewModel.clearTagFilters() } ) } } } - -internal struct WelcomeLibraryToolbar: ToolbarContent { - let viewModel: WelcomeViewModel - - var body: some ToolbarContent { - ToolbarItemGroup(placement: .primaryAction) { - Button { - WindowOpener.shared.openConnectionForm() - } label: { - Label(String(localized: "New Connection"), systemImage: "plus") - } - .help(newConnectionHelp) - .accessibilityIdentifier("welcome-toolbar-new-connection") - - Button { - viewModel.requestNewGroup(parentId: nil, movingConnectionIds: []) - } label: { - Label(String(localized: "New Group"), systemImage: "folder.badge.plus") - } - .help(String(localized: "New Group")) - .accessibilityIdentifier("welcome-toolbar-new-group") - - WelcomeViewOptionsMenu(viewModel: viewModel) - } - } - - private var newConnectionHelp: String { - let binding = AppSettingsManager.shared.keyboard.shortcut(for: .newConnection) - guard let displayString = binding?.displayString, !displayString.isEmpty else { - return String(localized: "New Connection") - } - return String(format: String(localized: "New Connection (%@)"), displayString) - } -} - -internal struct WelcomeViewOptionsMenu: View { - @ObservedObject var viewModel: WelcomeViewModel - - var body: some View { - Menu { - Picker(String(localized: "Sort By"), selection: sortSelection) { - ForEach(WelcomeSortOption.allCases, id: \.self) { option in - Text(option.title).tag(option.mode) - } - } - .pickerStyle(.menu) - - if !viewModel.availableTags.isEmpty { - Section(String(localized: "Filter by Tag")) { - ForEach(viewModel.availableTags) { tag in - Toggle(isOn: tokenBinding(for: tag)) { - Label { - Text(tag.name) - } icon: { - Image(nsImage: ConnectionLibrarySymbols.tagImage(for: tag.color) ?? NSImage()) - } - } - } - } - - if viewModel.searchTokens.count > 1 { - Picker(String(localized: "Match"), selection: $viewModel.tagMatch) { - Text("Any Selected Tag").tag(LibraryTagMatch.any) - Text("All Selected Tags").tag(LibraryTagMatch.all) - } - .pickerStyle(.inline) - } - - if !viewModel.searchTokens.isEmpty { - Button(String(localized: "Clear Filters")) { - viewModel.searchTokens.removeAll() - } - } - } - } label: { - Label(String(localized: "View Options"), systemImage: ToolbarSymbols.filter()) - } - /// A toolbar-hosted `Menu` is named by this modifier and not by its label: built against - /// the macOS 26 SDK, the label alone publishes "chevron.pulldown". An in-view `Menu` is the - /// reverse. - .accessibilityLabel(String(localized: "View Options")) - .help(String(localized: "Sort and filter connections")) - .accessibilityIdentifier("welcome-toolbar-view-options") - } - - private var sortSelection: Binding { - Binding( - get: { viewModel.sortMode }, - set: { viewModel.setSortMode($0) } - ) - } - - private func tokenBinding(for tag: ConnectionTag) -> Binding { - Binding( - get: { viewModel.searchTokens.contains { $0.id == tag.id } }, - set: { isOn in - if isOn { - guard !viewModel.searchTokens.contains(where: { $0.id == tag.id }) else { return } - viewModel.searchTokens.append(WelcomeViewModel.token(for: tag)) - } else { - viewModel.searchTokens.removeAll { $0.id == tag.id } - } - } - ) - } -} diff --git a/apple/TablePro/Views/Welcome/WelcomeSplitViewController.swift b/apple/TablePro/Views/Welcome/WelcomeSplitViewController.swift index 8337ef5da6..e95857503c 100644 --- a/apple/TablePro/Views/Welcome/WelcomeSplitViewController.swift +++ b/apple/TablePro/Views/Welcome/WelcomeSplitViewController.swift @@ -4,6 +4,7 @@ // import AppKit +import Combine import SwiftUI @MainActor @@ -12,6 +13,10 @@ internal final class WelcomeSplitViewController: NSSplitViewController { internal static let listMinimumWidth: CGFloat = 460 private let viewModel: WelcomeViewModel + private var listItem: NSSplitViewItem? + private var listPane: WelcomeListPaneController? + private(set) var tagFilterBar: WelcomeTagFilterBar? + private var tagFilterCancellable: AnyCancellable? internal init(viewModel: WelcomeViewModel) { self.viewModel = viewModel @@ -39,15 +44,54 @@ internal final class WelcomeSplitViewController: NSSplitViewController { .environment(\.appServices, .live) ) list.sizingOptions = [] - /// `sceneBridgingOptions` is macOS 14. It lets the hosted SwiftUI tree contribute toolbar - /// items to the window; on 13 the pane simply contributes none, and the window keeps the - /// toolbar the controller builds itself. - if #available(macOS 14.0, *) { - list.sceneBridgingOptions = [.toolbars] + let listItem: NSSplitViewItem + if #available(macOS 26.0, *) { + listItem = NSSplitViewItem(viewController: list) + } else { + let pane = WelcomeListPaneController(content: list) + listPane = pane + listItem = NSSplitViewItem(viewController: pane) } - let listItem = NSSplitViewItem(viewController: list) listItem.minimumThickness = Self.listMinimumWidth addSplitViewItem(listItem) + self.listItem = listItem + + tagFilterCancellable = viewModel.$tagFilter.sink { [weak self] filter in + self?.showTagFilter(filter) + } + } + + // Built when the first tag turns on, so the first frame never pays for it. + private func showTagFilter(_ filter: WelcomeTagFilter) { + guard filter.isActive else { + hideTagFilterBar() + return + } + if let tagFilterBar { + tagFilterBar.apply(filter) + return + } + let bar = WelcomeTagFilterBar(viewModel: viewModel) + bar.apply(filter) + tagFilterBar = bar + if #available(macOS 26.0, *) { + let accessory = NSSplitViewItemAccessoryViewController() + accessory.view = bar + listItem?.addTopAlignedAccessoryViewController(accessory) + } else { + listPane?.showBar(bar) + } + } + + private func hideTagFilterBar() { + guard tagFilterBar != nil else { return } + tagFilterBar = nil + if #available(macOS 26.0, *) { + guard let listItem, !listItem.topAlignedAccessoryViewControllers.isEmpty else { return } + listItem.removeTopAlignedAccessoryViewController(at: 0) + } else { + listPane?.showBar(nil) + } } } diff --git a/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift new file mode 100644 index 0000000000..a331d377d6 --- /dev/null +++ b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift @@ -0,0 +1,177 @@ +// +// WelcomeTagFilterBar.swift +// TablePro +// + +import AppKit +import TableProConnectionLibrary + +// The scope bar idiom of Finder's search and Mail's filter: AppKit has no public API for tokens +// in a search field, so the active tag filters sit above the list, one toggle per tag. +@MainActor +internal final class WelcomeTagFilterBar: NSView { + private let viewModel: WelcomeViewModel + private let stack = NSStackView() + private var tagIdsByButton: [ObjectIdentifier: UUID] = [:] + private(set) var tagButtons: [NSButton] = [] + private(set) var matchPopUp: NSPopUpButton? + private(set) lazy var clearButton: NSButton = { + let button = NSButton( + title: String(localized: "Clear Filters"), + target: self, + action: #selector(clearTagFilters(_:)) + ) + button.bezelStyle = .accessoryBarAction + return button + }() + + internal init(viewModel: WelcomeViewModel) { + self.viewModel = viewModel + super.init(frame: .zero) + stack.orientation = .horizontal + stack.alignment = .centerY + stack.spacing = 8 + stack.edgeInsets = NSEdgeInsets(top: 6, left: 12, bottom: 6, right: 12) + // Many active tags shrink their buttons rather than widen the fixed-size window. + stack.setClippingResistancePriority(.defaultLow, for: .horizontal) + stack.translatesAutoresizingMaskIntoConstraints = false + addSubview(stack) + NSLayoutConstraint.activate([ + stack.leadingAnchor.constraint(equalTo: leadingAnchor), + stack.trailingAnchor.constraint(equalTo: trailingAnchor), + stack.topAnchor.constraint(equalTo: topAnchor), + stack.bottomAnchor.constraint(equalTo: bottomAnchor), + ]) + setAccessibilityElement(true) + setAccessibilityRole(.group) + setAccessibilityLabel(String(localized: "Tag Filters")) + setAccessibilityIdentifier("welcome-tag-filter-bar") + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("WelcomeTagFilterBar does not support NSCoder init") + } + + internal func apply(_ filter: WelcomeTagFilter) { + tagIdsByButton = [:] + tagButtons = filter.tags.map(makeTagButton) + var leading: [NSView] = tagButtons + if filter.offersMatch { + let popUp = matchPopUp ?? makeMatchPopUp() + popUp.selectItem(at: LibraryTagMatch.allCases.firstIndex(of: filter.match) ?? 0) + matchPopUp = popUp + leading.append(popUp) + } else { + matchPopUp = nil + } + stack.setViews(leading, in: .leading) + stack.setViews([clearButton], in: .trailing) + } + + private func makeTagButton(_ tag: ConnectionTag) -> NSButton { + // A template glyph takes the selected content color on the button's accent fill. + let glyph = NSImage(systemSymbolName: "tag.fill", accessibilityDescription: nil) ?? NSImage() + let button = NSButton(title: tag.name, image: glyph, target: self, action: #selector(removeTag(_:))) + button.bezelStyle = .accessoryBar + button.setButtonType(.pushOnPushOff) + button.state = .on + button.imagePosition = .imageLeading + button.lineBreakMode = .byTruncatingTail + button.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + button.toolTip = String(format: String(localized: "Stop filtering by %@"), tag.name) + tagIdsByButton[ObjectIdentifier(button)] = tag.id + return button + } + + private func makeMatchPopUp() -> NSPopUpButton { + let popUp = NSPopUpButton(frame: .zero, pullsDown: false) + popUp.bezelStyle = .accessoryBarAction + for match in LibraryTagMatch.allCases { + popUp.addItem(withTitle: WelcomeToolbarController.title(for: match)) + popUp.lastItem?.representedObject = match + } + popUp.target = self + popUp.action = #selector(matchChanged(_:)) + popUp.setAccessibilityLabel(String(localized: "Match")) + return popUp + } + + @objc private func removeTag(_ sender: NSButton) { + guard let tagId = tagIdsByButton[ObjectIdentifier(sender)] else { return } + viewModel.setTagFilter(tagId, isOn: false) + } + + @objc private func matchChanged(_ sender: NSPopUpButton) { + guard let match = sender.selectedItem?.representedObject as? LibraryTagMatch else { return } + viewModel.tagMatch = match + } + + @objc private func clearTagFilters(_ sender: Any?) { + viewModel.clearTagFilters() + } +} + +// Before macOS 26 a split item has no accessory slot, so the bar sits at the top of the list pane +// under the toolbar, with a separator, where Mail put its filter bar. +@MainActor +internal final class WelcomeListPaneController: NSViewController { + private let content: NSViewController + private var barContainer: NSView? + private var contentTop: NSLayoutConstraint? + + internal init(content: NSViewController) { + self.content = content + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("WelcomeListPaneController does not support NSCoder init") + } + + override internal func loadView() { + let root = NSView() + addChild(content) + let contentView = content.view + contentView.translatesAutoresizingMaskIntoConstraints = false + root.addSubview(contentView) + let top = contentView.topAnchor.constraint(equalTo: root.topAnchor) + NSLayoutConstraint.activate([ + top, + contentView.leadingAnchor.constraint(equalTo: root.leadingAnchor), + contentView.trailingAnchor.constraint(equalTo: root.trailingAnchor), + contentView.bottomAnchor.constraint(equalTo: root.bottomAnchor), + ]) + contentTop = top + view = root + } + + internal func showBar(_ bar: NSView?) { + barContainer?.removeFromSuperview() + barContainer = nil + contentTop?.isActive = false + guard let bar else { + contentTop = content.view.topAnchor.constraint(equalTo: view.topAnchor) + contentTop?.isActive = true + return + } + let separator = NSBox() + separator.boxType = .separator + let container = NSStackView(views: [bar, separator]) + container.orientation = .vertical + container.spacing = 0 + container.alignment = .width + container.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(container) + let top = content.view.topAnchor.constraint(equalTo: container.bottomAnchor) + NSLayoutConstraint.activate([ + container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + container.leadingAnchor.constraint(equalTo: view.leadingAnchor), + container.trailingAnchor.constraint(equalTo: view.trailingAnchor), + top, + ]) + barContainer = container + contentTop = top + } +} diff --git a/apple/TablePro/Views/Welcome/WelcomeToolbar.swift b/apple/TablePro/Views/Welcome/WelcomeToolbar.swift new file mode 100644 index 0000000000..fd22035747 --- /dev/null +++ b/apple/TablePro/Views/Welcome/WelcomeToolbar.swift @@ -0,0 +1,332 @@ +// +// WelcomeToolbar.swift +// TablePro +// + +import AppKit +import Combine +import TableProConnectionLibrary + +extension NSToolbarItem.Identifier { + static let welcomeNewConnection = NSToolbarItem.Identifier("welcome-toolbar-new-connection") + static let welcomeNewGroup = NSToolbarItem.Identifier("welcome-toolbar-new-group") + static let welcomeViewOptions = NSToolbarItem.Identifier("welcome-toolbar-view-options") + static let welcomeSearch = NSToolbarItem.Identifier("welcome-toolbar-search") +} + +// AppKit on purpose: SwiftUI's bridged toolbar and `.searchable` cost the Welcome window's first +// frame about 100 ms of main-thread time, more than anything else in it. +@MainActor +internal final class WelcomeToolbarController: NSObject, NSToolbarDelegate, NSSearchFieldDelegate, NSMenuDelegate { + internal static let toolbarIdentifier = NSToolbar.Identifier("com.TablePro.welcome.toolbar") + + private let viewModel: WelcomeViewModel + private weak var newConnectionItem: NSToolbarItem? + private weak var viewOptionsItem: NSMenuToolbarItem? + private(set) weak var searchItem: NSSearchToolbarItem? + private(set) var viewOptionsSymbol = ToolbarSymbols.filter() + // `suggestionsDelegate` is weak. + private var tagSuggestions: AnyObject? + private var cancellables: Set = [] + + internal init(viewModel: WelcomeViewModel) { + self.viewModel = viewModel + super.init() + } + + internal func install(in window: NSWindow) { + let toolbar = NSToolbar(identifier: Self.toolbarIdentifier) + toolbar.delegate = self + toolbar.displayMode = .iconOnly + toolbar.allowsUserCustomization = false + toolbar.autosavesConfiguration = false + if #available(macOS 15.0, *) { + toolbar.allowsDisplayModeCustomization = false + } + window.toolbar = toolbar + window.toolbarStyle = .unified + observeViewModel() + } + + internal func beginSearch() { + searchItem?.beginSearchInteraction() + } + + private func observeViewModel() { + viewModel.$searchText + .sink { [weak self] text in + guard let field = self?.searchItem?.searchField, field.stringValue != text else { return } + field.stringValue = text + } + .store(in: &cancellables) + + viewModel.$tagFilter + .map(\.isActive) + .removeDuplicates() + .sink { [weak self] isActive in + self?.showViewOptionsSymbol(ToolbarSymbols.filter(isActive: isActive)) + } + .store(in: &cancellables) + + // The hop off the settings write keeps the item from changing part way through it. + viewModel.services.appEvents.keyboardSettingsChanged + .receive(on: RunLoop.main) + .sink { [weak self] in + guard let self else { return } + newConnectionItem?.toolTip = Self.newConnectionToolTip + } + .store(in: &cancellables) + } + + // MARK: - NSToolbarDelegate + + internal func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [.sidebarTrackingSeparator, .welcomeNewConnection, .welcomeNewGroup, .welcomeViewOptions, .flexibleSpace, .welcomeSearch] + } + + internal func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + toolbarDefaultItemIdentifiers(toolbar) + } + + internal func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + switch itemIdentifier { + case .welcomeNewConnection: + let item = makeButton( + itemIdentifier, + label: String(localized: "New Connection"), + symbol: "plus", + action: #selector(newConnection(_:)) + ) + item.toolTip = Self.newConnectionToolTip + newConnectionItem = item + return item + case .welcomeNewGroup: + return makeButton( + itemIdentifier, + label: String(localized: "New Group"), + symbol: "folder.badge.plus", + action: #selector(newGroup(_:)) + ) + case .welcomeViewOptions: + return makeViewOptionsItem(itemIdentifier) + case .welcomeSearch: + return makeSearchItem(itemIdentifier) + default: + return nil + } + } + + private static var newConnectionToolTip: String { + AppSettingsManager.shared.keyboard.shortcutHint(String(localized: "New Connection"), for: .newConnection) + } + + private func makeButton( + _ identifier: NSToolbarItem.Identifier, + label: String, + symbol: String, + action: Selector + ) -> NSToolbarItem { + let item = NSToolbarItem(itemIdentifier: identifier) + item.label = label + item.paletteLabel = label + item.toolTip = label + item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label) + item.isBordered = true + item.target = self + item.action = action + return item + } + + private func makeViewOptionsItem(_ identifier: NSToolbarItem.Identifier) -> NSToolbarItem { + let item = NSMenuToolbarItem(itemIdentifier: identifier) + let label = String(localized: "View Options") + item.label = label + item.paletteLabel = label + item.toolTip = String(localized: "Sort and filter connections") + item.image = NSImage(systemSymbolName: viewOptionsSymbol, accessibilityDescription: label) + item.showsIndicator = true + let menu = NSMenu(title: label) + menu.delegate = self + item.menu = menu + viewOptionsItem = item + return item + } + + private func makeSearchItem(_ identifier: NSToolbarItem.Identifier) -> NSToolbarItem { + let item = NSSearchToolbarItem(itemIdentifier: identifier) + item.label = String(localized: "Search") + item.paletteLabel = String(localized: "Search") + let field = item.searchField + field.placeholderString = String(localized: "Search Connections") + // The view model debounces, as it did for `.searchable`, so every keystroke goes through. + field.sendsSearchStringImmediately = true + field.sendsWholeSearchString = false + field.stringValue = viewModel.searchText + field.delegate = self + field.target = self + field.action = #selector(searchFieldChanged(_:)) + field.setAccessibilityIdentifier("welcome-toolbar-search") + if #available(macOS 15.0, *) { + let suggestions = WelcomeTagSuggestions(viewModel: viewModel) + field.suggestionsDelegate = suggestions + tagSuggestions = suggestions + } + searchItem = item + return item + } + + private func showViewOptionsSymbol(_ symbol: String) { + guard symbol != viewOptionsSymbol else { return } + viewOptionsSymbol = symbol + viewOptionsItem?.image = NSImage( + systemSymbolName: symbol, + accessibilityDescription: String(localized: "View Options") + ) + } + + // MARK: - Actions + + @objc private func newConnection(_ sender: Any?) { + WindowOpener.shared.openConnectionForm() + } + + @objc private func newGroup(_ sender: Any?) { + viewModel.requestNewGroup(parentId: nil, movingConnectionIds: []) + } + + @objc private func searchFieldChanged(_ sender: NSSearchField) { + viewModel.searchText = sender.stringValue + } + + @objc private func sortBy(_ sender: NSMenuItem) { + guard let mode = sender.representedObject as? LibrarySortMode else { return } + viewModel.setSortMode(mode) + } + + @objc private func toggleTagFilter(_ sender: NSMenuItem) { + guard let tagId = sender.representedObject as? UUID else { return } + viewModel.setTagFilter(tagId, isOn: sender.state != .on) + } + + @objc private func matchTags(_ sender: NSMenuItem) { + guard let match = sender.representedObject as? LibraryTagMatch else { return } + viewModel.tagMatch = match + } + + @objc private func clearTagFilters(_ sender: Any?) { + viewModel.clearTagFilters() + } + + // MARK: - NSSearchFieldDelegate + + internal func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { + guard commandSelector == #selector(NSResponder.insertNewline(_:)) else { return false } + viewModel.focusList(selectFirstRow: true) + return true + } + + // MARK: - NSMenuDelegate + + internal func menuNeedsUpdate(_ menu: NSMenu) { + menu.removeAllItems() + menu.addItem(.sectionHeaderCompat(title: String(localized: "Sort By"))) + for option in WelcomeSortOption.allCases { + menu.addItem(menuEntry( + option.title, + action: #selector(sortBy(_:)), + value: option.mode, + isOn: option.mode == viewModel.sortMode + )) + } + + let tags = viewModel.availableTags + guard !tags.isEmpty else { return } + let activeIds = Set(viewModel.tagFilterIds) + menu.addItem(.separator()) + menu.addItem(.sectionHeaderCompat(title: String(localized: "Filter by Tag"))) + for tag in tags { + let entry = menuEntry( + tag.name, + action: #selector(toggleTagFilter(_:)), + value: tag.id, + isOn: activeIds.contains(tag.id) + ) + entry.image = ConnectionLibrarySymbols.tagImage(for: tag.color) + menu.addItem(entry) + } + + let filter = viewModel.tagFilter + if filter.offersMatch { + menu.addItem(.separator()) + menu.addItem(.sectionHeaderCompat(title: String(localized: "Match"))) + for match in LibraryTagMatch.allCases { + menu.addItem(menuEntry( + Self.title(for: match), + action: #selector(matchTags(_:)), + value: match, + isOn: match == filter.match + )) + } + } + if filter.isActive { + menu.addItem(.separator()) + menu.addItem(menuEntry(String(localized: "Clear Filters"), action: #selector(clearTagFilters(_:)), value: nil, isOn: false)) + } + } + + internal static func title(for match: LibraryTagMatch) -> String { + switch match { + case .any: return String(localized: "Any Selected Tag") + case .all: return String(localized: "All Selected Tags") + } + } + + private func menuEntry(_ title: String, action: Selector, value: Any?, isOn: Bool) -> NSMenuItem { + let entry = NSMenuItem(title: title, action: action, keyEquivalent: "") + entry.target = self + entry.representedObject = value + entry.state = isOn ? .on : .off + return entry + } +} + +// Picking a tag while typing is the one way to reach a tag filter without opening View Options. +@available(macOS 15.0, *) +@MainActor +internal final class WelcomeTagSuggestions: NSTextSuggestionsDelegate { + internal typealias SuggestionItemType = UUID + + private weak var viewModel: WelcomeViewModel? + + internal init(viewModel: WelcomeViewModel) { + self.viewModel = viewModel + } + + internal func suggestions(for text: String) -> ItemResponse { + let tags = viewModel?.tagSuggestions(matching: text) ?? [] + guard !tags.isEmpty else { return ItemResponse() } + let items = tags.map { tag -> Item in + var item = Item(representedValue: tag.id, title: tag.name) + item.image = ConnectionLibrarySymbols.tagImage(for: tag.color) + return item + } + return ItemResponse(itemSections: [ItemSection(title: String(localized: "Tags"), items: items)]) + } + + internal func textField(_ textField: NSTextField, provideUpdatedSuggestions responseHandler: @escaping (ItemResponse) -> Void) { + responseHandler(suggestions(for: textField.stringValue)) + } + + // A tag name typed into the field would filter by text as well as by the tag. + internal func textField(_ textField: NSTextField, textCompletionFor item: Item) -> String? { + nil + } + + internal func textField(_ textField: NSTextField, didSelect item: Item) { + viewModel?.applyTagSuggestion(item.representedValue) + } +} diff --git a/apple/TablePro/Views/Welcome/WelcomeWindowController.swift b/apple/TablePro/Views/Welcome/WelcomeWindowController.swift index 4850ce47cd..df3c55f971 100644 --- a/apple/TablePro/Views/Welcome/WelcomeWindowController.swift +++ b/apple/TablePro/Views/Welcome/WelcomeWindowController.swift @@ -4,28 +4,8 @@ // import AppKit -import SwiftUI import TableProConnectionLibrary -@MainActor -private final class WelcomeWindow: NSWindow { - override var toolbar: NSToolbar? { - didSet { - guard let toolbar else { return } - Self.fixAtIconOnly(toolbar) - } - } - - private static func fixAtIconOnly(_ toolbar: NSToolbar) { - toolbar.displayMode = .iconOnly - toolbar.allowsUserCustomization = false - toolbar.autosavesConfiguration = false - if #available(macOS 15.0, *) { - toolbar.allowsDisplayModeCustomization = false - } - } -} - @MainActor internal final class WelcomeWindowController: NSWindowController, NSWindowDelegate { internal static let contentSize = NSSize(width: 900, height: 600) @@ -37,6 +17,7 @@ internal final class WelcomeWindowController: NSWindowController, NSWindowDelega private static var shared: WelcomeWindowController? private let viewModel: WelcomeViewModel + private let toolbarController: WelcomeToolbarController internal static func present() { let controller = shared ?? WelcomeWindowController(viewModel: WelcomeViewModel()) @@ -50,7 +31,7 @@ internal final class WelcomeWindowController: NSWindowController, NSWindowDelega } internal static func makeWelcomeWindow() -> NSWindow { - let window = WelcomeWindow( + let window = NSWindow( contentRect: NSRect(origin: .zero, size: Self.contentSize), styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], backing: .buffered, @@ -64,14 +45,15 @@ internal final class WelcomeWindowController: NSWindowController, NSWindowDelega window.isRestorable = false window.tabbingMode = .disallowed window.collectionBehavior.insert([.fullScreenNone, .fullScreenDisallowsTiling]) - window.toolbar = NSToolbar(identifier: "com.TablePro.welcome.toolbar") - window.toolbarStyle = .unified return window } private init(viewModel: WelcomeViewModel) { self.viewModel = viewModel let window = Self.makeWelcomeWindow() + let toolbarController = WelcomeToolbarController(viewModel: viewModel) + toolbarController.install(in: window) + self.toolbarController = toolbarController window.contentViewController = WelcomeSplitViewController(viewModel: viewModel) window.contentMinSize = Self.contentSize window.contentMaxSize = Self.contentSize @@ -104,8 +86,7 @@ internal final class WelcomeWindowController: NSWindowController, NSWindowDelega @objc internal func performFind(_ sender: Any?) { - let searchItem = window?.toolbar?.items.compactMap { $0 as? NSSearchToolbarItem }.first - searchItem?.beginSearchInteraction() + toolbarController.beginSearch() } @objc diff --git a/apple/TableProTests/ViewModels/WelcomeViewModelTests.swift b/apple/TableProTests/ViewModels/WelcomeViewModelTests.swift index db584186bc..293c537f49 100644 --- a/apple/TableProTests/ViewModels/WelcomeViewModelTests.swift +++ b/apple/TableProTests/ViewModels/WelcomeViewModelTests.swift @@ -125,10 +125,6 @@ final class WelcomeViewModelTests { return walk(outline.section(.connections)?.nodes ?? []) } - private func token(_ id: UUID) -> WelcomeTagToken { - WelcomeTagToken(id: id, name: id.uuidString, color: .none) - } - // MARK: - Groups @Test func testCreateGroupShowsImmediatelyInTheOutline() throws { @@ -360,7 +356,7 @@ final class WelcomeViewModelTests { viewModel.loadConnections() viewModel.tagMatch = .all - viewModel.searchTokens = [token(first), token(second)] + viewModel.tagFilterIds = [first, second] #expect(viewModel.listState == .noFilterMatch) } @@ -537,19 +533,19 @@ final class WelcomeViewModelTests { #expect(viewModel.selection.isEmpty, "A row the list no longer shows must not stay selected") } - @Test func testDeletingTheLastTaggedConnectionDropsItsTokenFromTheSearch() { + @Test func testDeletingTheLastTaggedConnectionDropsItsTagFilter() { let tagId = UUID() var tagged = DatabaseConnection(name: "Prod", type: .mysql, sortOrder: 0) tagged.tagIds = [tagId] let plain = DatabaseConnection(name: "Dev", type: .mysql, sortOrder: 1) save([tagged, plain]) viewModel.loadConnections() - viewModel.searchTokens = [token(tagId)] + viewModel.tagFilterIds = [tagId] viewModel.connectionsToDelete = [tagged] viewModel.deleteSelectedConnections() - #expect(viewModel.searchTokens.isEmpty, "A token for a tag nothing carries hides every connection") + #expect(viewModel.tagFilterIds.isEmpty, "A filter on a tag nothing carries hides every connection") #expect(viewModel.outline.connectionIds(in: .connections) == [plain.id]) #expect(viewModel.listState == .content) } diff --git a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift index 58dcebf880..b94048441b 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift @@ -1,92 +1,377 @@ import AppKit -import SwiftUI +import Foundation +@testable import TablePro +import TableProConnectionLibrary +import TableProPluginKit +import TableProSyncTransport import TableProTestSupport import Testing -@testable import TablePro +@MainActor +private final class WelcomeLibraryFixture { + let viewModel: WelcomeViewModel + let tags: [ConnectionTag] + private let suite: EphemeralDefaults + private let directory: URL + + // Alpha carries "prod" and "eu-west", Beta "prod", Gamma nothing; "unused" is on no connection. + init() throws { + suite = try EphemeralDefaults() + let defaults = suite.defaults + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("welcome-toolbar-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let events = AppEvents() + let tracker = SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: defaults)) + let connectionStorage = ConnectionStorage( + fileURL: directory.appendingPathComponent("connections.json"), + userDefaults: defaults, + syncTracker: tracker + ) + let groupStorage = GroupStorage(userDefaults: defaults, syncTracker: tracker, connectionStorage: connectionStorage) + let tagStorage = TagStorage(userDefaults: defaults, syncTracker: tracker, appEvents: events) + let prod = ConnectionTag(name: "prod", color: .red) + let euWest = ConnectionTag(name: "eu-west", color: .blue) + let unused = ConnectionTag(name: "unused-prod", color: .gray) + for tag in [prod, euWest, unused] { + try tagStorage.addTag(tag) + } + tags = [prod, euWest, unused] + + var alpha = DatabaseConnection(name: "Alpha", type: .mysql, sortOrder: 0) + alpha.tagIds = [prod.id, euWest.id] + var beta = DatabaseConnection(name: "Beta", type: .postgresql, sortOrder: 1) + beta.tagIds = [prod.id] + let gamma = DatabaseConnection(name: "Gamma", type: .mysql, sortOrder: 2) + #expect(connectionStorage.saveConnections([alpha, beta, gamma])) + + let live = AppServices.live + let services = AppServices( + appEvents: events, + appSettings: live.appSettings, + appSettingsStorage: AppSettingsStorage(userDefaults: defaults), + connectionStorage: connectionStorage, + databaseManager: live.databaseManager, + pluginManager: live.pluginManager, + schemaService: live.schemaService, + schemaRefreshService: live.schemaRefreshService, + schemaProviderRegistry: live.schemaProviderRegistry, + catalogChangeService: live.catalogChangeService, + sqlFavoriteManager: live.sqlFavoriteManager, + favoriteTablesStorage: live.favoriteTablesStorage, + favoriteDatabasesStorage: live.favoriteDatabasesStorage, + tableFolderStorage: live.tableFolderStorage, + aiChatStorage: live.aiChatStorage, + aiKeyStorage: live.aiKeyStorage, + aiAccessApprovals: live.aiAccessApprovals, + groupStorage: groupStorage, + tagStorage: tagStorage, + sshProfileStorage: live.sshProfileStorage, + credentialProfileStorage: live.credentialProfileStorage, + featureAccess: live.featureAccess, + syncMetadataStorage: live.syncMetadataStorage, + favoritesExpansionState: live.favoritesExpansionState, + linkedFolderWatcher: live.linkedFolderWatcher, + queryHistoryManager: live.queryHistoryManager, + dateFormattingService: live.dateFormattingService, + copilotService: live.copilotService, + mcpServerManager: live.mcpServerManager, + syncTracker: tracker, + welcomeRouter: WelcomeRouter(), + telemetry: live.telemetry + ) + viewModel = WelcomeViewModel( + services: services, + importableAppDetector: { false }, + groupExpansionStore: WelcomeGroupExpansionStore(defaults: defaults), + recentConnections: RecentConnectionsStore(defaults: defaults, appEvents: events), + listPreferences: ConnectionListPreferences(defaults: defaults, appEvents: events), + isUITestSandbox: false + ) + viewModel.loadConnections() + } + + var prod: ConnectionTag { tags[0] } + var euWest: ConnectionTag { tags[1] } + var unused: ConnectionTag { tags[2] } + + isolated deinit { + try? FileManager.default.removeItem(at: directory) + } +} + +@MainActor +private final class RecordingOutline: WelcomeOutlineControlling { + var focusRequests: [Bool] = [] + var outlineUndoManager: UndoManager? { nil } + func beginRename(_ row: LibraryRowID) {} + func focusList(selectFirstRow: Bool) { + focusRequests.append(selectFirstRow) + } +} @MainActor struct WelcomeToolbarTests { - private func withWelcomeWindow(_ body: (NSWindow) async throws -> Void) async rethrows { - let window = WelcomeWindowController.makeWelcomeWindow() - #expect(!window.isReleasedWhenClosed) - defer { - window.contentViewController = nil - window.close() - } - try await body(window) + private let fixture: WelcomeLibraryFixture + private let window: NSWindow + private let controller: WelcomeToolbarController + + init() throws { + fixture = try WelcomeLibraryFixture() + window = WelcomeWindowController.makeWelcomeWindow() + controller = WelcomeToolbarController(viewModel: fixture.viewModel) + controller.install(in: window) + } + + private func item(_ identifier: NSToolbarItem.Identifier) throws -> NSToolbarItem { + try #require(window.toolbar?.items.first { $0.itemIdentifier == identifier }) } - private func expectFixedAtIconOnly(_ toolbar: NSToolbar?) { - #expect(toolbar?.displayMode == .iconOnly) - #expect(toolbar?.allowsUserCustomization == false) - #expect(toolbar?.autosavesConfiguration == false) + private func viewOptionsMenu() throws -> NSMenu { + let menu = try #require((try item(.welcomeViewOptions) as? NSMenuToolbarItem)?.menu) + controller.menuNeedsUpdate(menu) + return menu + } + + private func choose(_ title: String, in menu: NSMenu) throws { + let index = menu.indexOfItem(withTitle: title) + try #require(index >= 0, "View Options has no \(title)") + menu.performActionForItem(at: index) + } + + @Test("The window's toolbar is AppKit's own, fixed at Icon Only") + func toolbarIsFixedAtIconOnly() throws { + let toolbar = try #require(window.toolbar) + #expect(toolbar.identifier == WelcomeToolbarController.toolbarIdentifier) + #expect(toolbar.delegate === controller) + #expect(window.toolbarStyle == .unified) + #expect(toolbar.displayMode == .iconOnly) + #expect(!toolbar.allowsUserCustomization) + #expect(!toolbar.autosavesConfiguration) if #available(macOS 15.0, *) { - #expect(toolbar?.allowsDisplayModeCustomization == false) + #expect(!toolbar.allowsDisplayModeCustomization) } } - @Test("The welcome window's own toolbar offers no display mode choice") - func ownToolbarIsFixedAtIconOnly() async { - await withWelcomeWindow { window in - #expect(window.toolbar != nil) - #expect(window.toolbarStyle == .unified) - expectFixedAtIconOnly(window.toolbar) - } + @Test("The buttons lead the list pane and search trails it, as they did") + func itemsKeepTheirPlaces() throws { + let identifiers = try #require(window.toolbar).items.map { $0.itemIdentifier } + #expect(identifiers == [ + .sidebarTrackingSeparator, .welcomeNewConnection, .welcomeNewGroup, .welcomeViewOptions, .flexibleSpace, + .welcomeSearch, + ]) } - @Test("A toolbar installed after the window is built is fixed at Icon Only too") - func laterToolbarIsFixedAtIconOnly() async { - await withWelcomeWindow { window in - let toolbar = NSToolbar(identifier: "com.TablePro.tests.welcome.replacement") - toolbar.displayMode = .iconAndLabel - toolbar.allowsUserCustomization = true - toolbar.autosavesConfiguration = true - if #available(macOS 15.0, *) { - toolbar.allowsDisplayModeCustomization = true - } + @Test("Each item names itself, which is what VoiceOver and UI tests read") + func itemsNameThemselves() throws { + #expect(try item(.welcomeNewConnection).label == "New Connection") + #expect(try item(.welcomeNewConnection).toolTip?.hasPrefix("New Connection") == true) + #expect(try item(.welcomeNewGroup).label == "New Group") + let viewOptions = try #require(try item(.welcomeViewOptions) as? NSMenuToolbarItem) + #expect(viewOptions.label == "View Options") + #expect(viewOptions.showsIndicator) + let search = try #require(try item(.welcomeSearch) as? NSSearchToolbarItem) + #expect(search.searchField.placeholderString == "Search Connections") + #expect(search.searchField.accessibilityIdentifier() == "welcome-toolbar-search") + } - window.toolbar = toolbar + @Test("View Options sorts, and lists only the tags a connection carries") + func viewOptionsSortsAndListsUsedTags() throws { + let menu = try viewOptionsMenu() + let titles = menu.items.filter { !$0.isSeparatorItem }.map { $0.title } + #expect(titles == ["Sort By", "Manual", "Name", "Database Type", "Last Connected", "Filter by Tag", "prod", "eu-west"]) + #expect(!titles.contains("Match")) + #expect(!titles.contains("Clear Filters")) - expectFixedAtIconOnly(window.toolbar) - } + try choose("Name", in: menu) + + #expect(fixture.viewModel.sortMode == .name) + let reopened = try viewOptionsMenu() + #expect(reopened.item(withTitle: "Name")?.state == .on) + #expect(reopened.item(withTitle: "Manual")?.state == .off) } - @Test("The toolbar SwiftUI installs for the list pane offers no display mode choice") - func bridgedToolbarIsFixedAtIconOnly() async throws { - guard #available(macOS 14.0, *) else { return } - try await withWelcomeWindow { window in - let seed = try #require(window.toolbar) - let content = NSHostingController(rootView: BridgedToolbarContent()) - content.sizingOptions = [] - content.sceneBridgingOptions = [.toolbars] + @Test("Two tags from View Options add Match and Clear Filters, and fill the glyph") + func viewOptionsFiltersByTag() throws { + #expect(controller.viewOptionsSymbol == ToolbarSymbols.filter(isActive: false)) - window.contentViewController = content - _ = try? await waitUntil { window.toolbar !== seed } + try choose("prod", in: try viewOptionsMenu()) + try choose("eu-west", in: try viewOptionsMenu()) - let bridged = try #require(window.toolbar) - #expect(bridged !== seed) - #expect(bridged.items.contains { $0 is NSSearchToolbarItem }) - expectFixedAtIconOnly(bridged) - } + #expect(fixture.viewModel.tagFilterIds == [fixture.prod.id, fixture.euWest.id]) + #expect(controller.viewOptionsSymbol == ToolbarSymbols.filter(isActive: true)) + let menu = try viewOptionsMenu() + #expect(menu.item(withTitle: "prod")?.state == .on) + #expect(menu.item(withTitle: "Any Selected Tag")?.state == .on) + + try choose("All Selected Tags", in: menu) + #expect(fixture.viewModel.tagMatch == .all) + + try choose("Clear Filters", in: try viewOptionsMenu()) + #expect(fixture.viewModel.tagFilterIds.isEmpty) + #expect(controller.viewOptionsSymbol == ToolbarSymbols.filter(isActive: false)) + } + + @Test("Typing sets the query, and a query the model clears empties the field") + func searchFieldFollowsTheQuery() throws { + let field = try #require(try item(.welcomeSearch) as? NSSearchToolbarItem).searchField + field.stringValue = "alp" + field.sendAction(field.action, to: field.target) + #expect(fixture.viewModel.searchText == "alp") + + fixture.viewModel.searchText = "" + + #expect(field.stringValue.isEmpty) + } + + @Test("Return in the search field hands the keyboard to the list, first row selected") + func returnFocusesTheList() throws { + let outline = RecordingOutline() + fixture.viewModel.outlineController = outline + let field = try #require(try item(.welcomeSearch) as? NSSearchToolbarItem).searchField + + #expect(controller.control(field, textView: NSTextView(), doCommandBy: #selector(NSResponder.insertNewline(_:)))) + #expect(!controller.control(field, textView: NSTextView(), doCommandBy: #selector(NSResponder.moveDown(_:)))) + + #expect(outline.focusRequests == [true]) + } +} + +@MainActor +struct WelcomeTagSuggestionsTests { + private let fixture: WelcomeLibraryFixture + + init() throws { + fixture = try WelcomeLibraryFixture() + } + + @available(macOS 15.0, *) + @Test("Typing offers the used tags whose name contains the text, and nothing for no text") + func suggestsMatchingUsedTags() throws { + let suggestions = WelcomeTagSuggestions(viewModel: fixture.viewModel) + + let response = suggestions.suggestions(for: "PRO") + + #expect(response.itemSections.map(\.title) == ["Tags"]) + #expect(response.itemSections.flatMap(\.items).map(\.title) == ["prod"]) + #expect(suggestions.suggestions(for: " ").itemSections.isEmpty) + } + + @available(macOS 15.0, *) + @Test("A tag already filtering is not offered again") + func skipsActiveTags() throws { + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + + let titles = WelcomeTagSuggestions(viewModel: fixture.viewModel).suggestions(for: "e") + .itemSections.flatMap(\.items).map(\.title) + + #expect(titles == ["eu-west"]) + } + + @available(macOS 15.0, *) + @Test("Choosing a suggestion filters by the tag and clears the typed text") + func choosingASuggestionFilters() throws { + let suggestions = WelcomeTagSuggestions(viewModel: fixture.viewModel) + fixture.viewModel.searchText = "pro" + let item = try #require(suggestions.suggestions(for: "pro").itemSections.first?.items.first) + + suggestions.textField(NSSearchField(), didSelect: item) + + #expect(fixture.viewModel.tagFilterIds == [fixture.prod.id]) + #expect(fixture.viewModel.searchText.isEmpty) + #expect(suggestions.textField(NSSearchField(), textCompletionFor: item) == nil) } } -private struct BridgedToolbarContent: View { - @State private var searchText = "" - - var body: some View { - Color.clear - .searchable(text: $searchText, placement: .toolbar) - .toolbar { - ToolbarItemGroup(placement: .primaryAction) { - Button {} label: { - Label("New Connection", systemImage: "plus") - } - Button {} label: { - Label("New Group", systemImage: "folder.badge.plus") - } - } - } +@MainActor +struct WelcomeTagFilterBarTests { + private let fixture: WelcomeLibraryFixture + + init() throws { + fixture = try WelcomeLibraryFixture() + } + + private func bar() -> WelcomeTagFilterBar { + let bar = WelcomeTagFilterBar(viewModel: fixture.viewModel) + bar.apply(fixture.viewModel.tagFilter) + return bar + } + + @Test("The filter names its tags from storage, in the order they were turned on") + func filterFollowsTheOrderTagsWereTurnedOn() { + fixture.viewModel.setTagFilter(fixture.euWest.id, isOn: true) + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + + let filter = fixture.viewModel.tagFilter + let names = filter.tags.map(\.name) + #expect(names == ["eu-west", "prod"]) + #expect(filter.isActive) + #expect(filter.offersMatch) + } + + @Test("One toggle per active tag, all on, with Any or All once two are on") + func oneTogglePerTag() { + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + let single = bar() + let singleTitles = single.tagButtons.map { $0.title } + #expect(singleTitles == ["prod"]) + #expect(single.matchPopUp == nil) + #expect(single.clearButton.title == "Clear Filters") + + fixture.viewModel.setTagFilter(fixture.euWest.id, isOn: true) + let both = bar() + let bothTitles = both.tagButtons.map { $0.title } + #expect(bothTitles == ["prod", "eu-west"]) + #expect(both.tagButtons.allSatisfy { $0.state == .on }) + #expect(both.matchPopUp?.titleOfSelectedItem == "Any Selected Tag") + } + + @Test("Clicking a tag stops filtering by that tag alone") + func clickingATagRemovesIt() throws { + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + fixture.viewModel.setTagFilter(fixture.euWest.id, isOn: true) + + try #require(bar().tagButtons.first).performClick(nil) + + #expect(fixture.viewModel.tagFilterIds == [fixture.euWest.id]) + } + + @Test("The match pop-up and Clear Filters reach the model") + func matchAndClearReachTheModel() throws { + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + fixture.viewModel.setTagFilter(fixture.euWest.id, isOn: true) + let bar = bar() + let popUp = try #require(bar.matchPopUp) + + popUp.selectItem(withTitle: "All Selected Tags") + popUp.sendAction(popUp.action, to: popUp.target) + #expect(fixture.viewModel.tagMatch == .all) + + bar.clearButton.performClick(nil) + #expect(fixture.viewModel.tagFilterIds.isEmpty) + } + + @Test("The bar exists only while a tag filters the list") + func barComesAndGoesWithTheFilter() throws { + let split = WelcomeSplitViewController(viewModel: fixture.viewModel) + _ = split.view + #expect(split.tagFilterBar == nil) + + fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) + let bar = try #require(split.tagFilterBar) + if #available(macOS 26.0, *) { + let accessories = try #require(split.splitViewItems.last).topAlignedAccessoryViewControllers + #expect(accessories.count == 1) + #expect(accessories.first?.view === bar) + } else { + #expect(bar.superview != nil) + } + + fixture.viewModel.clearTagFilters() + #expect(split.tagFilterBar == nil) + if #available(macOS 26.0, *) { + #expect(try #require(split.splitViewItems.last).topAlignedAccessoryViewControllers.isEmpty) + } } } diff --git a/apple/TableProUITests/WelcomeConnectionListUITests.swift b/apple/TableProUITests/WelcomeConnectionListUITests.swift index fac7679b2d..5d19b7a964 100644 --- a/apple/TableProUITests/WelcomeConnectionListUITests.swift +++ b/apple/TableProUITests/WelcomeConnectionListUITests.swift @@ -44,6 +44,48 @@ final class WelcomeConnectionListUITests: UITestCase { ) } + // AppKit publishes a toolbar item by its label, not its item identifier, so the items are found by name. + func testTheToolbarSearchesTheListAndOffersItsCommandsByName() throws { + try seedSQLiteSession(seededNames.map { ConnectionSeed(name: $0, tabs: [], isOpen: false) }) + let app = try launchApp() + let welcome = welcomeWindow(in: app) + XCTAssertTrue(welcome.waitToExist(timeout: 15)) + let list = welcomeConnectionList(in: welcome) + XCTAssertTrue(welcomeConnectionRow(named: "alpha-staging", in: list).waitToExist(timeout: 15)) + + let toolbar = welcome.toolbars.firstMatch + XCTAssertTrue(toolbar.buttons["New Connection"].waitToExist(timeout: 5), "The toolbar must offer New Connection") + XCTAssertTrue(toolbar.buttons["New Group"].exists, "The toolbar must offer New Group") + let viewOptions = toolbar.descendants(matching: .any).matching(identifier: "View Options").firstMatch + XCTAssertTrue(viewOptions.exists, "The toolbar must offer View Options") + + app.typeShortcut(.find) + let search = welcome.searchFields["welcome-toolbar-search"] + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(search) }, + "Find must put the keyboard in the toolbar's search field" + ) + app.typeText("charlie") + XCTAssertTrue( + waitForPredicate(timeout: 5) { !self.welcomeConnectionRow(named: "alpha-staging", in: list).exists }, + "Typing must narrow the list" + ) + let match = welcomeConnectionRow(named: "charlie-prod", in: list) + XCTAssertTrue(match.exists) + + app.typeKey(.return, modifierFlags: []) + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(list) && match.isSelected }, + "Return must hand the list the keyboard with the first match selected" + ) + + XCTAssertTrue(waitUntilHittable(viewOptions, timeout: 5)) + viewOptions.click() + let sortItem = contextMenuItem("Database Type", in: app) + XCTAssertTrue(sortItem.waitToExist(timeout: 5), "View Options must list the sort orders") + app.typeKey(.escape, modifierFlags: []) + } + func testReturnOnASelectedConnectionOpensIt() throws { try seedSQLiteSession([ConnectionSeed(name: "alpha-staging", tabs: [], isOpen: false)]) let app = try launchApp() From 409715ff769e0ed2ea1ca02864208bdc236bcf4a Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:22:13 +0700 Subject: [PATCH 2/5] test(welcome): drive the tag filter bar and toolbar search end to end --- .../Views/Welcome/WelcomeToolbarTests.swift | 5 +- .../Support/SeededSQLiteSession.swift | 17 ++++++- .../WelcomeConnectionListUITests.swift | 49 ++++++++++++------- 3 files changed, 50 insertions(+), 21 deletions(-) diff --git a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift index b94048441b..14eff6764c 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift @@ -356,12 +356,13 @@ struct WelcomeTagFilterBarTests { func barComesAndGoesWithTheFilter() throws { let split = WelcomeSplitViewController(viewModel: fixture.viewModel) _ = split.view + let listItem = try #require(split.splitViewItems.last) #expect(split.tagFilterBar == nil) fixture.viewModel.setTagFilter(fixture.prod.id, isOn: true) let bar = try #require(split.tagFilterBar) if #available(macOS 26.0, *) { - let accessories = try #require(split.splitViewItems.last).topAlignedAccessoryViewControllers + let accessories = listItem.topAlignedAccessoryViewControllers #expect(accessories.count == 1) #expect(accessories.first?.view === bar) } else { @@ -371,7 +372,7 @@ struct WelcomeTagFilterBarTests { fixture.viewModel.clearTagFilters() #expect(split.tagFilterBar == nil) if #available(macOS 26.0, *) { - #expect(try #require(split.splitViewItems.last).topAlignedAccessoryViewControllers.isEmpty) + #expect(listItem.topAlignedAccessoryViewControllers.isEmpty) } } } diff --git a/apple/TableProUITests/Support/SeededSQLiteSession.swift b/apple/TableProUITests/Support/SeededSQLiteSession.swift index c7564a24d0..7283cd16ea 100644 --- a/apple/TableProUITests/Support/SeededSQLiteSession.swift +++ b/apple/TableProUITests/Support/SeededSQLiteSession.swift @@ -12,23 +12,32 @@ internal struct ConnectionSeed { internal var safeModeLevel: String internal var tabs: [SeededTab] internal var isOpen: Bool + internal var tagIds: [String] // A seed that is not open is saved but never restored, so only a list or the switcher reaches it. + // Tag ids name the preset tags (`PresetTag`), which the app seeds into an empty store. internal init( name: String = UITestFixture.connectionName, databaseSQL: String = UITestFixture.sql, safeModeLevel: String = "silent", tabs: [SeededTab] = [.query("SELECT 1;")], - isOpen: Bool = true + isOpen: Bool = true, + tagIds: [String] = [] ) { self.name = name self.databaseSQL = databaseSQL self.safeModeLevel = safeModeLevel self.tabs = tabs self.isOpen = isOpen + self.tagIds = tagIds } } +internal enum PresetTag { + internal static let local = "00000000-0000-0000-0000-000000000001" + internal static let production = "00000000-0000-0000-0000-000000000003" +} + internal struct SeededConnection { internal let id: UUID internal let name: String @@ -53,7 +62,11 @@ internal extension UITestCase { database: root.appendingPathComponent("seeded-\(index).sqlite") ) makeDatabase(at: connection.database, sql: seed.databaseSQL) - payloads.append(connectionPayload(connection, sortOrder: index, safeModeLevel: seed.safeModeLevel)) + var payload = connectionPayload(connection, sortOrder: index, safeModeLevel: seed.safeModeLevel) + if !seed.tagIds.isEmpty { + payload["tagIds"] = seed.tagIds + } + payloads.append(payload) try writeJSON( tabState(seed.tabs), to: tabStateDirectory.appendingPathComponent("\(connection.id.uuidString).json") diff --git a/apple/TableProUITests/WelcomeConnectionListUITests.swift b/apple/TableProUITests/WelcomeConnectionListUITests.swift index 5d19b7a964..72d31571b3 100644 --- a/apple/TableProUITests/WelcomeConnectionListUITests.swift +++ b/apple/TableProUITests/WelcomeConnectionListUITests.swift @@ -45,19 +45,44 @@ final class WelcomeConnectionListUITests: UITestCase { } // AppKit publishes a toolbar item by its label, not its item identifier, so the items are found by name. - func testTheToolbarSearchesTheListAndOffersItsCommandsByName() throws { - try seedSQLiteSession(seededNames.map { ConnectionSeed(name: $0, tabs: [], isOpen: false) }) + func testTheToolbarFiltersByTagAndSearchesTheList() throws { + try seedSQLiteSession([ + ConnectionSeed(name: "delta-local", tabs: [], isOpen: false, tagIds: [PresetTag.local]), + ConnectionSeed(name: "alpha-staging", tabs: [], isOpen: false), + ConnectionSeed(name: "charlie-prod", tabs: [], isOpen: false, tagIds: [PresetTag.production]), + ]) let app = try launchApp() let welcome = welcomeWindow(in: app) XCTAssertTrue(welcome.waitToExist(timeout: 15)) let list = welcomeConnectionList(in: welcome) - XCTAssertTrue(welcomeConnectionRow(named: "alpha-staging", in: list).waitToExist(timeout: 15)) + let alpha = welcomeConnectionRow(named: "alpha-staging", in: list) + let charlie = welcomeConnectionRow(named: "charlie-prod", in: list) + XCTAssertTrue(alpha.waitToExist(timeout: 15)) let toolbar = welcome.toolbars.firstMatch XCTAssertTrue(toolbar.buttons["New Connection"].waitToExist(timeout: 5), "The toolbar must offer New Connection") XCTAssertTrue(toolbar.buttons["New Group"].exists, "The toolbar must offer New Group") let viewOptions = toolbar.descendants(matching: .any).matching(identifier: "View Options").firstMatch - XCTAssertTrue(viewOptions.exists, "The toolbar must offer View Options") + XCTAssertTrue(waitUntilHittable(viewOptions, timeout: 5), "The toolbar must offer View Options") + + viewOptions.click() + // View > Sort Connections By holds a closed copy of the item, so only the open menu's copy is hittable. + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.contextMenuItem("Database Type", in: app).isHittable }, + "View Options must list the sort orders" + ) + let production = contextMenuItem("production", in: app) + XCTAssertTrue(waitUntilHittable(production, timeout: 5), "View Options must list the tags in use") + production.click() + + let bar = welcome.descendants(matching: .any).matching(identifier: "welcome-tag-filter-bar").firstMatch + XCTAssertTrue(bar.waitToExist(timeout: 5), "A tag filter must show the filter bar") + XCTAssertTrue(waitForPredicate(timeout: 5) { !alpha.exists }, "The tag filter must hide untagged rows") + XCTAssertTrue(charlie.exists) + let barTag = bar.buttons["production"] + XCTAssertTrue(waitUntilHittable(barTag, timeout: 5)) + barTag.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { !bar.exists && alpha.exists }, "Clicking the tag must stop filtering") app.typeShortcut(.find) let search = welcome.searchFields["welcome-toolbar-search"] @@ -66,24 +91,14 @@ final class WelcomeConnectionListUITests: UITestCase { "Find must put the keyboard in the toolbar's search field" ) app.typeText("charlie") - XCTAssertTrue( - waitForPredicate(timeout: 5) { !self.welcomeConnectionRow(named: "alpha-staging", in: list).exists }, - "Typing must narrow the list" - ) - let match = welcomeConnectionRow(named: "charlie-prod", in: list) - XCTAssertTrue(match.exists) + XCTAssertTrue(waitForPredicate(timeout: 5) { !alpha.exists }, "Typing must narrow the list") + XCTAssertTrue(charlie.exists) app.typeKey(.return, modifierFlags: []) XCTAssertTrue( - waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(list) && match.isSelected }, + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(list) && charlie.isSelected }, "Return must hand the list the keyboard with the first match selected" ) - - XCTAssertTrue(waitUntilHittable(viewOptions, timeout: 5)) - viewOptions.click() - let sortItem = contextMenuItem("Database Type", in: app) - XCTAssertTrue(sortItem.waitToExist(timeout: 5), "View Options must list the sort orders") - app.typeKey(.escape, modifierFlags: []) } func testReturnOnASelectedConnectionOpensIt() throws { From 419a9605263e26431a1686a8c4d314b425a36fe3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:22:38 +0700 Subject: [PATCH 3/5] docs(changelog): Welcome toolbar fragment --- apple/changelog.d/4415.changed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 apple/changelog.d/4415.changed.md diff --git a/apple/changelog.d/4415.changed.md b/apple/changelog.d/4415.changed.md new file mode 100644 index 0000000000..5e48d75c62 --- /dev/null +++ b/apple/changelog.d/4415.changed.md @@ -0,0 +1 @@ +The Welcome window opens faster, and the tags you filter by show in a bar above the connection list. From 5883ee2b3017c281e9f7879a28463ba2b8df0009 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 00:38:31 +0700 Subject: [PATCH 4/5] fix(welcome): reuse catalog strings in the tag filter bar --- apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift index a331d377d6..537dcfb2b5 100644 --- a/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift +++ b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift @@ -44,7 +44,7 @@ internal final class WelcomeTagFilterBar: NSView { ]) setAccessibilityElement(true) setAccessibilityRole(.group) - setAccessibilityLabel(String(localized: "Tag Filters")) + setAccessibilityLabel(String(localized: "Filter by Tag")) setAccessibilityIdentifier("welcome-tag-filter-bar") } @@ -79,7 +79,7 @@ internal final class WelcomeTagFilterBar: NSView { button.imagePosition = .imageLeading button.lineBreakMode = .byTruncatingTail button.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - button.toolTip = String(format: String(localized: "Stop filtering by %@"), tag.name) + button.toolTip = String(localized: "Remove Filter") tagIdsByButton[ObjectIdentifier(button)] = tag.id return button } From 193bf285dddac26497754193033691f4cd1c778f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 01:55:21 +0700 Subject: [PATCH 5/5] fix(welcome): name each tag toggle for VoiceOver --- apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift | 2 ++ apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift | 2 ++ apple/TableProUITests/WelcomeConnectionListUITests.swift | 3 ++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift index 537dcfb2b5..cbff326df4 100644 --- a/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift +++ b/apple/TablePro/Views/Welcome/WelcomeTagFilterBar.swift @@ -79,6 +79,8 @@ internal final class WelcomeTagFilterBar: NSView { button.imagePosition = .imageLeading button.lineBreakMode = .byTruncatingTail button.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + // The symbol's own description ("tag") would otherwise be what VoiceOver reads first. + button.setAccessibilityLabel(tag.name) button.toolTip = String(localized: "Remove Filter") tagIdsByButton[ObjectIdentifier(button)] = tag.id return button diff --git a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift index 14eff6764c..48ea7550a6 100644 --- a/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift +++ b/apple/TableProTests/Views/Welcome/WelcomeToolbarTests.swift @@ -324,6 +324,8 @@ struct WelcomeTagFilterBarTests { let bothTitles = both.tagButtons.map { $0.title } #expect(bothTitles == ["prod", "eu-west"]) #expect(both.tagButtons.allSatisfy { $0.state == .on }) + let labels = both.tagButtons.map { $0.accessibilityLabel() } + #expect(labels == ["prod", "eu-west"]) #expect(both.matchPopUp?.titleOfSelectedItem == "Any Selected Tag") } diff --git a/apple/TableProUITests/WelcomeConnectionListUITests.swift b/apple/TableProUITests/WelcomeConnectionListUITests.swift index 72d31571b3..6d09dad1ca 100644 --- a/apple/TableProUITests/WelcomeConnectionListUITests.swift +++ b/apple/TableProUITests/WelcomeConnectionListUITests.swift @@ -79,7 +79,8 @@ final class WelcomeConnectionListUITests: UITestCase { XCTAssertTrue(bar.waitToExist(timeout: 5), "A tag filter must show the filter bar") XCTAssertTrue(waitForPredicate(timeout: 5) { !alpha.exists }, "The tag filter must hide untagged rows") XCTAssertTrue(charlie.exists) - let barTag = bar.buttons["production"] + // A toggle button reads as a checkbox to accessibility. + let barTag = bar.checkBoxes["production"] XCTAssertTrue(waitUntilHittable(barTag, timeout: 5)) barTag.click() XCTAssertTrue(waitForPredicate(timeout: 5) { !bar.exists && alpha.exists }, "Clicking the tag must stop filtering")