From 70bdefcbd6847cb3e002e02829c86a7aefad3ae1 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 09:35:43 +0700 Subject: [PATCH 01/48] feat(settings): sidebar window shell, General split, drill-in mechanism --- .../Settings/ConnectionsSettingsView.swift | 42 +++ .../Views/Settings/GeneralSettingsView.swift | 81 +----- .../Views/Settings/SettingsNavigation.swift | 72 +++++ .../Settings/SettingsPane+URLIdentifier.swift | 4 + .../Views/Settings/SettingsSubpage.swift | 27 ++ .../Views/Settings/SettingsView.swift | 6 +- .../Settings/SettingsWindowController.swift | 221 ++++++++++----- .../Settings/SidebarTabsSettingsView.swift | 73 +++++ .../Settings/AppearancePaneListTests.swift | 3 +- .../Settings/SettingsNavigationTests.swift | 59 ++++ .../SettingsPaneURLIdentifierTests.swift | 2 + .../SettingsPluginsPaneRegistryTests.swift | 10 +- .../Settings/SettingsWindowTitleTests.swift | 251 ++++++++++-------- 13 files changed, 587 insertions(+), 264 deletions(-) create mode 100644 apple/TablePro/Views/Settings/ConnectionsSettingsView.swift create mode 100644 apple/TablePro/Views/Settings/SettingsNavigation.swift create mode 100644 apple/TablePro/Views/Settings/SettingsSubpage.swift create mode 100644 apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsNavigationTests.swift diff --git a/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift new file mode 100644 index 0000000000..60bf8e810c --- /dev/null +++ b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift @@ -0,0 +1,42 @@ +// +// ConnectionsSettingsView.swift +// TablePro +// + +import SwiftUI + +struct ConnectionsSettingsView: View { + @Binding var settings: GeneralSettings + + private static let standardTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] + + private var queryTimeoutOptions: [Int] { + let current = settings.queryTimeoutSeconds + if current > 0, !Self.standardTimeouts.contains(current) { + return (Self.standardTimeouts + [current]).sorted() + } + return Self.standardTimeouts + } + + var body: some View { + Form { + ConnectionsSettingsSection(healthCheck: $settings.connectionHealthCheck) + + Section("Query Execution") { + Picker("Query timeout:", selection: $settings.queryTimeoutSeconds) { + Text("No limit").tag(0) + ForEach(queryTimeoutOptions, id: \.self) { seconds in + Text("\(seconds) seconds").tag(seconds) + } + } + .help(String(localized: "Maximum time to wait for a query to complete. Set to 0 for no limit. Applied to new connections.")) + } + } + .formStyle(.grouped) + } +} + +#Preview { + ConnectionsSettingsView(settings: .constant(.default)) + .frame(width: 520, height: 400) +} diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 4647f9378d..23f81cca4a 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -3,23 +3,10 @@ import SwiftUI struct GeneralSettingsView: View { @Binding var settings: GeneralSettings - @Binding var tabSettings: TabSettings - @ObservedObject var updater: SoftwareUpdater var onResetAll: () -> Void @State private var initialLanguage: AppLanguage? @State private var showResetConfirmation = false - @AppStorage(SidebarPersistenceKey.defaultLayout, store: AppStorageEnvironment.shared.defaults) private var defaultSidebarLayout: SidebarLayout = .flat - - private static let standardTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] - - private var queryTimeoutOptions: [Int] { - let current = settings.queryTimeoutSeconds - if current > 0, !Self.standardTimeouts.contains(current) { - return (Self.standardTimeouts + [current]).sorted() - } - return Self.standardTimeouts - } var body: some View { Form { @@ -48,75 +35,19 @@ 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.") - } - - Section("Sidebar") { - Toggle("Show connections", isOn: $settings.showWorkspaceRail) - .help("Adds a narrow strip on the window's leading edge listing every connection and database you have open, so one click switches to it.") - - Toggle("Show recent tables", isOn: $settings.showRecentTables) - .help("Adds a Recent section at the top of the Tables sidebar with the last tables you opened per connection and database.") - - Toggle("Show object icons", isOn: $settings.showObjectIcons) - .help("Shows a type icon before each object name in the sidebar. Turn it off for a plain list of names.") - - Toggle("Show object comments", isOn: $settings.showObjectComments) - .help("Shows database object comments next to tables in the sidebar and in grid column headers.") - - Toggle("Show system databases and schemas", isOn: $settings.showSystemContainers) - .accessibilityIdentifier("show-system-containers-toggle") - .help(String(localized: """ - Lists system databases such as mysql and information_schema, and system schemas, \ - in the sidebar tree and the database filter. Switchers always list them. - """)) - - Toggle("Show partitions", isOn: $settings.showPartitions) - .accessibilityIdentifier("show-partitions-toggle") - .help(String(localized: """ - Lists a partitioned table's partitions under it in the sidebar, with how many \ - it holds. Turn it off to keep partitioned tables as single rows. - """)) - - Picker("Row size:", selection: $settings.sidebarRowSize) { - ForEach(SidebarRowSizePreference.allCases, id: \.self) { size in - Text(size.title).tag(size) - } + Section { + NavigationLink(value: SettingsSubpage.commandLine) { + Label("Command Line Tool", systemImage: "terminal") } - .help(String(localized: """ - Match System follows Sidebar icon size in System Settings > Appearance. \ - Choose a size to fit more objects on screen than the rest of the system shows. - """)) - - Picker("Default layout for new connections:", selection: $defaultSidebarLayout) { - Text("List").tag(SidebarLayout.flat) - Text("Tree").tag(SidebarLayout.tree) + NavigationLink(value: SettingsSubpage.softwareUpdate) { + Label("Software Update", systemImage: "arrow.down.circle") } - .help(String(localized: "Layout for new connections on servers that support a database tree. Switch the current connection from the View menu.")) } - ConnectionsSettingsSection(healthCheck: $settings.connectionHealthCheck) - - Section("Query Execution") { - Picker("Query timeout:", selection: $settings.queryTimeoutSeconds) { - Text("No limit").tag(0) - ForEach(queryTimeoutOptions, id: \.self) { seconds in - Text("\(seconds) seconds").tag(seconds) - } - } - .help(String(localized: "Maximum time to wait for a query to complete. Set to 0 for no limit. Applied to new connections.")) - } - - CommandLineToolSection() - LinkedFoldersSection() TrustedExternalConnectionsSection() - SoftwareUpdateSection(updater: updater, updates: .shared) - Section { Toggle("Share usage data", isOn: $settings.shareAnalytics) } header: { @@ -153,8 +84,6 @@ struct GeneralSettingsView: View { #Preview { GeneralSettingsView( settings: .constant(.default), - tabSettings: .constant(.default), - updater: SoftwareUpdater.shared, onResetAll: {} ) .frame(width: 450, height: 500) diff --git a/apple/TablePro/Views/Settings/SettingsNavigation.swift b/apple/TablePro/Views/Settings/SettingsNavigation.swift new file mode 100644 index 0000000000..3bb7450f79 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsNavigation.swift @@ -0,0 +1,72 @@ +// +// SettingsNavigation.swift +// TablePro +// + +import Foundation + +// Pure model of the Settings window's sidebar: the ordered sections, the rows in each, and the +// search index. No AppKit, SwiftUI or storage, so it unit-tests without a host. The window shell +// and the deep-link layer read this; they never hardcode the order themselves. +enum SettingsSectionID: String, CaseIterable, Sendable { + case app + case integrations + case accountData +} + +struct SettingsSection: Equatable, Sendable { + let id: SettingsSectionID + let panes: [SettingsPane] +} + +enum SettingsNavigation { + static let sections: [SettingsSection] = [ + SettingsSection(id: .app, panes: [.general, .sidebar, .connections, .appearance, .editor, .data, .keyboard, .notifications]), + SettingsSection(id: .integrations, panes: [.ai, .mcp, .plugins]), + SettingsSection(id: .accountData, panes: [.profiles, .sync, .account]), + ] + + // The sidebar order, flattened. A permutation of SettingsPane.allCases: every pane once. + static let orderedPanes: [SettingsPane] = sections.flatMap(\.panes) + + static let defaultPane: SettingsPane = .general + + // The deep-link and last-used-pane vocabulary stays SettingsPane.urlIdentifier / rawValue. + static func pane(forURLIdentifier identifier: String) -> SettingsPane? { + SettingsPane(urlIdentifier: identifier) + } + + // Panes whose title or keywords contain every whitespace-split term of the query, in sidebar + // order. An empty query returns the full order. + static func panes(matching query: String) -> [SettingsPane] { + let terms = query.lowercased().split(whereSeparator: { $0.isWhitespace }).map(String.init) + guard !terms.isEmpty else { return orderedPanes } + return orderedPanes.filter { pane in + let haystack = ([pane.title] + pane.searchKeywords).joined(separator: " ").lowercased() + return terms.allSatisfy(haystack.contains) + } + } +} + +extension SettingsPane { + // Terms that should match a pane in the sidebar search beyond its visible title. Kept here, not + // in the pane enum, because they are a search concern, not the pane's identity. + var searchKeywords: [String] { + switch self { + case .general: ["language", "startup", "privacy", "analytics", "reset", "command line", "cli", "update", "linked folders", "trusted"] + case .sidebar: ["sidebar", "tabs", "preview tabs", "object icons", "object comments", "row size", "layout", "partitions", "system databases", "recent tables"] + case .connections: ["connection", "recent connections", "health check", "query timeout", "timeout"] + case .appearance: ["theme", "dark", "light", "color", "appearance mode"] + case .editor: ["font", "sql", "format", "formatter", "indent", "gutter", "code"] + case .data: ["grid", "results", "rows", "pagination", "history", "rewind", "null", "page size"] + case .keyboard: ["shortcut", "shortcuts", "key", "binding", "hotkey"] + case .notifications: ["alert", "notify", "badge"] + case .ai: ["assistant", "model", "provider", "apple intelligence", "slash command", "agent"] + case .mcp: ["server", "token", "client", "integration", "port"] + case .plugins: ["extension", "driver", "module", "install"] + case .profiles: ["credential", "ssh", "password", "profile", "bastion"] + case .sync: ["icloud", "backup", "device"] + case .account: ["license", "plan", "subscription", "team", "pro", "sign in"] + } + } +} diff --git a/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift b/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift index caf253d0b0..c89fc9f31c 100644 --- a/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift +++ b/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift @@ -11,6 +11,8 @@ internal extension SettingsPane { var urlIdentifier: String { switch self { case .general: "general" + case .sidebar: "sidebar" + case .connections: "connections" case .appearance: "appearance" case .editor: "editor" case .data: "data" @@ -28,6 +30,8 @@ internal extension SettingsPane { init?(urlIdentifier: String) { switch urlIdentifier { case "general": self = .general + case "sidebar": self = .sidebar + case "connections": self = .connections case "appearance": self = .appearance case "editor": self = .editor case "data": self = .data diff --git a/apple/TablePro/Views/Settings/SettingsSubpage.swift b/apple/TablePro/Views/Settings/SettingsSubpage.swift new file mode 100644 index 0000000000..784e781d9f --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsSubpage.swift @@ -0,0 +1,27 @@ +// +// SettingsSubpage.swift +// TablePro +// + +import Foundation + +// A drill-in page pushed onto a pane's NavigationStack in the Settings detail column. Payload-free +// so it is Hashable for navigationDestination and can carry a deep-link id later. Leaf editors that +// need an id (a plugin, a profile) stay sheets for now. +enum SettingsSubpage: String, Hashable, CaseIterable { + case softwareUpdate + case commandLine + + var parent: SettingsPane { + switch self { + case .softwareUpdate, .commandLine: .general + } + } + + var title: String { + switch self { + case .softwareUpdate: String(localized: "Software Update") + case .commandLine: String(localized: "Command Line Tool") + } + } +} diff --git a/apple/TablePro/Views/Settings/SettingsView.swift b/apple/TablePro/Views/Settings/SettingsView.swift index 1d86b7d138..159ed59fd7 100644 --- a/apple/TablePro/Views/Settings/SettingsView.swift +++ b/apple/TablePro/Views/Settings/SettingsView.swift @@ -6,11 +6,13 @@ import SwiftUI enum SettingsPane: String, CaseIterable { - case general, appearance, editor, data, keyboard, profiles, notifications, ai, mcp, plugins, sync, account + case general, sidebar, connections, appearance, editor, data, keyboard, profiles, notifications, ai, mcp, plugins, sync, account var title: String { switch self { case .general: String(localized: "General") + case .sidebar: String(localized: "Sidebar & Tabs") + case .connections: String(localized: "Connections") case .appearance: String(localized: "Appearance") case .editor: String(localized: "Editor") case .data: String(localized: "Data") @@ -31,6 +33,8 @@ enum SettingsPane: String, CaseIterable { var symbol: String { switch self { case .general: "gearshape" + case .sidebar: "sidebar.left" + case .connections: "cable.connector" case .appearance: "paintbrush" case .editor: "doc.text" case .data: "tablecells" diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index d4a54f321f..256e823d60 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -4,10 +4,11 @@ // import AppKit +import Combine import os import SwiftUI -// An AppKit window, so the app needs no SwiftUI Settings scene. +// An AppKit window, so the app needs no SwiftUI Settings scene (which would rewrite NSApp.mainMenu). @MainActor internal final class SettingsWindowController: NSWindowController { private static var shared: SettingsWindowController? @@ -15,14 +16,14 @@ internal final class SettingsWindowController: NSWindowController { internal static func present(pane: SettingsPane? = nil) { let controller = shared ?? SettingsWindowController() shared = controller - controller.paneController?.select(pane) + controller.split?.navigate(to: pane) controller.showWindow(nil) controller.window?.makeKeyAndOrderFront(nil) AppActivationPolicyController.shared.activate() } - private var paneController: SettingsPaneTabViewController? { - contentViewController as? SettingsPaneTabViewController + private var split: SettingsSplitViewController? { + contentViewController as? SettingsSplitViewController } // A defaulted parameter would let `SettingsWindowController()` resolve to the inherited `init()`, which builds no window. @@ -31,105 +32,190 @@ internal final class SettingsWindowController: NSWindowController { } internal convenience init(registryClient: RegistryClient) { - let panes = SettingsPaneTabViewController(registryClient: registryClient) + let split = SettingsSplitViewController(registryClient: registryClient) - // NSWindow(contentViewController:) binds the title to the panes controller's, so nothing writes window.title. - let window = NSWindow(contentViewController: panes) + // NSWindow(contentViewController:) binds the title to the split controller's, which mirrors the selected row. + let window = NSWindow(contentViewController: split) window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.settings) window.keepsKeyViewLoopCurrent() window.styleMask = [.titled, .closable, .resizable] - window.toolbarStyle = .preference window.isRestorable = false - window.contentMinSize = SettingsPaneTabViewController.paneSize - window.setContentSize(SettingsPaneTabViewController.paneSize) + window.contentMinSize = SettingsSplitViewController.minimumContentSize + window.setContentSize(SettingsSplitViewController.minimumContentSize) window.applyAutosaveName(WindowIdentifier.settings) - // contentMinSize only limits a drag, so a frame saved before the window had a minimum is grown back here. window.setContentSize( NSSize( - width: max(window.contentLayoutRect.width, SettingsPaneTabViewController.paneSize.width), - height: max(window.contentLayoutRect.height, SettingsPaneTabViewController.paneSize.height) + width: max(window.contentLayoutRect.width, SettingsSplitViewController.minimumContentSize.width), + height: max(window.contentLayoutRect.height, SettingsSplitViewController.minimumContentSize.height) ) ) self.init(window: window) } } -internal final class SettingsPaneTabViewController: NSTabViewController { - // Fits twelve items in a .preference toolbar; at 720 the last one hides behind an overflow chevron. - internal static let paneSize = NSSize(width: 800, height: 500) - internal static let paneOrder: [SettingsPane] = SettingsPane.allCases +// The sidebar list + detail pane. Replaces the twelve-item .preference toolbar; a scrolling +// sidebar has no item cap, and the detail hosts a NavigationStack so a row can push sub-pages. +internal final class SettingsSplitViewController: NSSplitViewController { + internal static let minimumContentSize = NSSize(width: 775, height: 520) + private static let sidebarMinWidth: CGFloat = 204 + private static let sidebarMaxWidth: CGFloat = 280 + private static let detailMinWidth: CGFloat = 560 private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") + internal let model: SettingsNavigationModel private let registryClient: RegistryClient + private var cancellables: Set = [] internal init(registryClient: RegistryClient = .shared) { self.registryClient = registryClient + self.model = SettingsNavigationModel(initial: Self.persistedPane) super.init(nibName: nil, bundle: nil) + title = model.selection.title } internal required init?(coder: NSCoder) { - fatalError("SettingsPaneTabViewController does not support NSCoder init") + fatalError("SettingsSplitViewController does not support NSCoder init") } - private var persistedPane: SettingsPane { + private static var persistedPane: SettingsPane { let stored = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) - guard let stored, let pane = SettingsPane(rawValue: stored) else { return .general } + guard let stored, let pane = SettingsPane(rawValue: stored) else { return SettingsNavigation.defaultPane } return pane } - internal func select(_ pane: SettingsPane?) { - // Before macOS 14, reading view loads it, which is all loadViewIfNeeded() does. - if #available(macOS 14.0, *) { - loadViewIfNeeded() - } else { - _ = view - } - let wanted = pane ?? persistedPane - guard let index = Self.paneOrder.firstIndex(of: wanted) else { - Self.logger.error("Settings pane \(wanted.rawValue, privacy: .public) has no tab and cannot be shown") - return - } - selectedTabViewItemIndex = index + // A user click persists as the new last-used pane; a programmatic jump (openSettings, deep link) + // navigates without clobbering it. + internal func navigate(to pane: SettingsPane?) { + _ = view // loads the view on every supported macOS, which attaches the selection observer + model.applyProgrammatic(pane ?? Self.persistedPane) } override func viewDidLoad() { super.viewDidLoad() - tabStyle = .toolbar - // Adding the first item selects and persists .general, so the saved pane is read before any item exists. - let restored = persistedPane - for pane in Self.paneOrder { - addTabViewItem(makeTabViewItem(for: pane)) - } - select(restored) + + let sidebar = NSHostingController(rootView: SettingsSidebarView(model: model)) + let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) + sidebarItem.minimumThickness = Self.sidebarMinWidth + sidebarItem.maximumThickness = Self.sidebarMaxWidth + sidebarItem.canCollapse = false + addSplitViewItem(sidebarItem) + + let detail = NSHostingController(rootView: SettingsDetailView(model: model, registryClient: registryClient)) + // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. + detail.sizingOptions = [] + let detailItem = NSSplitViewItem(viewController: detail) + detailItem.minimumThickness = Self.detailMinWidth + detailItem.holdingPriority = NSLayoutConstraint.Priority(260) // below dragThatCannotResizeWindow (490) + addSplitViewItem(detailItem) + + model.$selection + .removeDuplicates() + .sink { [weak self] pane in + self?.title = pane.title + self?.persistUserSelection(pane) + } + .store(in: &cancellables) } - override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) { - super.tabView(tabView, didSelect: tabViewItem) - guard let identifier = tabViewItem?.identifier as? String, - let pane = SettingsPane(rawValue: identifier) else { return } + private func persistUserSelection(_ pane: SettingsPane) { + guard !model.isApplyingProgrammatic else { return } AppStorageEnvironment.shared.defaults.set(pane.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name) } +} - private func makeTabViewItem(for pane: SettingsPane) -> NSTabViewItem { - let content = SettingsPaneContent(pane: pane, registryClient: registryClient) - .frame( - minWidth: Self.paneSize.width, - maxWidth: .infinity, - minHeight: Self.paneSize.height, - maxHeight: .infinity - ) - .environment(\.appServices, .live) - let hosting = NSHostingController(rootView: content) - // The window owns the minimum size; the title still reaches it, as NSTabViewController mirrors the selected child's. - hosting.sizingOptions = [] - hosting.title = pane.title - - let item = NSTabViewItem(viewController: hosting) - item.label = pane.title - item.image = NSImage(systemSymbolName: pane.symbol, accessibilityDescription: pane.title) - item.identifier = pane.rawValue - return item +@MainActor +internal final class SettingsNavigationModel: ObservableObject { + @Published internal var selection: SettingsPane + @Published internal var searchText: String = "" + internal private(set) var isApplyingProgrammatic = false + + internal init(initial: SettingsPane) { + self.selection = initial + } + + // From the sidebar list: the user picked a row, so it becomes the last-used pane. + internal func userSelect(_ pane: SettingsPane) { + isApplyingProgrammatic = false + selection = pane + } + + // From openSettings / a deep link: show the pane but do not rewrite the last-used pane. + internal func applyProgrammatic(_ pane: SettingsPane) { + isApplyingProgrammatic = true + selection = pane + isApplyingProgrammatic = false + } +} + +private struct SettingsSidebarView: View { + @ObservedObject fileprivate var model: SettingsNavigationModel + + private var selectionBinding: Binding { + Binding( + get: { model.selection }, + set: { if let pane = $0 { model.userSelect(pane) } } + ) + } + + fileprivate var body: some View { + List(selection: selectionBinding) { + ForEach(SettingsNavigation.sections, id: \.id) { section in + let panes = visiblePanes(in: section) + if !panes.isEmpty { + Section { + ForEach(panes, id: \.self) { pane in + Label(pane.title, systemImage: pane.symbol) + .tag(Optional(pane)) + } + } + } + } + } + .listStyle(.sidebar) + .searchable(text: $model.searchText, placement: .sidebar, prompt: Text("Search")) + } + + private func visiblePanes(in section: SettingsSection) -> [SettingsPane] { + let matches = Set(SettingsNavigation.panes(matching: model.searchText)) + return section.panes.filter(matches.contains) + } +} + +private struct SettingsDetailView: View { + @ObservedObject fileprivate var model: SettingsNavigationModel + fileprivate let registryClient: RegistryClient + + fileprivate var body: some View { + NavigationStack { + SettingsPaneContent(pane: model.selection, registryClient: registryClient) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .navigationDestination(for: SettingsSubpage.self) { subpage in + SettingsSubpageView(subpage: subpage) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + // Each pane owns its own navigation depth; switching panes resets any pushed sub-page. + .id(model.selection) + .environment(\.appServices, .live) + } +} + +// A pushed drill-in page. Back button and title come from the NavigationStack. +private struct SettingsSubpageView: View { + fileprivate let subpage: SettingsSubpage + + fileprivate var body: some View { + Form { + switch subpage { + case .softwareUpdate: + SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) + case .commandLine: + CommandLineToolSection() + } + } + .formStyle(.grouped) + .navigationTitle(subpage.title) } } @@ -149,10 +235,15 @@ private struct SettingsPaneContent: View { case .general: GeneralSettingsView( settings: $settingsManager.general, - tabSettings: $settingsManager.tabs, - updater: SoftwareUpdater.shared, onResetAll: { settingsManager.resetToDefaults() } ) + case .sidebar: + SidebarTabsSettingsView( + settings: $settingsManager.general, + tabSettings: $settingsManager.tabs + ) + case .connections: + ConnectionsSettingsView(settings: $settingsManager.general) case .appearance: AppearanceSettingsView(settings: $settingsManager.appearance) case .editor: diff --git a/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift b/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift new file mode 100644 index 0000000000..d55492fe4e --- /dev/null +++ b/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift @@ -0,0 +1,73 @@ +// +// SidebarTabsSettingsView.swift +// TablePro +// + +import SwiftUI + +struct SidebarTabsSettingsView: View { + @Binding var settings: GeneralSettings + @Binding var tabSettings: TabSettings + + @AppStorage(SidebarPersistenceKey.defaultLayout, store: AppStorageEnvironment.shared.defaults) + private var defaultSidebarLayout: SidebarLayout = .flat + + var body: some View { + Form { + Section("Tabs") { + Toggle("Enable preview tabs", isOn: $tabSettings.enablePreviewTabs) + .help("Single-clicking a table opens a temporary tab that gets replaced on next click.") + } + + Section("Sidebar") { + Toggle("Show connections", isOn: $settings.showWorkspaceRail) + .help("Adds a narrow strip on the window's leading edge listing every connection and database you have open, so one click switches to it.") + + Toggle("Show recent tables", isOn: $settings.showRecentTables) + .help("Adds a Recent section at the top of the Tables sidebar with the last tables you opened per connection and database.") + + Toggle("Show object icons", isOn: $settings.showObjectIcons) + .help("Shows a type icon before each object name in the sidebar. Turn it off for a plain list of names.") + + Toggle("Show object comments", isOn: $settings.showObjectComments) + .help("Shows database object comments next to tables in the sidebar and in grid column headers.") + + Toggle("Show system databases and schemas", isOn: $settings.showSystemContainers) + .accessibilityIdentifier("show-system-containers-toggle") + .help(String(localized: """ + Lists system databases such as mysql and information_schema, and system schemas, \ + in the sidebar tree and the database filter. Switchers always list them. + """)) + + Toggle("Show partitions", isOn: $settings.showPartitions) + .accessibilityIdentifier("show-partitions-toggle") + .help(String(localized: """ + Lists a partitioned table's partitions under it in the sidebar, with how many \ + it holds. Turn it off to keep partitioned tables as single rows. + """)) + + Picker("Row size:", selection: $settings.sidebarRowSize) { + ForEach(SidebarRowSizePreference.allCases, id: \.self) { size in + Text(size.title).tag(size) + } + } + .help(String(localized: """ + Match System follows Sidebar icon size in System Settings > Appearance. \ + Choose a size to fit more objects on screen than the rest of the system shows. + """)) + + Picker("Default layout for new connections:", selection: $defaultSidebarLayout) { + Text("List").tag(SidebarLayout.flat) + Text("Tree").tag(SidebarLayout.tree) + } + .help(String(localized: "Layout for new connections on servers that support a database tree. Switch the current connection from the View menu.")) + } + } + .formStyle(.grouped) + } +} + +#Preview { + SidebarTabsSettingsView(settings: .constant(.default), tabSettings: .constant(.default)) + .frame(width: 520, height: 500) +} diff --git a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift index 45f6b02e22..581d4d331f 100644 --- a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift +++ b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift @@ -43,7 +43,8 @@ struct AppearancePaneListTests { } private static func hostPane() throws -> HostedPane { - let paneSize = SettingsPaneTabViewController.paneSize + // The size of the Settings detail pane that hosts the Appearance view. + let paneSize = NSSize(width: 560, height: 480) let window = NSWindow( contentRect: NSRect(origin: .zero, size: paneSize), styleMask: [.titled], diff --git a/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift new file mode 100644 index 0000000000..52c0758a8b --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift @@ -0,0 +1,59 @@ +// +// SettingsNavigationTests.swift +// TableProTests +// + +@testable import TablePro +import Testing + +struct SettingsNavigationTests { + @Test("Every pane appears exactly once across the sections") + func sectionsCoverEveryPaneOnce() { + let flattened = SettingsNavigation.sections.flatMap(\.panes) + #expect(flattened == SettingsNavigation.orderedPanes) + #expect(flattened.count == SettingsPane.allCases.count) + #expect(Set(flattened) == Set(SettingsPane.allCases)) + } + + @Test("The default pane is General and is in the order") + func defaultPaneIsInOrder() { + #expect(SettingsNavigation.defaultPane == .general) + #expect(SettingsNavigation.orderedPanes.contains(.general)) + } + + @Test("A url identifier round-trips to its pane") + func urlIdentifierRoundTrips() { + for pane in SettingsPane.allCases { + #expect(SettingsNavigation.pane(forURLIdentifier: pane.urlIdentifier) == pane) + } + #expect(SettingsNavigation.pane(forURLIdentifier: "license") == .account) + #expect(SettingsNavigation.pane(forURLIdentifier: "plugins") == .plugins) + #expect(SettingsNavigation.pane(forURLIdentifier: "nope") == nil) + } + + @Test("An empty query returns the whole order") + func emptyQueryReturnsEverything() { + #expect(SettingsNavigation.panes(matching: "") == SettingsNavigation.orderedPanes) + #expect(SettingsNavigation.panes(matching: " ") == SettingsNavigation.orderedPanes) + } + + @Test("Search matches titles and keywords, case-insensitively") + func searchMatchesTitlesAndKeywords() { + #expect(SettingsNavigation.panes(matching: "theme") == [.appearance]) + #expect(SettingsNavigation.panes(matching: "shortcut") == [.keyboard]) + #expect(SettingsNavigation.panes(matching: "MCP") == [.mcp]) + #expect(SettingsNavigation.panes(matching: "sql format") == [.editor]) + #expect(SettingsNavigation.panes(matching: "license") == [.account]) + #expect(SettingsNavigation.panes(matching: "zzzznomatch").isEmpty) + } + + @Test("Search results keep sidebar order") + func searchResultsKeepSidebarOrder() { + // "connections" is a General keyword and the Connections concept; results stay in order. + let results = SettingsNavigation.panes(matching: "e") + let orderIndex = SettingsNavigation.orderedPanes.enumerated() + .reduce(into: [SettingsPane: Int]()) { $0[$1.element] = $1.offset } + let indices = results.compactMap { orderIndex[$0] } + #expect(indices == indices.sorted()) + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift index 35a63a187c..657b1840ec 100644 --- a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift @@ -10,6 +10,8 @@ struct SettingsPaneURLIdentifierTests { // Published at docs.tablepro.app/developers/url-scheme. Changing a value breaks links in other apps. private static let published: [SettingsPane: String] = [ .general: "general", + .sidebar: "sidebar", + .connections: "connections", .appearance: "appearance", .editor: "editor", .data: "data", diff --git a/apple/TableProTests/Views/Settings/SettingsPluginsPaneRegistryTests.swift b/apple/TableProTests/Views/Settings/SettingsPluginsPaneRegistryTests.swift index 1c436c00ee..348fa10e25 100644 --- a/apple/TableProTests/Views/Settings/SettingsPluginsPaneRegistryTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsPluginsPaneRegistryTests.swift @@ -13,12 +13,13 @@ extension GlobalStateSuites { let paneKey = PreferenceKeys.selectedSettingsPane.name let storedPane = defaults.string(forKey: paneKey) let registry = try OfflineRegistry() - let panes = SettingsPaneTabViewController(registryClient: registry.client) - let window = NSWindow(contentViewController: panes) + let split = SettingsSplitViewController(registryClient: registry.client) + let window = NSWindow(contentViewController: split) window.isReleasedWhenClosed = false + window.setContentSize(SettingsSplitViewController.minimumContentSize) defer { window.contentViewController = nil - window.close() + window.orderOut(nil) if let storedPane { defaults.set(storedPane, forKey: paneKey) } else { @@ -26,7 +27,8 @@ extension GlobalStateSuites { } } - panes.select(.plugins) + split.navigate(to: .plugins) + window.layoutIfNeeded() try await waitUntil { registry.client.isManifestCurrent } #expect(registry.requestCount == 1) diff --git a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift index bbeacea0e4..d8b9487d2c 100644 --- a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift @@ -5,136 +5,153 @@ import AppKit @testable import TablePro -import XCTest - -@MainActor -final class SettingsWindowTitleTests: XCTestCase { - private var storedPane: String? - private var windows: [NSWindow] = [] - private var registry: OfflineRegistry? - - override func setUpWithError() throws { - try super.setUpWithError() - registry = try OfflineRegistry() - } - - override func setUp() { - super.setUp() - storedPane = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) - } - - override func tearDown() async throws { - for window in windows { - window.contentViewController = nil - window.close() - } - windows = [] - await registry?.settle() - registry = nil - if let storedPane { - AppStorageEnvironment.shared.defaults.set(storedPane, forKey: PreferenceKeys.selectedSettingsPane.name) - } else { - AppStorageEnvironment.shared.defaults.removeObject(forKey: PreferenceKeys.selectedSettingsPane.name) +import TableProTestSupport +import Testing + +extension GlobalStateSuites { + // The sidebar window reads and writes the selected-pane default, so it nests here for serialized + // access to that process-wide value. + @MainActor + struct SettingsWindowNavigationTests { + @MainActor + private final class Host { + var windows: [NSWindow] = [] + let registry: OfflineRegistry + let storedPane: String? + + init() throws { + registry = try OfflineRegistry() + storedPane = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) + } + + func makeSplit() -> (SettingsSplitViewController, NSWindow) { + let split = SettingsSplitViewController(registryClient: registry.client) + let window = NSWindow(contentViewController: split) + window.isReleasedWhenClosed = false + windows.append(window) + return (split, window) + } + + func tearDown() async { + for window in windows { + window.contentViewController = nil + window.orderOut(nil) + } + windows = [] + await registry.settle() + let key = PreferenceKeys.selectedSettingsPane.name + if let storedPane { + AppStorageEnvironment.shared.defaults.set(storedPane, forKey: key) + } else { + AppStorageEnvironment.shared.defaults.removeObject(forKey: key) + } + } } - try await super.tearDown() - } - // The Plugins pane fetches the registry manifest when it appears. - private func offlineRegistryClient() -> RegistryClient { - guard let registry else { - XCTFail("setUpWithError builds the offline registry") - return RegistryClient.shared + @Test("The sidebar order is every pane exactly once") + func everyPaneIsReachableExactlyOnce() { + #expect(SettingsNavigation.orderedPanes.count == SettingsPane.allCases.count) + #expect(Set(SettingsNavigation.orderedPanes) == Set(SettingsPane.allCases)) } - return registry.client - } - private func makePanes() -> (SettingsPaneTabViewController, NSWindow) { - let panes = SettingsPaneTabViewController(registryClient: offlineRegistryClient()) - let window = NSWindow(contentViewController: panes) - window.isReleasedWhenClosed = false - windows.append(window) - return (panes, window) - } - - func testEveryPaneIsReachableAndCarriesItsOwnTitle() { - let (panes, _) = makePanes() - _ = panes.view + @Test("The window title follows the selected pane") + func windowTitleFollowsTheSelectedPane() async throws { + let host = try Host() + let (split, window) = host.makeSplit() - XCTAssertEqual(SettingsPaneTabViewController.paneOrder, SettingsPane.allCases) - XCTAssertEqual(panes.tabViewItems.count, SettingsPane.allCases.count) - for (item, pane) in zip(panes.tabViewItems, SettingsPane.allCases) { - XCTAssertEqual(item.viewController?.title, pane.title) - XCTAssertEqual(item.label, pane.title) + for pane in SettingsPane.allCases { + split.navigate(to: pane) + #expect(window.title == pane.title) + } + await host.tearDown() } - } - - /// `NSWindow(contentViewController:)` binds the window title to that controller's title and - /// substitutes "Untitled" whenever it is nil, so a pane switch used to erase the title. - func testTheWindowTitleFollowsTheSelectedPane() { - let (panes, window) = makePanes() - for pane in SettingsPane.allCases { - panes.select(pane) - XCTAssertEqual(window.title, pane.title) + @Test("A fresh controller opens on the persisted pane") + func freshControllerOpensOnThePersistedPane() async throws { + let host = try Host() + AppStorageEnvironment.shared.defaults.set( + SettingsPane.keyboard.rawValue, + forKey: PreferenceKeys.selectedSettingsPane.name + ) + let (_, window) = host.makeSplit() + #expect(window.title == SettingsPane.keyboard.title) + await host.tearDown() } - } - - func testAFreshControllerOpensOnThePersistedPane() { - AppStorageEnvironment.shared.defaults.set( - SettingsPane.keyboard.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name - ) - let (_, window) = makePanes() - - XCTAssertEqual(window.title, SettingsPane.keyboard.title) - } - - func testAStoredMCPPaneRestoresThePaneTitledMCP() { - AppStorageEnvironment.shared.defaults.set("mcp", forKey: PreferenceKeys.selectedSettingsPane.name) - - let (_, window) = makePanes() - - XCTAssertEqual(window.title, "MCP") - } - - // The rawValue is the persisted pane and the tab item identifier, so it outlives any title. - func testPaneIdentifiersSurviveTitleChanges() { - XCTAssertEqual(SettingsPane.mcp.rawValue, "mcp") - XCTAssertEqual(SettingsPane.account.rawValue, "account") - } - - func testAskingForNoPaneReadsTheStoredPaneRatherThanStayingPut() { - let (panes, window) = makePanes() - panes.select(.plugins) - XCTAssertEqual(window.title, SettingsPane.plugins.title) - - AppStorageEnvironment.shared.defaults.set( - SettingsPane.editor.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name - ) - panes.select(nil) + @Test("A stored MCP pane restores the pane titled MCP") + func storedMCPPaneRestoresTheMCPTitle() async throws { + let host = try Host() + AppStorageEnvironment.shared.defaults.set("mcp", forKey: PreferenceKeys.selectedSettingsPane.name) + let (_, window) = host.makeSplit() + #expect(window.title == "MCP") + await host.tearDown() + } - XCTAssertEqual(window.title, SettingsPane.editor.title) - } + // The rawValue is the persisted pane and the deep-link id, so it outlives any title. + @Test("Pane identifiers survive title changes") + func paneIdentifiersSurviveTitleChanges() { + #expect(SettingsPane.mcp.rawValue == "mcp") + #expect(SettingsPane.account.rawValue == "account") + #expect(SettingsPane.account.urlIdentifier == "license") + } - func testTheWindowRefusesToShrinkBelowAPane() { - let controller = SettingsWindowController(registryClient: offlineRegistryClient()) - guard let window = controller.window else { return XCTFail("The controller must build a window") } - windows.append(window) + @Test("Navigating with no pane reads the stored pane rather than staying put") + func navigatingWithNoPaneReadsTheStoredPane() async throws { + let host = try Host() + let (split, window) = host.makeSplit() + split.navigate(to: .plugins) + #expect(window.title == SettingsPane.plugins.title) + + AppStorageEnvironment.shared.defaults.set( + SettingsPane.editor.rawValue, + forKey: PreferenceKeys.selectedSettingsPane.name + ) + split.navigate(to: nil) + #expect(window.title == SettingsPane.editor.title) + await host.tearDown() + } - XCTAssertEqual(window.contentMinSize, SettingsPaneTabViewController.paneSize) - } + // A deep link / openSettings jump must not overwrite the user's last-used pane. + @Test("A programmatic jump does not clobber the persisted pane") + func programmaticJumpDoesNotClobberThePersistedPane() async throws { + let host = try Host() + let key = PreferenceKeys.selectedSettingsPane.name + AppStorageEnvironment.shared.defaults.set(SettingsPane.editor.rawValue, forKey: key) + let (split, _) = host.makeSplit() + + split.navigate(to: .ai) + #expect(AppStorageEnvironment.shared.defaults.string(forKey: key) == SettingsPane.editor.rawValue) + + // A user click, by contrast, persists. + split.model.userSelect(.mcp) + #expect(AppStorageEnvironment.shared.defaults.string(forKey: key) == SettingsPane.mcp.rawValue) + await host.tearDown() + } - func testTheInitializerPresentUsesBuildsTheSettingsWindow() { - AppStorageEnvironment.shared.defaults.set( - SettingsPane.general.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name - ) - let controller = SettingsWindowController() - guard let window = controller.window else { return XCTFail("Cmd-comma and settings links present this controller") } - windows.append(window) + @Test("The window refuses to shrink below the sidebar plus detail minimum") + func theWindowRefusesToShrinkBelowTheMinimum() async throws { + let host = try Host() + let controller = SettingsWindowController(registryClient: host.registry.client) + let window = try #require(controller.window, "The controller must build a window") + window.isReleasedWhenClosed = false + host.windows.append(window) + #expect(window.contentMinSize == SettingsSplitViewController.minimumContentSize) + await host.tearDown() + } - XCTAssertEqual(window.identifier?.rawValue, WindowIdentifier.settings) + @Test("present() builds the settings window with its identifier") + func presentBuildsTheSettingsWindow() async throws { + let host = try Host() + AppStorageEnvironment.shared.defaults.set( + SettingsPane.general.rawValue, + forKey: PreferenceKeys.selectedSettingsPane.name + ) + let controller = SettingsWindowController() + let window = try #require(controller.window, "Cmd-comma and settings links present this controller") + window.isReleasedWhenClosed = false + host.windows.append(window) + #expect(window.identifier?.rawValue == WindowIdentifier.settings) + await host.tearDown() + } } } From ac9312a3d18e5835d03736a981ab59a0f7622c3a Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 10:04:27 +0700 Subject: [PATCH 02/48] feat(settings): drill-in sub-pages with push/back nav for Appearance, Editor, Data, Sync --- .../Settings/AppearanceSettingsView.swift | 17 ++--- .../Settings/DataResultsSettingsView.swift | 13 ++-- .../Views/Settings/EditorSettingsView.swift | 9 ++- .../Views/Settings/Sections/SyncSection.swift | 14 +++- .../Views/Settings/SettingsSubpage.swift | 14 ++++ .../Settings/SettingsWindowController.swift | 75 ++++++++++++++++--- .../Settings/AppearancePaneListTests.swift | 6 +- 7 files changed, 112 insertions(+), 36 deletions(-) diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index 9170061c6a..d4b43c0395 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -10,15 +10,6 @@ internal struct AppearanceSettingsView: View { private static let modes: [AppAppearanceMode] = [.auto, .light, .dark] internal var body: some View { - VStack(spacing: 0) { - settingsForm - ThemeLibrarySection() - } - } - - // A List inside a scrolling grouped Form does not scroll (measured on macOS 27), so the Form - // keeps its own height and the theme list sits below it. - private var settingsForm: some View { Form { Section { Picker(String(localized: "Appearance"), selection: $settingsManager.appearanceMode) { @@ -37,10 +28,14 @@ internal struct AppearanceSettingsView: View { } footer: { Text("Themes color the editor, the data grid, other content views and the window background. Controls, sidebars and Settings follow the system appearance.") } + + Section { + NavigationLink(value: SettingsSubpage.manageThemes) { + Label("Manage Themes", systemImage: "paintpalette") + } + } } .formStyle(.grouped) - .scrollDisabled(true) - .fixedSize(horizontal: false, vertical: true) } private static func title(for mode: AppAppearanceMode) -> String { diff --git a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift index bda0adaed7..0a71ad4606 100644 --- a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift +++ b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift @@ -8,7 +8,6 @@ import SwiftUI struct DataResultsSettingsView: View { @Binding var dataGrid: DataGridSettings @Binding var valueColors: ValueColorSettings - @Binding var history: HistorySettings @Binding var editor: EditorSettings @Binding var typography: TypographySettings @@ -25,9 +24,14 @@ struct DataResultsSettingsView: View { } } - HistorySection(settings: $history) - - DataRewindSection(settings: $history) + Section { + NavigationLink(value: SettingsSubpage.queryHistory) { + Label("Query History", systemImage: "clock.arrow.circlepath") + } + NavigationLink(value: SettingsSubpage.dataRewind) { + Label("Data Rewind", systemImage: "arrow.uturn.backward") + } + } } .formStyle(.grouped) } @@ -37,7 +41,6 @@ struct DataResultsSettingsView: View { DataResultsSettingsView( dataGrid: .constant(.default), valueColors: .constant(.default), - history: .constant(.default), editor: .constant(.default), typography: .constant(.default) ) diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index 9d9d68da78..ceedf3e0f3 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -8,7 +8,6 @@ import TableProAutocomplete struct EditorSettingsView: View { @Binding var settings: EditorSettings - @Binding var formatter: SQLFormatterSettings @Binding var typography: TypographySettings var body: some View { @@ -50,13 +49,17 @@ struct EditorSettingsView: View { .accessibilityIdentifier("key-bindings-picker") } - FormatterSection(settings: $formatter, editor: settings) + Section { + NavigationLink(value: SettingsSubpage.sqlFormatting) { + Label("SQL Formatting", systemImage: "text.alignleft") + } + } } .formStyle(.grouped) } } #Preview { - EditorSettingsView(settings: .constant(.default), formatter: .constant(.default), typography: .constant(.default)) + EditorSettingsView(settings: .constant(.default), typography: .constant(.default)) .frame(width: 450, height: 500) } diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift index ba96e48ba2..881191edac 100644 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ b/apple/TablePro/Views/Settings/Sections/SyncSection.swift @@ -30,7 +30,11 @@ struct SyncSection: View { if settingsManager.sync.enabled && isProAvailable { statusSection - categoriesSection + Section { + NavigationLink(value: SettingsSubpage.whatSyncs) { + Label("What Syncs", systemImage: "checklist") + } + } } } @@ -76,9 +80,13 @@ struct SyncSection: View { } } - // MARK: - Categories +} + +// The sync-category toggles, shown on the What Syncs drill-in. +struct SyncCategoriesSection: View { + @ObservedObject private var settingsManager = AppSettingsManager.shared - private var categoriesSection: some View { + var body: some View { Section("Sync Categories") { Toggle("Connections", isOn: $settingsManager.sync.syncConnections) .onChange(of: settingsManager.sync.syncConnections) { newValue in diff --git a/apple/TablePro/Views/Settings/SettingsSubpage.swift b/apple/TablePro/Views/Settings/SettingsSubpage.swift index 784e781d9f..44e40da0bc 100644 --- a/apple/TablePro/Views/Settings/SettingsSubpage.swift +++ b/apple/TablePro/Views/Settings/SettingsSubpage.swift @@ -11,10 +11,19 @@ import Foundation enum SettingsSubpage: String, Hashable, CaseIterable { case softwareUpdate case commandLine + case manageThemes + case sqlFormatting + case queryHistory + case dataRewind + case whatSyncs var parent: SettingsPane { switch self { case .softwareUpdate, .commandLine: .general + case .manageThemes: .appearance + case .sqlFormatting: .editor + case .queryHistory, .dataRewind: .data + case .whatSyncs: .sync } } @@ -22,6 +31,11 @@ enum SettingsSubpage: String, Hashable, CaseIterable { switch self { case .softwareUpdate: String(localized: "Software Update") case .commandLine: String(localized: "Command Line Tool") + case .manageThemes: String(localized: "Manage Themes") + case .sqlFormatting: String(localized: "SQL Formatting") + case .queryHistory: String(localized: "Query History") + case .dataRewind: String(localized: "Data Rewind") + case .whatSyncs: String(localized: "What Syncs") } } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 256e823d60..0486715f34 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -39,6 +39,9 @@ internal final class SettingsWindowController: NSWindowController { window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.settings) window.keepsKeyViewLoopCurrent() window.styleMask = [.titled, .closable, .resizable] + // The detail's NavigationStack renders its back button and title into the window toolbar. + window.toolbar = NSToolbar() + window.toolbarStyle = .unified window.isRestorable = false window.contentMinSize = SettingsSplitViewController.minimumContentSize window.setContentSize(SettingsSplitViewController.minimumContentSize) @@ -104,6 +107,10 @@ internal final class SettingsSplitViewController: NSSplitViewController { let detail = NSHostingController(rootView: SettingsDetailView(model: model, registryClient: registryClient)) // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. detail.sizingOptions = [] + // Bridge the detail's NavigationStack toolbar (back button, title) into the window toolbar. + if #available(macOS 14.0, *) { + detail.sceneBridgingOptions = [.toolbars] + } let detailItem = NSSplitViewItem(viewController: detail) detailItem.minimumThickness = Self.detailMinWidth detailItem.holdingPriority = NSLayoutConstraint.Priority(260) // below dragThatCannotResizeWindow (490) @@ -184,14 +191,16 @@ private struct SettingsSidebarView: View { private struct SettingsDetailView: View { @ObservedObject fileprivate var model: SettingsNavigationModel + @ObservedObject fileprivate var settingsManager = AppSettingsManager.shared fileprivate let registryClient: RegistryClient fileprivate var body: some View { NavigationStack { SettingsPaneContent(pane: model.selection, registryClient: registryClient) .frame(maxWidth: .infinity, maxHeight: .infinity) + .navigationTitle(model.selection.title) .navigationDestination(for: SettingsSubpage.self) { subpage in - SettingsSubpageView(subpage: subpage) + SettingsSubpageView(settingsManager: settingsManager, subpage: subpage) .frame(maxWidth: .infinity, maxHeight: .infinity) } } @@ -203,19 +212,65 @@ private struct SettingsDetailView: View { // A pushed drill-in page. Back button and title come from the NavigationStack. private struct SettingsSubpageView: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject fileprivate var settingsManager: AppSettingsManager fileprivate let subpage: SettingsSubpage fileprivate var body: some View { - Form { - switch subpage { - case .softwareUpdate: - SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) - case .commandLine: - CommandLineToolSection() + content + .navigationTitle(subpage.title) + .toolbar { + ToolbarItem(placement: .navigation) { backButton } } + .safeAreaInset(edge: .top, spacing: 0) { + // macOS 13 does not bridge the NavigationStack back button to the window toolbar. + if #unavailable(macOS 14.0) { + HStack { + backButton + Spacer() + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(.bar) + } + } + } + + private var backButton: some View { + Button { + dismiss() + } label: { + Image(systemName: "chevron.backward") + } + .help(String(localized: "Back")) + .accessibilityLabel(String(localized: "Back")) + } + + @ViewBuilder private var content: some View { + switch subpage { + case .softwareUpdate: + Form { SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) } + .formStyle(.grouped) + case .commandLine: + Form { CommandLineToolSection() } + .formStyle(.grouped) + case .manageThemes: + // Not wrapped in a Form: a List inside a grouped Form does not scroll on macOS. + ThemeLibrarySection() + .frame(maxWidth: .infinity, maxHeight: .infinity) + case .sqlFormatting: + Form { FormatterSection(settings: $settingsManager.formatter, editor: settingsManager.editor) } + .formStyle(.grouped) + case .queryHistory: + Form { HistorySection(settings: $settingsManager.history) } + .formStyle(.grouped) + case .dataRewind: + Form { DataRewindSection(settings: $settingsManager.history) } + .formStyle(.grouped) + case .whatSyncs: + Form { SyncCategoriesSection() } + .formStyle(.grouped) } - .formStyle(.grouped) - .navigationTitle(subpage.title) } } @@ -249,14 +304,12 @@ private struct SettingsPaneContent: View { case .editor: EditorSettingsView( settings: $settingsManager.editor, - formatter: $settingsManager.formatter, typography: $settingsManager.typography ) case .data: DataResultsSettingsView( dataGrid: $settingsManager.dataGrid, valueColors: $settingsManager.valueColors, - history: $settingsManager.history, editor: $settingsManager.editor, typography: $settingsManager.typography ) diff --git a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift index 581d4d331f..b5b875c556 100644 --- a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift +++ b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift @@ -4,8 +4,8 @@ import ApplicationServices import SwiftUI import Testing -/// A List inside the pane's scrolling grouped Form had its scrolling turned off by SwiftUI, so the -/// themes below the first few rows could never be reached. +/// The Themes list lives in the Manage Themes drill-in, free of the grouped Form that used to +/// disable its scrolling. It must scroll on its own and hold still while accessibility reads it. @MainActor struct AppearancePaneListTests { private struct HostedPane { @@ -54,7 +54,7 @@ struct AppearancePaneListTests { window.isReleasedWhenClosed = false window.title = windowTitle // As the Settings window hosts a pane: the window keeps its size whatever the content asks. - let hosting = NSHostingController(rootView: AppearanceSettingsView(settings: .constant(.default))) + let hosting = NSHostingController(rootView: ThemeLibrarySection()) hosting.sizingOptions = [] window.contentViewController = hosting window.setContentSize(paneSize) From 93df2482eeb8ab3e3e863445d373247d1ddd2f78 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 10:14:21 +0700 Subject: [PATCH 03/48] feat(settings): Account drill-ins (Features, Devices, Teams, Offline) + shared drill-in chrome --- .../Account/AccountSettingsView.swift | 63 ++++++++++++++++--- .../Settings/SettingsDrillInChrome.swift | 49 +++++++++++++++ .../Settings/SettingsWindowController.swift | 28 +-------- 3 files changed, 105 insertions(+), 35 deletions(-) create mode 100644 apple/TablePro/Views/Settings/SettingsDrillInChrome.swift diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift index 51a2de5c4f..ac37ac9a77 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift @@ -16,6 +16,16 @@ internal struct AccountSettingsView: View { _model = StateObject(wrappedValue: model()) } + private enum Subpage: Hashable { + case features, devices, teams, offline + } + + private var showsTeams: Bool { + let content = model.content + let failure = model.access.state.isSignedIn ? model.profile.failure : nil + return content.teams?.isEmpty == false || failure != nil || (content.teams == nil && model.profile.isLoading) + } + var body: some View { let content = model.content Form { @@ -25,17 +35,29 @@ internal struct AccountSettingsView: View { planSection(content) } - AccountFeaturesSection(access: model.access, offersPurchase: content.identity == .signedOut) - - if content.showsDevices { - devicesSection(content.devices) + Section { + NavigationLink(value: Subpage.features) { + Label("Features", systemImage: "star") + } + if content.showsDevices { + NavigationLink(value: Subpage.devices) { + Label("Devices", systemImage: "laptopcomputer") + } + } + if showsTeams { + NavigationLink(value: Subpage.teams) { + Label("Teams", systemImage: "person.2") + } + } + NavigationLink(value: Subpage.offline) { + Label("Offline", systemImage: "wifi.slash") + } } - - teamsSection(content.teams) - - AccountOfflineSection(model: model, content: content) } .formStyle(.grouped) + .navigationDestination(for: Subpage.self) { subpage in + destination(for: subpage) + } .task { await model.reload() } .sheet(isPresented: $model.presentsDeviceLimit) { DeviceLimitSheet(model: DeviceLimitModel(services: model.services)) @@ -80,6 +102,31 @@ internal struct AccountSettingsView: View { } } + @ViewBuilder + private func destination(for subpage: Subpage) -> some View { + let content = model.content + switch subpage { + case .features: + Form { + AccountFeaturesSection(access: model.access, offersPurchase: content.identity == .signedOut) + } + .formStyle(.grouped) + .settingsDrillIn(title: String(localized: "Features")) + case .devices: + Form { devicesSection(content.devices) } + .formStyle(.grouped) + .settingsDrillIn(title: String(localized: "Devices")) + case .teams: + Form { teamsSection(content.teams) } + .formStyle(.grouped) + .settingsDrillIn(title: String(localized: "Teams")) + case .offline: + Form { AccountOfflineSection(model: model, content: content) } + .formStyle(.grouped) + .settingsDrillIn(title: String(localized: "Offline")) + } + } + // MARK: - Plan private func planSection(_ content: AccountSettingsContent) -> some View { diff --git a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift new file mode 100644 index 0000000000..612a178dda --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift @@ -0,0 +1,49 @@ +// +// SettingsDrillInChrome.swift +// TablePro +// + +import SwiftUI + +// Title and a Back control for any page pushed onto a Settings pane's NavigationStack. The back +// button rides the window toolbar on macOS 14+ (the detail hosting controller bridges toolbars); +// macOS 13 cannot bridge it, so an inline bar carries the same button there. +private struct SettingsDrillInChrome: ViewModifier { + @Environment(\.dismiss) private var dismiss + let title: String + + func body(content: Content) -> some View { + content + .navigationTitle(title) + .toolbar { + ToolbarItem(placement: .navigation) { backButton } + } + .safeAreaInset(edge: .top, spacing: 0) { + if #unavailable(macOS 14.0) { + HStack { + backButton + Spacer() + } + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(.bar) + } + } + } + + private var backButton: some View { + Button { + dismiss() + } label: { + Image(systemName: "chevron.backward") + } + .help(String(localized: "Back")) + .accessibilityLabel(String(localized: "Back")) + } +} + +extension View { + func settingsDrillIn(title: String) -> some View { + modifier(SettingsDrillInChrome(title: title)) + } +} diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 0486715f34..a92f8eb0cb 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -212,38 +212,12 @@ private struct SettingsDetailView: View { // A pushed drill-in page. Back button and title come from the NavigationStack. private struct SettingsSubpageView: View { - @Environment(\.dismiss) private var dismiss @ObservedObject fileprivate var settingsManager: AppSettingsManager fileprivate let subpage: SettingsSubpage fileprivate var body: some View { content - .navigationTitle(subpage.title) - .toolbar { - ToolbarItem(placement: .navigation) { backButton } - } - .safeAreaInset(edge: .top, spacing: 0) { - // macOS 13 does not bridge the NavigationStack back button to the window toolbar. - if #unavailable(macOS 14.0) { - HStack { - backButton - Spacer() - } - .padding(.horizontal, 12) - .padding(.vertical, 6) - .background(.bar) - } - } - } - - private var backButton: some View { - Button { - dismiss() - } label: { - Image(systemName: "chevron.backward") - } - .help(String(localized: "Back")) - .accessibilityLabel(String(localized: "Back")) + .settingsDrillIn(title: subpage.title) } @ViewBuilder private var content: some View { From 6c7cd9d3140b14aecbceda3077d7b5a565dcd0e4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 10:28:33 +0700 Subject: [PATCH 04/48] feat(settings): Extensions list + push detail, replacing the nested split --- .../Plugins/InstalledPluginsView.swift | 156 +++++++----------- .../Settings/SettingsWindowController.swift | 30 +++- 2 files changed, 77 insertions(+), 109 deletions(-) diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index a2e78f03f2..0ed38eabe3 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -12,15 +12,16 @@ struct InstalledPluginsView: View { @ObservedObject private var modules = AppModuleSettings.shared @ObservedObject private var updates = UpdateCenter.shared - @State private var selection: PluginListSelection? + @Binding private var path: NavigationPath @State private var searchText = "" @State private var showErrorAlert = false @State private var errorAlertTitle = "" @State private var errorAlertMessage = "" @State private var isRetryingRejected = false - init(registryClient: RegistryClient = .shared) { + init(registryClient: RegistryClient = .shared, path: Binding = .constant(NavigationPath())) { self.registryClient = registryClient + self._path = path } private var filteredPlugins: [PluginEntry] { @@ -38,17 +39,14 @@ struct InstalledPluginsView: View { } var body: some View { - HSplitView { - pluginList - .frame(minWidth: 200, idealWidth: 240, maxWidth: 280) - - detailPane - .frame(minWidth: 340) - } - .task { - await registryClient.fetch(policy: .ifStale) - } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + pluginList + .task { + await registryClient.fetch(policy: .ifStale) + } + .navigationDestination(for: PluginListSelection.self) { selection in + detailPage(for: selection) + } + .onDrop(of: [.fileURL], isTargeted: nil) { providers in guard let provider = providers.first, provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) else { return false @@ -73,7 +71,6 @@ struct InstalledPluginsView: View { // MARK: - Relaunch Row - // Untagged, so it never takes the selection; the list is where the pending removal is. private var relaunchRow: some View { HStack(spacing: 8) { Label { @@ -217,7 +214,7 @@ struct InstalledPluginsView: View { showErrorAlert = true return } - if selection == .rejected(plugin.url) { selection = nil } + if !path.isEmpty { path.removeLast() } } } @@ -229,60 +226,43 @@ struct InstalledPluginsView: View { .padding(.horizontal, 8) .padding(.vertical, 6) - ScrollViewReader { proxy in - List(selection: $selection) { - if pluginManager.needsRestart { - Section { - relaunchRow - } + List { + if pluginManager.needsRestart { + Section { + relaunchRow } - if !filteredModules.isEmpty { - // Untagged, so a module row toggles but never takes the plugin selection. - Section(String(localized: "Modules")) { - ForEach(filteredModules, id: \.self) { module in - ModuleToggleRow(module: module, settings: modules) - } + } + if !filteredModules.isEmpty { + Section(String(localized: "Modules")) { + ForEach(filteredModules, id: \.self) { module in + ModuleToggleRow(module: module, settings: modules) } } - if !filteredRejected.isEmpty { - Section(String(localized: "Couldn't Load")) { - ForEach(filteredRejected, id: \.url) { plugin in + } + if !filteredRejected.isEmpty { + Section(String(localized: "Couldn't Load")) { + ForEach(filteredRejected, id: \.url) { plugin in + NavigationLink(value: PluginListSelection.rejected(plugin.url)) { rejectedRow(plugin) - .tag(PluginListSelection.rejected(plugin.url)) - .id(PluginListSelection.rejected(plugin.url)) } } } - Section(String(localized: "Plugins")) { - ForEach(filteredPlugins) { plugin in + } + Section(String(localized: "Plugins")) { + ForEach(filteredPlugins) { plugin in + NavigationLink(value: PluginListSelection.plugin(plugin.id)) { pluginRow(plugin) - .tag(PluginListSelection.plugin(plugin.id)) - .id(PluginListSelection.plugin(plugin.id)) } } } - .listStyle(.inset) - .safeAreaInset(edge: .bottom, spacing: 0) { - listBottomBar - } - .onAppear { revealRequestedPlugin() } - .onChange(of: navigation.pendingRequest) { _ in - revealRequestedPlugin() - } - .onChange(of: selection) { selection in - guard let selection else { return } - proxy.scrollTo(selection) - } } - } - .onChange(of: searchText) { _ in - switch selection { - case .plugin(let id) where !filteredPlugins.contains(where: { $0.id == id }): - selection = nil - case .rejected(let url) where !filteredRejected.contains(where: { $0.url == url }): - selection = nil - default: - break + .listStyle(.inset) + .safeAreaInset(edge: .bottom, spacing: 0) { + listBottomBar + } + .onAppear { revealRequestedPlugin() } + .onChange(of: navigation.pendingRequest) { _ in + revealRequestedPlugin() } } } @@ -397,21 +377,6 @@ struct InstalledPluginsView: View { .disabled(pluginManager.isInstalling) .accessibilityLabel(String(localized: "Install plugin from file")) - Button { - if let plugin = selectedPlugin { - uninstallPlugin(plugin) - } - } label: { - Image(systemName: "minus") - .frame(width: 24, height: 20) - } - .buttonStyle(.borderless) - .disabled(selectedPlugin == nil || selectedPlugin?.source == .builtIn) - .accessibilityLabel( - selectedPlugin.map { String(format: String(localized: "Uninstall %@"), $0.name) } - ?? String(localized: "Uninstall plugin") - ) - Spacer() } .padding(.horizontal, 8) @@ -483,22 +448,24 @@ struct InstalledPluginsView: View { // MARK: - Detail Pane - private var selectedPlugin: PluginEntry? { - guard case .plugin(let id) = selection else { return nil } - return pluginManager.plugins.first { $0.id == id } - } - - private var selectedRejected: RejectedPlugin? { - guard case .rejected(let url) = selection else { return nil } - return pluginManager.rejectedPlugins.first { $0.url == url } + @ViewBuilder + private func detailPage(for selection: PluginListSelection) -> some View { + switch selection { + case .rejected(let url): + if let rejected = pluginManager.rejectedPlugins.first(where: { $0.url == url }) { + rejectedDetail(rejected) + .settingsDrillIn(title: rejected.name) + } + case .plugin(let id): + if let selected = pluginManager.plugins.first(where: { $0.id == id }) { + pluginDetail(selected) + .settingsDrillIn(title: selected.name) + } + } } - @ViewBuilder - private var detailPane: some View { - if let rejected = selectedRejected { - rejectedDetail(rejected) - } else if let selected = selectedPlugin { - ScrollView { + private func pluginDetail(_ selected: PluginEntry) -> some View { + ScrollView { VStack(alignment: .leading, spacing: 16) { Text(selected.name) .font(.title3.weight(.semibold)) @@ -575,18 +542,7 @@ struct InstalledPluginsView: View { .padding(20) .frame(maxWidth: .infinity, alignment: .leading) } - } else { - VStack(spacing: 8) { - Image(systemName: "puzzlepiece.extension") - .font(.title) - .foregroundStyle(.tertiary) - Text("Select a plugin to view details") - .font(.headline) - .foregroundStyle(.secondary) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) } - } // A failure shows on the plugin's row or in the list's bottom bar, from the tracker. private func updatePlugin(_ registryPlugin: RegistryPlugin) { @@ -616,7 +572,7 @@ struct InstalledPluginsView: View { rejected: pluginManager.rejectedPlugins ) else { return } searchText = "" - selection = target + path.append(target) } private func installFromFile() { @@ -638,7 +594,7 @@ struct InstalledPluginsView: View { private func installPlugin(from url: URL) { Task { guard let entry = try? await pluginManager.installPlugin(from: url) else { return } - selection = .plugin(entry.id) + path.append(PluginListSelection.plugin(entry.id)) } } @@ -655,7 +611,7 @@ struct InstalledPluginsView: View { do { try await pluginManager.uninstallPlugin(id: plugin.id) - selection = nil + if !path.isEmpty { path.removeLast() } } catch { errorAlertTitle = String(localized: "Uninstall Failed") errorAlertMessage = error.localizedDescription diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index a92f8eb0cb..f3590bb660 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -191,22 +191,32 @@ private struct SettingsSidebarView: View { private struct SettingsDetailView: View { @ObservedObject fileprivate var model: SettingsNavigationModel - @ObservedObject fileprivate var settingsManager = AppSettingsManager.shared fileprivate let registryClient: RegistryClient fileprivate var body: some View { - NavigationStack { - SettingsPaneContent(pane: model.selection, registryClient: registryClient) + // Each pane owns its own stack, keyed by selection, so switching panes resets its depth. + SettingsPaneStack(pane: model.selection, registryClient: registryClient) + .id(model.selection) + .environment(\.appServices, .live) + } +} + +private struct SettingsPaneStack: View { + @ObservedObject private var settingsManager = AppSettingsManager.shared + fileprivate let pane: SettingsPane + fileprivate let registryClient: RegistryClient + @State private var path = NavigationPath() + + fileprivate var body: some View { + NavigationStack(path: $path) { + SettingsPaneContent(pane: pane, registryClient: registryClient, path: $path) .frame(maxWidth: .infinity, maxHeight: .infinity) - .navigationTitle(model.selection.title) + .navigationTitle(pane.title) .navigationDestination(for: SettingsSubpage.self) { subpage in SettingsSubpageView(settingsManager: settingsManager, subpage: subpage) .frame(maxWidth: .infinity, maxHeight: .infinity) } } - // Each pane owns its own navigation depth; switching panes resets any pushed sub-page. - .id(model.selection) - .environment(\.appServices, .live) } } @@ -253,10 +263,12 @@ private struct SettingsPaneContent: View { private let pane: SettingsPane private let registryClient: RegistryClient + private let path: Binding - fileprivate init(pane: SettingsPane, registryClient: RegistryClient) { + fileprivate init(pane: SettingsPane, registryClient: RegistryClient, path: Binding) { self.pane = pane self.registryClient = registryClient + self.path = path } fileprivate var body: some View { @@ -298,7 +310,7 @@ private struct SettingsPaneContent: View { case .mcp: MCPSettingsView(settings: $settingsManager.mcp) case .plugins: - InstalledPluginsView(registryClient: registryClient) + InstalledPluginsView(registryClient: registryClient, path: path) .frame(maxWidth: .infinity, maxHeight: .infinity) case .sync: SyncSettingsView() From 3f2ebc8be989c7b565195e10efb53f2d0ac5e504 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 10:36:16 +0700 Subject: [PATCH 05/48] chore(settings): changelog fragment and lint fixes --- .../Plugins/InstalledPluginsView.swift | 114 +++++++++--------- .../Views/Settings/Sections/SyncSection.swift | 1 - apple/changelog.d/4413.changed.md | 1 + 3 files changed, 58 insertions(+), 58 deletions(-) create mode 100644 apple/changelog.d/4413.changed.md diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index 0ed38eabe3..c02d3a3b15 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -40,13 +40,13 @@ struct InstalledPluginsView: View { var body: some View { pluginList - .task { - await registryClient.fetch(policy: .ifStale) - } - .navigationDestination(for: PluginListSelection.self) { selection in - detailPage(for: selection) - } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + .task { + await registryClient.fetch(policy: .ifStale) + } + .navigationDestination(for: PluginListSelection.self) { selection in + detailPage(for: selection) + } + .onDrop(of: [.fileURL], isTargeted: nil) { providers in guard let provider = providers.first, provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) else { return false @@ -466,83 +466,83 @@ struct InstalledPluginsView: View { private func pluginDetail(_ selected: PluginEntry) -> some View { ScrollView { - VStack(alignment: .leading, spacing: 16) { - Text(selected.name) - .font(.title3.weight(.semibold)) + VStack(alignment: .leading, spacing: 16) { + Text(selected.name) + .font(.title3.weight(.semibold)) + + Text("v\(selected.version), \(selected.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed"))") + .font(.subheadline) + .foregroundStyle(.secondary) - Text("v\(selected.version), \(selected.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed"))") - .font(.subheadline) + if !selected.pluginDescription.isEmpty { + Text(selected.pluginDescription) + .font(.callout) .foregroundStyle(.secondary) + } + + Divider() - if !selected.pluginDescription.isEmpty { - Text(selected.pluginDescription) - .font(.callout) + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { + GridRow { + Text("Bundle ID") .foregroundStyle(.secondary) + .gridColumnAlignment(.leading) + Text(selected.id) + .textSelection(.enabled) + .gridColumnAlignment(.leading) } - Divider() + if !selected.capabilities.isEmpty { + GridRow { + Text("Capabilities") + .foregroundStyle(.secondary) + Text(selected.capabilities.map(\.displayName).joined(separator: ", ")) + } + } - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { + if let typeId = selected.databaseTypeId { GridRow { - Text("Bundle ID") + Text("Database Type") .foregroundStyle(.secondary) - .gridColumnAlignment(.leading) - Text(selected.id) - .textSelection(.enabled) - .gridColumnAlignment(.leading) + Text(typeId) } - if !selected.capabilities.isEmpty { + if !selected.additionalTypeIds.isEmpty { GridRow { - Text("Capabilities") + Text("Also handles") .foregroundStyle(.secondary) - Text(selected.capabilities.map(\.displayName).joined(separator: ", ")) + Text(selected.additionalTypeIds.joined(separator: ", ")) } } - if let typeId = selected.databaseTypeId { + if let port = selected.defaultPort { GridRow { - Text("Database Type") + Text("Default Port") .foregroundStyle(.secondary) - Text(typeId) - } - - if !selected.additionalTypeIds.isEmpty { - GridRow { - Text("Also handles") - .foregroundStyle(.secondary) - Text(selected.additionalTypeIds.joined(separator: ", ")) - } - } - - if let port = selected.defaultPort { - GridRow { - Text("Default Port") - .foregroundStyle(.secondary) - Text(verbatim: "\(port)") - } + Text(verbatim: "\(port)") } } } - .font(.callout) + } + .font(.callout) - if let settable = pluginManager.pluginInstances[selected.id] as? any SettablePluginDiscoverable, - let pluginSettings = settable.settingsView() { - Divider() - pluginSettings - } + if let settable = pluginManager.pluginInstances[selected.id] as? any SettablePluginDiscoverable, + let pluginSettings = settable.settingsView() { + Divider() + pluginSettings + } - if selected.source == .userInstalled { - Divider() - Button("Uninstall", role: .destructive) { - uninstallPlugin(selected) - } + if selected.source == .userInstalled { + Divider() + Button("Uninstall", role: .destructive) { + uninstallPlugin(selected) } } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) } + .padding(20) + .frame(maxWidth: .infinity, alignment: .leading) } + } // A failure shows on the plugin's row or in the list's bottom bar, from the tracker. private func updatePlugin(_ registryPlugin: RegistryPlugin) { diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift index 881191edac..caac197539 100644 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ b/apple/TablePro/Views/Settings/Sections/SyncSection.swift @@ -79,7 +79,6 @@ struct SyncSection: View { } } } - } // The sync-category toggles, shown on the What Syncs drill-in. diff --git a/apple/changelog.d/4413.changed.md b/apple/changelog.d/4413.changed.md new file mode 100644 index 0000000000..67e206bb59 --- /dev/null +++ b/apple/changelog.d/4413.changed.md @@ -0,0 +1 @@ +Settings moved to a macOS sidebar layout, with General split into General, Sidebar & Tabs and Connections. From 36a3ac538458ecb3c5daff88829a23ca22d358b4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 10:59:22 +0700 Subject: [PATCH 06/48] fix(settings): authentic System Settings look (colorful tiles, transparent titlebar, sizing) + review fixes --- .../Views/Settings/GeneralSettingsView.swift | 10 +++--- .../Plugins/InstalledPluginsView.swift | 2 ++ .../Views/Settings/SettingsRowIcon.swift | 26 ++++++++++++++++ .../Views/Settings/SettingsView.swift | 21 +++++++++++++ .../Settings/SettingsWindowController.swift | 31 ++++++++++++------- 5 files changed, 74 insertions(+), 16 deletions(-) create mode 100644 apple/TablePro/Views/Settings/SettingsRowIcon.swift diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 23f81cca4a..91874491c0 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -5,9 +5,12 @@ struct GeneralSettingsView: View { @Binding var settings: GeneralSettings var onResetAll: () -> Void - @State private var initialLanguage: AppLanguage? @State private var showResetConfirmation = false + // The UI language is fixed until a relaunch, so the prompt compares against the language in + // effect when Settings first opened this run, not against per-view state the pane rebuild resets. + @MainActor private static let launchLanguage = AppSettingsManager.shared.general.language + var body: some View { Form { Picker("Language:", selection: $settings.language) { @@ -16,7 +19,7 @@ struct GeneralSettingsView: View { } } - if let initial = initialLanguage, settings.language != initial { + if settings.language != Self.launchLanguage { LabeledContent { Button(String(localized: "Relaunch")) { UpdateCenter.shared.relaunch() @@ -75,9 +78,6 @@ struct GeneralSettingsView: View { } message: { Text("This will reset all settings across every section to their default values. AI providers, their API keys and Enable AI Features are kept.") } - .onAppear { - if initialLanguage == nil { initialLanguage = settings.language } - } } } diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index c02d3a3b15..dc47fa79d9 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -548,6 +548,8 @@ struct InstalledPluginsView: View { private func updatePlugin(_ registryPlugin: RegistryPlugin) { Task { _ = await pluginManager.performRegistryUpdate(registryPlugin) + // A rejected plugin that updated is no longer rejected; pop its now-dead detail page. + if !path.isEmpty { path.removeLast() } } } diff --git a/apple/TablePro/Views/Settings/SettingsRowIcon.swift b/apple/TablePro/Views/Settings/SettingsRowIcon.swift new file mode 100644 index 0000000000..63b5c58701 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsRowIcon.swift @@ -0,0 +1,26 @@ +// +// SettingsRowIcon.swift +// TablePro +// + +import SwiftUI + +// The colorful rounded-square tile a System Settings sidebar row shows: a white SF Symbol on a +// fixed per-category tint. The tint is a hardcoded system color, never a theme slot, so the Settings +// chrome stays off the theme engine (.claude/rules/theme.md). +struct SettingsRowIcon: View { + let systemName: String + let tint: Color + + var body: some View { + RoundedRectangle(cornerRadius: 6, style: .continuous) + .fill(tint) + .frame(width: 20, height: 20) + .overlay { + Image(systemName: systemName) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.white) + } + .accessibilityHidden(true) + } +} diff --git a/apple/TablePro/Views/Settings/SettingsView.swift b/apple/TablePro/Views/Settings/SettingsView.swift index 159ed59fd7..a336965d72 100644 --- a/apple/TablePro/Views/Settings/SettingsView.swift +++ b/apple/TablePro/Views/Settings/SettingsView.swift @@ -48,4 +48,25 @@ enum SettingsPane: String, CaseIterable { case .account: "person.crop.circle" } } + + // Fixed per-category tint for the sidebar row tile, System Settings style. A hardcoded system + // color, never a theme slot, so the Settings chrome stays off the theme engine. + var tint: Color { + switch self { + case .general: .gray + case .sidebar: .indigo + case .connections: .green + case .appearance: .pink + case .editor: .blue + case .data: .teal + case .keyboard: .gray + case .notifications: .red + case .ai: .purple + case .mcp: .cyan + case .plugins: .orange + case .profiles: .blue + case .sync: .teal + case .account: .indigo + } + } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index f3590bb660..9e1aeac400 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -39,16 +39,20 @@ internal final class SettingsWindowController: NSWindowController { window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.settings) window.keepsKeyViewLoopCurrent() window.styleMask = [.titled, .closable, .resizable] - // The detail's NavigationStack renders its back button and title into the window toolbar. + // The detail's NavigationStack renders its back button and title into the window toolbar; + // a transparent titlebar lets the sidebar material flow full-height under it (no empty band). window.toolbar = NSToolbar() window.toolbarStyle = .unified + window.titlebarAppearsTransparent = true window.isRestorable = false + // Width fixed (sidebar + detail); height resizes. window.contentMinSize = SettingsSplitViewController.minimumContentSize - window.setContentSize(SettingsSplitViewController.minimumContentSize) + window.contentMaxSize = NSSize(width: SettingsSplitViewController.minimumContentSize.width, height: .greatestFiniteMagnitude) + window.setContentSize(SettingsSplitViewController.defaultContentSize) window.applyAutosaveName(WindowIdentifier.settings) window.setContentSize( NSSize( - width: max(window.contentLayoutRect.width, SettingsSplitViewController.minimumContentSize.width), + width: SettingsSplitViewController.minimumContentSize.width, height: max(window.contentLayoutRect.height, SettingsSplitViewController.minimumContentSize.height) ) ) @@ -59,10 +63,11 @@ internal final class SettingsWindowController: NSWindowController { // The sidebar list + detail pane. Replaces the twelve-item .preference toolbar; a scrolling // sidebar has no item cap, and the detail hosts a NavigationStack so a row can push sub-pages. internal final class SettingsSplitViewController: NSSplitViewController { - internal static let minimumContentSize = NSSize(width: 775, height: 520) - private static let sidebarMinWidth: CGFloat = 204 - private static let sidebarMaxWidth: CGFloat = 280 - private static let detailMinWidth: CGFloat = 560 + // System Settings keeps a fixed width and resizes in height only. + internal static let minimumContentSize = NSSize(width: sidebarWidth + detailMinWidth, height: 480) + internal static let defaultContentSize = NSSize(width: sidebarWidth + detailMinWidth, height: 700) + private static let sidebarWidth: CGFloat = 248 + private static let detailMinWidth: CGFloat = 520 private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") @@ -99,8 +104,8 @@ internal final class SettingsSplitViewController: NSSplitViewController { let sidebar = NSHostingController(rootView: SettingsSidebarView(model: model)) let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) - sidebarItem.minimumThickness = Self.sidebarMinWidth - sidebarItem.maximumThickness = Self.sidebarMaxWidth + sidebarItem.minimumThickness = Self.sidebarWidth + sidebarItem.maximumThickness = Self.sidebarWidth sidebarItem.canCollapse = false addSplitViewItem(sidebarItem) @@ -172,8 +177,12 @@ private struct SettingsSidebarView: View { if !panes.isEmpty { Section { ForEach(panes, id: \.self) { pane in - Label(pane.title, systemImage: pane.symbol) - .tag(Optional(pane)) + Label { + Text(pane.title) + } icon: { + SettingsRowIcon(systemName: pane.symbol, tint: pane.tint) + } + .tag(Optional(pane)) } } } From 345c8bb968df97cd6275a3da3c69b16c92ef31ee Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 12:31:14 +0700 Subject: [PATCH 07/48] fix(settings): sidebar search field, in-pane back control, string catalog and ratchet fixes --- .../Models/Settings/LanguageLaunchState.swift | 14 +++++ .../TablePro/Resources/Localizable.xcstrings | 15 ++++++ .../Views/Settings/GeneralSettingsView.swift | 6 +-- .../Views/Settings/Sections/SyncSection.swift | 2 +- .../Settings/SettingsDrillInChrome.swift | 44 ++++++++-------- .../Settings/SettingsWindowController.swift | 51 ++++++++++--------- 6 files changed, 80 insertions(+), 52 deletions(-) create mode 100644 apple/TablePro/Models/Settings/LanguageLaunchState.swift diff --git a/apple/TablePro/Models/Settings/LanguageLaunchState.swift b/apple/TablePro/Models/Settings/LanguageLaunchState.swift new file mode 100644 index 0000000000..918e84f158 --- /dev/null +++ b/apple/TablePro/Models/Settings/LanguageLaunchState.swift @@ -0,0 +1,14 @@ +// +// LanguageLaunchState.swift +// TablePro +// + +import Foundation + +// The UI language in effect for this process, captured once. A language change needs a relaunch, +// so this is the value to compare a pending change against. Lives outside the view layer so the +// comparison does not read a singleton from a SwiftUI view. +@MainActor +enum LanguageLaunchState { + static let language: AppLanguage = AppSettingsManager.shared.general.language +} diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 6b3b73e9e4..5e79de120b 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -46176,6 +46176,9 @@ } } } + }, + "Command Line Tool" : { + }, "Command line tool failed: %@" : { "localizations" : { @@ -109646,6 +109649,9 @@ } } } + }, + "Manage Themes" : { + }, "Manage…" : { @@ -172050,6 +172056,9 @@ } } } + }, + "Sidebar & Tabs" : { + }, "Sidebar as List" : { "localizations" : { @@ -175998,6 +176007,9 @@ } } } + }, + "SQL Formatting" : { + }, "SQL Functions" : { "localizations" : { @@ -220925,6 +220937,9 @@ } } } + }, + "What Syncs" : { + }, "What the check looks for, with its threshold" : { diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 91874491c0..dd47e2c88d 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -7,10 +7,6 @@ struct GeneralSettingsView: View { @State private var showResetConfirmation = false - // The UI language is fixed until a relaunch, so the prompt compares against the language in - // effect when Settings first opened this run, not against per-view state the pane rebuild resets. - @MainActor private static let launchLanguage = AppSettingsManager.shared.general.language - var body: some View { Form { Picker("Language:", selection: $settings.language) { @@ -19,7 +15,7 @@ struct GeneralSettingsView: View { } } - if settings.language != Self.launchLanguage { + if settings.language != LanguageLaunchState.language { LabeledContent { Button(String(localized: "Relaunch")) { UpdateCenter.shared.relaunch() diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift index caac197539..c325cac6e2 100644 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ b/apple/TablePro/Views/Settings/Sections/SyncSection.swift @@ -83,7 +83,7 @@ struct SyncSection: View { // The sync-category toggles, shown on the What Syncs drill-in. struct SyncCategoriesSection: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject var settingsManager: AppSettingsManager var body: some View { Section("Sync Categories") { diff --git a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift index 612a178dda..e543f25a8f 100644 --- a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift +++ b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift @@ -5,9 +5,9 @@ import SwiftUI -// Title and a Back control for any page pushed onto a Settings pane's NavigationStack. The back -// button rides the window toolbar on macOS 14+ (the detail hosting controller bridges toolbars); -// macOS 13 cannot bridge it, so an inline bar carries the same button there. +// Title and a Back control for any page pushed onto a Settings pane's NavigationStack. The control +// sits at the top of the detail column (like System Settings), not in the window toolbar, so it +// never overlaps the sidebar. private struct SettingsDrillInChrome: ViewModifier { @Environment(\.dismiss) private var dismiss let title: String @@ -15,31 +15,29 @@ private struct SettingsDrillInChrome: ViewModifier { func body(content: Content) -> some View { content .navigationTitle(title) - .toolbar { - ToolbarItem(placement: .navigation) { backButton } - } .safeAreaInset(edge: .top, spacing: 0) { - if #unavailable(macOS 14.0) { - HStack { - backButton - Spacer() + HStack(spacing: 6) { + Button { + dismiss() + } label: { + Image(systemName: "chevron.backward") + .fontWeight(.semibold) + .contentShape(Rectangle()) } - .padding(.horizontal, 12) - .padding(.vertical, 6) - .background(.bar) + .buttonStyle(.borderless) + .help(String(localized: "Back")) + .accessibilityLabel(String(localized: "Back")) + + Text(title) + .font(.headline) + + Spacer() } + .padding(.horizontal, 20) + .padding(.vertical, 10) + .background(.bar) } } - - private var backButton: some View { - Button { - dismiss() - } label: { - Image(systemName: "chevron.backward") - } - .help(String(localized: "Back")) - .accessibilityLabel(String(localized: "Back")) - } } extension View { diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 9e1aeac400..a0bde5c0a7 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -112,10 +112,6 @@ internal final class SettingsSplitViewController: NSSplitViewController { let detail = NSHostingController(rootView: SettingsDetailView(model: model, registryClient: registryClient)) // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. detail.sizingOptions = [] - // Bridge the detail's NavigationStack toolbar (back button, title) into the window toolbar. - if #available(macOS 14.0, *) { - detail.sceneBridgingOptions = [.toolbars] - } let detailItem = NSSplitViewItem(viewController: detail) detailItem.minimumThickness = Self.detailMinWidth detailItem.holdingPriority = NSLayoutConstraint.Priority(260) // below dragThatCannotResizeWindow (490) @@ -171,25 +167,31 @@ private struct SettingsSidebarView: View { } fileprivate var body: some View { - List(selection: selectionBinding) { - ForEach(SettingsNavigation.sections, id: \.id) { section in - let panes = visiblePanes(in: section) - if !panes.isEmpty { - Section { - ForEach(panes, id: \.self) { pane in - Label { - Text(pane.title) - } icon: { - SettingsRowIcon(systemName: pane.symbol, tint: pane.tint) + VStack(spacing: 0) { + NativeSearchField(text: $model.searchText, placeholder: String(localized: "Search")) + .padding(.horizontal, 10) + .padding(.top, 10) + .padding(.bottom, 6) + + List(selection: selectionBinding) { + ForEach(SettingsNavigation.sections, id: \.id) { section in + let panes = visiblePanes(in: section) + if !panes.isEmpty { + Section { + ForEach(panes, id: \.self) { pane in + Label { + Text(pane.title) + } icon: { + SettingsRowIcon(systemName: pane.symbol, tint: pane.tint) + } + .tag(Optional(pane)) } - .tag(Optional(pane)) } } } } + .listStyle(.sidebar) } - .listStyle(.sidebar) - .searchable(text: $model.searchText, placement: .sidebar, prompt: Text("Search")) } private func visiblePanes(in section: SettingsSection) -> [SettingsPane] { @@ -211,7 +213,6 @@ private struct SettingsDetailView: View { } private struct SettingsPaneStack: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared fileprivate let pane: SettingsPane fileprivate let registryClient: RegistryClient @State private var path = NavigationPath() @@ -221,10 +222,6 @@ private struct SettingsPaneStack: View { SettingsPaneContent(pane: pane, registryClient: registryClient, path: $path) .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationTitle(pane.title) - .navigationDestination(for: SettingsSubpage.self) { subpage in - SettingsSubpageView(settingsManager: settingsManager, subpage: subpage) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } } } } @@ -261,7 +258,7 @@ private struct SettingsSubpageView: View { Form { DataRewindSection(settings: $settingsManager.history) } .formStyle(.grouped) case .whatSyncs: - Form { SyncCategoriesSection() } + Form { SyncCategoriesSection(settingsManager: settingsManager) } .formStyle(.grouped) } } @@ -281,6 +278,14 @@ private struct SettingsPaneContent: View { } fileprivate var body: some View { + paneContent + .navigationDestination(for: SettingsSubpage.self) { subpage in + SettingsSubpageView(settingsManager: settingsManager, subpage: subpage) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + + @ViewBuilder private var paneContent: some View { switch pane { case .general: GeneralSettingsView( From 1ecc4aaf07ffc295c6a58d63cce7adcf8dd95feb Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:08:58 +0700 Subject: [PATCH 08/48] fix(settings): native System Settings toolbar (back/forward, leading title, full-height sidebar) --- .../Settings/SettingsDrillInChrome.swift | 41 ++----- .../Settings/SettingsWindowController.swift | 51 ++++++--- .../Settings/SettingsWindowToolbar.swift | 105 ++++++++++++++++++ .../Settings/SettingsWindowTitleTests.swift | 43 +++++-- 4 files changed, 183 insertions(+), 57 deletions(-) create mode 100644 apple/TablePro/Views/Settings/SettingsWindowToolbar.swift diff --git a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift index e543f25a8f..fecac11d6b 100644 --- a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift +++ b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift @@ -5,43 +5,20 @@ import SwiftUI -// Title and a Back control for any page pushed onto a Settings pane's NavigationStack. The control -// sits at the top of the detail column (like System Settings), not in the window toolbar, so it -// never overlaps the sidebar. -private struct SettingsDrillInChrome: ViewModifier { - @Environment(\.dismiss) private var dismiss - let title: String +// A pushed Settings page reports its title up to the pane's NavigationStack, which hands it to the +// window toolbar (shown next to the Back control, System Settings style). The Back button and the +// title live in the toolbar, so a drill-in page adds no chrome of its own. +struct SettingsPageTitleKey: PreferenceKey { + static var defaultValue: String? { nil } - func body(content: Content) -> some View { - content - .navigationTitle(title) - .safeAreaInset(edge: .top, spacing: 0) { - HStack(spacing: 6) { - Button { - dismiss() - } label: { - Image(systemName: "chevron.backward") - .fontWeight(.semibold) - .contentShape(Rectangle()) - } - .buttonStyle(.borderless) - .help(String(localized: "Back")) - .accessibilityLabel(String(localized: "Back")) - - Text(title) - .font(.headline) - - Spacer() - } - .padding(.horizontal, 20) - .padding(.vertical, 10) - .background(.bar) - } + static func reduce(value: inout String?, nextValue: () -> String?) { + if let next = nextValue() { value = next } } } extension View { func settingsDrillIn(title: String) -> some View { - modifier(SettingsDrillInChrome(title: title)) + navigationTitle(title) + .preference(key: SettingsPageTitleKey.self, value: title) } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index a0bde5c0a7..74f5f1d603 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -34,16 +34,17 @@ internal final class SettingsWindowController: NSWindowController { internal convenience init(registryClient: RegistryClient) { let split = SettingsSplitViewController(registryClient: registryClient) - // NSWindow(contentViewController:) binds the title to the split controller's, which mirrors the selected row. let window = NSWindow(contentViewController: split) window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.settings) window.keepsKeyViewLoopCurrent() - window.styleMask = [.titled, .closable, .resizable] - // The detail's NavigationStack renders its back button and title into the window toolbar; - // a transparent titlebar lets the sidebar material flow full-height under it (no empty band). - window.toolbar = NSToolbar() - window.toolbarStyle = .unified + // fullSizeContentView lets the sidebar material run the full window height, behind the + // traffic lights, like System Settings and other native sidebar windows. + window.styleMask = [.titled, .closable, .resizable, .fullSizeContentView] + // No centered window title; the pane name lives in the toolbar beside Back. + window.titleVisibility = .hidden window.titlebarAppearsTransparent = true + window.toolbarStyle = .unified + window.toolbar = split.toolbarController.makeToolbar() window.isRestorable = false // Width fixed (sidebar + detail); height resizes. window.contentMinSize = SettingsSplitViewController.minimumContentSize @@ -72,14 +73,16 @@ internal final class SettingsSplitViewController: NSSplitViewController { private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") internal let model: SettingsNavigationModel + internal let toolbarController: SettingsWindowToolbar private let registryClient: RegistryClient private var cancellables: Set = [] internal init(registryClient: RegistryClient = .shared) { self.registryClient = registryClient - self.model = SettingsNavigationModel(initial: Self.persistedPane) + let model = SettingsNavigationModel(initial: Self.persistedPane) + self.model = model + self.toolbarController = SettingsWindowToolbar(model: model) super.init(nibName: nil, bundle: nil) - title = model.selection.title } internal required init?(coder: NSCoder) { @@ -120,7 +123,6 @@ internal final class SettingsSplitViewController: NSSplitViewController { model.$selection .removeDuplicates() .sink { [weak self] pane in - self?.title = pane.title self?.persistUserSelection(pane) } .store(in: &cancellables) @@ -136,24 +138,43 @@ internal final class SettingsSplitViewController: NSSplitViewController { internal final class SettingsNavigationModel: ObservableObject { @Published internal var selection: SettingsPane @Published internal var searchText: String = "" + // The detail's NavigationStack path, owned here so the window toolbar can read depth and drive Back. + @Published internal var path = NavigationPath() + // The pushed page's title, reported by the drill-in modifier; nil at a pane root. + @Published internal var drillTitle: String? internal private(set) var isApplyingProgrammatic = false + internal var currentTitle: String { drillTitle ?? selection.title } + internal var canGoBack: Bool { !path.isEmpty } + internal init(initial: SettingsPane) { self.selection = initial } // From the sidebar list: the user picked a row, so it becomes the last-used pane. internal func userSelect(_ pane: SettingsPane) { + resetDepth() isApplyingProgrammatic = false selection = pane } // From openSettings / a deep link: show the pane but do not rewrite the last-used pane. internal func applyProgrammatic(_ pane: SettingsPane) { + resetDepth() isApplyingProgrammatic = true selection = pane isApplyingProgrammatic = false } + + internal func goBack() { + guard !path.isEmpty else { return } + path.removeLast() + } + + private func resetDepth() { + path = NavigationPath() + drillTitle = nil + } } private struct SettingsSidebarView: View { @@ -206,22 +227,24 @@ private struct SettingsDetailView: View { fileprivate var body: some View { // Each pane owns its own stack, keyed by selection, so switching panes resets its depth. - SettingsPaneStack(pane: model.selection, registryClient: registryClient) + SettingsPaneStack(model: model, pane: model.selection, registryClient: registryClient) .id(model.selection) .environment(\.appServices, .live) } } private struct SettingsPaneStack: View { + @ObservedObject fileprivate var model: SettingsNavigationModel fileprivate let pane: SettingsPane fileprivate let registryClient: RegistryClient - @State private var path = NavigationPath() fileprivate var body: some View { - NavigationStack(path: $path) { - SettingsPaneContent(pane: pane, registryClient: registryClient, path: $path) + NavigationStack(path: $model.path) { + SettingsPaneContent(pane: pane, registryClient: registryClient, path: $model.path) .frame(maxWidth: .infinity, maxHeight: .infinity) - .navigationTitle(pane.title) + } + .onPreferenceChange(SettingsPageTitleKey.self) { title in + MainActor.assumeIsolated { model.drillTitle = title } } } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift new file mode 100644 index 0000000000..e61d75b364 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift @@ -0,0 +1,105 @@ +// +// SettingsWindowToolbar.swift +// TablePro +// + +import AppKit +import Combine + +// The System Settings toolbar: a back/forward navigation group pinned to the leading edge of the +// detail region, then the current page title in bold. AppKit draws the sidebar/detail tracking +// separator. Forward stays disabled (a NavigationStack is back-only), which matches the reference's +// idle state. No centered window title. +@MainActor +internal final class SettingsWindowToolbar: NSObject, NSToolbarDelegate { + private static let backForward = NSToolbarItem.Identifier("com.TablePro.settings.backForward") + private static let pageTitle = NSToolbarItem.Identifier("com.TablePro.settings.title") + + private let model: SettingsNavigationModel + private weak var backItem: NSToolbarItem? + private weak var titleField: NSTextField? + private var cancellable: AnyCancellable? + + internal init(model: SettingsNavigationModel) { + self.model = model + super.init() + cancellable = model.objectWillChange.sink { [weak self] in + // objectWillChange fires before the value updates; read it on the next runloop turn. + Task { @MainActor in self?.sync() } + } + } + + internal func makeToolbar() -> NSToolbar { + let toolbar = NSToolbar(identifier: "com.TablePro.settings.toolbar") + toolbar.delegate = self + toolbar.displayMode = .iconOnly + toolbar.allowsUserCustomization = false + return toolbar + } + + internal func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [.sidebarTrackingSeparator, Self.backForward, Self.pageTitle, .flexibleSpace] + } + + internal func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + toolbarDefaultItemIdentifiers(toolbar) + } + + internal func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier identifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + switch identifier { + case Self.backForward: + let back = chevron(id: "com.TablePro.settings.back", symbol: "chevron.backward", label: String(localized: "Back")) + back.target = self + back.action = #selector(goBack(_:)) + back.isEnabled = model.canGoBack + backItem = back + + let forward = chevron(id: "com.TablePro.settings.forward", symbol: "chevron.forward", label: String(localized: "Forward")) + forward.isEnabled = false + + // isNavigational pins the pair to the leading edge of the detail region (Finder/Safari/System Settings). + let group = NSToolbarItemGroup(itemIdentifier: identifier) + group.label = String(localized: "Navigation") + group.paletteLabel = String(localized: "Navigation") + group.subitems = [back, forward] + group.isNavigational = true + return group + + case Self.pageTitle: + let item = NSToolbarItem(itemIdentifier: identifier) + let field = NSTextField(labelWithString: model.currentTitle) + field.font = .systemFont(ofSize: NSFont.systemFontSize + 1, weight: .bold) + field.lineBreakMode = .byTruncatingTail + field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + item.view = field + item.visibilityPriority = .high + titleField = field + return item + + default: + return nil + } + } + + private func chevron(id: String, symbol: String, label: String) -> NSToolbarItem { + let item = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(id)) + item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label) + item.label = label + item.paletteLabel = label + item.isBordered = true + return item + } + + private func sync() { + titleField?.stringValue = model.currentTitle + backItem?.isEnabled = model.canGoBack + } + + @objc private func goBack(_ sender: Any?) { + model.goBack() + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift index d8b9487d2c..283bdf60e2 100644 --- a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift @@ -4,6 +4,7 @@ // import AppKit +import SwiftUI @testable import TablePro import TableProTestSupport import Testing @@ -54,14 +55,14 @@ extension GlobalStateSuites { #expect(Set(SettingsNavigation.orderedPanes) == Set(SettingsPane.allCases)) } - @Test("The window title follows the selected pane") - func windowTitleFollowsTheSelectedPane() async throws { + @Test("The toolbar title follows the selected pane") + func toolbarTitleFollowsTheSelectedPane() async throws { let host = try Host() - let (split, window) = host.makeSplit() + let (split, _) = host.makeSplit() for pane in SettingsPane.allCases { split.navigate(to: pane) - #expect(window.title == pane.title) + #expect(split.model.currentTitle == pane.title) } await host.tearDown() } @@ -73,8 +74,8 @@ extension GlobalStateSuites { SettingsPane.keyboard.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name ) - let (_, window) = host.makeSplit() - #expect(window.title == SettingsPane.keyboard.title) + let (split, _) = host.makeSplit() + #expect(split.model.currentTitle == SettingsPane.keyboard.title) await host.tearDown() } @@ -82,8 +83,8 @@ extension GlobalStateSuites { func storedMCPPaneRestoresTheMCPTitle() async throws { let host = try Host() AppStorageEnvironment.shared.defaults.set("mcp", forKey: PreferenceKeys.selectedSettingsPane.name) - let (_, window) = host.makeSplit() - #expect(window.title == "MCP") + let (split, _) = host.makeSplit() + #expect(split.model.currentTitle == "MCP") await host.tearDown() } @@ -98,16 +99,16 @@ extension GlobalStateSuites { @Test("Navigating with no pane reads the stored pane rather than staying put") func navigatingWithNoPaneReadsTheStoredPane() async throws { let host = try Host() - let (split, window) = host.makeSplit() + let (split, _) = host.makeSplit() split.navigate(to: .plugins) - #expect(window.title == SettingsPane.plugins.title) + #expect(split.model.currentTitle == SettingsPane.plugins.title) AppStorageEnvironment.shared.defaults.set( SettingsPane.editor.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name ) split.navigate(to: nil) - #expect(window.title == SettingsPane.editor.title) + #expect(split.model.currentTitle == SettingsPane.editor.title) await host.tearDown() } @@ -128,6 +129,26 @@ extension GlobalStateSuites { await host.tearDown() } + // The toolbar reads these: Back is enabled only while the detail stack has a pushed page, + // and a pane switch pops back to the pane's own title. + @Test("Back enablement and title track the detail stack depth") + func backEnablementTracksDepth() { + let model = SettingsNavigationModel(initial: .appearance) + #expect(!model.canGoBack) + #expect(model.currentTitle == SettingsPane.appearance.title) + + model.path.append(SettingsSubpage.manageThemes) + #expect(model.canGoBack) + + model.goBack() + #expect(!model.canGoBack) + + model.path.append(SettingsSubpage.manageThemes) + model.userSelect(.editor) + #expect(!model.canGoBack) + #expect(model.currentTitle == SettingsPane.editor.title) + } + @Test("The window refuses to shrink below the sidebar plus detail minimum") func theWindowRefusesToShrinkBelowTheMinimum() async throws { let host = try Host() From 33652950fab3357660839ac717d0bd2c458c61b0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:11:48 +0700 Subject: [PATCH 09/48] fix(settings): dim Back at a pane root (disable toolbar item autovalidation) --- apple/TablePro/Views/Settings/SettingsWindowToolbar.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift index e61d75b364..edd716f2c5 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift @@ -91,6 +91,9 @@ internal final class SettingsWindowToolbar: NSObject, NSToolbarDelegate { item.label = label item.paletteLabel = label item.isBordered = true + // Enablement is driven by canGoBack; without this AppKit auto-enables Back because its + // target responds to the action, so it would never dim at a pane root. + item.autovalidates = false return item } From cdb626291bc5b87f5a1f3f6d3663f94ea7ef9280 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:38:23 +0700 Subject: [PATCH 10/48] fix(settings): native sidebar tile inset + taller search, scope search off nav model --- .../Views/Settings/SettingsRowIcon.swift | 7 ++++- .../Settings/SettingsWindowController.swift | 27 ++++++++++--------- .../Views/Sidebar/NativeSearchField.swift | 8 ++++++ 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/apple/TablePro/Views/Settings/SettingsRowIcon.swift b/apple/TablePro/Views/Settings/SettingsRowIcon.swift index 63b5c58701..f9dfcfbd78 100644 --- a/apple/TablePro/Views/Settings/SettingsRowIcon.swift +++ b/apple/TablePro/Views/Settings/SettingsRowIcon.swift @@ -17,8 +17,13 @@ struct SettingsRowIcon: View { .fill(tint) .frame(width: 20, height: 20) .overlay { + // Fit the glyph to a fixed 11pt box so wide symbols (paintbrush) and narrow ones + // (bell) keep the same ~4.5pt inset, matching the System Settings tile. Image(systemName: systemName) - .font(.system(size: 12, weight: .semibold)) + .resizable() + .scaledToFit() + .fontWeight(.medium) + .frame(width: 11, height: 11) .foregroundStyle(.white) } .accessibilityHidden(true) diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 74f5f1d603..7195f424be 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -137,7 +137,6 @@ internal final class SettingsSplitViewController: NSSplitViewController { @MainActor internal final class SettingsNavigationModel: ObservableObject { @Published internal var selection: SettingsPane - @Published internal var searchText: String = "" // The detail's NavigationStack path, owned here so the window toolbar can read depth and drive Back. @Published internal var path = NavigationPath() // The pushed page's title, reported by the drill-in modifier; nil at a pane root. @@ -179,6 +178,9 @@ internal final class SettingsNavigationModel: ObservableObject { private struct SettingsSidebarView: View { @ObservedObject fileprivate var model: SettingsNavigationModel + // Search lives here, not on the nav model, so typing re-renders only the sidebar list and never + // the detail pane or the toolbar. + @State private var searchText = "" private var selectionBinding: Binding { Binding( @@ -188,15 +190,21 @@ private struct SettingsSidebarView: View { } fileprivate var body: some View { - VStack(spacing: 0) { - NativeSearchField(text: $model.searchText, placeholder: String(localized: "Search")) - .padding(.horizontal, 10) - .padding(.top, 10) - .padding(.bottom, 6) + let matches = Set(SettingsNavigation.panes(matching: searchText)) + return VStack(spacing: 0) { + NativeSearchField( + text: $searchText, + placeholder: String(localized: "Search"), + fixedHeight: 28, + accessibilityIdentifier: "settings-sidebar-search" + ) + .padding(.horizontal, 10) + .padding(.top, 10) + .padding(.bottom, 8) List(selection: selectionBinding) { ForEach(SettingsNavigation.sections, id: \.id) { section in - let panes = visiblePanes(in: section) + let panes = section.panes.filter(matches.contains) if !panes.isEmpty { Section { ForEach(panes, id: \.self) { pane in @@ -214,11 +222,6 @@ private struct SettingsSidebarView: View { .listStyle(.sidebar) } } - - private func visiblePanes(in section: SettingsSection) -> [SettingsPane] { - let matches = Set(SettingsNavigation.panes(matching: model.searchText)) - return section.panes.filter(matches.contains) - } } private struct SettingsDetailView: View { diff --git a/apple/TablePro/Views/Sidebar/NativeSearchField.swift b/apple/TablePro/Views/Sidebar/NativeSearchField.swift index 6e51937171..25dac44ce5 100644 --- a/apple/TablePro/Views/Sidebar/NativeSearchField.swift +++ b/apple/TablePro/Views/Sidebar/NativeSearchField.swift @@ -11,9 +11,15 @@ import SwiftUI private final class IntrinsicHeightSearchField: NSSearchField { var focusOnAppear = false + // When set, the field reports this height instead of the text-cell height; the Settings sidebar + // uses it to reach the taller System Settings search pill. + var fixedHeight: CGFloat? private let windowKeyObserver = OSAllocatedUnfairLock<(any NSObjectProtocol)?>(uncheckedState: nil) override var intrinsicContentSize: NSSize { + if let fixedHeight { + return NSSize(width: NSView.noIntrinsicMetric, height: fixedHeight) + } let cellHeight = cell?.cellSize.height ?? super.intrinsicContentSize.height return NSSize(width: NSView.noIntrinsicMetric, height: cellHeight) } @@ -63,6 +69,7 @@ struct NativeSearchField: NSViewRepresentable { var focusOnAppear: Bool = false var focusTrigger: Int = 0 var maxWidth: CGFloat? + var fixedHeight: CGFloat? var accessibilityIdentifier: String = "sidebar-filter" func makeNSView(context: Context) -> NSSearchField { @@ -70,6 +77,7 @@ struct NativeSearchField: NSViewRepresentable { field.placeholderString = placeholder field.delegate = context.coordinator field.controlSize = controlSize + field.fixedHeight = fixedHeight field.sendsSearchStringImmediately = true field.setAccessibilityIdentifier(accessibilityIdentifier) field.cell?.usesSingleLineMode = true From db3fb98b01a1b29aedcd587d6916dd68bc81ccf2 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:47:04 +0700 Subject: [PATCH 11/48] perf(settings): stop per-keystroke/no-op settings writes and app-wide fan-out - NULL display commits on submit/blur, not per character (was reformatting every open grid) - equality guards on general/appearance/editor/dataGrid/tabs/keyboard/ai didSets - gate language.apply() and dateFormat reformat behind the field that changed - move NULL display and row-cap validation into the section footer --- .../Core/Storage/AppSettingsManager.swift | 15 ++++- .../Settings/Sections/DataGridSection.swift | 58 ++++++++++++------- 2 files changed, 51 insertions(+), 22 deletions(-) diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index f444064e16..eb00a7ec6a 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -10,7 +10,10 @@ final class AppSettingsManager: ObservableObject { @Published var general: GeneralSettings { didSet { - general.language.apply() + guard general != oldValue else { return } + if oldValue.language != general.language { + general.language.apply() + } storage.saveGeneral(general) if oldValue.showWorkspaceRail != general.showWorkspaceRail { appEvents.workspaceRailVisibilityChanged.send(()) @@ -24,6 +27,7 @@ final class AppSettingsManager: ObservableObject { @Published var appearance: AppearanceSettings { didSet { + guard appearance != oldValue else { return } storage.saveAppearance(appearance) themeEngine.select( lightThemeId: appearance.preferredLightThemeId, @@ -44,6 +48,7 @@ final class AppSettingsManager: ObservableObject { @Published var editor: EditorSettings { didSet { + guard editor != oldValue else { return } storage.saveEditor(editor) appEvents.editorSettingsChanged.send(()) syncTracker.markDirty(.settings, id: AppSettingsCategory.editor) @@ -99,8 +104,11 @@ final class AppSettingsManager: ObservableObject { isValidating = false } + guard validated != oldValue else { return } storage.saveDataGrid(validated) - dateFormattingService.updateFormat(validated.dateFormat) + if validated.dateFormat != oldValue.dateFormat { + dateFormattingService.updateFormat(validated.dateFormat) + } appEvents.dataGridSettingsChanged.send(()) syncTracker.markDirty(.settings, id: AppSettingsCategory.dataGrid) } @@ -136,6 +144,7 @@ final class AppSettingsManager: ObservableObject { @Published var tabs: TabSettings { didSet { + guard tabs != oldValue else { return } storage.saveTabs(tabs) syncTracker.markDirty(.settings, id: AppSettingsCategory.tabs) } @@ -143,6 +152,7 @@ final class AppSettingsManager: ObservableObject { @Published var keyboard: KeyboardSettings { didSet { + guard keyboard != oldValue else { return } storage.saveKeyboard(keyboard) syncTracker.markDirty(.settings, id: AppSettingsCategory.keyboard) MainMenuBuilder.syncKeyEquivalents(keyboard: keyboard) @@ -152,6 +162,7 @@ final class AppSettingsManager: ObservableObject { @Published var ai: AISettings { didSet { + guard ai != oldValue else { return } storage.saveAI(ai) syncTracker.markDirty(.settings, id: AppSettingsCategory.ai) appEvents.aiSettingsChanged.send(()) diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index d350bb320b..3c42f96c46 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -9,6 +9,17 @@ struct DataGridSection: View { @Binding var settings: DataGridSettings @Binding var valueColors: ValueColorSettings + // NULL display commits on Return/focus loss, not per keystroke: a live binding re-encodes the + // whole settings struct and reformats every open grid on each character. + @State private var nullDisplayDraft = "" + @FocusState private var nullDisplayFocused: Bool + + private func commitNullDisplay() { + if settings.nullDisplay != nullDisplayDraft { + settings.nullDisplay = nullDisplayDraft + } + } + var body: some View { Section { Picker("Row height:", selection: $settings.rowHeight) { @@ -23,15 +34,17 @@ struct DataGridSection: View { } } - VStack(alignment: .leading, spacing: 4) { - TextField("NULL display:", text: $settings.nullDisplay) - .help("Max \(SettingsValidationRules.nullDisplayMaxLength) characters") - - if let error = settings.nullDisplayValidationError { - NoticeLabel(error, severity: .error) - .font(.caption) + TextField("NULL display:", text: $nullDisplayDraft) + .focused($nullDisplayFocused) + .help("Max \(SettingsValidationRules.nullDisplayMaxLength) characters") + .onSubmit(commitNullDisplay) + .onChange(of: nullDisplayFocused) { focused in + if !focused { commitNullDisplay() } } - } + .onChange(of: settings.nullDisplay) { value in + if !nullDisplayFocused { nullDisplayDraft = value } + } + .onAppear { nullDisplayDraft = settings.nullDisplay } Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) Toggle("Show row numbers", isOn: $settings.showRowNumbers) @@ -59,7 +72,12 @@ struct DataGridSection: View { } header: { Text("Data Grid") } footer: { - Text("Default row sort is applied when a table first opens. Sort direction also sets which way the first click on a column header sorts.") + VStack(alignment: .leading, spacing: 4) { + if let error = settings.nullDisplayValidationError { + NoticeLabel(error, severity: .error) + } + Text("Default row sort is applied when a table first opens. Sort direction also sets which way the first click on a column header sorts.") + } } Section { @@ -110,21 +128,21 @@ struct DataGridSection: View { Text("100,000").tag(100_000) Text("500,000").tag(500_000) } - - if let error = settings.queryResultRowCapValidationError { - NoticeLabel(error, severity: .error) - .font(.caption) - } } } header: { Text("Query Result Row Cap") } footer: { - if settings.truncateQueryResults, settings.queryResultRowCapValidationError == nil { - Text(""" - SELECT queries without their own LIMIT run with this cap applied. The query text in the \ - editor never changes. Capped results show a Fetch All button, and Execute Without Limit \ - skips the cap for one run. - """) + VStack(alignment: .leading, spacing: 4) { + if let error = settings.queryResultRowCapValidationError { + NoticeLabel(error, severity: .error) + } + if settings.truncateQueryResults, settings.queryResultRowCapValidationError == nil { + Text(""" + SELECT queries without their own LIMIT run with this cap applied. The query text in the \ + editor never changes. Capped results show a Fetch All button, and Execute Without Limit \ + skips the cap for one run. + """) + } } } From ac26d7e532e7a2ec4d41b008b37f81020703f981 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:47:04 +0700 Subject: [PATCH 12/48] fix(settings): native HIG fixes across panes - drop the fake push chevron from the AI provider and Profiles rows (they open sheets) - Notifications threshold reads "1 minute" not "1 minutes" - distinct a11y id for the Keyboard shortcut search - probe Apple Intelligence availability on appear, not every AI form pass - Profiles loads once on appear instead of re-decoding connections.json on every visit --- apple/TablePro/Resources/Localizable.xcstrings | 3 +++ .../TablePro/Views/Settings/AISettingsView.swift | 16 ++++++---------- .../Views/Settings/KeyboardSettingsView.swift | 3 ++- .../Settings/NotificationsSettingsView.swift | 6 +++++- .../Settings/Profiles/ProfilesSettingsView.swift | 8 ++++---- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 5e79de120b..0e7072f1c6 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -13872,6 +13872,9 @@ } } } + }, + "1 minute" : { + }, "1 more message." : { diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 581c4a9d24..de3289c96d 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -12,6 +12,8 @@ struct AISettingsView: View { @State private var editingProviderID: UUID? @State private var addingProvider: AIProviderConfig? @State private var pendingDeleteID: UUID? + // Probed on appear, not on every body pass (the whole AI form re-evaluates on any settings change). + @State private var appleIntelligence: AppleIntelligenceAvailability = .unavailable(.unknown) @ObservedObject private var chatGPTCodexService = ChatGPTCodexService.shared @ObservedObject private var claudeAgentService = ClaudeAgentService.shared @ObservedObject private var copilotService = CopilotService.shared @@ -186,10 +188,6 @@ struct AISettingsView: View { } Spacer() - - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) } .padding(.vertical, 2) .task { @@ -250,17 +248,15 @@ struct AISettingsView: View { // MARK: - Apple Intelligence private var appleIntelligenceSection: some View { - let availability = SystemOnDeviceLanguageModel().availability - return Section { + Section { Toggle("Use for inline suggestions and query actions", isOn: $settings.useAppleIntelligence) - .disabled(!availability.isAvailable && !settings.useAppleIntelligence) + .disabled(!appleIntelligence.isAvailable && !settings.useAppleIntelligence) } header: { Text(AppleIntelligenceAvailability.displayName) } footer: { - Text(Self.appleIntelligenceFooter(availability)) - .font(.caption) - .foregroundStyle(.secondary) + Text(Self.appleIntelligenceFooter(appleIntelligence)) } + .onAppear { appleIntelligence = SystemOnDeviceLanguageModel().availability } } private static func appleIntelligenceFooter(_ availability: AppleIntelligenceAvailability) -> String { diff --git a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift index 499c040a9d..f2e4288fce 100644 --- a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift +++ b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift @@ -24,7 +24,8 @@ struct KeyboardSettingsView: View { VStack(spacing: 0) { NativeSearchField( text: $searchText, - placeholder: String(localized: "Search shortcuts…") + placeholder: String(localized: "Search shortcuts…"), + accessibilityIdentifier: "shortcut-search" ) .padding(.horizontal, 20) .padding(.top, 16) diff --git a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift index 7517f80564..5914fda4d7 100644 --- a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift +++ b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift @@ -54,7 +54,11 @@ struct NotificationsSettingsView: View { guard seconds >= 60 else { return String(format: String(localized: "%lld seconds"), seconds) } - return String(format: String(localized: "%lld minutes"), seconds / 60) + let minutes = seconds / 60 + if minutes == 1 { + return String(localized: "1 minute") + } + return String(format: String(localized: "%lld minutes"), minutes) } private static func openSystemSettings() { diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift index 74542bd7fe..4fbe361abe 100644 --- a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift @@ -19,6 +19,7 @@ struct ProfilesSettingsView: View { @State private var isAddingSSHProfile = false @State private var connectionCounts: [UUID: Int] = [:] + @State private var hasLoaded = false var body: some View { Form { @@ -26,7 +27,9 @@ struct ProfilesSettingsView: View { sshSection } .formStyle(.grouped) - .onAppear(perform: reload) + // Load once, not on every re-add: reload() synchronously decodes the whole connections file + // on the main actor. The change notifications below keep the list fresh after that. + .onAppear { if !hasLoaded { hasLoaded = true; reload() } } /// The Settings window is kept alive between openings, so a profile created from a /// connection window has to reach this list while it is already on screen. .onReceive(NotificationCenter.default.publisher(for: .credentialProfilesDidChange)) { _ in reload() } @@ -159,9 +162,6 @@ struct ProfilesSettingsView: View { Text(usedByLabel(usedBy)) .font(.caption) .foregroundStyle(.secondary) - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) } .contentShape(Rectangle()) } From 12beeee62d7ca26515d44b6126a1b338bc2a39f6 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 13:52:44 +0700 Subject: [PATCH 13/48] fix(settings): segmented appearance-mode control, matching System Settings --- apple/TablePro/Views/Settings/AppearanceSettingsView.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index d4b43c0395..d54f3f5686 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -17,6 +17,7 @@ internal struct AppearanceSettingsView: View { Text(Self.title(for: mode)).tag(mode) } } + .pickerStyle(.segmented) .accessibilityIdentifier("appearance-mode-picker") } footer: { Text("Applies to this Mac.") From a9626ddc635d35b5a59f68bdd37815c78cc39d64 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 14:01:27 +0700 Subject: [PATCH 14/48] refactor(settings): Xcode-style sidebar glyphs, drop colored tiles --- .../Views/Settings/SettingsRowIcon.swift | 31 ------------------- .../Views/Settings/SettingsView.swift | 23 +------------- .../Settings/SettingsWindowController.swift | 10 +++--- 3 files changed, 5 insertions(+), 59 deletions(-) delete mode 100644 apple/TablePro/Views/Settings/SettingsRowIcon.swift diff --git a/apple/TablePro/Views/Settings/SettingsRowIcon.swift b/apple/TablePro/Views/Settings/SettingsRowIcon.swift deleted file mode 100644 index f9dfcfbd78..0000000000 --- a/apple/TablePro/Views/Settings/SettingsRowIcon.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// SettingsRowIcon.swift -// TablePro -// - -import SwiftUI - -// The colorful rounded-square tile a System Settings sidebar row shows: a white SF Symbol on a -// fixed per-category tint. The tint is a hardcoded system color, never a theme slot, so the Settings -// chrome stays off the theme engine (.claude/rules/theme.md). -struct SettingsRowIcon: View { - let systemName: String - let tint: Color - - var body: some View { - RoundedRectangle(cornerRadius: 6, style: .continuous) - .fill(tint) - .frame(width: 20, height: 20) - .overlay { - // Fit the glyph to a fixed 11pt box so wide symbols (paintbrush) and narrow ones - // (bell) keep the same ~4.5pt inset, matching the System Settings tile. - Image(systemName: systemName) - .resizable() - .scaledToFit() - .fontWeight(.medium) - .frame(width: 11, height: 11) - .foregroundStyle(.white) - } - .accessibilityHidden(true) - } -} diff --git a/apple/TablePro/Views/Settings/SettingsView.swift b/apple/TablePro/Views/Settings/SettingsView.swift index a336965d72..defe8881f8 100644 --- a/apple/TablePro/Views/Settings/SettingsView.swift +++ b/apple/TablePro/Views/Settings/SettingsView.swift @@ -3,7 +3,7 @@ // TablePro // -import SwiftUI +import Foundation enum SettingsPane: String, CaseIterable { case general, sidebar, connections, appearance, editor, data, keyboard, profiles, notifications, ai, mcp, plugins, sync, account @@ -48,25 +48,4 @@ enum SettingsPane: String, CaseIterable { case .account: "person.crop.circle" } } - - // Fixed per-category tint for the sidebar row tile, System Settings style. A hardcoded system - // color, never a theme slot, so the Settings chrome stays off the theme engine. - var tint: Color { - switch self { - case .general: .gray - case .sidebar: .indigo - case .connections: .green - case .appearance: .pink - case .editor: .blue - case .data: .teal - case .keyboard: .gray - case .notifications: .red - case .ai: .purple - case .mcp: .cyan - case .plugins: .orange - case .profiles: .blue - case .sync: .teal - case .account: .indigo - } - } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 7195f424be..f8138c2397 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -208,12 +208,10 @@ private struct SettingsSidebarView: View { if !panes.isEmpty { Section { ForEach(panes, id: \.self) { pane in - Label { - Text(pane.title) - } icon: { - SettingsRowIcon(systemName: pane.symbol, tint: pane.tint) - } - .tag(Optional(pane)) + // The sidebar tints the symbol with the accent and inverts it on + // selection (Xcode's Settings sidebar), so no custom icon view. + Label(pane.title, systemImage: pane.symbol) + .tag(Optional(pane)) } } } From d11ba02da6e61262f1ae7a18a0e327dfcacb0871 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:05 +0700 Subject: [PATCH 15/48] perf(settings): per-category settings slices with one commit path --- apple/TablePro/AppDelegate.swift | 45 +- .../Core/Storage/AppSettingsManager.swift | 525 +++++++++++------- .../Core/Storage/AppSettingsStorage.swift | 54 +- .../TablePro/Core/Storage/SettingsSlice.swift | 41 ++ .../Models/Settings/LanguageLaunchState.swift | 30 +- .../Views/Editor/SQLEditorController.swift | 49 +- .../AppSettingsStorageResetTests.swift | 30 +- .../AppSettingsSyncSideEffectsTests.swift | 16 + .../Core/Storage/SettingsSliceTests.swift | 280 ++++++++++ .../Settings/LanguageLaunchStateTests.swift | 29 + 10 files changed, 761 insertions(+), 338 deletions(-) create mode 100644 apple/TablePro/Core/Storage/SettingsSlice.swift create mode 100644 apple/TableProTests/Core/Storage/SettingsSliceTests.swift create mode 100644 apple/TableProTests/Models/Settings/LanguageLaunchStateTests.swift diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 5e76ec815b..84e4e68a66 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -1,8 +1,3 @@ -// -// AppDelegate.swift -// TablePro -// - import AppKit import Combine import os @@ -16,8 +11,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { private var hasRunPostLaunchActivation = false - // MARK: - URL & File Open - func applicationWillFinishLaunching(_ notification: Notification) { LaunchTracer.shared.mark(.willFinishLaunchingBegan) // First: the migration below writes the flag that tells an existing install from a new one. @@ -28,6 +21,8 @@ class AppDelegate: NSObject, NSApplicationDelegate { AppSettingsStorage.shared.migrateStartupBehaviorToReopenLastIfNeeded() AppSettingsStorage.shared.removeRetiredFieldHeightKeys() AIProviderRegistration.registerAll() + // Before sync can pull a language change, and not earlier: settings built before the migrations above would miss them. + LanguageLaunchState.record() // Before any window exists, so the bar is right from the first frame. MainMenuBuilder.install(keyboard: AppSettingsManager.shared.keyboard) @@ -60,8 +55,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { AppLaunchCoordinator.shared.handleReopen(hasVisibleWindows: flag) } - // MARK: - Lifecycle - func applicationDidFinishLaunching(_ notification: Notification) { LaunchTracer.shared.mark(.didFinishLaunchingBegan) if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil { @@ -69,8 +62,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { return } - /// `AppSettingsManager.init` has already resolved the theme from these same three values. - /// Only a screenshot run overrides the mode, so only a screenshot run resolves it twice. + // AppSettingsManager.init already resolved the theme; only a screenshot run overrides the mode and resolves again. if let screenshotMode = ScreenshotEnvironment.appearanceMode { let appearanceSettings = AppSettingsManager.shared.appearance ThemeEngine.shared.apply( @@ -95,20 +87,14 @@ class AppDelegate: NSObject, NSApplicationDelegate { DatabaseManager.shared.startObservingSystemEvents() DatabaseManager.shared.tabStatePersister = SessionTabStatePersister() - /// A notification the person acted on to launch the app is delivered as soon as - /// `applicationDidFinishLaunching` returns, before any window has a frame. Apple documents - /// the delegate assignment for that reason, and the two services below own the categories - /// `NotificationRouter` looks the action up in, so deferring either drops the action. + // Not deferred: a launching notification's action arrives as soon as this returns, and these services own its categories. UNUserNotificationCenter.current().delegate = self PluginNotificationService.shared.setUp() OperationCompletionReporter.shared.setUp() AgentAttentionNotifier.shared.setUp() ChatToolBootstrap.register() - /// Prerequisites for a connection, not post-launch work: a `cloudflared` or - /// `cloud-sql-proxy` left behind by a crash still holds its local port, and a restored - /// connection reaches `ensureConnected` while intents are routing. Both hop straight off - /// the main actor, so starting them here costs the first frame nothing. + // Not post-launch work: a crashed run's tunnel still holds its port when a restored connection reconnects. Task { await CloudflareTunnelManager.shared.sweepStalePidsIfNeeded() } Task { await CloudSQLProxyManager.shared.sweepStalePidsIfNeeded() } Task { await TunnelCommandManager.shared.sweepStalePidsIfNeeded() } @@ -159,7 +145,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { SoftwareUpdater.shared.start() // Before the account starts, so a stored key's migration reaches it as a sign-in. Telemetry.shared.start( - sharesUsageData: AppSettingsManager.shared.$general.map(\.shareAnalytics).eraseToAnyPublisher(), + sharesUsageData: AppSettingsManager.shared.generalSlice.publisher.map(\.shareAnalytics).eraseToAnyPublisher(), account: AccountServices.shared ) AccountServices.shared.start() @@ -173,8 +159,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { true } - // MARK: - Remote Notifications - func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { SyncCoordinator.shared.pushRegistrationDidFinish(registered: true) } @@ -188,8 +172,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { SyncCoordinator.shared.handleRemoteNotification(userInfo) } - /// Unhiding is the one way a window comes back without any window notification firing, and the - /// app reports every window it owns as invisible while it is hidden. + // Unhiding brings windows back with no window notification, and while hidden every window reports invisible. func applicationDidUnhide(_ notification: Notification) { AppActivationPolicyController.shared.reevaluate() } @@ -221,8 +204,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { SessionRecoveryTracker.saveOnQuit() - /// Synchronously, because an actor hop at terminate may never be scheduled: a session killed - /// mid-reply used to come back with its last turn missing. + // Synchronously: an actor hop at terminate may never run, which lost a killed session's last turn. AgentSessionRegistry.shared.persistSynchronouslyForTermination() LinkedFolderWatcher.shared.stop() SQLFolderWatcher.shared.stop() @@ -238,9 +220,6 @@ class AppDelegate: NSObject, NSApplicationDelegate { SQLFolderWatcher.shared.reload() } - - // MARK: - Window Notifications - @objc func windowWillClose(_ notification: Notification) { guard let window = notification.object as? NSWindow else { return } @@ -262,13 +241,10 @@ class AppDelegate: NSObject, NSApplicationDelegate { } else { csvLogger.debug("AppDelegate.windowWillClose - non-main window '\(window.identifier?.rawValue ?? "nil", privacy: .public)' closing") } - /// Any window, not only a primary one: a machine-started session can have nothing on screen - /// but a settings window, and closing it leaves the process with no user interface again. + // Any window: a machine-started session may show only a settings window, and closing it leaves no UI. AppActivationPolicyController.shared.reevaluate(excluding: window) } - // MARK: - Dock Menu - func applicationDockMenu(_ sender: NSApplication) -> NSMenu? { let menu = NSMenu() @@ -331,8 +307,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { } } -/// Carries a UserNotifications callback from the delegate thread to the main actor. -/// UNUserNotificationCenter hands each one over exactly once and keeps no reference. +// The center hands each callback over exactly once and keeps no reference, so carrying it to the main actor is safe. private struct NotificationDelivery: @unchecked Sendable { let payload: Payload let complete: () -> Void diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index eb00a7ec6a..2730e647c3 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -1,211 +1,107 @@ import AppKit import Combine import Foundation -import os import TableProSyncTransport @MainActor final class AppSettingsManager: ObservableObject { static let shared = AppSettingsManager() - @Published var general: GeneralSettings { - didSet { - guard general != oldValue else { return } - if oldValue.language != general.language { - general.language.apply() - } - storage.saveGeneral(general) - if oldValue.showWorkspaceRail != general.showWorkspaceRail { - appEvents.workspaceRailVisibilityChanged.send(()) - } - if oldValue.connectionHealthCheck != general.connectionHealthCheck { - appEvents.connectionHealthCheckChanged.send(()) - } - syncTracker.markDirty(.settings, id: AppSettingsCategory.general) - } + let generalSlice: SettingsSlice + let appearanceSlice: SettingsSlice + // Device-local, like typography: each Mac picks Auto, Light or Dark for itself. + let appearanceModeSlice: SettingsSlice + let editorSlice: SettingsSlice + let formatterSlice: SettingsSlice + // Device-local, absent from `AppSettingsCategory.synced`: a zoom press never pushes a record an older build could reset. + let typographySlice: SettingsSlice + let notificationsSlice: SettingsSlice + let dataGridSlice: SettingsSlice + let valueColorsSlice: SettingsSlice + let historySlice: SettingsSlice + let tabsSlice: SettingsSlice + let keyboardSlice: SettingsSlice + let aiSlice: SettingsSlice + let syncSlice: SettingsSlice + let mcpSlice: SettingsSlice + + var general: GeneralSettings { + get { generalSlice.value } + set { generalSlice.value = newValue } } - @Published var appearance: AppearanceSettings { - didSet { - guard appearance != oldValue else { return } - storage.saveAppearance(appearance) - themeEngine.select( - lightThemeId: appearance.preferredLightThemeId, - darkThemeId: appearance.preferredDarkThemeId - ) - syncTracker.markDirty(.settings, id: AppSettingsCategory.appearance) - } + var appearance: AppearanceSettings { + get { appearanceSlice.value } + set { appearanceSlice.value = newValue } } - // Device-local, like typography: each Mac picks Auto, Light or Dark for itself. - @Published var appearanceMode: AppAppearanceMode { - didSet { - guard appearanceMode != oldValue else { return } - storage.saveAppearanceMode(appearanceMode) - themeEngine.apply(mode: appearanceMode) - } + var appearanceMode: AppAppearanceMode { + get { appearanceModeSlice.value } + set { appearanceModeSlice.value = newValue } } - @Published var editor: EditorSettings { - didSet { - guard editor != oldValue else { return } - storage.saveEditor(editor) - appEvents.editorSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.editor) - } + var editor: EditorSettings { + get { editorSlice.value } + set { editorSlice.value = newValue } } - @Published var formatter: SQLFormatterSettings { - didSet { - guard formatter != oldValue else { return } - storage.saveFormatter(formatter) - syncTracker.markDirty(.settings, id: AppSettingsCategory.formatter) - } + var formatter: SQLFormatterSettings { + get { formatterSlice.value } + set { formatterSlice.value = newValue } } var formatterOptions: SQLFormatterOptions { formatter.options(for: editor) } - // Device-local, absent from `AppSettingsCategory.synced`: a zoom press never pushes a record an older build could reset. - @Published var typography: TypographySettings { - didSet { - guard typography != oldValue else { return } - storage.saveTypography(typography) - themeEngine.apply(typography: typography) - } + var typography: TypographySettings { + get { typographySlice.value } + set { typographySlice.value = newValue } } - @Published var notifications: NotificationSettings { - didSet { - guard !isValidating else { return } - var validated = notifications - validated.thresholdSeconds = notifications.validatedThresholdSeconds - if validated != notifications { - isValidating = true - notifications = validated - isValidating = false - } - storage.saveNotifications(notifications) - syncTracker.markDirty(.settings, id: AppSettingsCategory.notifications) - } + var notifications: NotificationSettings { + get { notificationsSlice.value } + set { notificationsSlice.value = newValue } } - @Published var dataGrid: DataGridSettings { - didSet { - guard !isValidating else { return } - var validated = dataGrid - validated.nullDisplay = dataGrid.validatedNullDisplay - validated.defaultPageSize = dataGrid.validatedDefaultPageSize - - if validated != dataGrid { - isValidating = true - dataGrid = validated - isValidating = false - } - - guard validated != oldValue else { return } - storage.saveDataGrid(validated) - if validated.dateFormat != oldValue.dateFormat { - dateFormattingService.updateFormat(validated.dateFormat) - } - appEvents.dataGridSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.dataGrid) - } + var dataGrid: DataGridSettings { + get { dataGridSlice.value } + set { dataGridSlice.value = newValue } } - @Published var valueColors: ValueColorSettings { - didSet { - guard valueColors != oldValue else { return } - storage.saveValueColors(valueColors) - appEvents.valueColorSettingsChanged.send(()) - syncTracker.markDirty(.settings, id: AppSettingsCategory.valueColors) - } + var valueColors: ValueColorSettings { + get { valueColorsSlice.value } + set { valueColorsSlice.value = newValue } } - @Published var history: HistorySettings { - didSet { - guard !isValidating else { return } - var validated = history - validated.maxEntries = history.validatedMaxEntries - validated.maxDays = history.validatedMaxDays - - if validated != history { - isValidating = true - history = validated - isValidating = false - } - - storage.saveHistory(validated) - Task { await applyHistorySettingsImmediately() } - syncTracker.markDirty(.settings, id: AppSettingsCategory.history) - } + var history: HistorySettings { + get { historySlice.value } + set { historySlice.value = newValue } } - @Published var tabs: TabSettings { - didSet { - guard tabs != oldValue else { return } - storage.saveTabs(tabs) - syncTracker.markDirty(.settings, id: AppSettingsCategory.tabs) - } + var tabs: TabSettings { + get { tabsSlice.value } + set { tabsSlice.value = newValue } } - @Published var keyboard: KeyboardSettings { - didSet { - guard keyboard != oldValue else { return } - storage.saveKeyboard(keyboard) - syncTracker.markDirty(.settings, id: AppSettingsCategory.keyboard) - MainMenuBuilder.syncKeyEquivalents(keyboard: keyboard) - appEvents.keyboardSettingsChanged.send(()) - } + var keyboard: KeyboardSettings { + get { keyboardSlice.value } + set { keyboardSlice.value = newValue } } - @Published var ai: AISettings { - didSet { - guard ai != oldValue else { return } - storage.saveAI(ai) - syncTracker.markDirty(.settings, id: AppSettingsCategory.ai) - appEvents.aiSettingsChanged.send(()) - copilotService.stopIfDisallowed(by: ai) - } + var ai: AISettings { + get { aiSlice.value } + set { aiSlice.value = newValue } } - // Every writer, a reset from another pane included, has to reach the Keychain flag and the coordinator. - @Published var sync: SyncSettings { - didSet { - storage.saveSync(sync) - passwordSyncDefaults.set(sync.syncsPasswords, forKey: KeychainHelper.passwordSyncEnabledKey) - if oldValue.enabled != sync.enabled { - switchSync(sync.enabled) - } - } + var sync: SyncSettings { + get { syncSlice.value } + set { syncSlice.value = newValue } } - @Published var mcp: MCPSettings { - didSet { - guard !isValidating else { return } - var validated = mcp - validated.port = mcp.validatedPort - validated.maxRowLimit = mcp.validatedMaxRowLimit - validated.defaultRowLimit = mcp.validatedDefaultRowLimit - validated.queryTimeoutSeconds = mcp.validatedQueryTimeoutSeconds - if validated != mcp { - isValidating = true - mcp = validated - isValidating = false - } - - storage.saveMCP(validated) - let enabledChanged = mcp.enabled != oldValue.enabled - let portChanged = mcp.port != oldValue.port - if enabledChanged || portChanged { - if mcp.enabled { - mcpServerManager.scheduleRestart(port: UInt16(clamping: mcp.port)) - } else { - mcpServerManager.scheduleStop() - } - } - } + var mcp: MCPSettings { + get { mcpSlice.value } + set { mcpSlice.value = newValue } } private let storage: AppSettingsStorage @@ -213,13 +109,15 @@ final class AppSettingsManager: ObservableObject { private let syncTracker: SyncChangeTracker private let appEvents: AppEvents private let dateFormattingService: DateFormattingService - private let queryHistoryManager: QueryHistoryManager private let mcpServerManager: MCPServerManager private let copilotService: CopilotService private let connectionListPreferences: ConnectionListPreferences private let passwordSyncDefaults: UserDefaults private let switchSync: @MainActor (Bool) -> Void - private var isValidating = false + private let applyHistoryRetention: @MainActor () -> Void + private let resetOutsideSettings: @MainActor () -> Void + private var deferredDirtyCategories: [String]? + private var sliceChanges: AnyCancellable? init( storage: AppSettingsStorage = .shared, @@ -227,7 +125,6 @@ final class AppSettingsManager: ObservableObject { syncTracker: SyncChangeTracker = .shared, appEvents: AppEvents = .shared, dateFormattingService: DateFormattingService = .shared, - queryHistoryManager: QueryHistoryManager = .shared, mcpServerManager: MCPServerManager = .shared, copilotService: CopilotService = .shared, connectionListPreferences: ConnectionListPreferences = .shared, @@ -239,6 +136,15 @@ final class AppSettingsManager: ObservableObject { } else { SyncCoordinator.shared.disableSync() } + }, + applyHistoryRetention: @escaping @MainActor () -> Void = { + Task { await QueryHistoryManager.shared.applySettingsChange() } + }, + resetOutsideSettings: @escaping @MainActor () -> Void = { + InspectorFieldHeightStore.shared.reload() + // The reset alert promises every section, so Sparkle's update preferences go too. + SoftwareUpdater.shared.resetUpdatePreferences() + AppModuleActivation.resetToDefaults() } ) { self.storage = storage @@ -246,39 +152,45 @@ final class AppSettingsManager: ObservableObject { self.syncTracker = syncTracker self.appEvents = appEvents self.dateFormattingService = dateFormattingService - self.queryHistoryManager = queryHistoryManager self.mcpServerManager = mcpServerManager self.copilotService = copilotService self.connectionListPreferences = connectionListPreferences self.passwordSyncDefaults = passwordSyncDefaults self.switchSync = switchSync + self.applyHistoryRetention = applyHistoryRetention + self.resetOutsideSettings = resetOutsideSettings + + generalSlice = SettingsSlice(storage.loadGeneral()) + appearanceSlice = SettingsSlice(storage.loadAppearance()) + appearanceModeSlice = SettingsSlice(storage.loadAppearanceMode()) + editorSlice = SettingsSlice(storage.loadEditor()) + formatterSlice = SettingsSlice(storage.loadFormatter()) + dataGridSlice = SettingsSlice(storage.loadDataGrid(), normalize: { $0.normalized }) + valueColorsSlice = SettingsSlice(storage.loadValueColors()) + historySlice = SettingsSlice(storage.loadHistory(), normalize: { $0.normalized }) + tabsSlice = SettingsSlice(storage.loadTabs()) + keyboardSlice = SettingsSlice(storage.loadKeyboard()) + aiSlice = SettingsSlice(Self.migrateAI(storage.loadAI())) + syncSlice = SettingsSlice(storage.loadSync()) + mcpSlice = SettingsSlice(storage.loadMCP(), normalize: { $0.normalized }) + notificationsSlice = SettingsSlice(storage.loadNotifications(), normalize: { $0.normalized }) + typographySlice = SettingsSlice( + storage.loadTypography(systemIsDark: NSApp?.effectiveAppearance.isDarkTheme ?? false) + ) - self.general = storage.loadGeneral() - self.appearance = storage.loadAppearance() - self.appearanceMode = storage.loadAppearanceMode() - self.editor = storage.loadEditor() - self.formatter = storage.loadFormatter() - self.dataGrid = storage.loadDataGrid() - self.valueColors = storage.loadValueColors() - self.history = storage.loadHistory() - self.tabs = storage.loadTabs() - self.keyboard = storage.loadKeyboard() - self.ai = Self.migrateAI(storage.loadAI()) - self.sync = storage.loadSync() - self.mcp = storage.loadMCP() - self.notifications = storage.loadNotifications() - self.typography = storage.loadTypography(systemIsDark: NSApp?.effectiveAppearance.isDarkTheme ?? false) - - general.language.apply() - - themeEngine.apply(typography: typography) + generalSlice.value.language.apply() + + themeEngine.apply(typography: typographySlice.value) themeEngine.apply( - mode: appearanceMode, - lightThemeId: appearance.preferredLightThemeId, - darkThemeId: appearance.preferredDarkThemeId + mode: appearanceModeSlice.value, + lightThemeId: appearanceSlice.value.preferredLightThemeId, + darkThemeId: appearanceSlice.value.preferredDarkThemeId ) - dateFormattingService.updateFormat(dataGrid.dateFormat) + dateFormattingService.updateFormat(dataGridSlice.value.dateFormat) + + attachCommits() + forwardSliceChanges() } // Settings saved before there was an active provider would otherwise read as AI turned off. @@ -291,19 +203,18 @@ final class AppSettingsManager: ObservableObject { return migrated } - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "AppSettingsManager") - - private func applyHistorySettingsImmediately() async { - await queryHistoryManager.applySettingsChange() - } - - // Resets Sparkle's update preferences too: the reset alert promises every section. func resetToDefaults() { - general = .default + var resetGeneral = GeneralSettings.default + // Share usage data is a consent choice, so a reset keeps it. + resetGeneral.shareAnalytics = general.shareAnalytics + + deferredDirtyCategories = [] + general = resetGeneral appearance = .default appearanceMode = .auto editor = .default formatter = .default + notifications = .default dataGrid = .default valueColors = .default history = .default @@ -314,9 +225,213 @@ final class AppSettingsManager: ObservableObject { mcp = .default typography = .default storage.resetToDefaults() - InspectorFieldHeightStore.shared.reload() + let changedCategories = deferredDirtyCategories ?? [] + deferredDirtyCategories = nil + syncTracker.markDirty(.settings, ids: changedCategories) + connectionListPreferences.resetShowsRecent() - SoftwareUpdater.shared.resetUpdatePreferences() - AppModuleActivation.resetToDefaults() + resetOutsideSettings() + } + + private func attachCommits() { + generalSlice.attach { [weak self] old, new in self?.commitGeneral(from: old, to: new) } + appearanceSlice.attach { [weak self] _, new in self?.commitAppearance(new) } + appearanceModeSlice.attach { [weak self] _, new in self?.commitAppearanceMode(new) } + editorSlice.attach { [weak self] _, new in self?.commitEditor(new) } + formatterSlice.attach { [weak self] _, new in self?.commitFormatter(new) } + typographySlice.attach { [weak self] _, new in self?.commitTypography(new) } + notificationsSlice.attach { [weak self] _, new in self?.commitNotifications(new) } + dataGridSlice.attach { [weak self] old, new in self?.commitDataGrid(from: old, to: new) } + valueColorsSlice.attach { [weak self] _, new in self?.commitValueColors(new) } + historySlice.attach { [weak self] old, new in self?.commitHistory(from: old, to: new) } + tabsSlice.attach { [weak self] _, new in self?.commitTabs(new) } + keyboardSlice.attach { [weak self] _, new in self?.commitKeyboard(new) } + aiSlice.attach { [weak self] _, new in self?.commitAI(new) } + syncSlice.attach { [weak self] old, new in self?.commitSync(from: old, to: new) } + mcpSlice.attach { [weak self] old, new in self?.commitMCP(from: old, to: new) } + } + + // For views that still observe the whole manager. + private func forwardSliceChanges() { + let changes: [ObservableObjectPublisher] = [ + generalSlice.objectWillChange, + appearanceSlice.objectWillChange, + appearanceModeSlice.objectWillChange, + editorSlice.objectWillChange, + formatterSlice.objectWillChange, + typographySlice.objectWillChange, + notificationsSlice.objectWillChange, + dataGridSlice.objectWillChange, + valueColorsSlice.objectWillChange, + historySlice.objectWillChange, + tabsSlice.objectWillChange, + keyboardSlice.objectWillChange, + aiSlice.objectWillChange, + syncSlice.objectWillChange, + mcpSlice.objectWillChange, + ] + sliceChanges = Publishers.MergeMany(changes).sink { [weak self] _ in + self?.objectWillChange.send() + } + } + + // A reset collects its categories and marks them once, after the whole reset is saved. + private func markDirty(_ category: String) { + if deferredDirtyCategories != nil { + deferredDirtyCategories?.append(category) + } else { + syncTracker.markDirty(.settings, id: category) + } + } + + private func commitGeneral(from old: GeneralSettings, to new: GeneralSettings) { + storage.saveGeneral(new) + if old.language != new.language { + new.language.apply() + } + if old.showWorkspaceRail != new.showWorkspaceRail { + appEvents.workspaceRailVisibilityChanged.send(()) + } + if old.connectionHealthCheck != new.connectionHealthCheck { + appEvents.connectionHealthCheckChanged.send(()) + } + markDirty(AppSettingsCategory.general) + } + + private func commitAppearance(_ new: AppearanceSettings) { + storage.saveAppearance(new) + themeEngine.select(lightThemeId: new.preferredLightThemeId, darkThemeId: new.preferredDarkThemeId) + markDirty(AppSettingsCategory.appearance) + } + + private func commitAppearanceMode(_ new: AppAppearanceMode) { + storage.saveAppearanceMode(new) + themeEngine.apply(mode: new) + } + + private func commitEditor(_ new: EditorSettings) { + storage.saveEditor(new) + appEvents.editorSettingsChanged.send(()) + markDirty(AppSettingsCategory.editor) + } + + private func commitFormatter(_ new: SQLFormatterSettings) { + storage.saveFormatter(new) + markDirty(AppSettingsCategory.formatter) + } + + private func commitTypography(_ new: TypographySettings) { + storage.saveTypography(new) + themeEngine.apply(typography: new) + } + + private func commitNotifications(_ new: NotificationSettings) { + storage.saveNotifications(new) + markDirty(AppSettingsCategory.notifications) + } + + private func commitDataGrid(from old: DataGridSettings, to new: DataGridSettings) { + storage.saveDataGrid(new) + if old.dateFormat != new.dateFormat { + dateFormattingService.updateFormat(new.dateFormat) + } + appEvents.dataGridSettingsChanged.send(()) + markDirty(AppSettingsCategory.dataGrid) + } + + private func commitValueColors(_ new: ValueColorSettings) { + storage.saveValueColors(new) + appEvents.valueColorSettingsChanged.send(()) + markDirty(AppSettingsCategory.valueColors) + } + + private func commitHistory(from old: HistorySettings, to new: HistorySettings) { + storage.saveHistory(new) + if !new.hasSameRetention(as: old) { + applyHistoryRetention() + } + markDirty(AppSettingsCategory.history) + } + + private func commitTabs(_ new: TabSettings) { + storage.saveTabs(new) + markDirty(AppSettingsCategory.tabs) + } + + private func commitKeyboard(_ new: KeyboardSettings) { + storage.saveKeyboard(new) + markDirty(AppSettingsCategory.keyboard) + MainMenuBuilder.syncKeyEquivalents(keyboard: new) + appEvents.keyboardSettingsChanged.send(()) + } + + private func commitAI(_ new: AISettings) { + storage.saveAI(new) + markDirty(AppSettingsCategory.ai) + appEvents.aiSettingsChanged.send(()) + copilotService.stopIfDisallowed(by: new) + } + + // Every writer, a reset from another pane included, has to reach the Keychain flag and the coordinator. + private func commitSync(from old: SyncSettings, to new: SyncSettings) { + storage.saveSync(new) + passwordSyncDefaults.set(new.syncsPasswords, forKey: KeychainHelper.passwordSyncEnabledKey) + if old.enabled != new.enabled { + switchSync(new.enabled) + } + } + + private func commitMCP(from old: MCPSettings, to new: MCPSettings) { + storage.saveMCP(new) + guard old.enabled != new.enabled || old.port != new.port else { return } + if new.enabled { + mcpServerManager.scheduleRestart(port: UInt16(clamping: new.port)) + } else { + mcpServerManager.scheduleStop() + } + } +} + +extension HistorySettings { + // Data Rewind's switch is not retention, so turning it never starts a cleanup. + func hasSameRetention(as other: HistorySettings) -> Bool { + maxEntries == other.maxEntries && maxDays == other.maxDays && autoCleanup == other.autoCleanup + } +} + +private extension NotificationSettings { + var normalized: NotificationSettings { + var settings = self + settings.thresholdSeconds = validatedThresholdSeconds + return settings + } +} + +private extension DataGridSettings { + var normalized: DataGridSettings { + var settings = self + settings.nullDisplay = validatedNullDisplay + settings.defaultPageSize = validatedDefaultPageSize + return settings + } +} + +private extension HistorySettings { + var normalized: HistorySettings { + var settings = self + settings.maxEntries = validatedMaxEntries + settings.maxDays = validatedMaxDays + return settings + } +} + +private extension MCPSettings { + var normalized: MCPSettings { + var settings = self + settings.port = validatedPort + settings.maxRowLimit = validatedMaxRowLimit + settings.defaultRowLimit = validatedDefaultRowLimit + settings.queryTimeoutSeconds = validatedQueryTimeoutSeconds + return settings } } diff --git a/apple/TablePro/Core/Storage/AppSettingsStorage.swift b/apple/TablePro/Core/Storage/AppSettingsStorage.swift index 742bdfb3b6..f1d1d2ab2b 100644 --- a/apple/TablePro/Core/Storage/AppSettingsStorage.swift +++ b/apple/TablePro/Core/Storage/AppSettingsStorage.swift @@ -1,11 +1,3 @@ -// -// AppSettingsStorage.swift -// TablePro -// -// Persistent storage for application settings using UserDefaults. -// Follows FilterSettingsStorage pattern - singleton with JSON encoding. -// - import Foundation import os @@ -17,8 +9,6 @@ final class AppSettingsStorage: Sendable { private let decoder = JSONDecoder() private let encoder = JSONEncoder() - // MARK: - UserDefaults Keys - private enum Keys { static let general = "com.TablePro.settings.general" static let appearance = "com.TablePro.settings.appearance" @@ -52,8 +42,6 @@ final class AppSettingsStorage: Sendable { self.defaults = userDefaults } - // MARK: - General Settings - func loadGeneral() -> GeneralSettings { load(key: Keys.general, default: .default) } @@ -84,8 +72,6 @@ final class AppSettingsStorage: Sendable { } } - // MARK: - Appearance Settings - func loadAppearance() -> AppearanceSettings { load(key: Keys.appearance, default: .default) } @@ -94,8 +80,7 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.appearance) } - // Older builds kept the mode inside the synced appearance blob. The first load carries it to its - // own key and writes it there, because the next save of the blob drops the field. + // Older builds kept the mode in the synced appearance blob; the first load moves it, since the blob's next save drops it. func loadAppearanceMode() -> AppAppearanceMode { if let stored = defaults.string(forKey: Keys.appearanceMode) { guard let mode = AppAppearanceMode(rawValue: stored) else { @@ -156,8 +141,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.typography) } - // MARK: - Editor Settings - func loadEditor() -> EditorSettings { load(key: Keys.editor, default: .default) } @@ -166,8 +149,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.editor) } - // MARK: - Formatter Settings - func loadFormatter() -> SQLFormatterSettings { load(key: Keys.formatter, default: .default) } @@ -176,8 +157,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.formatter) } - // MARK: - Data Grid Settings - func loadDataGrid() -> DataGridSettings { load(key: Keys.dataGrid, default: .default) } @@ -186,8 +165,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.dataGrid) } - // MARK: - Value Color Settings - func loadValueColors() -> ValueColorSettings { load(key: Keys.valueColors, default: .default) } @@ -196,8 +173,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.valueColors) } - // MARK: - History Settings - func loadHistory() -> HistorySettings { load(key: Keys.history, default: .default) } @@ -206,9 +181,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.history) } - - // MARK: - Tab Settings - func loadTabs() -> TabSettings { load(key: Keys.tabs, default: .default) } @@ -217,8 +189,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.tabs) } - // MARK: - Keyboard Settings - func loadKeyboard() -> KeyboardSettings { load(key: Keys.keyboard, default: KeyboardSettings.default).sanitized() } @@ -227,8 +197,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.keyboard) } - // MARK: - AI Settings - func loadAI() -> AISettings { load(key: Keys.ai, default: .default) } @@ -237,8 +205,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.ai) } - // MARK: - Sync Settings - func loadSync() -> SyncSettings { load(key: Keys.sync, default: .default) } @@ -247,8 +213,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.sync) } - // MARK: - MCP Settings - func loadNotifications() -> NotificationSettings { load(key: Keys.notifications, default: .default) } @@ -265,8 +229,6 @@ final class AppSettingsStorage: Sendable { save(settings, key: Keys.mcp) } - // MARK: - Last Selected Database (per connection) - func saveLastDatabase(_ database: String?, for connectionId: UUID) { if let database { defaults.set(database, forKey: "com.TablePro.lastSelectedDatabase.\(connectionId)") @@ -279,8 +241,6 @@ final class AppSettingsStorage: Sendable { defaults.string(forKey: "com.TablePro.lastSelectedDatabase.\(connectionId)") } - // MARK: - Last Selected Schema (per connection) - func saveLastSchema(_ schema: String?, for connectionId: UUID) { if let schema { defaults.set(schema, forKey: "com.TablePro.lastSelectedSchema.\(connectionId)") @@ -293,8 +253,6 @@ final class AppSettingsStorage: Sendable { defaults.string(forKey: "com.TablePro.lastSelectedSchema.\(connectionId)") } - // MARK: - Welcome Sheet - func hasSeenWelcomeSheet() -> Bool { defaults.bool(forKey: Keys.hasSeenWelcomeSheet) } @@ -303,10 +261,11 @@ final class AppSettingsStorage: Sendable { defaults.set(true, forKey: Keys.hasSeenWelcomeSheet) } - // MARK: - Reset - func resetToDefaults() { - saveGeneral(.default) + var general = GeneralSettings.default + // Share usage data is a consent choice, so a reset keeps it. + general.shareAnalytics = loadGeneral().shareAnalytics + saveGeneral(general) saveAppearance(.default) saveAppearanceMode(.auto) saveEditor(.default) @@ -319,6 +278,7 @@ final class AppSettingsStorage: Sendable { saveAI(loadAI().resetKeepingProviders) saveSync(.default) saveMCP(.default) + saveNotifications(.default) saveTypography(.default) defaults.removeObject(forKey: PreferenceKeys.selectedSettingsPane.name) defaults.removeObject(forKey: PreferenceKeys.rowInspectorFieldHeights.name) @@ -327,8 +287,6 @@ final class AppSettingsStorage: Sendable { RoutineDebugOptionStore(defaults: { [defaults] in defaults }).removeAll() } - // MARK: - Helpers - private func load(key: String, default defaultValue: T) -> T { guard let data = defaults.data(forKey: key) else { return defaultValue diff --git a/apple/TablePro/Core/Storage/SettingsSlice.swift b/apple/TablePro/Core/Storage/SettingsSlice.swift new file mode 100644 index 0000000000..989a4b0a1a --- /dev/null +++ b/apple/TablePro/Core/Storage/SettingsSlice.swift @@ -0,0 +1,41 @@ +import Combine +import Foundation + +// One settings category per object, so a write re-renders only the views that read that category. +@MainActor +final class SettingsSlice: ObservableObject { + @Published private var stored: Value + private let normalize: (Value) -> Value + private var onCommit: (@MainActor (_ old: Value, _ new: Value) -> Void)? + + init(_ initial: Value, normalize: @escaping (Value) -> Value = { $0 }) { + stored = initial + self.normalize = normalize + } + + var value: Value { + get { stored } + set { assign(newValue) } + } + + var publisher: Published.Publisher { $stored } + + func update(_ body: (inout Value) -> Void) { + var next = stored + body(&next) + assign(next) + } + + // Attached after init, so loading a value never saves it or marks it for sync. + func attach(_ onCommit: @escaping @MainActor (_ old: Value, _ new: Value) -> Void) { + self.onCommit = onCommit + } + + private func assign(_ newValue: Value) { + let candidate = normalize(newValue) + guard candidate != stored else { return } + let old = stored + stored = candidate + onCommit?(old, candidate) + } +} diff --git a/apple/TablePro/Models/Settings/LanguageLaunchState.swift b/apple/TablePro/Models/Settings/LanguageLaunchState.swift index 918e84f158..0de1818db6 100644 --- a/apple/TablePro/Models/Settings/LanguageLaunchState.swift +++ b/apple/TablePro/Models/Settings/LanguageLaunchState.swift @@ -1,14 +1,26 @@ -// -// LanguageLaunchState.swift -// TablePro -// - import Foundation -// The UI language in effect for this process, captured once. A language change needs a relaunch, -// so this is the value to compare a pending change against. Lives outside the view layer so the -// comparison does not read a singleton from a SwiftUI view. +// Captured at launch: a language change needs a relaunch, so a pending choice is compared with this. @MainActor enum LanguageLaunchState { - static let language: AppLanguage = AppSettingsManager.shared.general.language + private static var launch = LaunchLanguage() + + static var language: AppLanguage { + launch.capture(AppSettingsManager.shared.general.language) + } + + static func record() { + launch.capture(AppSettingsManager.shared.general.language) + } +} + +struct LaunchLanguage { + private(set) var language: AppLanguage? + + @discardableResult + mutating func capture(_ current: AppLanguage) -> AppLanguage { + if let language { return language } + language = current + return current + } } diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index b0f49a3245..1e88ef5b96 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -1,8 +1,3 @@ -// -// SQLEditorController.swift -// TablePro -// - import AppKit import Combine import SwiftUI @@ -12,7 +7,6 @@ import TableProPluginKit import TableProSQLGrammar import TableProTextEngine -/// What a query tab hands the SQL editor on every update. struct SQLEditorInput { var text: Binding var cursorPositions: Binding<[CursorPosition]> @@ -24,7 +18,7 @@ struct SQLEditorInput { var undoHistories: EditorUndoHistories? var sourceFileURL: URL? var claimFocusOnAppear = false - /// Called once the editor has latched a focus claim, so the owner's one-shot intent is cleared. + // Called once the editor latched a focus claim, so the owner clears its one-shot intent. var onFocusClaimed: (() -> Void)? var restoredCursorRange: NSRange? var pendingStatementJump: StatementAnchor? @@ -37,7 +31,7 @@ struct SQLEditorInput { var onSelectAdjacentTab: ((Int) -> Void)? var tabCount: (() -> Int)? var onRunStatement: ((String, Int) -> Bool)? - /// A tab runs one thing at a time, so the gutter's run controls go dim for the length of a query. + // A tab runs one thing at a time, so the gutter's run controls go dim for the length of a query. var isExecuting = false var currentAIAvailability: (() -> AIQueryActionAvailability)? var onAIAction: ((AIQueryAction, AIQueryTarget) -> Void)? @@ -45,12 +39,10 @@ struct SQLEditorInput { var onShareQuery: ((String) -> Void)? } -/// The SQL editor in AppKit, so the query tab hosts it with no SwiftUI host around it: each one above an editor -/// forced the window to lay out every hosting view again as the editor's views went in. +// AppKit, so no SwiftUI host wraps the editor: each one made the window lay out every hosting view as the editor went in. @MainActor final class SQLEditorController { let coordinator = SQLEditorCoordinator() - /// Reports Vim's mode to whatever draws it beside the editor. var onVimModeChange: ((VimMode) -> Void)? private let completionAdapter = QueryCompletionAdapter(schemaProvider: nil, databaseType: nil) @@ -127,9 +119,7 @@ final class SQLEditorController { configureCompletion() setupFavoritesObserver() } - /// A tab rebound to another database keeps its editor and its connection, so only the scope moves. Without - /// this the editor keeps completing against the previous database's provider until the profile resolution - /// returns, which leases a metadata driver and on a non-poolable engine can queue behind a running query. + // Otherwise completion keeps the old database's provider until the profile resolves, which can queue behind a query. if newInput.databaseScope != old.databaseScope { completionProfile = nil configureCompletion() @@ -138,8 +128,7 @@ final class SQLEditorController { resolveCompletionProfileIfNeeded() } - /// The editor's terminal teardown, run when its query tab area goes away for good, never when it only leaves - /// the window. + // Runs when the query tab area goes away for good, never when it only leaves the window. func teardown() { guard !isTornDown else { return } isTornDown = true @@ -153,8 +142,7 @@ final class SQLEditorController { host?.dismantle() } - // A large document's last keys are still on their way to the binding when the editor moves to another tab or - // goes away. Both run inside a SwiftUI update, where writing the tab would publish mid-update, so it lands next turn. + // Late keys arrive inside a SwiftUI update, where writing the tab would publish mid-update, so they land next turn. private func handOverPendingText(to binding: Binding) { guard let text = host?.takePendingTextWriteback() else { return } Task { @MainActor in binding.wrappedValue = text } @@ -215,8 +203,7 @@ final class SQLEditorController { refreshSessionGrammar() } - /// The grammar the session lexes with: KingbaseES in Oracle mode, MySQL under `NO_BACKSLASH_ESCAPES`, or - /// PostgreSQL with `standard_conforming_strings` off each split text differently from the engine's default. + // KingbaseES in Oracle mode, MySQL under NO_BACKSLASH_ESCAPES or PostgreSQL without standard_conforming_strings lex differently. private func refreshSessionGrammar() { guard let databaseType = input.databaseType else { return } let grammar: SQLLexicalGrammar @@ -278,8 +265,7 @@ final class SQLEditorController { } } - // An edit reports its caret before its text is written back, so the caret waits for the text; one from a document - // the binding does not hold, as across a tab switch, is never passed on. + // The caret arrives before its text, so it waits; one from a document the binding does not hold is dropped. private func passPendingCaretOn() { guard let positions = pendingCaret else { return } let editorLength = (textViewController.textView.string as NSString).length @@ -288,11 +274,9 @@ final class SQLEditorController { input.cursorPositions.wrappedValue = positions } - // MARK: - Settings - private func observeEditorSettings() { - // `$editor` publishes before the value is stored; the theme reads the stored settings too. - AppSettingsManager.shared.$editor + // The slice publishes before the value is stored; the theme reads the stored settings too. + AppSettingsManager.shared.editorSlice.publisher .dropFirst() .receive(on: RunLoop.main) .sink { [weak self] editor in @@ -346,10 +330,7 @@ final class SQLEditorController { ) } - // MARK: - Completion - - /// The one place the completion service is configured. Configuring without a profile anywhere else put the - /// editor back on the app's own dialect after the resolver had run, with nothing scheduled to correct it. + // The only place completion is configured: doing it elsewhere without a profile reverted the dialect the resolver set. private func configureCompletion() { completionAdapter.configure( schemaProvider: input.schemaProvider, @@ -360,9 +341,7 @@ final class SQLEditorController { ) } - /// This scope's box alone, never the registry: the registry publishes on every fetch, and resolving again for - /// each of them would run while the user types. A `@Published` publisher delivers its current value on - /// subscribe, so the revision starts in step with the box. + // This scope's box, not the registry, which publishes on every fetch and would resolve again while the user types. private func subscribeToCompletionRevision() { revisionSubscription = nil guard let scope = input.databaseScope else { return } @@ -383,7 +362,7 @@ final class SQLEditorController { ) } - /// The revision is part of the request, so an invalidation of this scope restarts the resolution. + // The revision is part of the request, so an invalidation of this scope restarts the resolution. private func resolveCompletionProfileIfNeeded() { let request = completionProfileRequest guard request != profileRequest, !isTornDown else { return } @@ -404,8 +383,6 @@ final class SQLEditorController { } } - // MARK: - Favorites - private func setupFavoritesObserver() { favoritesCancellables.removeAll() refreshFavoriteKeywords() diff --git a/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift b/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift index b7b4918911..8b1cc23800 100644 --- a/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift +++ b/apple/TableProTests/Core/Storage/AppSettingsStorageResetTests.swift @@ -1,8 +1,3 @@ -// -// AppSettingsStorageResetTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -58,4 +53,29 @@ struct AppSettingsStorageResetTests { #expect(defaults.object(forKey: PreferenceKeys.rowInspectorFieldHeights.name) == nil) #expect(defaults.object(forKey: PreferenceKeys.rowInspectorGeometryFieldMode.name) == nil) } + + @Test("Reset returns notifications to their defaults") + func resetRestoresNotifications() throws { + let storage = AppSettingsStorage(userDefaults: try pool.make().defaults) + storage.saveNotifications(NotificationSettings(isEnabled: false, thresholdSeconds: 120)) + + storage.resetToDefaults() + + #expect(storage.loadNotifications() == .default) + } + + @Test("Reset keeps the Share usage data choice and resets the rest of General") + func resetKeepsShareUsageData() throws { + let storage = AppSettingsStorage(userDefaults: try pool.make().defaults) + var general = GeneralSettings.default + general.shareAnalytics = false + general.showRecentTables.toggle() + storage.saveGeneral(general) + + storage.resetToDefaults() + + var expected = GeneralSettings.default + expected.shareAnalytics = false + #expect(storage.loadGeneral() == expected) + } } diff --git a/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift index 0dc7026d58..8c17c7deef 100644 --- a/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift +++ b/apple/TableProTests/Core/Storage/AppSettingsSyncSideEffectsTests.swift @@ -75,4 +75,20 @@ struct AppSettingsSyncSideEffectsTests { #expect(recorder.calls.isEmpty) #expect(!flagDefaults.bool(forKey: KeychainHelper.passwordSyncEnabledKey)) } + + @Test("Writing the sync settings already held neither calls the coordinator nor rewrites the Keychain flag") + func unchangedSyncSettingsDoNothing() throws { + let flagDefaults = try pool.make().defaults + let recorder = SyncSwitchRecorder() + let root = Self.makeRoot() + defer { try? FileManager.default.removeItem(at: root) } + let manager = try makeManager(flagDefaults: flagDefaults, recorder: recorder, root: root) + flagDefaults.set(true, forKey: KeychainHelper.passwordSyncEnabledKey) + + let current = manager.sync + manager.sync = current + + #expect(recorder.calls.isEmpty) + #expect(flagDefaults.bool(forKey: KeychainHelper.passwordSyncEnabledKey)) + } } diff --git a/apple/TableProTests/Core/Storage/SettingsSliceTests.swift b/apple/TableProTests/Core/Storage/SettingsSliceTests.swift new file mode 100644 index 0000000000..fe93481ec9 --- /dev/null +++ b/apple/TableProTests/Core/Storage/SettingsSliceTests.swift @@ -0,0 +1,280 @@ +import Combine +import Foundation +import os +@testable import TablePro +import TableProSyncTransport +import TableProTheme +import Testing + +@MainActor +private final class SliceRecorder { + var publishes = 0 + var commits: [(old: Value, new: Value)] = [] + private var subscription: AnyCancellable? + + init(_ slice: SettingsSlice) { + subscription = slice.objectWillChange.sink { [weak self] _ in self?.publishes += 1 } + slice.attach { [weak self] old, new in self?.commits.append((old, new)) } + } +} + +@MainActor +private final class PublishCounter { + private(set) var count = 0 + private var subscription: AnyCancellable? + + init(_ publisher: ObservableObjectPublisher) { + subscription = publisher.sink { [weak self] _ in self?.count += 1 } + } +} + +@MainActor +private final class OutsideEffects { + var historyRetentionApplies = 0 + var outsideResets = 0 +} + +// Each defaults write posts one change notification, so the log shows every write and its order. +@MainActor +private final class DefaultsWriteLog { + private let entries = OSAllocatedUnfairLock(initialState: [String]()) + private var tokens: [NSObjectProtocol] = [] + + var all: [String] { entries.withLock { $0 } } + + func watch(_ defaults: UserDefaults, as label: String) { + let entries = entries + let token = NotificationCenter.default.addObserver( + forName: UserDefaults.didChangeNotification, + object: defaults, + queue: nil + ) { _ in + entries.withLock { $0.append(label) } + } + tokens.append(token) + } + + func stop() { + for token in tokens { + NotificationCenter.default.removeObserver(token) + } + tokens.removeAll() + } +} + +@MainActor +private final class ManagerFixture { + let storageSuite: EphemeralDefaults + let metadataSuite: EphemeralDefaults + let localSuite: EphemeralDefaults + let root: URL + let tracker: SyncChangeTracker + let effects: OutsideEffects + let manager: AppSettingsManager + + var storage: AppSettingsStorage { AppSettingsStorage(userDefaults: storageSuite.defaults) } + + init() throws { + storageSuite = try EphemeralDefaults() + metadataSuite = try EphemeralDefaults() + localSuite = try EphemeralDefaults() + root = FileManager.default.temporaryDirectory + .appendingPathComponent("SettingsSliceTests-\(UUID().uuidString)", isDirectory: true) + tracker = SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: metadataSuite.defaults)) + let catalog = ThemeCatalog( + userDirectory: root.appendingPathComponent("Themes", isDirectory: true), + bundleDirectory: nil, + fileTrash: .folder(root.appendingPathComponent("Trash", isDirectory: true)), + syncTracker: tracker + ) + let effects = OutsideEffects() + self.effects = effects + manager = AppSettingsManager( + storage: AppSettingsStorage(userDefaults: storageSuite.defaults), + themeEngine: ThemeEngine(catalog: catalog), + syncTracker: tracker, + appEvents: AppEvents(), + connectionListPreferences: ConnectionListPreferences(defaults: localSuite.defaults, appEvents: AppEvents()), + passwordSyncDefaults: localSuite.defaults, + switchSync: { _ in }, + applyHistoryRetention: { effects.historyRetentionApplies += 1 }, + resetOutsideSettings: { effects.outsideResets += 1 } + ) + } + + deinit { + try? FileManager.default.removeItem(at: root) + } +} + +@MainActor +struct SettingsSliceTests { + nonisolated private static func clampingMaxEntries(_ settings: HistorySettings) -> HistorySettings { + var clamped = settings + clamped.maxEntries = max(0, settings.maxEntries) + return clamped + } + + @Test("Writing the value a slice already holds neither publishes nor commits") + func equalWriteDoesNothing() { + let slice = SettingsSlice(NotificationSettings(isEnabled: true, thresholdSeconds: 30)) + let recorder = SliceRecorder(slice) + + slice.value = NotificationSettings(isEnabled: true, thresholdSeconds: 30) + slice.update { $0.isEnabled = true } + + #expect(recorder.publishes == 0) + #expect(recorder.commits.isEmpty) + } + + @Test("A change publishes once and commits the old and new values") + func changeCommitsOnce() { + let slice = SettingsSlice(NotificationSettings(isEnabled: true, thresholdSeconds: 30)) + let recorder = SliceRecorder(slice) + + slice.value.isEnabled = false + + #expect(recorder.publishes == 1) + #expect(recorder.commits.count == 1) + #expect(recorder.commits.first?.old.isEnabled == true) + #expect(recorder.commits.first?.new.isEnabled == false) + #expect(!slice.value.isEnabled) + } + + @Test("A write that needs normalizing publishes and commits the normalized value once") + func normalizedWritePublishesOnce() { + let slice = SettingsSlice(HistorySettings(maxEntries: 50), normalize: Self.clampingMaxEntries) + let recorder = SliceRecorder(slice) + + slice.value.maxEntries = -5 + + #expect(slice.value.maxEntries == 0) + #expect(recorder.publishes == 1) + #expect(recorder.commits.map { $0.new.maxEntries } == [0]) + + slice.value.maxEntries = -9 + + #expect(recorder.publishes == 1) + #expect(recorder.commits.count == 1) + } + + @Test("Building a slice never commits, so loading a value never saves it") + func initNeverCommits() { + let slice = SettingsSlice(HistorySettings(maxEntries: -5), normalize: Self.clampingMaxEntries) + let recorder = SliceRecorder(slice) + + #expect(slice.value.maxEntries == -5) + #expect(recorder.commits.isEmpty) + } + + @Test("The publisher delivers each real change and skips equal writes") + func publisherDeliversChanges() { + let slice = SettingsSlice(TabSettings(enablePreviewTabs: true)) + var received: [Bool] = [] + let subscription = slice.publisher.dropFirst().sink { received.append($0.enablePreviewTabs) } + defer { subscription.cancel() } + + slice.value.enablePreviewTabs = false + slice.value.enablePreviewTabs = false + slice.value.enablePreviewTabs = true + + #expect(received == [false, true]) + } + + @Test("A write through the manager publishes only its own slice, and the manager once") + func facadeWritePublishesOnlyItsSlice() throws { + let fixture = try ManagerFixture() + let manager = fixture.manager + let editor = PublishCounter(manager.editorSlice.objectWillChange) + let general = PublishCounter(manager.generalSlice.objectWillChange) + let dataGrid = PublishCounter(manager.dataGridSlice.objectWillChange) + let whole = PublishCounter(manager.objectWillChange) + + manager.editor.showLineNumbers.toggle() + + #expect(editor.count == 1) + #expect(general.count == 0) + #expect(dataGrid.count == 0) + #expect(whole.count == 1) + } + + @Test("A change is saved, then marked for sync, before the assignment returns") + func saveThenMarkBeforeReturn() throws { + let fixture = try ManagerFixture() + let log = DefaultsWriteLog() + log.watch(fixture.storageSuite.defaults, as: "save") + log.watch(fixture.metadataSuite.defaults, as: "mark") + defer { log.stop() } + + fixture.manager.editor.showLineNumbers.toggle() + + #expect(log.all == ["save", "mark"]) + #expect(fixture.storage.loadEditor() == fixture.manager.editor) + #expect(fixture.tracker.dirtyRecords(for: .settings) == [AppSettingsCategory.editor]) + } + + @Test("History retention is reapplied only when a retention setting changes") + func historyRetentionOnlyOnRetentionChange() throws { + let fixture = try ManagerFixture() + let manager = fixture.manager + + manager.history.keepRewindHistory.toggle() + + #expect(fixture.effects.historyRetentionApplies == 0) + #expect(fixture.storage.loadHistory().keepRewindHistory == manager.history.keepRewindHistory) + #expect(fixture.tracker.dirtyRecords(for: .settings) == [AppSettingsCategory.history]) + + manager.history.maxDays = 30 + manager.history.maxDays = 30 + + #expect(fixture.effects.historyRetentionApplies == 1) + + manager.history.maxEntries = -3 + + #expect(manager.history.maxEntries == 0) + #expect(fixture.effects.historyRetentionApplies == 2) + } + + @Test("Reset covers notifications, keeps Share usage data and marks every changed category in one write") + func resetMarksOnce() throws { + let fixture = try ManagerFixture() + let manager = fixture.manager + manager.general.shareAnalytics = false + manager.general.showRecentTables.toggle() + manager.notifications = NotificationSettings(isEnabled: false, thresholdSeconds: 120) + manager.tabs.enablePreviewTabs.toggle() + manager.editor.showLineNumbers.toggle() + fixture.tracker.clearAllDirty(.settings) + let log = DefaultsWriteLog() + log.watch(fixture.metadataSuite.defaults, as: "mark") + defer { log.stop() } + + manager.resetToDefaults() + + var expectedGeneral = GeneralSettings.default + expectedGeneral.shareAnalytics = false + #expect(manager.general == expectedGeneral) + #expect(fixture.storage.loadGeneral() == expectedGeneral) + #expect(manager.notifications == .default) + #expect(fixture.storage.loadNotifications() == .default) + #expect(manager.tabs == .default) + #expect(manager.editor == .default) + #expect(log.all == ["mark"]) + #expect(fixture.tracker.dirtyRecords(for: .settings) == [ + AppSettingsCategory.general, + AppSettingsCategory.notifications, + AppSettingsCategory.tabs, + AppSettingsCategory.editor, + ]) + #expect(fixture.effects.outsideResets == 1) + } + + @Test("A reset with nothing to change marks nothing for sync") + func resetOfDefaultsMarksNothing() throws { + let fixture = try ManagerFixture() + + fixture.manager.resetToDefaults() + + #expect(fixture.tracker.dirtyRecords(for: .settings).isEmpty) + } +} diff --git a/apple/TableProTests/Models/Settings/LanguageLaunchStateTests.swift b/apple/TableProTests/Models/Settings/LanguageLaunchStateTests.swift new file mode 100644 index 0000000000..86187af395 --- /dev/null +++ b/apple/TableProTests/Models/Settings/LanguageLaunchStateTests.swift @@ -0,0 +1,29 @@ +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct LanguageLaunchStateTests { + @Test("Nothing is captured before the launch records a language") + func emptyUntilRecorded() { + #expect(LaunchLanguage().language == nil) + } + + @Test("The first recorded language stays after a later record or a general settings change") + func firstRecordWins() { + var launch = LaunchLanguage() + + #expect(launch.capture(.vietnamese) == .vietnamese) + #expect(launch.capture(.french) == .vietnamese) + #expect(launch.language == .vietnamese) + } + + @Test("The app's launch language ignores a record after launch") + func appLaunchLanguageIgnoresLaterRecord() { + let launched = LanguageLaunchState.language + + LanguageLaunchState.record() + + #expect(LanguageLaunchState.language == launched) + } +} From ccadbe68f71528e6670004249a6d5af5b582aca0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:06 +0700 Subject: [PATCH 16/48] feat(settings): shared Settings form components --- .../Components/LicenseNoticeControls.swift | 19 +- .../Settings/Components/SettingsChoices.swift | 29 +++ .../Components/SettingsDrillRow.swift | 43 ++++ .../Settings/Components/SettingsFormat.swift | 38 ++++ .../Components/SettingsFullPageList.swift | 30 +++ .../Settings/Components/SettingsHelpRow.swift | 22 ++ .../Settings/Components/SettingsListBar.swift | 97 +++++++++ .../Components/SettingsNumberField.swift | 161 ++++++++++++++ .../Components/SettingsRecordRow.swift | 137 ++++++++++++ .../Components/SettingsSectionActions.swift | 16 ++ .../Components/SettingsTextDraft.swift | 68 ++++++ .../Components/SettingsTextField.swift | 65 ++++++ .../Views/Settings/SettingsChoicesTests.swift | 42 ++++ .../Views/Settings/SettingsFormatTests.swift | 46 ++++ .../Settings/SettingsTextDraftTests.swift | 199 ++++++++++++++++++ 15 files changed, 996 insertions(+), 16 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Components/SettingsChoices.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsFormat.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsListBar.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsNumberField.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift create mode 100644 apple/TablePro/Views/Settings/Components/SettingsTextField.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsChoicesTests.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsFormatTests.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsTextDraftTests.swift diff --git a/apple/TablePro/Views/Components/LicenseNoticeControls.swift b/apple/TablePro/Views/Components/LicenseNoticeControls.swift index a57692e680..bfbe854ec8 100644 --- a/apple/TablePro/Views/Components/LicenseNoticeControls.swift +++ b/apple/TablePro/Views/Components/LicenseNoticeControls.swift @@ -1,8 +1,3 @@ -// -// LicenseNoticeControls.swift -// TablePro -// - import AppKit import SwiftUI import TableProHTTP @@ -50,20 +45,12 @@ struct LicenseCheckFailureLine: View { var body: some View { if let failure = LicensePresentation.checkFailureMessage(featureAccess.state.refresh) { - Label { - Text(failure) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - } - .font(.callout) + NoticeLabel(failure, severity: .warning) + .font(.subheadline) } } } -// A control a plan unlocks says what it needs and offers the way there. struct LicenseGateRow: View { let feature: ProFeature @@ -76,7 +63,7 @@ struct LicenseGateRow: View { Text(notice.title) Text(notice.message) - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) diff --git a/apple/TablePro/Views/Settings/Components/SettingsChoices.swift b/apple/TablePro/Views/Settings/Components/SettingsChoices.swift new file mode 100644 index 0000000000..798a43b822 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsChoices.swift @@ -0,0 +1,29 @@ +import SwiftUI + +enum SettingsChoices { + static func options(_ fixed: [Value], including current: Value) -> (fixed: [Value], extra: Value?) { + (fixed, fixed.contains(current) ? nil : current) + } +} + +// A pop-up whose stored value is off its list draws blank, so that value gets its own item after a divider. +struct SettingsChoiceItems: View { + private let fixed: [Value] + private let extra: Value? + private let title: (Value) -> Title + + init(_ values: [Value], including current: Value, @ViewBuilder title: @escaping (Value) -> Title) { + (fixed, extra) = SettingsChoices.options(values, including: current) + self.title = title + } + + var body: some View { + ForEach(fixed, id: \.self) { value in + title(value).tag(value) + } + if let extra { + Divider() + title(extra).tag(extra) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift new file mode 100644 index 0000000000..f99d8cbdcd --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift @@ -0,0 +1,43 @@ +import SwiftUI + +protocol SettingsDrillIdentifying { + var settingsDrillIdentifier: String? { get } +} + +struct SettingsDrillRow: View { + private let route: Route + private let title: Text + private let value: String? + private let identifier: String? + + init(route: Route, title: LocalizedStringKey, value: String? = nil, identifier: String? = nil) { + self.init(route: route, titleText: Text(title), value: value, identifier: identifier) + } + + @_disfavoredOverload + init(route: Route, title: Title, value: String? = nil, identifier: String? = nil) { + self.init(route: route, titleText: Text(title), value: value, identifier: identifier) + } + + private init(route: Route, titleText: Text, value: String?, identifier: String?) { + self.route = route + self.title = titleText + self.value = value + // Route stays any Hashable for NavigationLink, so the page id comes from a route that adopts the protocol. + self.identifier = identifier ?? (route as? any SettingsDrillIdentifying)?.settingsDrillIdentifier + } + + var body: some View { + NavigationLink(value: route) { + LabeledContent { + if let value { + Text(value) + .foregroundStyle(.secondary) + } + } label: { + title + } + } + .accessibilityIdentifier(identifier ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFormat.swift b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift new file mode 100644 index 0000000000..48369c424d --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFormat.swift @@ -0,0 +1,38 @@ +import Foundation + +enum SettingsFormat { + static var ungrouped: IntegerFormatStyle { .number.grouping(.never) } + + static func duration(seconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + Duration.seconds(seconds).formatted( + Duration.UnitsFormatStyle(allowedUnits: [.hours, .minutes, .seconds], width: .wide).locale(locale) + ) + } + + static func count(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(.number.locale(locale)) + } + + // Ports and identifiers: "23508", never "23,508" or "23.508". + static func identifier(_ value: Int, locale: Locale = .autoupdatingCurrent) -> String { + value.formatted(ungrouped.locale(locale)) + } + + // Whole years read as "1 year" rather than "365 days". + static func days(_ days: Int, locale: Locale = .autoupdatingCurrent) -> String { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .full + var calendar = Calendar.autoupdatingCurrent + calendar.locale = locale + formatter.calendar = calendar + let components: DateComponents + if days != 0, days.isMultiple(of: 365) { + formatter.allowedUnits = [.year] + components = DateComponents(year: days / 365) + } else { + formatter.allowedUnits = [.day] + components = DateComponents(day: days) + } + return formatter.string(from: components) ?? count(days, locale: locale) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift new file mode 100644 index 0000000000..9fe9a42a6d --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift @@ -0,0 +1,30 @@ +import SwiftUI + +// Not a grouped Form: a List inside one does not scroll. +struct SettingsFullPageList: View { + private let content: Content + private let emptyState: EmptyState + private let bar: Bar + + init( + @ViewBuilder content: () -> Content, + @ViewBuilder emptyState: () -> EmptyState = { EmptyView() }, + @ViewBuilder bar: () -> Bar = { EmptyView() } + ) { + self.content = content() + self.emptyState = emptyState() + self.bar = bar() + } + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + content + .listStyle(.bordered(alternatesRowBackgrounds: false)) + .frame(maxHeight: .infinity) + .overlay { emptyState } + + bar + } + .padding(20) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift b/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift new file mode 100644 index 0000000000..60477fdced --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsHelpRow.swift @@ -0,0 +1,22 @@ +import SwiftUI + +struct SettingsHelpRow: View { + private let text: Text + + init(_ text: LocalizedStringKey) { + self.text = Text(text) + } + + @_disfavoredOverload + init(_ text: S) { + self.text = Text(text) + } + + var body: some View { + text + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsListBar.swift b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift new file mode 100644 index 0000000000..34ad28567a --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift @@ -0,0 +1,97 @@ +import SwiftUI + +struct SettingsListBar: View { + private let addRemove: AddRemoveControlGroup? + private let actionsLabel: String + private let actionsIdentifier: String? + private let actions: Actions + private let leading: Leading + private let trailing: Trailing + + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + onAdd: @escaping () -> Void, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + addRemove = AddRemoveControlGroup( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: onAdd, + onRemove: onRemove + ) + self.actionsLabel = actionsLabel + self.actionsIdentifier = actionsIdentifier + self.actions = actions() + self.leading = leading() + self.trailing = trailing() + } + + init( + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + addRemove = nil + self.actionsLabel = actionsLabel + self.actionsIdentifier = actionsIdentifier + self.actions = actions() + self.leading = leading() + self.trailing = trailing() + } + + var body: some View { + HStack(spacing: 8) { + if let addRemove { + addRemove + } + + if Actions.self != EmptyView.self { + actionsMenu + } + + leading + + Spacer(minLength: 0) + + trailing + } + } + + // A label inside an icon-only Menu's label closure leaves VoiceOver reading "More"; .contain plus a label on the menu names it. + private var actionsMenu: some View { + Menu { + actions + } label: { + Label(actionsLabel, systemImage: "ellipsis.circle") + .labelStyle(.iconOnly) + } + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.hidden) + .fixedSize() + .help(actionsLabel) + .accessibilityElement(children: .contain) + .accessibilityLabel(actionsLabel) + .accessibilityIdentifier(actionsIdentifier ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift new file mode 100644 index 0000000000..5fa38897c4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsNumberField.swift @@ -0,0 +1,161 @@ +import SwiftUI + +enum SettingsInvalidEntry: Equatable, Sendable { + case clamp + case reject(String) +} + +enum SettingsIntegerInput { + // Foundation's integer parsing reads "1,000" as 1 and "1e3" as 1000, so only a sign and decimal digits pass. + static func parse(_ text: String) -> Int? { + var digits = Substring(text.trimmingCharacters(in: .whitespacesAndNewlines)) + var isNegative = false + if let sign = digits.first, sign == "-" || sign == "\u{2212}" { + isNegative = true + digits = digits.dropFirst() + } + guard !digits.isEmpty else { return nil } + var magnitude = 0 + for character in digits { + guard character.unicodeScalars.count == 1, + let scalar = character.unicodeScalars.first, + scalar.properties.numericType == .decimal, + let digit = character.wholeNumberValue else { return nil } + let (shifted, shiftOverflow) = magnitude.multipliedReportingOverflow(by: 10) + let (sum, addOverflow) = shifted.addingReportingOverflow(digit) + guard !shiftOverflow, !addOverflow else { return nil } + magnitude = sum + } + return isNegative ? -magnitude : magnitude + } + + static func resolve(_ text: String, in range: ClosedRange, invalid: SettingsInvalidEntry) -> SettingsDraftResolution { + guard let number = parse(text) else { + switch invalid { + case .clamp: return .revert + case .reject(let message): return .reject(message) + } + } + if range.contains(number) { return .accept(number) } + switch invalid { + case .clamp: return .accept(min(max(number, range.lowerBound), range.upperBound)) + case .reject(let message): return .reject(message) + } + } +} + +struct SettingsNumberField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var value: Int + private let range: ClosedRange + private let step: Int? + private let unit: LocalizedStringResource? + private let width: CGFloat + private let invalid: SettingsInvalidEntry + private let identifier: String? + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + value: Binding, + range: ClosedRange, + step: Int? = nil, + unit: LocalizedStringResource? = nil, + width: CGFloat = 64, + invalid: SettingsInvalidEntry = .clamp, + identifier: String? = nil + ) { + self.title = title + self.subtitle = subtitle + _value = value + self.range = range + self.step = step + self.unit = unit + self.width = width + self.invalid = invalid + self.identifier = identifier + _draft = State(initialValue: SettingsTextDraft(SettingsFormat.identifier(value.wrappedValue))) + } + + var body: some View { + LabeledContent { + HStack(alignment: .firstTextBaseline, spacing: 6) { + TextField(text: $draft.text, prompt: nil) { Text(title) } + .labelsHidden() + .textFieldStyle(.roundedBorder) + .multilineTextAlignment(.trailing) + .frame(width: width) + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .accessibilityIdentifier(identifier ?? "") + + if let step { + Stepper(value: stepperValue, in: range, step: step) { Text(title) } + .labelsHidden() + .accessibilityValue(Text(verbatim: spokenValue)) + .accessibilityIdentifier(identifier.map { "\($0)-stepper" } ?? "") + } + + if let unit { + Text(unit) + .foregroundStyle(.secondary) + } + } + } label: { + Text(title) + if let error = draft.error { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: draft.text) { _ in + draft.clearError(ifResolvedBy: resolve) + } + .onChange(of: value) { newValue in + draft.resync(to: SettingsFormat.identifier(newValue)) + } + .onAppear { + draft.resync(to: SettingsFormat.identifier(value)) + } + .onDisappear(perform: commit) + } + + private var spokenValue: String { + let number = SettingsFormat.identifier(value) + guard let unit else { return number } + return "\(number) \(String(localized: unit))" + } + + private var stepperValue: Binding { + Binding( + get: { value }, + set: { stepped in + let clamped = min(max(stepped, range.lowerBound), range.upperBound) + if clamped != value { value = clamped } + draft.settle(to: SettingsFormat.identifier(value)) + } + ) + } + + private func resolve(_ text: String) -> SettingsDraftResolution { + SettingsIntegerInput.resolve(text, in: range, invalid: invalid) + } + + private func commit() { + if let committed = draft.commit(to: value, resolve: resolve) { + value = committed + } + if draft.error == nil { + draft.settle(to: SettingsFormat.identifier(value)) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift b/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift new file mode 100644 index 0000000000..00e0e48b85 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsRecordRow.swift @@ -0,0 +1,137 @@ +import SwiftUI + +struct SettingsRecordRemoval { + let menuTitle: String + let actionName: String + let action: () -> Void + + static func remove(_ action: @escaping () -> Void) -> SettingsRecordRemoval { + SettingsRecordRemoval(menuTitle: String(localized: "Remove…"), actionName: String(localized: "Remove"), action: action) + } + + static func delete(_ action: @escaping () -> Void) -> SettingsRecordRemoval { + SettingsRecordRemoval(menuTitle: String(localized: "Delete…"), actionName: String(localized: "Delete"), action: action) + } +} + +struct SettingsRecordRow: View { + private struct EditActions { + let onEdit: () -> Void + let onDuplicate: (() -> Void)? + let removal: SettingsRecordRemoval? + let identifier: String? + } + + private let title: String + private let subtitle: String? + private let value: String? + private let trailing: Trailing + private var editActions: EditActions? + + init( + title: String, + subtitle: String? = nil, + value: String? = nil, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.title = title + self.subtitle = subtitle + self.value = value + self.trailing = trailing() + } + + func infoButton( + onEdit: @escaping () -> Void, + onDuplicate: (() -> Void)? = nil, + removal: SettingsRecordRemoval? = nil, + identifier: String? = nil + ) -> SettingsRecordRow { + var row = self + row.editActions = EditActions(onEdit: onEdit, onDuplicate: onDuplicate, removal: removal, identifier: identifier) + return row + } + + var body: some View { + HStack(spacing: 10) { + VStack(alignment: .leading, spacing: 1) { + Text(verbatim: title) + .lineLimit(1) + if let subtitle { + Text(verbatim: subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + .accessibilityElement(children: .combine) + .accessibilityActions { + if let editActions { + Button(String(localized: "Edit"), action: editActions.onEdit) + otherActions(editActions) + } + } + + Spacer(minLength: 8) + + if let value { + Text(verbatim: value) + .foregroundStyle(.secondary) + .monospacedDigit() + } + + trailing + + if let editActions { + Button(action: editActions.onEdit) { + Image(systemName: "info.circle") + .frame(width: 20, height: 20, alignment: .trailing) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .foregroundStyle(.secondary) + .help(String(localized: "Edit")) + .accessibilityLabel(String(format: String(localized: "Edit %@"), title)) + .accessibilityIdentifier(editActions.identifier ?? "") + .accessibilityActions { + otherActions(editActions) + } + } + } + .contentShape(Rectangle()) + .modifier(EditMenu(actions: editActions)) + .accessibilityElement(children: .contain) + } + + // An empty inner context menu would shadow one the caller attaches to the row. + private struct EditMenu: ViewModifier { + let actions: EditActions? + + func body(content: Content) -> some View { + if let actions { + content.contextMenu { + Button(String(localized: "Edit…"), action: actions.onEdit) + if let onDuplicate = actions.onDuplicate { + Button(String(localized: "Duplicate"), action: onDuplicate) + } + if let removal = actions.removal { + Divider() + Button(removal.menuTitle, role: .destructive, action: removal.action) + } + } + } else { + content + } + } + } + + @ViewBuilder + private func otherActions(_ actions: EditActions) -> some View { + if let onDuplicate = actions.onDuplicate { + Button(String(localized: "Duplicate"), action: onDuplicate) + } + if let removal = actions.removal { + Button(removal.actionName, action: removal.action) + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift b/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift new file mode 100644 index 0000000000..ed619daf1b --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsSectionActions.swift @@ -0,0 +1,16 @@ +import SwiftUI + +struct SettingsSectionActions: View { + private let content: Content + + init(@ViewBuilder content: () -> Content) { + self.content = content() + } + + var body: some View { + HStack(spacing: 8) { + Spacer(minLength: 0) + content + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift new file mode 100644 index 0000000000..ecdf479883 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextDraft.swift @@ -0,0 +1,68 @@ +import Foundation + +enum SettingsDraftResolution: Equatable { + case accept(Value) + case revert + case reject(String) +} + +// Storage sees a value only through commit: typing never writes, and an untouched draft never overwrites a remote change. +struct SettingsTextDraft: Equatable, Sendable { + var text: String + private(set) var seed: String + private(set) var error: String? + + init(_ seed: String) { + text = seed + self.seed = seed + } + + var isEdited: Bool { text != seed } + + mutating func revert() { + text = seed + error = nil + } + + mutating func resync(to value: String) { + if text == seed { + text = value + error = nil + } + seed = value + } + + mutating func settle(to value: String) { + text = value + seed = value + error = nil + } + + mutating func commit( + to current: Value, + resolve: (String) -> SettingsDraftResolution + ) -> Value? { + guard isEdited else { + error = nil + return nil + } + switch resolve(text) { + case .accept(let value): + error = nil + return value == current ? nil : value + case .revert: + revert() + return nil + case .reject(let message): + error = message + return nil + } + } + + mutating func clearError(ifResolvedBy resolve: (String) -> SettingsDraftResolution) { + guard error != nil else { return } + if case .accept = resolve(text) { + error = nil + } + } +} diff --git a/apple/TablePro/Views/Settings/Components/SettingsTextField.swift b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift new file mode 100644 index 0000000000..fd813d4ac4 --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/SettingsTextField.swift @@ -0,0 +1,65 @@ +import SwiftUI + +struct SettingsTextField: View { + private let title: LocalizedStringKey + private let subtitle: LocalizedStringKey? + @Binding private var text: String + private let prompt: Text? + private let validate: (String) -> String? + private let normalize: (String) -> String + + @State private var draft: SettingsTextDraft + @FocusState private var isFocused: Bool + + init( + _ title: LocalizedStringKey, + subtitle: LocalizedStringKey? = nil, + text: Binding, + prompt: Text? = nil, + validate: @escaping (String) -> String? = { _ in nil }, + normalize: @escaping (String) -> String = { $0 } + ) { + self.title = title + self.subtitle = subtitle + _text = text + self.prompt = prompt + self.validate = validate + self.normalize = normalize + _draft = State(initialValue: SettingsTextDraft(text.wrappedValue)) + } + + var body: some View { + TextField(text: $draft.text, prompt: prompt) { + Text(title) + if let error = validate(draft.text) { + NoticeLabel(error, severity: .error) + } else if let subtitle { + Text(subtitle) + } + } + .focused($isFocused) + .onSubmit(commit) + .onExitCommand { draft.revert() } + .onChange(of: isFocused) { focused in + if !focused { commit() } + } + .onChange(of: text) { newValue in + draft.resync(to: newValue) + } + .onAppear { + draft.resync(to: text) + } + .onDisappear(perform: commit) + } + + private func resolve(_ candidate: String) -> SettingsDraftResolution { + validate(candidate) == nil ? .accept(normalize(candidate)) : .revert + } + + private func commit() { + if let committed = draft.commit(to: text, resolve: resolve) { + text = committed + } + draft.settle(to: text) + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsChoicesTests.swift b/apple/TableProTests/Views/Settings/SettingsChoicesTests.swift new file mode 100644 index 0000000000..0dc1994a87 --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsChoicesTests.swift @@ -0,0 +1,42 @@ +@testable import TablePro +import Testing + +struct SettingsChoicesTests { + @Test("A stored value on the list adds no extra item") + func onListValueAddsNothing() { + let options = SettingsChoices.options([5, 10, 30, 60], including: 30) + #expect(options.fixed == [5, 10, 30, 60]) + #expect(options.extra == nil) + } + + @Test("An off-list value becomes the extra item and the fixed list stays as it was") + func offListValueBecomesExtra() { + let options = SettingsChoices.options([5, 10, 30, 60], including: 90) + #expect(options.fixed == [5, 10, 30, 60]) + #expect(options.extra == 90) + } + + @Test("A value is never listed twice") + func neverDuplicates() { + for current in [5, 10, 45] { + let options = SettingsChoices.options([5, 10], including: current) + let shown = options.fixed + [options.extra].compactMap { $0 } + #expect(Set(shown).count == shown.count) + #expect(shown.contains(current)) + } + } + + @Test("A font family that is no longer installed is kept as the extra item") + func stringValues() { + let options = SettingsChoices.options(["Menlo", "SF Mono"], including: "Fira Code") + #expect(options.fixed == ["Menlo", "SF Mono"]) + #expect(options.extra == "Fira Code") + } + + @Test("An optional selection such as No limit works the same way") + func optionalValues() { + let fixed: [Int?] = [nil, 100, 1000] + #expect(SettingsChoices.options(fixed, including: nil).extra == nil) + #expect(SettingsChoices.options(fixed, including: 250).extra == .some(250)) + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsFormatTests.swift b/apple/TableProTests/Views/Settings/SettingsFormatTests.swift new file mode 100644 index 0000000000..33e0823507 --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsFormatTests.swift @@ -0,0 +1,46 @@ +import Foundation +@testable import TablePro +import Testing + +struct SettingsFormatTests { + private static let english = Locale(identifier: "en_US") + + @Test( + "Durations use whole words", + arguments: [ + (1, "1 second"), + (30, "30 seconds"), + (60, "1 minute"), + (90, "1 minute, 30 seconds"), + (300, "5 minutes"), + (3600, "1 hour"), + ] + ) + func durations(seconds: Int, expected: String) { + #expect(SettingsFormat.duration(seconds: seconds, locale: Self.english) == expected) + } + + @Test("Ports stay ungrouped where counts are grouped") + func portsAreUngrouped() { + let vietnam = Locale(identifier: "en_VN") + #expect(SettingsFormat.identifier(23508, locale: vietnam) == "23508") + #expect(SettingsFormat.identifier(23508, locale: Self.english) == "23508") + #expect(SettingsFormat.count(23508, locale: vietnam) == "23.508") + #expect(SettingsFormat.count(1000, locale: Self.english) == "1,000") + } + + @Test( + "Day spans read as days, and whole years as years", + arguments: [ + (1, "1 day"), + (7, "7 days"), + (30, "30 days"), + (90, "90 days"), + (365, "1 year"), + (730, "2 years"), + ] + ) + func daySpans(days: Int, expected: String) { + #expect(SettingsFormat.days(days, locale: Self.english) == expected) + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsTextDraftTests.swift b/apple/TableProTests/Views/Settings/SettingsTextDraftTests.swift new file mode 100644 index 0000000000..72d204e7c3 --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsTextDraftTests.swift @@ -0,0 +1,199 @@ +import Foundation +@testable import TablePro +import Testing + +struct SettingsTextDraftTests { + // Drives a draft the way SettingsNumberField does: a write only on commit, then a read-back. + private struct NumberFieldHarness { + var stored: Int + var draft: SettingsTextDraft + var writes: [Int] = [] + let range: ClosedRange + let invalid: SettingsInvalidEntry + + init(stored: Int, range: ClosedRange, invalid: SettingsInvalidEntry) { + self.stored = stored + self.range = range + self.invalid = invalid + draft = SettingsTextDraft(SettingsFormat.identifier(stored)) + } + + mutating func type(_ text: String) { + draft.text = text + draft.clearError(ifResolvedBy: resolve) + } + + mutating func commit() { + if let committed = draft.commit(to: stored, resolve: resolve) { + stored = committed + writes.append(committed) + } + if draft.error == nil { + draft.settle(to: SettingsFormat.identifier(stored)) + } + } + + mutating func remoteChange(_ value: Int) { + stored = value + draft.resync(to: SettingsFormat.identifier(value)) + } + + private func resolve(_ text: String) -> SettingsDraftResolution { + SettingsIntegerInput.resolve(text, in: range, invalid: invalid) + } + } + + @Test("Typing writes nothing, and Return then focus loss writes the final value once") + func commitsOnceWithTheFinalValue() { + var field = NumberFieldHarness(stored: 23508, range: 1024...65535, invalid: .reject("Choose a port from 1024 to 65535.")) + for text in ["2", "23", "235", "2350", "23509"] { + field.type(text) + } + #expect(field.writes.isEmpty) + + field.commit() + field.commit() + field.commit() + + #expect(field.writes == [23509]) + #expect(field.draft.text == "23509") + #expect(!field.draft.isEdited) + } + + @Test("An untouched draft follows a remote change and never writes over it") + func untouchedDraftNeverOverwritesRemoteChange() { + var field = NumberFieldHarness(stored: 500, range: 1...10000, invalid: .clamp) + field.remoteChange(800) + field.commit() + + #expect(field.writes.isEmpty) + #expect(field.stored == 800) + #expect(field.draft.text == "800") + } + + @Test("A commit before the remote change reaches the draft writes nothing") + func untouchedCommitBeforeResyncWritesNothing() { + var draft = SettingsTextDraft("NULL") + let committed = draft.commit(to: "(null)") { .accept($0) } + #expect(committed == nil) + } + + @Test("An edited draft keeps the user's text when a remote change arrives") + func editedDraftSurvivesRemoteChange() { + var draft = SettingsTextDraft("NULL") + draft.text = "nil" + draft.resync(to: "(null)") + + #expect(draft.text == "nil") + #expect(draft.seed == "(null)") + let committed = draft.commit(to: "(null)") { .accept($0) } + #expect(committed == "nil") + } + + @Test("Escape restores the stored text and nothing is written") + func escapeReverts() { + var field = NumberFieldHarness(stored: 30, range: 1...300, invalid: .clamp) + field.type("45") + field.draft.revert() + field.commit() + + #expect(field.draft.text == "30") + #expect(field.writes.isEmpty) + } + + @Test("Reject keeps the draft and shows the message, and a valid edit clears it") + func rejectKeepsDraftAndError() { + let message = "Choose a port from 1024 to 65535." + var field = NumberFieldHarness(stored: 23508, range: 1024...65535, invalid: .reject(message)) + field.type("80") + field.commit() + + #expect(field.writes.isEmpty) + #expect(field.draft.text == "80") + #expect(field.draft.error == message) + + field.type("8080") + #expect(field.draft.error == nil) + field.commit() + #expect(field.writes == [8080]) + } + + @Test("Escape clears a rejection") + func escapeClearsRejection() { + var field = NumberFieldHarness(stored: 23508, range: 1024...65535, invalid: .reject("x")) + field.type("abc") + field.commit() + #expect(field.draft.error == "x") + + field.draft.revert() + #expect(field.draft.error == nil) + #expect(field.draft.text == "23508") + } + + @Test("Clamp writes the nearest bound once and shows it") + func clampWritesBound() { + var field = NumberFieldHarness(stored: 500, range: 1...10000, invalid: .clamp) + field.type("50000") + field.commit() + + #expect(field.writes == [10000]) + #expect(field.draft.text == "10000") + } + + @Test("Clamp reverts text that is not a number") + func clampRevertsUnparsableText() { + var field = NumberFieldHarness(stored: 500, range: 1...10000, invalid: .clamp) + field.type("5x") + field.commit() + + #expect(field.writes.isEmpty) + #expect(field.draft.text == "500") + } + + @Test("A draft that parses to the stored value writes nothing and shows it plainly") + func equalValueWritesNothing() { + var field = NumberFieldHarness(stored: 500, range: 1...10000, invalid: .clamp) + field.type(" 0500 ") + field.commit() + + #expect(field.writes.isEmpty) + #expect(field.draft.text == "500") + } + + @Test( + "Integer parsing takes only a sign and digits", + arguments: [ + ("23509", 23509 as Int?), + (" 80 ", 80), + ("-5", -5), + ("\u{0664}\u{0662}", 42), + ("1,000", nil), + ("1.000", nil), + ("1e3", nil), + ("80abc", nil), + ("", nil), + ("-", nil), + ("99999999999999999999999", nil), + ] + ) + func parsesStrictly(text: String, expected: Int?) { + #expect(SettingsIntegerInput.parse(text) == expected) + } + + @Test("The text field commit normalizes and reverts invalid text") + func textFieldResolution() { + var draft = SettingsTextDraft("NULL") + let resolve: (String) -> SettingsDraftResolution = { text in + text.trimmingCharacters(in: .whitespaces).isEmpty ? .revert : .accept(text.trimmingCharacters(in: .whitespaces)) + } + + draft.text = " " + let blank = draft.commit(to: "NULL", resolve: resolve) + #expect(blank == nil) + #expect(draft.text == "NULL") + + draft.text = " nil " + let trimmed = draft.commit(to: "NULL", resolve: resolve) + #expect(trimmed == "nil") + } +} From 3f3ea16c33372316f8431309fe5624b590d2475d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:06 +0700 Subject: [PATCH 17/48] feat(settings): typed navigation model with history, page routes and search index --- .../Views/Settings/SettingsNavigation.swift | 480 ++++++++++++++++-- .../Settings/SettingsNavigationModel.swift | 213 ++++++++ .../Settings/SettingsPane+URLIdentifier.swift | 29 +- .../Views/Settings/SettingsRoute.swift | 170 +++++++ .../Views/Settings/SettingsView.swift | 23 +- .../Settings/SettingsWindowController.swift | 13 +- .../Settings/SettingsWindowToolbar.swift | 4 +- .../SettingsNavigationModelTests.swift | 450 ++++++++++++++++ .../Settings/SettingsNavigationTests.swift | 152 +++++- .../SettingsPaneURLIdentifierTests.swift | 91 +++- .../Settings/SettingsWindowTitleTests.swift | 2 +- 11 files changed, 1530 insertions(+), 97 deletions(-) create mode 100644 apple/TablePro/Views/Settings/SettingsNavigationModel.swift create mode 100644 apple/TablePro/Views/Settings/SettingsRoute.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsNavigationModelTests.swift diff --git a/apple/TablePro/Views/Settings/SettingsNavigation.swift b/apple/TablePro/Views/Settings/SettingsNavigation.swift index 3bb7450f79..617c5c9100 100644 --- a/apple/TablePro/Views/Settings/SettingsNavigation.swift +++ b/apple/TablePro/Views/Settings/SettingsNavigation.swift @@ -1,17 +1,10 @@ -// -// SettingsNavigation.swift -// TablePro -// - import Foundation -// Pure model of the Settings window's sidebar: the ordered sections, the rows in each, and the -// search index. No AppKit, SwiftUI or storage, so it unit-tests without a host. The window shell -// and the deep-link layer read this; they never hardcode the order themselves. enum SettingsSectionID: String, CaseIterable, Sendable { case app + case workspace case integrations - case accountData + case account } struct SettingsSection: Equatable, Sendable { @@ -19,54 +12,467 @@ struct SettingsSection: Equatable, Sendable { let panes: [SettingsPane] } +enum SettingsSidebarRow: Hashable, Sendable { + case pane(SettingsPane) + case page(title: String, location: SettingsLocation) + case spacer(before: SettingsSectionID) +} + +struct SettingsSearchResult: Hashable, Sendable { + struct Page: Hashable, Sendable { + let title: String + let location: SettingsLocation + } + + let pane: SettingsPane + let pages: [Page] +} + +// A root location matches its pane; any other location lists as a page row under it. +struct SettingsSearchEntry: Hashable, Sendable { + let title: String + let keywords: [String] + let location: SettingsLocation + + init(title: String, keywords: [String] = [], location: SettingsLocation) { + self.title = title + self.keywords = keywords + self.location = location + } +} + enum SettingsNavigation { static let sections: [SettingsSection] = [ - SettingsSection(id: .app, panes: [.general, .sidebar, .connections, .appearance, .editor, .data, .keyboard, .notifications]), + SettingsSection(id: .app, panes: [.general, .appearance, .notifications, .keyboard]), + SettingsSection(id: .workspace, panes: [.connections, .profiles, .sidebar, .editor, .data]), SettingsSection(id: .integrations, panes: [.ai, .mcp, .plugins]), - SettingsSection(id: .accountData, panes: [.profiles, .sync, .account]), + SettingsSection(id: .account, panes: [.sync, .account]), ] - // The sidebar order, flattened. A permutation of SettingsPane.allCases: every pane once. static let orderedPanes: [SettingsPane] = sections.flatMap(\.panes) static let defaultPane: SettingsPane = .general - // The deep-link and last-used-pane vocabulary stays SettingsPane.urlIdentifier / rawValue. static func pane(forURLIdentifier identifier: String) -> SettingsPane? { SettingsPane(urlIdentifier: identifier) } - // Panes whose title or keywords contain every whitespace-split term of the query, in sidebar - // order. An empty query returns the full order. - static func panes(matching query: String) -> [SettingsPane] { - let terms = query.lowercased().split(whereSeparator: { $0.isWhitespace }).map(String.init) - guard !terms.isEmpty else { return orderedPanes } - return orderedPanes.filter { pane in - let haystack = ([pane.title] + pane.searchKeywords).joined(separator: " ").lowercased() - return terms.allSatisfy(haystack.contains) + // Dynamic entries are names only the running app knows: plugin names, AI provider names. + static func results(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsSearchResult] { + index(adding: dynamicEntries).results(matching: query) + } + + static func panes(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsPane] { + results(matching: query, adding: dynamicEntries).map(\.pane) + } + + static func rows(matching query: String, adding dynamicEntries: [SettingsSearchEntry] = []) -> [SettingsSidebarRow] { + guard SettingsSearchIndex.isFiltering(query) else { + return sections.enumerated().flatMap { offset, section -> [SettingsSidebarRow] in + let spacer: [SettingsSidebarRow] = offset == 0 ? [] : [.spacer(before: section.id)] + return spacer + section.panes.map { .pane($0) } + } + } + return results(matching: query, adding: dynamicEntries).flatMap { result -> [SettingsSidebarRow] in + [.pane(result.pane)] + result.pages.map { .page(title: $0.title, location: $0.location) } + } + } + + static var standardEntries: [SettingsSearchEntry] { + let panes = SettingsPane.allCases.map { + SettingsSearchEntry(title: $0.title, keywords: $0.searchKeywords, location: .root($0)) + } + let pages = SettingsPage.allCases.map { + SettingsSearchEntry(title: $0.title, keywords: $0.searchKeywords, location: SettingsLocation(page: $0)) + } + return panes + pages + } + + private static let standardIndex = SettingsSearchIndex(entries: standardEntries) + + private static func index(adding dynamicEntries: [SettingsSearchEntry]) -> SettingsSearchIndex { + dynamicEntries.isEmpty ? standardIndex : standardIndex.adding(dynamicEntries) + } +} + +// Each term must start a word of one entry, so "date" never finds "Update". +struct SettingsSearchIndex: Sendable { + private struct Prepared: Sendable { + let entry: SettingsSearchEntry + let wordStarts: [String] + + func matches(_ terms: [String]) -> Bool { + terms.allSatisfy { term in wordStarts.contains { $0.hasPrefix(term) } } + } + } + + private let locale: Locale + private let prepared: [Prepared] + + init(entries: [SettingsSearchEntry], locale: Locale = .current) { + self.locale = locale + self.prepared = entries.map { Self.prepare($0, locale: locale) } + } + + private init(locale: Locale, prepared: [Prepared]) { + self.locale = locale + self.prepared = prepared + } + + func adding(_ entries: [SettingsSearchEntry]) -> SettingsSearchIndex { + SettingsSearchIndex(locale: locale, prepared: prepared + entries.map { Self.prepare($0, locale: locale) }) + } + + func results(matching query: String) -> [SettingsSearchResult] { + let terms = Self.terms(in: query, locale: locale) + guard !terms.isEmpty else { + return SettingsNavigation.orderedPanes.map { SettingsSearchResult(pane: $0, pages: []) } + } + var matchedPanes: Set = [] + var pages: [SettingsPane: [SettingsSearchResult.Page]] = [:] + for item in prepared where item.matches(terms) { + let location = item.entry.location + if location.isRoot { + matchedPanes.insert(location.pane) + } else if pages[location.pane]?.contains(where: { $0.location == location }) != true { + pages[location.pane, default: []].append(.init(title: item.entry.title, location: location)) + } + } + return SettingsNavigation.orderedPanes.compactMap { pane in + let panePages = pages[pane] ?? [] + guard matchedPanes.contains(pane) || !panePages.isEmpty else { return nil } + return SettingsSearchResult(pane: pane, pages: panePages) + } + } + + static func isFiltering(_ query: String, locale: Locale = .current) -> Bool { + !terms(in: query, locale: locale).isEmpty + } + + static func terms(in query: String, locale: Locale) -> [String] { + query.split(whereSeparator: \.isWhitespace) + .map { fold(String($0).trimmingCharacters(in: .punctuationCharacters), locale: locale) } + .filter { term in term.contains { $0.isLetter || $0.isNumber } } + } + + static func fold(_ text: String, locale: Locale) -> String { + // Vietnamese đ is a letter of its own, not d with a diacritic, so folding keeps it. + text.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: locale) + .replacingOccurrences(of: "đ", with: "d") + } + + private static func prepare(_ entry: SettingsSearchEntry, locale: Locale) -> Prepared { + let texts = [entry.title] + entry.keywords + return Prepared(entry: entry, wordStarts: texts.flatMap { wordStarts(in: fold($0, locale: locale)) }) + } + + // Han text has no spaces, so each ideograph also starts a word. + private static func wordStarts(in text: String) -> [String] { + var starts: Set = [] + text.enumerateSubstrings(in: text.startIndex.. Request? { + let request = pending + pending = nil + return request + } +} + +// Every mutation goes through apply, which syncs the pane paths and then calls onLocationChange once. +@MainActor +final class SettingsNavigationModel { + private(set) var location: SettingsLocation + private var backStack: [SettingsLocation] = [] + private var forwardStack: [SettingsLocation] = [] + private var panePaths: [SettingsPane: SettingsPanePath] = [:] + + let pluginReveal = SettingsPluginReveal() + + var isRouteAvailable: (SettingsRoute) -> Bool + var titleResolver: (SettingsRoute) -> String? + var onLocationChange: ((SettingsLocation) -> Void)? + var onUserPick: ((SettingsPane) -> Void)? + + init( + initial: SettingsLocation = .root(SettingsNavigation.defaultPane), + isRouteAvailable: @escaping (SettingsRoute) -> Bool = { _ in true }, + titleResolver: @escaping (SettingsRoute) -> String? = { _ in nil } + ) { + self.location = initial + self.isRouteAvailable = isRouteAvailable + self.titleResolver = titleResolver + } + + var canGoBack: Bool { backStack.contains { isAvailable($0) } } + var canGoForward: Bool { forwardStack.contains { isAvailable($0) } } + + var title: String { title(for: location) } + + func title(for location: SettingsLocation) -> String { + guard let route = location.routes.last else { return location.pane.title } + return title(for: route) + } + + func title(for route: SettingsRoute) -> String { + titleResolver(route) ?? route.defaultTitle + } + + func isAvailable(_ location: SettingsLocation) -> Bool { + location.routes.allSatisfy { isRouteAvailable($0) } + } + + func path(for pane: SettingsPane) -> SettingsPanePath { + if let path = panePaths[pane] { return path } + let path = SettingsPanePath(pane: pane, routes: pane == location.pane ? location.routes : []) + panePaths[pane] = path + return path + } + + // Only a user's sidebar pick persists the pane. + func select(_ pane: SettingsPane) { + onUserPick?(pane) + let target = SettingsLocation.root(pane) + guard target != location else { return } + record(target) + } + + // The NavigationStack path binding: a pop to the previous entry counts as Back. + func setRoutes(_ routes: [SettingsRoute], for pane: SettingsPane) { + guard pane == location.pane else { return } + let target = SettingsLocation(pane: pane, routes: routes) + guard target != location else { return } + if target.routes.count < location.routes.count, backStack.last == target { + apply(target, back: Array(backStack.dropLast()), forward: forwardStack + [location]) + } else { + record(target) + } + } + + // For async completions: a no-op unless the pane is still current and the route is not already on top. + @discardableResult + func push(_ route: SettingsRoute, in pane: SettingsPane) -> Bool { + guard pane == location.pane, route.pane == pane, location.routes.last != route else { return false } + record(SettingsLocation(pane: pane, routes: location.routes + [route])) + return true + } + + // The route's subject is gone, so no history entry may lead back to it. + func removeRoute(_ route: SettingsRoute) { + var current = location + if let index = location.routes.firstIndex(of: route) { + current = SettingsLocation(pane: location.pane, routes: Array(location.routes[.. SettingsPluginReveal.Request? { + pluginReveal.consume() + } + + private func record(_ target: SettingsLocation) { + apply(target, back: backStack + [location], forward: []) + } + + // An unloaded plugin becomes a pending reveal the Extensions pane resolves after its list loads. + private func availablePrefix(of requested: SettingsLocation) -> SettingsLocation { + guard let index = requested.routes.firstIndex(where: { !isRouteAvailable($0) }) else { return requested } + if case .plugin(let id) = requested.routes[index] { + requestPluginReveal(id) + } + return SettingsLocation(pane: requested.pane, routes: Array(requested.routes[.. [SettingsLocation] { + var result: [SettingsLocation] = [] + for entry in entries where entry != result.last { + result.append(entry) + } + while result.last == next { + result.removeLast() + } + return result + } +} diff --git a/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift b/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift index c89fc9f31c..5ab16c0e15 100644 --- a/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift +++ b/apple/TablePro/Views/Settings/SettingsPane+URLIdentifier.swift @@ -1,13 +1,7 @@ -// -// SettingsPane+URLIdentifier.swift -// TablePro -// - import Foundation -/// The ids in `tablepro://settings/` links. They are public and documented, so they never -/// follow a pane's title or rawValue. -internal extension SettingsPane { +// Published ids of tablepro://settings/ links, so they never follow a title or rawValue. +extension SettingsPane { var urlIdentifier: String { switch self { case .general: "general" @@ -28,22 +22,7 @@ internal extension SettingsPane { } init?(urlIdentifier: String) { - switch urlIdentifier { - case "general": self = .general - case "sidebar": self = .sidebar - case "connections": self = .connections - case "appearance": self = .appearance - case "editor": self = .editor - case "data": self = .data - case "keyboard": self = .keyboard - case "profiles": self = .profiles - case "notifications": self = .notifications - case "ai": self = .ai - case "mcp": self = .mcp - case "plugins": self = .plugins - case "sync": self = .sync - case "license": self = .account - default: return nil - } + guard let pane = Self.allCases.first(where: { $0.urlIdentifier == urlIdentifier }) else { return nil } + self = pane } } diff --git a/apple/TablePro/Views/Settings/SettingsRoute.swift b/apple/TablePro/Views/Settings/SettingsRoute.swift new file mode 100644 index 0000000000..74a663daf9 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsRoute.swift @@ -0,0 +1,170 @@ +import Foundation + +enum SettingsPage: CaseIterable, Hashable, Sendable { + case softwareUpdate + case commandLineTool + case manageThemes + case linkedFolders + case trustedLinks + case sqlFormatting + case queryHistory + case dataRewind + case slashCommands + case mcpApprovals + case mcpTokens + case accountFeatures + case accountDevices + case accountTeams + case accountOffline + + var parent: SettingsPane { + switch self { + case .softwareUpdate, .commandLineTool: .general + case .manageThemes: .appearance + case .linkedFolders, .trustedLinks: .connections + case .sqlFormatting: .editor + case .queryHistory, .dataRewind: .data + case .slashCommands: .ai + case .mcpApprovals, .mcpTokens: .mcp + case .accountFeatures, .accountDevices, .accountTeams, .accountOffline: .account + } + } + + var title: String { + switch self { + case .softwareUpdate: String(localized: "Software Update") + case .commandLineTool: String(localized: "Command Line Tool") + case .manageThemes: String(localized: "Manage Themes") + case .linkedFolders: String(localized: "Linked Folders") + case .trustedLinks: String(localized: "Trusted Links") + case .sqlFormatting: String(localized: "SQL Formatting") + case .queryHistory: String(localized: "Query History") + case .dataRewind: String(localized: "Data Rewind") + case .slashCommands: String(localized: "Slash Commands") + case .mcpApprovals: String(localized: "Approved Connections") + case .mcpTokens: String(localized: "Tokens") + case .accountFeatures: String(localized: "Features") + case .accountDevices: String(localized: "Devices") + case .accountTeams: String(localized: "Teams") + case .accountOffline: String(localized: "Offline File and License Key") + } + } + + // Published in tablepro://settings// links, so it never follows a title. + var urlIdentifier: String { + switch self { + case .softwareUpdate: "software-update" + case .commandLineTool: "command-line-tool" + case .manageThemes: "themes" + case .linkedFolders: "linked-folders" + case .trustedLinks: "trusted-links" + case .sqlFormatting: "sql-formatting" + case .queryHistory: "query-history" + case .dataRewind: "data-rewind" + case .slashCommands: "slash-commands" + case .mcpApprovals: "approvals" + case .mcpTokens: "tokens" + case .accountFeatures: "features" + case .accountDevices: "devices" + case .accountTeams: "teams" + case .accountOffline: "offline" + } + } + + var drillIdentifier: String { "settings-drill-\(urlIdentifier)" } + var pageIdentifier: String { "settings-page-\(urlIdentifier)" } + + init?(urlIdentifier: String, in pane: SettingsPane) { + guard let page = Self.pages(in: pane).first(where: { $0.urlIdentifier == urlIdentifier }) else { return nil } + self = page + } + + static func pages(in pane: SettingsPane) -> [SettingsPage] { + allCases.filter { $0.parent == pane } + } +} + +enum SettingsRoute: Hashable, Sendable { + case page(SettingsPage) + case plugin(id: String) + // A rejected bundle can carry the id of a loaded plugin, so it is told apart by its URL. + case rejectedPlugin(URL) + case aiProvider(UUID) + + var pane: SettingsPane { + switch self { + case .page(let page): page.parent + case .plugin, .rejectedPlugin: .plugins + case .aiProvider: .ai + } + } + + var page: SettingsPage? { + if case .page(let page) = self { return page } + return nil + } + + var defaultTitle: String { + switch self { + case .page(let page): page.title + case .plugin: String(localized: "Extension") + case .rejectedPlugin(let url): url.deletingPathExtension().lastPathComponent + case .aiProvider: String(localized: "AI Provider") + } + } +} + +extension SettingsRoute: SettingsDrillIdentifying { + var settingsDrillIdentifier: String? { page?.drillIdentifier } +} + +struct SettingsLocation: Hashable, Sendable { + let pane: SettingsPane + let routes: [SettingsRoute] + + // A route of another pane could never be shown under this one. + init(pane: SettingsPane, routes: [SettingsRoute] = []) { + self.pane = pane + self.routes = Array(routes.prefix { $0.pane == pane }) + } + + init(page: SettingsPage) { + self.init(pane: page.parent, routes: [.page(page)]) + } + + init(route: SettingsRoute) { + self.init(pane: route.pane, routes: [route]) + } + + static func root(_ pane: SettingsPane) -> SettingsLocation { + SettingsLocation(pane: pane) + } + + var isRoot: Bool { routes.isEmpty } + + var root: SettingsLocation { .root(pane) } + + // Never fails on a known pane, so a link to a newer page still opens Settings on an older app. + init?(urlPathSegments segments: [String]) { + guard let first = segments.first, let pane = SettingsPane(urlIdentifier: first) else { return nil } + guard segments.count > 1 else { + self.init(pane: pane) + return + } + let second = segments[1] + if pane == .plugins { + self.init(pane: pane, routes: Self.isPluginIdentifier(second) ? [.plugin(id: second)] : []) + } else if let page = SettingsPage(urlIdentifier: second, in: pane) { + self.init(page: page) + } else { + self.init(pane: pane) + } + } + + private static func isPluginIdentifier(_ value: String) -> Bool { + guard !value.isEmpty, value.utf8.count <= 255 else { return false } + return value.unicodeScalars.allSatisfy { scalar in + scalar.isASCII && (CharacterSet.alphanumerics.contains(scalar) || scalar == "." || scalar == "-" || scalar == "_") + } + } +} diff --git a/apple/TablePro/Views/Settings/SettingsView.swift b/apple/TablePro/Views/Settings/SettingsView.swift index defe8881f8..c8293ecbaa 100644 --- a/apple/TablePro/Views/Settings/SettingsView.swift +++ b/apple/TablePro/Views/Settings/SettingsView.swift @@ -1,11 +1,7 @@ -// -// SettingsView.swift -// TablePro -// - import Foundation -enum SettingsPane: String, CaseIterable { +// The rawValue is the stored last-used pane, so it never follows a title. +enum SettingsPane: String, CaseIterable, Sendable { case general, sidebar, connections, appearance, editor, data, keyboard, profiles, notifications, ai, mcp, plugins, sync, account var title: String { @@ -21,11 +17,8 @@ enum SettingsPane: String, CaseIterable { case .notifications: String(localized: "Notifications") case .ai: String(localized: "AI") case .mcp: "MCP" - // The rawValue and the URL id stay "plugins": they are the stored pane and a published link. case .plugins: String(localized: "Extensions") - case .sync: String(localized: "Sync") - /// The stored rawValue stays "account": it is the tab item identifier and the pane the - /// window restores, so renaming it would silently reset everyone's last-used pane. + case .sync: String(localized: "iCloud Sync") case .account: String(localized: "Account") } } @@ -34,17 +27,17 @@ enum SettingsPane: String, CaseIterable { switch self { case .general: "gearshape" case .sidebar: "sidebar.left" - case .connections: "cable.connector" - case .appearance: "paintbrush" - case .editor: "doc.text" + case .connections: "cylinder.split.1x2" + case .appearance: "circle.lefthalf.filled" + case .editor: "square.and.pencil" case .data: "tablecells" case .keyboard: "keyboard" case .profiles: "person.badge.key" case .notifications: "bell" case .ai: "sparkles" - case .mcp: "network" + case .mcp: "point.3.connected.trianglepath.dotted" case .plugins: "puzzlepiece.extension" - case .sync: "arrow.triangle.2.circlepath" + case .sync: "icloud" case .account: "person.crop.circle" } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index f8138c2397..8d482b0b45 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -72,14 +72,14 @@ internal final class SettingsSplitViewController: NSSplitViewController { private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") - internal let model: SettingsNavigationModel + internal let model: LegacySettingsNavigationModel internal let toolbarController: SettingsWindowToolbar private let registryClient: RegistryClient private var cancellables: Set = [] internal init(registryClient: RegistryClient = .shared) { self.registryClient = registryClient - let model = SettingsNavigationModel(initial: Self.persistedPane) + let model = LegacySettingsNavigationModel(initial: Self.persistedPane) self.model = model self.toolbarController = SettingsWindowToolbar(model: model) super.init(nibName: nil, bundle: nil) @@ -134,8 +134,9 @@ internal final class SettingsSplitViewController: NSSplitViewController { } } +// Goes away with this shell once it moves to SettingsNavigationModel. @MainActor -internal final class SettingsNavigationModel: ObservableObject { +internal final class LegacySettingsNavigationModel: ObservableObject { @Published internal var selection: SettingsPane // The detail's NavigationStack path, owned here so the window toolbar can read depth and drive Back. @Published internal var path = NavigationPath() @@ -177,7 +178,7 @@ internal final class SettingsNavigationModel: ObservableObject { } private struct SettingsSidebarView: View { - @ObservedObject fileprivate var model: SettingsNavigationModel + @ObservedObject fileprivate var model: LegacySettingsNavigationModel // Search lives here, not on the nav model, so typing re-renders only the sidebar list and never // the detail pane or the toolbar. @State private var searchText = "" @@ -223,7 +224,7 @@ private struct SettingsSidebarView: View { } private struct SettingsDetailView: View { - @ObservedObject fileprivate var model: SettingsNavigationModel + @ObservedObject fileprivate var model: LegacySettingsNavigationModel fileprivate let registryClient: RegistryClient fileprivate var body: some View { @@ -235,7 +236,7 @@ private struct SettingsDetailView: View { } private struct SettingsPaneStack: View { - @ObservedObject fileprivate var model: SettingsNavigationModel + @ObservedObject fileprivate var model: LegacySettingsNavigationModel fileprivate let pane: SettingsPane fileprivate let registryClient: RegistryClient diff --git a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift index edd716f2c5..245b523675 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift @@ -15,12 +15,12 @@ internal final class SettingsWindowToolbar: NSObject, NSToolbarDelegate { private static let backForward = NSToolbarItem.Identifier("com.TablePro.settings.backForward") private static let pageTitle = NSToolbarItem.Identifier("com.TablePro.settings.title") - private let model: SettingsNavigationModel + private let model: LegacySettingsNavigationModel private weak var backItem: NSToolbarItem? private weak var titleField: NSTextField? private var cancellable: AnyCancellable? - internal init(model: SettingsNavigationModel) { + internal init(model: LegacySettingsNavigationModel) { self.model = model super.init() cancellable = model.objectWillChange.sink { [weak self] in diff --git a/apple/TableProTests/Views/Settings/SettingsNavigationModelTests.swift b/apple/TableProTests/Views/Settings/SettingsNavigationModelTests.swift new file mode 100644 index 0000000000..d4d29924df --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsNavigationModelTests.swift @@ -0,0 +1,450 @@ +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct SettingsNavigationModelTests { + @MainActor + private final class Recorder { + var locations: [SettingsLocation] = [] + var picks: [SettingsPane] = [] + var unavailable: Set = [] + + func attach(to model: SettingsNavigationModel) { + model.onLocationChange = { [unowned self] in locations.append($0) } + model.onUserPick = { [unowned self] in picks.append($0) } + model.isRouteAvailable = { [unowned self] in !unavailable.contains($0) } + } + } + + private let themes = SettingsLocation(page: .manageThemes) + private let sqlFormatting = SettingsLocation(page: .sqlFormatting) + private let driver = SettingsRoute.plugin(id: "com.example.driver") + + @Test("A sidebar pick is a history entry that Back leaves and Forward returns to") + func paneSwitchRecordsHistory() { + let model = SettingsNavigationModel(initial: .root(.general)) + #expect(!model.canGoBack) + #expect(!model.canGoForward) + + model.select(.editor) + #expect(model.location == .root(.editor)) + #expect(model.canGoBack) + #expect(!model.canGoForward) + + model.goBack() + #expect(model.location == .root(.general)) + #expect(!model.canGoBack) + #expect(model.canGoForward) + + model.goForward() + #expect(model.location == .root(.editor)) + #expect(model.canGoBack) + #expect(!model.canGoForward) + } + + @Test("Picking the current pane at its root changes nothing") + func reselectingTheRootChangesNothing() { + let model = SettingsNavigationModel(initial: .root(.general)) + let recorder = Recorder() + recorder.attach(to: model) + + model.select(.general) + #expect(recorder.locations.isEmpty) + #expect(!model.canGoBack) + } + + @Test("Picking the current pane while on one of its pages pops to the root as a new entry") + func reselectingWhileDrilledPopsToRoot() { + let model = SettingsNavigationModel(initial: .root(.appearance)) + #expect(model.push(.page(.manageThemes), in: .appearance)) + #expect(model.location == themes) + + model.select(.appearance) + #expect(model.location == .root(.appearance)) + #expect(model.canGoBack) + + model.goBack() + #expect(model.location == themes) + } + + @Test("A push is a history entry and the title follows the top route") + func pushRecordsHistoryAndTitles() { + let model = SettingsNavigationModel(initial: .root(.appearance)) + #expect(model.title == SettingsPane.appearance.title) + + model.push(.page(.manageThemes), in: .appearance) + #expect(model.title == SettingsPage.manageThemes.title) + #expect(model.canGoBack) + + model.goBack() + #expect(model.title == SettingsPane.appearance.title) + #expect(model.canGoForward) + } + + @Test("A push from another pane, of another pane's route or of the route already on top does nothing") + func pushIsGuardedByTheCurrentPane() { + let model = SettingsNavigationModel(initial: .root(.appearance)) + let recorder = Recorder() + recorder.attach(to: model) + + #expect(!model.push(.page(.sqlFormatting), in: .editor)) + #expect(!model.push(.page(.sqlFormatting), in: .appearance)) + #expect(recorder.locations.isEmpty) + + #expect(model.push(.page(.manageThemes), in: .appearance)) + #expect(!model.push(.page(.manageThemes), in: .appearance)) + #expect(model.location == themes) + #expect(recorder.locations == [themes]) + } + + @Test("A new entry after Back drops the forward history") + func newEntryTruncatesForwardHistory() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.editor) + model.select(.data) + model.goBack() + model.goBack() + #expect(model.location == .root(.general)) + #expect(model.canGoForward) + + model.select(.ai) + #expect(!model.canGoForward) + + model.goBack() + #expect(model.location == .root(.general)) + model.goForward() + #expect(model.location == .root(.ai)) + } + + @Test("A stack that grows records an entry, and a pop to the previous entry is a Back") + func stackBindingGrowsAndPops() { + let model = SettingsNavigationModel(initial: .root(.editor)) + + model.setRoutes([.page(.sqlFormatting)], for: .editor) + #expect(model.location == sqlFormatting) + #expect(model.canGoBack) + #expect(!model.canGoForward) + + model.setRoutes([], for: .editor) + #expect(model.location == .root(.editor)) + #expect(!model.canGoBack) + #expect(model.canGoForward) + + model.goForward() + #expect(model.location == sqlFormatting) + } + + @Test("A pop that does not match the previous entry records a new entry") + func stackPopToAnOlderLocationRecordsAnEntry() { + let other = SettingsRoute.plugin(id: "com.example.other") + let model = SettingsNavigationModel(initial: .root(.plugins)) + model.push(driver, in: .plugins) + model.push(other, in: .plugins) + + model.setRoutes([], for: .plugins) + #expect(model.location == .root(.plugins)) + #expect(!model.canGoForward) + + model.goBack() + #expect(model.location == SettingsLocation(pane: .plugins, routes: [driver, other])) + } + + @Test("A stack binding of a pane that is no longer current is ignored") + func stackBindingOfAnotherPaneIsIgnored() { + let model = SettingsNavigationModel(initial: .root(.editor)) + let recorder = Recorder() + recorder.attach(to: model) + + model.setRoutes([.page(.manageThemes)], for: .appearance) + model.setRoutes([], for: .editor) + #expect(model.location == .root(.editor)) + #expect(recorder.locations.isEmpty) + } + + @Test("Back and Forward skip unavailable entries and keep them in order") + func unavailableEntriesAreSkipped() { + let model = SettingsNavigationModel(initial: .root(.general)) + let recorder = Recorder() + recorder.attach(to: model) + model.select(.plugins) + model.push(driver, in: .plugins) + model.select(.editor) + + recorder.unavailable = [driver] + model.goBack() + #expect(model.location == .root(.plugins)) + + model.goForward() + #expect(model.location == .root(.editor)) + + recorder.unavailable = [] + model.goBack() + #expect(model.location == SettingsLocation(route: driver)) + model.goBack() + #expect(model.location == .root(.plugins)) + } + + @Test("Back is disabled when every earlier entry is unavailable") + func backIsDisabledWhenNothingEarlierIsAvailable() { + let model = SettingsNavigationModel(initial: SettingsLocation(route: driver)) + let recorder = Recorder() + recorder.attach(to: model) + model.select(.editor) + #expect(model.canGoBack) + + recorder.unavailable = [driver] + #expect(!model.canGoBack) + model.goBack() + #expect(model.location == .root(.editor)) + } + + @Test("Forward is disabled when every later entry is unavailable") + func forwardIsDisabledWhenNothingLaterIsAvailable() { + let model = SettingsNavigationModel(initial: .root(.plugins)) + let recorder = Recorder() + recorder.attach(to: model) + model.push(driver, in: .plugins) + model.setRoutes([], for: .plugins) + #expect(model.canGoForward) + + recorder.unavailable = [driver] + #expect(!model.canGoForward) + model.goForward() + #expect(model.location == .root(.plugins)) + } + + @Test("A deep link into a closed window opens the page with Back to its pane root") + func closedWindowDeepLinkSeedsThePaneRoot() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.editor) + model.select(.data) + + model.open(themes, recordsHistory: false) + #expect(model.location == themes) + #expect(model.canGoBack) + #expect(!model.canGoForward) + + model.goBack() + #expect(model.location == .root(.appearance)) + #expect(!model.canGoBack) + } + + @Test("Opening a pane root into a closed window starts with no history") + func closedWindowOpenOfARootHasNoHistory() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.editor) + + model.open(.root(.ai), recordsHistory: false) + #expect(model.location == .root(.ai)) + #expect(!model.canGoBack) + #expect(!model.canGoForward) + } + + @Test("A deep link into an open window records an entry and Back passes the page's pane root") + func openWindowDeepLinkRecordsHistory() { + let model = SettingsNavigationModel(initial: .root(.general)) + + model.open(sqlFormatting, recordsHistory: true) + #expect(model.location == sqlFormatting) + + model.goBack() + #expect(model.location == .root(.editor)) + model.goBack() + #expect(model.location == .root(.general)) + #expect(!model.canGoBack) + } + + @Test("A deep link from the page's own pane root adds one entry") + func openWindowDeepLinkFromTheSameRoot() { + let model = SettingsNavigationModel(initial: .root(.editor)) + + model.open(sqlFormatting, recordsHistory: true) + model.goBack() + #expect(model.location == .root(.editor)) + #expect(!model.canGoBack) + } + + @Test("A deep link to the location already shown changes nothing") + func openWindowDeepLinkToTheCurrentLocation() { + let model = SettingsNavigationModel(initial: sqlFormatting) + let recorder = Recorder() + recorder.attach(to: model) + + model.open(sqlFormatting, recordsHistory: true) + #expect(recorder.locations.isEmpty) + #expect(!model.canGoBack) + } + + @Test("An open stops at the first unavailable route, and an unloaded plugin becomes a pending reveal") + func openTruncatesAtAnUnavailableRoute() { + let model = SettingsNavigationModel(initial: .root(.general)) + let recorder = Recorder() + recorder.attach(to: model) + recorder.unavailable = [driver, .page(.accountTeams)] + + model.open(SettingsLocation(route: driver), recordsHistory: false) + #expect(model.location == .root(.plugins)) + #expect(!model.canGoBack) + #expect(model.pendingPluginReveal?.pluginId == "com.example.driver") + + model.open(SettingsLocation(page: .accountTeams), recordsHistory: true) + #expect(model.location == .root(.account)) + } + + @Test("Only a sidebar pick reports a pane to persist") + func onlyAUserPickPersists() { + let model = SettingsNavigationModel(initial: .root(.general)) + let recorder = Recorder() + recorder.attach(to: model) + + model.open(.root(.ai), recordsHistory: true) + model.open(themes, recordsHistory: false) + model.push(.page(.manageThemes), in: .appearance) + model.setRoutes([], for: .appearance) + model.goBack() + model.goForward() + model.removeRoute(.page(.manageThemes)) + model.resetHistory() + #expect(recorder.picks.isEmpty) + + model.select(.mcp) + #expect(recorder.picks == [.mcp]) + } + + @Test("Removing a route pops the page shown and drops it from history") + func removeRoutePopsAndPurges() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.plugins) + model.push(driver, in: .plugins) + + model.removeRoute(driver) + #expect(model.location == .root(.plugins)) + #expect(!model.canGoForward) + model.goBack() + #expect(model.location == .root(.general)) + #expect(!model.canGoBack) + } + + @Test("Removing a route that is not shown leaves the location and drops it from both stacks") + func removeRouteFromHistoryOnly() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.plugins) + model.push(driver, in: .plugins) + model.select(.editor) + model.select(.data) + model.goBack() + + model.removeRoute(driver) + #expect(model.location == .root(.editor)) + model.goBack() + #expect(model.location == .root(.plugins)) + model.goBack() + #expect(model.location == .root(.general)) + model.goForward() + model.goForward() + model.goForward() + #expect(model.location == .root(.data)) + } + + @Test("Removing a route that appears nowhere does nothing") + func removeRouteThatIsAbsent() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.editor) + let recorder = Recorder() + recorder.attach(to: model) + + model.removeRoute(driver) + #expect(recorder.locations.isEmpty) + #expect(model.canGoBack) + } + + @Test("Resetting history keeps the location") + func resetHistoryKeepsTheLocation() { + let model = SettingsNavigationModel(initial: .root(.general)) + model.select(.editor) + model.select(.data) + model.goBack() + + model.resetHistory() + #expect(model.location == .root(.editor)) + #expect(!model.canGoBack) + #expect(!model.canGoForward) + } + + @Test("Each pane path holds the routes only while its pane is current") + func panePathsFollowTheLocation() { + let model = SettingsNavigationModel(initial: .root(.appearance)) + let appearance = model.path(for: .appearance) + let editor = model.path(for: .editor) + #expect(model.path(for: .appearance) === appearance) + + model.push(.page(.manageThemes), in: .appearance) + #expect(appearance.routes == [.page(.manageThemes)]) + #expect(editor.routes.isEmpty) + + model.select(.editor) + #expect(appearance.routes.isEmpty) + + model.goBack() + #expect(appearance.routes == [.page(.manageThemes)]) + #expect(model.path(for: .data).routes.isEmpty) + } + + @Test("onLocationChange runs once per change") + func locationChangeIsReportedOnce() { + let model = SettingsNavigationModel(initial: .root(.general)) + let recorder = Recorder() + recorder.attach(to: model) + + model.select(.editor) + model.push(.page(.sqlFormatting), in: .editor) + model.goBack() + #expect(recorder.locations == [.root(.editor), sqlFormatting, .root(.editor)]) + } + + @Test("Dynamic titles come from the resolver, with a fallback per route") + func titlesComeFromTheResolver() { + let provider = UUID() + let model = SettingsNavigationModel( + initial: .root(.plugins), + titleResolver: { route in route == .plugin(id: "com.example.driver") ? "Example Driver" : nil } + ) + + model.push(driver, in: .plugins) + #expect(model.title == "Example Driver") + + let rejected = URL(fileURLWithPath: "/tmp/Old Driver.tableplugin") + #expect(model.title(for: .rejectedPlugin(rejected)) == "Old Driver") + #expect(model.title(for: .plugin(id: "com.example.other")) == SettingsRoute.plugin(id: "x").defaultTitle) + #expect(model.title(for: .aiProvider(provider)) == SettingsRoute.aiProvider(provider).defaultTitle) + #expect(model.title(for: .page(.accountOffline)) == SettingsPage.accountOffline.title) + } + + @Test("A plugin reveal is consumed once, and each request is distinct") + func pluginRevealIsConsumedOnce() { + let model = SettingsNavigationModel() + #expect(model.pendingPluginReveal == nil) + + model.requestPluginReveal(nil) + let first = model.pendingPluginReveal + model.requestPluginReveal(nil) + let second = model.pendingPluginReveal + #expect(first != nil) + #expect(first != second) + #expect(second?.pluginId == nil) + + #expect(model.consumePluginReveal() == second) + #expect(model.consumePluginReveal() == nil) + #expect(model.pluginReveal.pending == nil) + } + + @Test("A location keeps only the routes of its own pane") + func locationDropsForeignRoutes() { + let location = SettingsLocation(pane: .editor, routes: [.page(.sqlFormatting), .page(.manageThemes), .page(.sqlFormatting)]) + #expect(location.routes == [.page(.sqlFormatting)]) + #expect(SettingsLocation(pane: .ai, routes: [.page(.manageThemes)]).isRoot) + #expect(SettingsLocation(route: .aiProvider(UUID())).pane == .ai) + #expect(SettingsLocation(route: .rejectedPlugin(URL(fileURLWithPath: "/tmp/x.tableplugin"))).pane == .plugins) + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift index 52c0758a8b..ad19c8b297 100644 --- a/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift @@ -1,12 +1,19 @@ -// -// SettingsNavigationTests.swift -// TableProTests -// - +import Foundation @testable import TablePro import Testing struct SettingsNavigationTests { + @Test("The sidebar has four sections in the agreed order") + func sectionsFollowTheAgreedOrder() { + #expect(SettingsNavigation.sections.map { $0.id } == [.app, .workspace, .integrations, .account]) + #expect(SettingsNavigation.orderedPanes == [ + .general, .appearance, .notifications, .keyboard, + .connections, .profiles, .sidebar, .editor, .data, + .ai, .mcp, .plugins, + .sync, .account, + ]) + } + @Test("Every pane appears exactly once across the sections") func sectionsCoverEveryPaneOnce() { let flattened = SettingsNavigation.sections.flatMap(\.panes) @@ -21,6 +28,16 @@ struct SettingsNavigationTests { #expect(SettingsNavigation.orderedPanes.contains(.general)) } + @Test("Sync is titled iCloud Sync and every pane has its own symbol") + func titlesAndSymbols() { + #expect(SettingsPane.sync.title == String(localized: "iCloud Sync")) + #expect(SettingsPane.mcp.title == "MCP") + let symbols = SettingsPane.allCases.map(\.symbol) + #expect(Set(symbols).count == symbols.count) + #expect(SettingsPane.connections.symbol == "cylinder.split.1x2") + #expect(SettingsPane.mcp.symbol == "point.3.connected.trianglepath.dotted") + } + @Test("A url identifier round-trips to its pane") func urlIdentifierRoundTrips() { for pane in SettingsPane.allCases { @@ -35,6 +52,7 @@ struct SettingsNavigationTests { func emptyQueryReturnsEverything() { #expect(SettingsNavigation.panes(matching: "") == SettingsNavigation.orderedPanes) #expect(SettingsNavigation.panes(matching: " ") == SettingsNavigation.orderedPanes) + #expect(SettingsNavigation.panes(matching: " & ") == SettingsNavigation.orderedPanes) } @Test("Search matches titles and keywords, case-insensitively") @@ -47,13 +65,135 @@ struct SettingsNavigationTests { #expect(SettingsNavigation.panes(matching: "zzzznomatch").isEmpty) } + @Test("A term has to start a word, so date skips Update and count skips Account") + func termsMatchWordPrefixes() { + let date = SettingsNavigation.panes(matching: "date") + #expect(date.contains(.data)) + #expect(!date.contains(.general)) + + let count = SettingsNavigation.panes(matching: "count") + #expect(count.contains(.data)) + #expect(!count.contains(.account)) + } + + private static let unitKeywordCases: [(String, [SettingsPane])] = [ + ("SQL Formatting", [.editor]), + ("vim", [.editor]), + ("line numbers", [.editor]), + ("themes", [.appearance]), + ("manage themes", [.appearance]), + ("strip", [.sidebar]), + ("default layout", [.sidebar]), + ("view options", [.sidebar]), + ("json", [.data]), + ("password", [.profiles, .sync]), + ("debugger", [.plugins]), + ("long-running", [.notifications]), + ("Sidebar & Tabs", [.sidebar]), + ] + + @Test("Each unit's keywords find their pane", arguments: unitKeywordCases) + func unitKeywordsFindTheirPane(query: String, expected: [SettingsPane]) { + #expect(SettingsNavigation.panes(matching: query) == expected) + } + + @Test("A page title lists the page under its pane") + func pageTitlesProducePageResults() { + let expected = SettingsSearchResult( + pane: .appearance, + pages: [.init(title: SettingsPage.manageThemes.title, location: SettingsLocation(page: .manageThemes))] + ) + #expect(SettingsNavigation.results(matching: "manage themes") == [expected]) + + let editor = SettingsNavigation.results(matching: "SQL Formatting") + #expect(editor.first?.pages.map { $0.location } == [SettingsLocation(page: .sqlFormatting)]) + } + + @Test("A pane that matches only its keywords lists no pages") + func paneKeywordMatchListsNoPages() { + #expect(SettingsNavigation.results(matching: "vim") == [SettingsSearchResult(pane: .editor, pages: [])]) + } + + @Test("Every page is found by its title") + func everyPageIsFoundByItsTitle() { + for page in SettingsPage.allCases { + let result = SettingsNavigation.results(matching: page.title).first { $0.pane == page.parent } + #expect(result?.pages.contains { $0.location == SettingsLocation(page: page) } == true, "\(page)") + } + } + + @Test("Names only the app knows are searchable and open their page") + func dynamicEntriesAreSearchable() { + let provider = UUID() + let entries = [ + SettingsSearchEntry(title: "PostgreSQL", location: SettingsLocation(route: .plugin(id: "com.tablepro.postgresql"))), + SettingsSearchEntry(title: "Work Ollama", location: SettingsLocation(route: .aiProvider(provider))), + ] + + let postgres = SettingsNavigation.results(matching: "postgres", adding: entries) + #expect(postgres.map { $0.pane } == [.plugins]) + #expect(postgres.first?.pages.map { $0.title } == ["PostgreSQL"]) + + let ollama = SettingsNavigation.results(matching: "work oll", adding: entries) + #expect(ollama.map { $0.pane } == [.ai]) + #expect(ollama.first?.pages.map { $0.location } == [SettingsLocation(route: .aiProvider(provider))]) + + #expect(SettingsNavigation.panes(matching: "postgres").isEmpty) + } + + @Test("Matching ignores diacritics, case and width, and needs a word start") + func vietnameseTitlesMatchWithoutDiacritics() { + let index = SettingsSearchIndex( + entries: [ + SettingsSearchEntry(title: "Giao diện", location: .root(.appearance)), + SettingsSearchEntry(title: "Đồng bộ iCloud", location: .root(.sync)), + SettingsSearchEntry(title: "Lịch sử truy vấn", location: SettingsLocation(page: .queryHistory)), + ], + locale: Locale(identifier: "vi") + ) + #expect(index.results(matching: "giao dien").map { $0.pane } == [.appearance]) + #expect(index.results(matching: "GIAO DIỆN").map { $0.pane } == [.appearance]) + #expect(index.results(matching: "dien").map { $0.pane } == [.appearance]) + #expect(index.results(matching: "iao").isEmpty) + #expect(index.results(matching: "dong bo").map { $0.pane } == [.sync]) + #expect(index.results(matching: "lich su").first?.pages.map { $0.location } == [SettingsLocation(page: .queryHistory)]) + } + + @Test("Each Han character starts a word") + func hanCharactersStartWords() { + let index = SettingsSearchIndex(entries: [SettingsSearchEntry(title: "外观设置", location: .root(.appearance))]) + #expect(index.results(matching: "设置").map { $0.pane } == [.appearance]) + #expect(index.results(matching: "外").map { $0.pane } == [.appearance]) + } + @Test("Search results keep sidebar order") func searchResultsKeepSidebarOrder() { - // "connections" is a General keyword and the Connections concept; results stay in order. let results = SettingsNavigation.panes(matching: "e") let orderIndex = SettingsNavigation.orderedPanes.enumerated() .reduce(into: [SettingsPane: Int]()) { $0[$1.element] = $1.offset } let indices = results.compactMap { orderIndex[$0] } #expect(indices == indices.sorted()) } + + @Test("Unfiltered rows are every pane with a spacer between sections") + func unfilteredRowsHaveSpacers() { + let rows = SettingsNavigation.rows(matching: "") + let panes = rows.compactMap { row -> SettingsPane? in + if case .pane(let pane) = row { return pane } + return nil + } + #expect(panes == SettingsNavigation.orderedPanes) + #expect(rows.filter { $0 == .spacer(before: .workspace) || $0 == .spacer(before: .integrations) || $0 == .spacer(before: .account) }.count == 3) + #expect(rows.count == SettingsNavigation.orderedPanes.count + 3) + #expect(rows.first == .pane(.general)) + } + + @Test("Filtered rows have no spacers and put each page under its pane") + func filteredRowsListPagesUnderTheirPane() { + let rows = SettingsNavigation.rows(matching: "manage themes") + #expect(rows == [ + .pane(.appearance), + .page(title: SettingsPage.manageThemes.title, location: SettingsLocation(page: .manageThemes)), + ]) + } } diff --git a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift index 657b1840ec..da64eda2d9 100644 --- a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift @@ -1,8 +1,4 @@ -// -// SettingsPaneURLIdentifierTests.swift -// TableProTests -// - +import Foundation @testable import TablePro import Testing @@ -25,6 +21,28 @@ struct SettingsPaneURLIdentifierTests { .account: "license", ] + private static let publishedPages: [SettingsPage: String] = [ + .softwareUpdate: "general/software-update", + .commandLineTool: "general/command-line-tool", + .manageThemes: "appearance/themes", + .linkedFolders: "connections/linked-folders", + .trustedLinks: "connections/trusted-links", + .sqlFormatting: "editor/sql-formatting", + .queryHistory: "data/query-history", + .dataRewind: "data/data-rewind", + .slashCommands: "ai/slash-commands", + .mcpApprovals: "mcp/approvals", + .mcpTokens: "mcp/tokens", + .accountFeatures: "license/features", + .accountDevices: "license/devices", + .accountTeams: "license/teams", + .accountOffline: "license/offline", + ] + + private func location(_ path: String) -> SettingsLocation? { + SettingsLocation(urlPathSegments: path.split(separator: "/").map(String.init)) + } + @Test("Every pane has the published id") func everyPaneHasThePublishedId() { #expect(Self.published.count == SettingsPane.allCases.count) @@ -49,10 +67,73 @@ struct SettingsPaneURLIdentifierTests { #expect(SettingsPane.account.urlIdentifier == "license") #expect(SettingsPane(urlIdentifier: "license") == .account) #expect(SettingsPane(urlIdentifier: "account") == nil) + #expect(SettingsPane.plugins.urlIdentifier == "plugins") + #expect(SettingsPane.plugins.rawValue == "plugins") } @Test("Matching is exact and lowercase", arguments: ["MCP", "Mcp", " mcp", "mcp ", "Integrations", "integrations", ""]) func matchingIsExact(raw: String) { #expect(SettingsPane(urlIdentifier: raw) == nil) } + + @Test("Every page has the published pane and page id") + func everyPageHasThePublishedPath() { + #expect(Self.publishedPages.count == SettingsPage.allCases.count) + for page in SettingsPage.allCases { + #expect("\(page.parent.urlIdentifier)/\(page.urlIdentifier)" == Self.publishedPages[page]) + } + } + + @Test("Every page id opens its page", arguments: SettingsPage.allCases) + func pageIdRoundTrips(page: SettingsPage) { + #expect(SettingsLocation(urlPathSegments: [page.parent.urlIdentifier, page.urlIdentifier]) == SettingsLocation(page: page)) + #expect(SettingsPage(urlIdentifier: page.urlIdentifier, in: page.parent) == page) + } + + @Test("Page ids are unique within their pane, and a page id under another pane is no page") + func pageIdsAreScopedToTheirPane() { + for pane in SettingsPane.allCases { + let ids = SettingsPage.pages(in: pane).map(\.urlIdentifier) + #expect(Set(ids).count == ids.count) + } + #expect(SettingsPage(urlIdentifier: "themes", in: .general) == nil) + #expect(location("general/themes") == .root(.general)) + } + + @Test("A pane link opens the pane root") + func paneLinksOpenTheRoot() { + #expect(location("license") == .root(.account)) + #expect(location("plugins") == .root(.plugins)) + #expect(location("profiles") == .root(.profiles)) + } + + @Test("No segment or an unknown pane parses to nothing, so the last-used pane opens") + func unknownPaneParsesToNothing() { + #expect(SettingsLocation(urlPathSegments: []) == nil) + #expect(location("nope") == nil) + #expect(location("account/devices") == nil) + } + + @Test("An unknown page, a wrong case or extra segments open the pane root") + func unknownPageOpensThePaneRoot() { + #expect(location("mcp/authentication") == .root(.mcp)) + #expect(location("ai/providers/openai") == .root(.ai)) + #expect(location("editor/SQL-Formatting") == .root(.editor)) + #expect(location("license/devices/extra") == SettingsLocation(page: .accountDevices)) + } + + @Test("plugins/ opens that plugin's page") + func pluginLinksOpenThePluginPage() { + #expect(location("plugins/com.tablepro.postgresql") == SettingsLocation(route: .plugin(id: "com.tablepro.postgresql"))) + #expect(SettingsLocation(urlPathSegments: ["plugins", "not a bundle id"]) == .root(.plugins)) + #expect(SettingsLocation(urlPathSegments: ["plugins", ""]) == .root(.plugins)) + } + + @Test("Drill rows and page roots derive their identifiers from the page id") + func accessibilityIdentifiersUseThePageId() { + #expect(SettingsPage.sqlFormatting.drillIdentifier == "settings-drill-sql-formatting") + #expect(SettingsPage.commandLineTool.pageIdentifier == "settings-page-command-line-tool") + #expect(SettingsRoute.page(.mcpTokens).settingsDrillIdentifier == "settings-drill-tokens") + #expect(SettingsRoute.plugin(id: "com.tablepro.postgresql").settingsDrillIdentifier == nil) + } } diff --git a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift index 283bdf60e2..31e7859261 100644 --- a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift @@ -133,7 +133,7 @@ extension GlobalStateSuites { // and a pane switch pops back to the pane's own title. @Test("Back enablement and title track the detail stack depth") func backEnablementTracksDepth() { - let model = SettingsNavigationModel(initial: .appearance) + let model = LegacySettingsNavigationModel(initial: .appearance) #expect(!model.canGoBack) #expect(model.currentTitle == SettingsPane.appearance.title) From 8e5e5b7e082804db2fff425cda7aa7a8608342b3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:06 +0700 Subject: [PATCH 18/48] fix(ui): native list add/remove bar instead of a navigation capsule --- .../Components/AddRemoveControlGroup.swift | 104 ++++++++++++++---- .../Views/Connection/HostListFieldRow.swift | 36 ++---- .../AttachedDatabaseListEditor.swift | 36 +++--- .../LoadableExtensionListEditor.swift | 44 +++----- .../Views/ERDiagram/ERDiagramEditSheets.swift | 35 +++--- .../UserType/UserTypeMembersPane.swift | 66 +++++------ .../Structure/StructureDefinitionPage.swift | 51 +++++---- .../Views/UsersRoles/PrincipalListPane.swift | 26 ++--- 8 files changed, 199 insertions(+), 199 deletions(-) diff --git a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift index 3311733336..729a965f46 100644 --- a/apple/TablePro/Views/Components/AddRemoveControlGroup.swift +++ b/apple/TablePro/Views/Components/AddRemoveControlGroup.swift @@ -2,19 +2,17 @@ // AddRemoveControlGroup.swift // TablePro // -// The add/remove pair that sits under a list, which is where macOS puts a list's own +/-. -// Shared by the structure editor's footer and the Users & Roles list. -// +import AppKit import SwiftUI +// Borderless glyphs split by a separator, as System Settings draws a list's bar; the navigation ControlGroup is back and forward. struct AddRemoveControlGroup: View { let addLabel: String let removeLabel: String var canAdd = true var canRemove = true - /// What the tooltip says. Defaults to the label; a withheld control sets it to the reason - /// instead, which is the only place a disabled button has to explain itself. + // A withheld control sets its help to the reason, the only place a disabled button explains itself. var addHelp: String? var removeHelp: String? var addIdentifier: String? @@ -23,27 +21,89 @@ struct AddRemoveControlGroup: View { let onRemove: () -> Void var body: some View { - ControlGroup { - Button(action: onAdd) { - Label(addLabel, systemImage: "plus") - .labelStyle(.iconOnly) - } - .help(addHelp ?? addLabel) - .accessibilityLabel(addLabel) - .accessibilityIdentifier(addIdentifier ?? "") + HStack(spacing: 0) { + ListBarButton( + label: addLabel, + systemImage: "plus", + help: addHelp, + identifier: addIdentifier, + action: onAdd + ) .disabled(!canAdd) - Button(action: onRemove) { - Label(removeLabel, systemImage: "minus") - .labelStyle(.iconOnly) - } - .help(removeHelp ?? removeLabel) - .accessibilityLabel(removeLabel) - .accessibilityIdentifier(removeIdentifier ?? "") + ListBarSeparator() + + ListBarButton( + label: removeLabel, + systemImage: "minus", + help: removeHelp, + identifier: removeIdentifier, + action: onRemove + ) .disabled(!canRemove) } - .controlGroupStyle(.navigation) - .controlSize(.small) .fixedSize() } } + +// Measured from System Settings > General > Login Items on macOS 27. +enum ListBarMetrics { + static let contentHeight: CGFloat = 23 + static let height: CGFloat = contentHeight + 1 + static let buttonWidth: CGFloat = 24 + static let separatorHeight: CGFloat = 16 +} + +struct ListBarButton: View { + let label: String + let systemImage: String + var help: String? + var identifier: String? + let action: () -> Void + + var body: some View { + Button(action: action) { + Label(label, systemImage: systemImage) + .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") + } +} + +struct ListBarSeparator: View { + var body: some View { + Divider() + .frame(height: ListBarMetrics.separatorHeight) + } +} + +struct ListBar: View { + @ViewBuilder let content: Content + + var body: some View { + VStack(spacing: 0) { + Divider() + HStack(spacing: 0) { + content + Spacer(minLength: 0) + } + .frame(minHeight: ListBarMetrics.contentHeight) + } + } +} + +extension View { + // An overlay, not a safe area inset: an inset shrinks a bordered list and leaves the bar outside its border. + // The caller's list height counts ListBarMetrics.height, so no row ever sits under the bar. + func listBar(@ViewBuilder _ content: () -> Content) -> some View { + overlay(alignment: .bottom) { + ListBar(content: content) + } + } +} diff --git a/apple/TablePro/Views/Connection/HostListFieldRow.swift b/apple/TablePro/Views/Connection/HostListFieldRow.swift index 6f04a92dd4..4e0bc05cbf 100644 --- a/apple/TablePro/Views/Connection/HostListFieldRow.swift +++ b/apple/TablePro/Views/Connection/HostListFieldRow.swift @@ -10,7 +10,6 @@ struct HostEntry: Identifiable { var value: String } -/// Selection arithmetic for `HostListFieldRow`. enum HostListSelection { static func nextSelection( afterRemoving removedIds: Set, @@ -40,25 +39,14 @@ struct HostListFieldRow: View { } .listStyle(.bordered(alternatesRowBackgrounds: false)) .frame(height: listHeight) - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Host"), - removeLabel: String(localized: "Remove Host"), - canRemove: !selectedId.isEmpty && entries.count > 1, - onAdd: { addEntry() }, - onRemove: { removeSelected() } - ) - .controlSize(.small) - - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Host"), + removeLabel: String(localized: "Remove Host"), + canRemove: !selectedId.isEmpty && entries.count > 1, + onAdd: { addEntry() }, + onRemove: { removeSelected() } + ) } } label: { Text(label) @@ -67,8 +55,7 @@ struct HostListFieldRow: View { .onChange(of: value) { _ in parseValue() } } - /// A plugin can declare a per-field example, which matters when one form has two host lists - /// on different default ports: Sentinel answers on 26379 and a cluster seed on 6379. + // A plugin's per-field example, since one form can hold host lists on different default ports (Sentinel 26379, cluster 6379). private var prompt: String { placeholder.isEmpty ? "hostname:\(defaultPort)" : placeholder } @@ -76,11 +63,8 @@ struct HostListFieldRow: View { private var listHeight: CGFloat { let rowHeight: CGFloat = 24 let rows = CGFloat(max(entries.count, 1)) - /// The control group brings its own intrinsic height, which is taller than the two - /// hand-sized 20pt buttons this row used to draw. - let buttonBarHeight: CGFloat = 32 // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func bindingForEntry(_ entry: HostEntry) -> Binding { diff --git a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift index c3ea5aa3f7..89a893ff1c 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/AttachedDatabaseListEditor.swift @@ -6,7 +6,7 @@ import AppKit import SwiftUI -/// Built like the Extensions list below it, so the two lists in Options behave the same. +// Built like the Extensions list below it, so the two lists in Options behave the same. struct AttachedDatabaseListEditor: View { @Binding var value: String let databaseType: DatabaseType @@ -53,38 +53,28 @@ struct AttachedDatabaseListEditor: View { if model.rows.isEmpty { Text("No Attached Databases") .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) + .padding(.bottom, ListBarMetrics.height) } } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Attach Database…"), - removeLabel: String(localized: "Remove Attached Database"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-attached-databases-add", - removeIdentifier: "connection-attached-databases-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Attach Database…"), + removeLabel: String(localized: "Remove Attached Database"), + canRemove: !selection.isEmpty, + addIdentifier: "connection-attached-databases-add", + removeIdentifier: "connection-attached-databases-remove", + onAdd: { chooseFiles() }, + onRemove: { removeSelection() } + ) } } private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 private var listHeight: CGFloat { // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func nameBinding(for id: UUID) -> Binding { diff --git a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift index 182eea6353..b7e97dd830 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/LoadableExtensionListEditor.swift @@ -7,12 +7,7 @@ import AppKit import SwiftUI import UniformTypeIdentifiers -/// The ordered list of SQLite extension libraries a connection loads, edited in place. -/// -/// Built like the other lists in this form: a bordered list with the add and remove pair beneath -/// it, rows reordered by dragging or with the Move Up and Move Down accessibility actions, and -/// Delete removing the selection. Add opens a file panel, the only way a row is created; once it -/// exists, its path and entry point are edited in place. +// Add opens a file panel, the only way a row is created; a row's path and entry point are then edited in place. struct LoadableExtensionListEditor: View { @Binding var value: String @@ -58,38 +53,28 @@ struct LoadableExtensionListEditor: View { if model.rows.isEmpty { Text("No Extensions") .foregroundStyle(.secondary) - .padding(.bottom, buttonBarHeight) + .padding(.bottom, ListBarMetrics.height) } } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Extension…"), - removeLabel: String(localized: "Remove Extension"), - canRemove: !selection.isEmpty, - addIdentifier: "connection-extensions-add", - removeIdentifier: "connection-extensions-remove", - onAdd: { chooseFiles() }, - onRemove: { removeSelection() } - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Extension…"), + removeLabel: String(localized: "Remove Extension"), + canRemove: !selection.isEmpty, + addIdentifier: "connection-extensions-add", + removeIdentifier: "connection-extensions-remove", + onAdd: { chooseFiles() }, + onRemove: { removeSelection() } + ) } } private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 private var listHeight: CGFloat { // No cap: a List in a grouped Form never scrolls, so it shows every row and the Form scrolls. let rows = CGFloat(max(model.rows.count, 2)) - return rows * rowHeight + buttonBarHeight + 8 + return rows * rowHeight + ListBarMetrics.height + 8 } private func pathBinding(for id: UUID) -> Binding { @@ -203,8 +188,7 @@ private struct LoadableExtensionRowView: View { } } -/// Refuses a file that is not a Mach-O library before it reaches the list. The panel's content types -/// only dim other files, and `.so` has no type of its own, so the choice is checked here as well. +// The panel's content types only dim other files, and .so has no type of its own, so the choice is checked here too. private final class LoadableExtensionPanelValidator: NSObject, NSOpenSavePanelDelegate { static let contentTypes: [UTType] = [ UTType(filenameExtension: "dylib"), diff --git a/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift b/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift index 206e1e56b3..1210702226 100644 --- a/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift +++ b/apple/TablePro/Views/ERDiagram/ERDiagramEditSheets.swift @@ -147,34 +147,25 @@ struct ERDiagramForeignKeySheet: View { .listStyle(.bordered(alternatesRowBackgrounds: false)) .frame(height: listHeight) .onDeleteCommand { removeSelection() } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - AddRemoveControlGroup( - addLabel: String(localized: "Add Column Pair"), - removeLabel: String(localized: "Remove Column Pair"), - canRemove: canRemoveSelection, - addIdentifier: "er-diagram-foreign-key-add-pair", - removeIdentifier: "er-diagram-foreign-key-remove-pair", - onAdd: addPair, - onRemove: removeSelection - ) - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + .listBar { + AddRemoveControlGroup( + addLabel: String(localized: "Add Column Pair"), + removeLabel: String(localized: "Remove Column Pair"), + canRemove: canRemoveSelection, + addIdentifier: "er-diagram-foreign-key-add-pair", + removeIdentifier: "er-diagram-foreign-key-remove-pair", + onAdd: addPair, + onRemove: removeSelection + ) } } - private let rowHeight: CGFloat = 26 - private let buttonBarHeight: CGFloat = 32 + // A row of two pop-up buttons is 32pt on macOS 27, taller than a text field row. + private let rowHeight: CGFloat = 32 // No cap: a List in a grouped Form never scrolls, so it shows every pair and the Form scrolls. private var listHeight: CGFloat { - CGFloat(max(draft.pairs.count, 2)) * rowHeight + buttonBarHeight + 8 + CGFloat(max(draft.pairs.count, 2)) * rowHeight + ListBarMetrics.height + 8 } private var canRemoveSelection: Bool { diff --git a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift index d10f859689..a948160cf6 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMembersPane.swift @@ -6,8 +6,7 @@ import SwiftUI import TableProPluginKit -/// An enum's labels, a composite's fields or a domain's checks, as they will be after the queue -/// runs. Each row says what the queue does to it. +// Members as they will be after the queue runs; each row says what the queue does to it. struct UserTypeMembersPane: View { @ObservedObject var model: UserTypeEditorModel let draft: UserTypeDraft @@ -41,32 +40,31 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-labels") - Divider() - HStack(spacing: 8) { - Button { - present(.addLabel) - } label: { - Label(String(localized: "Add Label"), systemImage: "plus") - .labelStyle(.iconOnly) - } - .help(String(localized: "Add Label")) + ListBar { + ListBarButton( + label: String(localized: "Add Label"), + systemImage: "plus", + identifier: "user-type-add-label", + action: { present(.addLabel) } + ) .disabled(isDisabled || !model.support.addLabel) - .accessibilityIdentifier("user-type-add-label") - Button(String(localized: "Rename…")) { - if let label = selectedLabel { present(.renameLabel(label.name)) } + HStack(spacing: 8) { + Button(String(localized: "Rename…")) { + if let label = selectedLabel { present(.renameLabel(label.name)) } + } + .disabled(isDisabled || selectedLabel == nil || !model.support.renameLabel) + .help(model.support.renameLabel + ? String(localized: "Rename the selected label") + : String(localized: "This server cannot rename a label.")) + Text("A label cannot be removed or moved once it exists.") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .padding(.vertical, 4) } - .disabled(isDisabled || selectedLabel == nil || !model.support.renameLabel) - .help(model.support.renameLabel - ? String(localized: "Rename the selected label") - : String(localized: "This server cannot rename a label.")) - Text("A label cannot be removed or moved once it exists.") - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } @@ -91,8 +89,7 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-fields") - Divider() - HStack(spacing: 8) { + ListBar { AddRemoveControlGroup( addLabel: String(localized: "Add Field"), removeLabel: String(localized: "Drop Field"), @@ -107,10 +104,9 @@ struct UserTypeMembersPane: View { if let field = selectedField { present(.editField(name: field.name, type: field.type)) } } .disabled(isDisabled || !canEditSelectedField) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } @@ -128,7 +124,7 @@ struct UserTypeMembersPane: View { selectedField != nil && (model.support.renameField || model.support.changeFieldType) } - /// A field this queue added is taken back by removing its addition, not by queuing a drop. + // A field this queue added is taken back by removing its addition, not by queuing a drop. private func removeSelectedField() { guard let field = selectedField else { return } if case .added(let changeId) = field.origin { @@ -168,8 +164,7 @@ struct UserTypeMembersPane: View { .width(min: 120, ideal: 180) } .accessibilityIdentifier("user-type-constraints") - Divider() - HStack(spacing: 8) { + ListBar { AddRemoveControlGroup( addLabel: String(localized: "Add Check"), removeLabel: String(localized: "Drop Constraint"), @@ -185,10 +180,9 @@ struct UserTypeMembersPane: View { } .disabled(isDisabled || !canValidateSelectedConstraint) .help(String(localized: "Check the values already stored against the selected constraint")) - Spacer() + .controlSize(.small) + .padding(.horizontal, 8) } - .controlSize(.small) - .padding(8) } } diff --git a/apple/TablePro/Views/Structure/StructureDefinitionPage.swift b/apple/TablePro/Views/Structure/StructureDefinitionPage.swift index 542df40dd0..112f0cb132 100644 --- a/apple/TablePro/Views/Structure/StructureDefinitionPage.swift +++ b/apple/TablePro/Views/Structure/StructureDefinitionPage.swift @@ -134,16 +134,20 @@ struct StructureSectionView: View { } else { emptyRow } - ForEach(notes) { note in - Label(note.text, systemImage: note.systemImage) - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - .padding(.horizontal, 10) - .padding(.top, 6) - .accessibilityIdentifier(note.identifier) - } footer + if !notes.isEmpty { + VStack(alignment: .leading, spacing: 6) { + ForEach(notes) { note in + Label(note.text, systemImage: note.systemImage) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier(note.identifier) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + } } } @@ -185,21 +189,20 @@ struct StructureSectionView: View { private var footer: some View { let labels = StructureFooterPolicy.labels(for: section) let reason = editor.refusal(adding: section) - return AddRemoveControlGroup( - addLabel: labels.add, - removeLabel: labels.remove, - canAdd: editor.canAdd(section), - canRemove: editor.canRemoveSelection(in: section), - addHelp: reason, - removeHelp: reason, - addIdentifier: "structure-\(section.rawValue)-add", - removeIdentifier: "structure-\(section.rawValue)-remove", - onAdd: { editor.add(section) }, - onRemove: { editor.removeSelection(in: section) } - ) - .padding(.horizontal, 10) - .padding(.top, 6) - .padding(.bottom, 10) + return ListBar { + AddRemoveControlGroup( + addLabel: labels.add, + removeLabel: labels.remove, + canAdd: editor.canAdd(section), + canRemove: editor.canRemoveSelection(in: section), + addHelp: reason, + removeHelp: reason, + addIdentifier: "structure-\(section.rawValue)-add", + removeIdentifier: "structure-\(section.rawValue)-remove", + onAdd: { editor.add(section) }, + onRemove: { editor.removeSelection(in: section) } + ) + } } } diff --git a/apple/TablePro/Views/UsersRoles/PrincipalListPane.swift b/apple/TablePro/Views/UsersRoles/PrincipalListPane.swift index cd73778209..2203074217 100644 --- a/apple/TablePro/Views/UsersRoles/PrincipalListPane.swift +++ b/apple/TablePro/Views/UsersRoles/PrincipalListPane.swift @@ -29,22 +29,16 @@ struct PrincipalListPane: View { .paneBarBackground(Color(nsColor: .controlBackgroundColor)) } .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider() - HStack { - AddRemoveControlGroup( - addLabel: String(localized: "New User or Role"), - removeLabel: String(localized: "Drop"), - canRemove: !viewModel.selectedRefs.isEmpty && !viewModel.isResolvingDrop, - addIdentifier: "usersroles-add", - removeIdentifier: "usersroles-remove", - onAdd: { viewModel.activeSheet = .create }, - onRemove: { Task { await viewModel.requestDrop(viewModel.selectedRefs) } } - ) - Spacer() - } - .padding(.horizontal, 8) - .padding(.vertical, 6) + ListBar { + AddRemoveControlGroup( + addLabel: String(localized: "New User or Role"), + removeLabel: String(localized: "Drop"), + canRemove: !viewModel.selectedRefs.isEmpty && !viewModel.isResolvingDrop, + addIdentifier: "usersroles-add", + removeIdentifier: "usersroles-remove", + onAdd: { viewModel.activeSheet = .create }, + onRemove: { Task { await viewModel.requestDrop(viewModel.selectedRefs) } } + ) } .paneBarBackground(Color(nsColor: .controlBackgroundColor)) } From b0b791a23c75a1068e963d805fe0750900e57396 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:07 +0700 Subject: [PATCH 19/48] fix(notifications): play the system sound on posted notifications --- .../Notifications/AgentAttentionNotifier.swift | 5 +++-- .../OperationCompletionReporter+Handling.swift | 4 ++-- .../Operations/OperationCompletionReporter.swift | 1 + .../Operations/AgentAttentionNotifierTests.swift | 12 ++++++++++++ .../OperationCompletionReporterTests.swift | 11 +++++++++++ 5 files changed, 29 insertions(+), 4 deletions(-) diff --git a/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift b/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift index 065a13b1df..c5f353e3db 100644 --- a/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift +++ b/apple/TablePro/Core/Services/Notifications/AgentAttentionNotifier.swift @@ -114,6 +114,7 @@ internal final class AgentAttentionNotifier { content.subtitle = subtitle } content.body = body + content.sound = .default content.categoryIdentifier = Self.categoryId content.threadIdentifier = session.connectionId.uuidString content.userInfo = [ @@ -149,8 +150,8 @@ internal final class AgentAttentionNotifier { extension AgentAttentionNotifier: NotificationHandling { internal func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { - guard let session = session(from: notification.request.content.userInfo) else { return [.banner, .list] } - return isOnScreen(session) ? [] : [.banner, .list] + guard let session = session(from: notification.request.content.userInfo) else { return [.banner, .list, .sound] } + return isOnScreen(session) ? [] : [.banner, .list, .sound] } internal func handle(_ response: UNNotificationResponse) { diff --git a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift index f5b72ebdd0..de8de9cd12 100644 --- a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift +++ b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter+Handling.swift @@ -12,14 +12,14 @@ extension OperationCompletionReporter: NotificationHandling { internal func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { guard let payload = OperationNotificationPayload(userInfo: notification.request.content.userInfo), let connectionId = payload.connectionId - else { return [.banner, .list] } + else { return [.banner, .list, .sound] } let owner: OperationOwner = payload.compareWindowId.map { .compareWindow($0) } ?? payload.tabId.map { .tab(windowId: payload.windowId, tabId: $0) } ?? .connection(connectionId) let visibility = ResultVisibilityResolver.resolve(owner: owner, connectionId: connectionId) - return visibility.resultIsOnScreen ? [] : [.banner, .list] + return visibility.resultIsOnScreen ? [] : [.banner, .list, .sound] } internal func handle(_ response: UNNotificationResponse) { diff --git a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift index de33e57ffc..35b41eb5d8 100644 --- a/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift +++ b/apple/TablePro/Core/Services/Operations/OperationCompletionReporter.swift @@ -119,6 +119,7 @@ internal final class OperationCompletionReporter { content.subtitle = subtitle } content.body = plan.body + content.sound = .default content.categoryIdentifier = plan.categoryIdentifier content.threadIdentifier = plan.threadIdentifier content.userInfo = OperationNotificationPayload(plan: plan).userInfo diff --git a/apple/TableProTests/Core/Operations/AgentAttentionNotifierTests.swift b/apple/TableProTests/Core/Operations/AgentAttentionNotifierTests.swift index 15f65cc255..7c6deb7101 100644 --- a/apple/TableProTests/Core/Operations/AgentAttentionNotifierTests.swift +++ b/apple/TableProTests/Core/Operations/AgentAttentionNotifierTests.swift @@ -67,6 +67,18 @@ struct AgentAttentionNotifierTests { #expect(request.content.body == "The agent is waiting for your answer.") } + @Test("The notification carries the default sound, so the system Play sound switch decides") + func notificationCarriesDefaultSound() async throws { + let session = makeSession() + session.mark(.waitingOnYou) + let notifier = makeNotifier() + + await notifier.statusChanged(session, to: .waitingOnYou)?.value + + let request = try #require(presenter.posted.first) + #expect(request.content.sound == .default) + } + @Test("A failed reply out of sight notifies too") func failedNotifies() async { let session = makeSession() diff --git a/apple/TableProTests/Core/Operations/OperationCompletionReporterTests.swift b/apple/TableProTests/Core/Operations/OperationCompletionReporterTests.swift index 8c783b5f54..f18f9c2a56 100644 --- a/apple/TableProTests/Core/Operations/OperationCompletionReporterTests.swift +++ b/apple/TableProTests/Core/Operations/OperationCompletionReporterTests.swift @@ -76,6 +76,17 @@ struct OperationCompletionReporterTests { #expect(content.body == "3 rows in 1m 00s") } + @Test("The notification carries the default sound, so the system Play sound switch decides") + func notificationCarriesDefaultSound() async throws { + let presenter = FakeNotificationPresenter() + let reporter = makeReporter(presenter: presenter) + + await reporter.report(completion())?.value + + let content = try #require(presenter.posted.first?.content) + #expect(content.sound == .default) + } + @Test("Work the user cancelled posts nothing") func cancelledPostsNothing() async throws { let presenter = FakeNotificationPresenter() From c08baf7832beebf95da19b6bf68827ed2908bf86 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:07 +0700 Subject: [PATCH 20/48] fix(ai): fill {{body}} in custom slash commands with the typed text --- .../TablePro/Core/AI/Chat/SlashCommand.swift | 25 ++++++----- .../TablePro/ViewModels/AIChatViewModel.swift | 13 ++++++ .../Core/AI/SlashCommandTests.swift | 28 ++++++++++++ .../AIChatViewModelSlashTests.swift | 43 +++++++++++++++++++ 4 files changed, 96 insertions(+), 13 deletions(-) diff --git a/apple/TablePro/Core/AI/Chat/SlashCommand.swift b/apple/TablePro/Core/AI/Chat/SlashCommand.swift index c05ba82af2..e905814447 100644 --- a/apple/TablePro/Core/AI/Chat/SlashCommand.swift +++ b/apple/TablePro/Core/AI/Chat/SlashCommand.swift @@ -46,24 +46,23 @@ enum SlashCommand: String, CaseIterable, Identifiable, Sendable { SlashCommand(rawValue: name.trimmingCharacters(in: .whitespaces).lowercased()) != nil } - /// Parses a typed input. Returns the command and any body text after it, - /// or nil if the text doesn't start with a known slash command. - /// Examples: - /// "/explain" -> (.explain, "") - /// "/explain SELECT 1" -> (.explain, "SELECT 1") - /// "/Notacommand" -> nil - /// "hello" -> nil static func parse(_ text: String) -> (command: SlashCommand, body: String)? { + guard let invocation = invocation(in: text), + let command = SlashCommand(rawValue: invocation.name.lowercased()) + else { return nil } + return (command, invocation.body) + } + + static func invocation(in text: String) -> (name: String, body: String)? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmed.hasPrefix("/") else { return nil } let afterSlash = trimmed.dropFirst() - let nameSubstring = afterSlash.prefix(while: { !$0.isWhitespace }) - let name = String(nameSubstring).lowercased() - guard let command = SlashCommand(rawValue: name) else { return nil } + let name = afterSlash.prefix(while: { !$0.isWhitespace }) + guard !name.isEmpty else { return nil } let body = afterSlash - .dropFirst(nameSubstring.count) - .trimmingCharacters(in: .whitespaces) - return (command, body) + .dropFirst(name.count) + .trimmingCharacters(in: .whitespacesAndNewlines) + return (String(name), body) } static func match(prefix: String) -> [SlashCommand] { diff --git a/apple/TablePro/ViewModels/AIChatViewModel.swift b/apple/TablePro/ViewModels/AIChatViewModel.swift index 6253afffe7..868534d720 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel.swift @@ -114,6 +114,9 @@ final class AIChatViewModel: ObservableObject { var inFlightSchemaLoad: Task? var relevantTableNames: [String] = [] var schemaRanker: @Sendable (AISchemaRankingInput) -> [String] = AISchemaContext.relevantTableNames(for:) + var customSlashCommandNamed: @MainActor (String) -> CustomSlashCommand? = { + CustomSlashCommandStorage.shared.command(named: $0) + } @Published var tableMentions = TableMentionIndex.empty var tableMentionSource: [TableInfo] = [] var tableMentionBuild: Task? @@ -199,6 +202,16 @@ final class AIChatViewModel: ObservableObject { return } + if let invocation = SlashCommand.invocation(in: text), + let command = customSlashCommandNamed(invocation.name), + command.isValid { + guard !isStreaming else { return } + // Cleared now, so a second Return before the task runs finds nothing to send. + inputText = "" + Task { await runCustomSlashCommand(command, body: invocation.body) } + return + } + var blocks: [ChatContentBlock] = [] if !text.isEmpty { blocks.append(.text(text)) diff --git a/apple/TableProTests/Core/AI/SlashCommandTests.swift b/apple/TableProTests/Core/AI/SlashCommandTests.swift index 71978ad834..0e7935cd97 100644 --- a/apple/TableProTests/Core/AI/SlashCommandTests.swift +++ b/apple/TableProTests/Core/AI/SlashCommandTests.swift @@ -95,6 +95,34 @@ struct SlashCommandTests { #expect(SlashCommand.match(prefix: "/re") == [.review]) } + @Test("invocation splits any typed command into its name and the text after it") + func invocationSplitsNameAndBody() { + let custom = SlashCommand.invocation(in: " /Summarize last week's orders ") + #expect(custom?.name == "Summarize") + #expect(custom?.body == "last week's orders") + + let bare = SlashCommand.invocation(in: "/summarize") + #expect(bare?.name == "summarize") + #expect(bare?.body == "") + + let multiline = SlashCommand.invocation(in: "/summarize\norders\nby region") + #expect(multiline?.name == "summarize") + #expect(multiline?.body == "orders\nby region") + } + + @Test("invocation returns nil without a name after the slash") + func invocationRejectsMissingName() { + #expect(SlashCommand.invocation(in: "summarize this") == nil) + #expect(SlashCommand.invocation(in: "/") == nil) + #expect(SlashCommand.invocation(in: "/ summarize") == nil) + #expect(SlashCommand.invocation(in: "") == nil) + } + + @Test("A body on its own line reaches a built-in without the line break") + func parseDropsLeadingNewlineFromBody() { + #expect(SlashCommand.parse("/explain\nSELECT 1")?.body == "SELECT 1") + } + @Test("Built-in names are recognised whatever their case or padding") func builtInNames() { #expect(SlashCommand.isBuiltIn(name: "review")) diff --git a/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift b/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift index f9aa71cb7a..2f991531ac 100644 --- a/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift +++ b/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift @@ -6,6 +6,7 @@ import Foundation @testable import TablePro import TableProPluginKit +import TableProTestSupport import Testing @MainActor @@ -98,6 +99,48 @@ struct AIChatViewModelSlashTests { #expect(vm.errorMessage == nil) } + @Test("A typed custom command runs with the text after its name as {{body}}") + func typedCustomCommandFillsBody() async throws { + let vm = AIChatViewModel() + let command = CustomSlashCommand(name: "summarize", promptTemplate: "Summarize: {{body}}") + vm.customSlashCommandNamed = { name in + name.caseInsensitiveCompare(command.name) == .orderedSame ? command : nil + } + vm.inputText = "/Summarize last week's orders" + + vm.sendMessage() + + #expect(vm.inputText.isEmpty) + try await waitUntil { + vm.messages.contains { turn in turn.plainText == "Summarize: last week's orders" } + } + let firstUserTurn = vm.messages.first { turn in turn.role == .user } + #expect(firstUserTurn?.plainText == "/summarize last week's orders") + } + + @Test("Typing a built-in name runs the built-in even when a custom command shares it") + func typedBuiltInWinsOverCustom() { + let vm = AIChatViewModel() + vm.customSlashCommandNamed = { _ in CustomSlashCommand(name: "help", promptTemplate: "Custom {{body}}") } + vm.inputText = "/help" + + vm.sendMessage() + + let assistant = vm.messages.last { turn in turn.role == .assistant } + #expect(assistant?.plainText.contains("Available commands") == true) + } + + @Test("A slash word that names no command is sent as an ordinary message") + func unknownSlashWordIsAMessage() { + let vm = AIChatViewModel() + vm.customSlashCommandNamed = { _ in nil } + vm.inputText = "/etc/hosts is missing" + + vm.sendMessage() + + #expect(vm.messages.first?.plainText == "/etc/hosts is missing") + } + @Test("A custom command's turn ranks tables by its body, not by the schema it rendered") func customCommandRanksByBody() { let rendered = ChatTurn(role: .user, blocks: [.text("Schema:\n- customers\n - customer_id\nlist the logs")]) From 3b4072fbfc00a57b3c9a63c2e56a40a07e6410e3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 16:25:07 +0700 Subject: [PATCH 21/48] fix(connection-form): show AI Policy while AI is off and the real global query timeout --- .../Panes/OptionsPaneView.swift | 77 ++++++++++--------- .../OptionsPaneQueryTimeoutTests.swift | 44 +++++++++++ 2 files changed, 84 insertions(+), 37 deletions(-) create mode 100644 apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift diff --git a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift index 3bd7c4acd5..fc86b88662 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift @@ -68,13 +68,13 @@ struct OptionsPaneView: View { } .help(connectTimeoutHelp) - LabeledContent(String(localized: "Query timeout")) { + LabeledContent { HStack(spacing: 4) { TextField( String(localized: "Query timeout"), value: $coordinator.customization.queryTimeoutSeconds, format: .number.grouping(.never), - prompt: Text(verbatim: queryTimeoutPlaceholder) + prompt: Text(verbatim: Self.queryTimeoutPlaceholder(globalSeconds: globalQueryTimeoutSeconds)) ) .labelsHidden() .frame(width: 100) @@ -83,8 +83,10 @@ struct OptionsPaneView: View { Text(String(localized: "seconds")) .foregroundStyle(.secondary) } + } label: { + Text(String(localized: "Query timeout")) + Text(verbatim: Self.queryTimeoutInheritance(globalSeconds: globalQueryTimeoutSeconds)) } - .help(queryTimeoutHelp) } header: { Text(String(localized: "Timeouts")) } footer: { @@ -116,28 +118,33 @@ struct OptionsPaneView: View { ) } - private var queryTimeoutPlaceholder: String { - String( - format: String(localized: "Global (%d)"), - settingsManager.general.queryTimeoutSeconds + private var globalQueryTimeoutSeconds: Int { settingsManager.general.queryTimeoutSeconds } + + // The field is 100 points wide beside a "seconds" label, so words go in the subtitle and the prompt stays short. + nonisolated static func queryTimeoutPlaceholder(globalSeconds: Int) -> String { + let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( + configuredSeconds: nil, + globalSeconds: globalSeconds ) + guard seconds > 0 else { return String(localized: "No limit") } + return String(format: String(localized: "Global (%d)"), seconds) } - private var queryTimeoutHelp: String { - let globalQueryTimeoutSeconds = settingsManager.general.queryTimeoutSeconds - guard globalQueryTimeoutSeconds > 0 else { - return String(localized: """ - Leave blank to use the global setting, which has no limit. \ - This setting applies only to database drivers that support it. - """) + nonisolated static func queryTimeoutInheritance( + globalSeconds: Int, + locale: Locale = .autoupdatingCurrent + ) -> String { + let seconds = ConnectionTimeoutPolicy.effectiveQueryTimeoutSeconds( + configuredSeconds: nil, + globalSeconds: globalSeconds + ) + guard seconds > 0 else { + return String(localized: "Leave blank to use Settings > Connections: no limit.") } - return String( - format: String(localized: """ - Leave blank to use the global %d-second timeout. \ - This setting applies only to database drivers that support it. - """), - globalQueryTimeoutSeconds + let duration = Duration.seconds(seconds).formatted( + .units(allowed: [.hours, .minutes, .seconds], width: .wide).locale(locale) ) + return String(format: String(localized: "Leave blank to use Settings > Connections: %@."), duration) } // MARK: - Binary values @@ -356,15 +363,16 @@ struct OptionsPaneView: View { safeModeRow Toggle(String(localized: "Manual Commit"), isOn: $coordinator.effectiveManualCommit) .disabled(!coordinator.isManualCommitAvailable) - if aiIsEnabled { - Picker(String(localized: "AI Policy"), selection: $coordinator.advanced.aiPolicy) { - Text(String(localized: "Use Default")) - .tag(AIConnectionPolicy?.none as AIConnectionPolicy?) - ForEach(AIConnectionPolicy.allCases) { policy in - Text(policy.displayName) - .tag(AIConnectionPolicy?.some(policy) as AIConnectionPolicy?) - } + // MCP enforces the policy whether or not AI features are on, so it stays editable. + Picker(String(localized: "AI Policy"), selection: $coordinator.advanced.aiPolicy) { + Text(String(localized: "Use Default")) + .tag(AIConnectionPolicy?.none as AIConnectionPolicy?) + ForEach(AIConnectionPolicy.allCases) { policy in + Text(policy.displayName) + .tag(AIConnectionPolicy?.some(policy) as AIConnectionPolicy?) } + } + if aiIsEnabled { ForEach(coordinator.advanced.aiAlwaysAllowedTools, id: \.self) { tool in alwaysAllowedRow(tool) } @@ -420,15 +428,10 @@ struct OptionsPaneView: View { } else { Text(ManualCommit.unavailableExplanation) } - if aiIsEnabled { - // swiftlint:disable:next line_length - Text(String(localized: "AI Policy controls in-app AI agents. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level.")) - if !coordinator.advanced.aiAlwaysAllowedTools.isEmpty { - Text(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) - } - } else { - // swiftlint:disable:next line_length - Text(String(localized: "Controls how external clients (Raycast, Cursor, Claude Desktop, AppleScript, Shortcuts) access this connection. Tokens cannot exceed this level even with full-access scope.")) + // swiftlint:disable:next line_length + Text(String(localized: "AI Policy applies to AI features and MCP clients. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level.")) + if aiIsEnabled, !coordinator.advanced.aiAlwaysAllowedTools.isEmpty { + Text(String(localized: "Always Allow on an assistant tool card adds the tool here. Forget makes its next call ask again.")) } if coordinator.advanced.externalAccess == .readOnly { Text( diff --git a/apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift b/apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift new file mode 100644 index 0000000000..973b9f272d --- /dev/null +++ b/apple/TableProTests/Views/ConnectionForm/OptionsPaneQueryTimeoutTests.swift @@ -0,0 +1,44 @@ +import Foundation +@testable import TablePro +import Testing + +struct OptionsPaneQueryTimeoutTests { + private let english = Locale(identifier: "en_US") + + @Test("No global limit reads as no limit, never as zero") + func zeroReadsAsNoLimit() { + #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 0) == "No limit") + #expect( + OptionsPaneView.queryTimeoutInheritance(globalSeconds: 0, locale: english) + == "Leave blank to use Settings > Connections: no limit." + ) + } + + @Test("A global limit reads as a duration in words", arguments: [ + (1, "1 second"), + (60, "1 minute"), + (90, "1 minute, 30 seconds"), + (300, "5 minutes"), + (3_600, "1 hour") + ]) + func limitReadsAsDuration(seconds: Int, words: String) { + #expect( + OptionsPaneView.queryTimeoutInheritance(globalSeconds: seconds, locale: english) + == "Leave blank to use Settings > Connections: \(words)." + ) + } + + @Test("The prompt inside the seconds field keeps the number") + func placeholderKeepsSeconds() { + #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 60) == "Global (60)") + } + + @Test("An out-of-range global value shows what a connection actually gets") + func outOfRangeGlobalIsClamped() { + #expect(OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: -5) == "No limit") + #expect( + OptionsPaneView.queryTimeoutPlaceholder(globalSeconds: 9_999_999) + == "Global (\(DatabaseConnection.queryTimeoutSecondsRange.upperBound))" + ) + } +} From 90985e3d559c5829a689cc6ce5d2d15c44bcfd1e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 17:46:51 +0700 Subject: [PATCH 22/48] fix(settings): keep the list add/remove bar inside the bordered list --- .../Components/SettingsFullPageList.swift | 30 ++- .../Settings/Components/SettingsListBar.swift | 253 ++++++++++++++---- .../Settings/SettingsFullPageListTests.swift | 246 +++++++++++++++++ 3 files changed, 473 insertions(+), 56 deletions(-) create mode 100644 apple/TableProTests/Views/Settings/SettingsFullPageListTests.swift diff --git a/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift index 9fe9a42a6d..ab753adf2c 100644 --- a/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift +++ b/apple/TablePro/Views/Settings/Components/SettingsFullPageList.swift @@ -1,7 +1,10 @@ +import AppKit import SwiftUI // Not a grouped Form: a List inside one does not scroll. struct SettingsFullPageList: View { + private static var borderWidth: CGFloat { 1 } + private let content: Content private let emptyState: EmptyState private let bar: Bar @@ -17,14 +20,27 @@ struct SettingsFullPageList: View { } var body: some View { - VStack(alignment: .leading, spacing: 6) { - content - .listStyle(.bordered(alternatesRowBackgrounds: false)) - .frame(maxHeight: .infinity) - .overlay { emptyState } + list + .frame(maxHeight: .infinity) + .padding(20) + } + + @ViewBuilder + private var list: some View { + let bordered = content + .listStyle(.bordered(alternatesRowBackgrounds: false)) + .overlay { emptyState } - bar + if Bar.self == EmptyView.self { + bordered + } else { + // An inset, unlike the .listBar overlay, scrolls the last row clear of the bar. + bordered.safeAreaInset(edge: .bottom, spacing: 0) { + ListBar { bar } + // Rows scroll under the bar, so it needs the list's fill, kept inside the border. + .background(Color(nsColor: .controlBackgroundColor)) + .padding([.horizontal, .bottom], Self.borderWidth) + } } - .padding(20) } } diff --git a/apple/TablePro/Views/Settings/Components/SettingsListBar.swift b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift index 34ad28567a..ce3b27fc76 100644 --- a/apple/TablePro/Views/Settings/Components/SettingsListBar.swift +++ b/apple/TablePro/Views/Settings/Components/SettingsListBar.swift @@ -1,13 +1,50 @@ +import AppKit import SwiftUI -struct SettingsListBar: View { - private let addRemove: AddRemoveControlGroup? +// Only the row: SettingsFullPageList draws the bar's divider and fill inside the list's border. +struct SettingsListBar: View { + private struct AddRemove { + let addLabel: String + let removeLabel: String + let canAdd: Bool + let canRemove: Bool + let addHelp: String? + let removeHelp: String? + let addIdentifier: String? + let removeIdentifier: String? + // nil when + opens the add menu. + let onAdd: (() -> Void)? + let onRemove: () -> Void + } + + private static var slotInset: CGFloat { 8 } + + private let addRemove: AddRemove? + private let addMenu: AddMenu private let actionsLabel: String private let actionsIdentifier: String? private let actions: Actions private let leading: Leading private let trailing: Trailing + private init( + addRemove: AddRemove?, + addMenu: AddMenu, + actionsLabel: String, + actionsIdentifier: String?, + actions: Actions, + leading: Leading, + trailing: Trailing + ) { + self.addRemove = addRemove + self.addMenu = addMenu + self.actionsLabel = actionsLabel + self.actionsIdentifier = actionsIdentifier + self.actions = actions + self.leading = leading + self.trailing = trailing + } + init( addLabel: String, removeLabel: String, @@ -17,7 +54,7 @@ struct SettingsListBar: View { removeHelp: String? = nil, addIdentifier: String? = nil, removeIdentifier: String? = nil, - onAdd: @escaping () -> Void, + @ViewBuilder addMenu: () -> AddMenu, onRemove: @escaping () -> Void, actionsLabel: String = String(localized: "Actions"), actionsIdentifier: String? = nil, @@ -25,73 +62,191 @@ struct SettingsListBar: View { @ViewBuilder leading: () -> Leading = { EmptyView() }, @ViewBuilder trailing: () -> Trailing = { EmptyView() } ) { - addRemove = AddRemoveControlGroup( - addLabel: addLabel, - removeLabel: removeLabel, - canAdd: canAdd, - canRemove: canRemove, - addHelp: addHelp, - removeHelp: removeHelp, - addIdentifier: addIdentifier, - removeIdentifier: removeIdentifier, - onAdd: onAdd, - onRemove: onRemove + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: nil, + onRemove: onRemove + ), + addMenu: addMenu(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() ) - self.actionsLabel = actionsLabel - self.actionsIdentifier = actionsIdentifier - self.actions = actions() - self.leading = leading() - self.trailing = trailing() - } - - init( - actionsLabel: String = String(localized: "Actions"), - actionsIdentifier: String? = nil, - @ViewBuilder actions: () -> Actions = { EmptyView() }, - @ViewBuilder leading: () -> Leading = { EmptyView() }, - @ViewBuilder trailing: () -> Trailing = { EmptyView() } - ) { - addRemove = nil - self.actionsLabel = actionsLabel - self.actionsIdentifier = actionsIdentifier - self.actions = actions() - self.leading = leading() - self.trailing = trailing() } var body: some View { - HStack(spacing: 8) { + HStack(spacing: 0) { if let addRemove { - addRemove + addControl(addRemove) + ListBarSeparator() + ListBarButton( + label: addRemove.removeLabel, + systemImage: "minus", + help: addRemove.removeHelp, + identifier: addRemove.removeIdentifier, + action: addRemove.onRemove + ) + .disabled(!addRemove.canRemove) } - if Actions.self != EmptyView.self { - actionsMenu + if Self.isPresent(Actions.self) { + if addRemove != nil { + ListBarSeparator() + } + SettingsListBarMenu( + label: actionsLabel, + systemImage: "ellipsis.circle", + help: nil, + identifier: actionsIdentifier + ) { + actions + } } - leading + if Self.isPresent(Leading.self) { + slot(leading) + } Spacer(minLength: 0) - trailing + if Self.isPresent(Trailing.self) { + slot(trailing) + .fixedSize() + } + } + } + + @ViewBuilder + private func addControl(_ addRemove: AddRemove) -> some View { + if let onAdd = addRemove.onAdd { + ListBarButton( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier, + action: onAdd + ) + .disabled(!addRemove.canAdd) + } else { + SettingsListBarMenu( + label: addRemove.addLabel, + systemImage: "plus", + help: addRemove.addHelp, + identifier: addRemove.addIdentifier + ) { + addMenu + } + .disabled(!addRemove.canAdd) } } - // A label inside an icon-only Menu's label closure leaves VoiceOver reading "More"; .contain plus a label on the menu names it. - private var actionsMenu: some View { + // A regular push button is taller than the 23pt bar. + private func slot(_ content: some View) -> some View { + content + .font(.subheadline) + .controlSize(.small) + .lineLimit(1) + .padding(.horizontal, Self.slotInset) + } + + private static func isPresent(_: V.Type) -> Bool { + V.self != EmptyView.self + } +} + +extension SettingsListBar where AddMenu == EmptyView { + init( + addLabel: String, + removeLabel: String, + canAdd: Bool = true, + canRemove: Bool = true, + addHelp: String? = nil, + removeHelp: String? = nil, + addIdentifier: String? = nil, + removeIdentifier: String? = nil, + onAdd: @escaping () -> Void, + onRemove: @escaping () -> Void, + actionsLabel: String = String(localized: "Actions"), + actionsIdentifier: String? = nil, + @ViewBuilder actions: () -> Actions = { EmptyView() }, + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: AddRemove( + addLabel: addLabel, + removeLabel: removeLabel, + canAdd: canAdd, + canRemove: canRemove, + addHelp: addHelp, + removeHelp: removeHelp, + addIdentifier: addIdentifier, + removeIdentifier: removeIdentifier, + onAdd: onAdd, + onRemove: onRemove + ), + addMenu: EmptyView(), + actionsLabel: actionsLabel, + actionsIdentifier: actionsIdentifier, + actions: actions(), + leading: leading(), + trailing: trailing() + ) + } +} + +extension SettingsListBar where AddMenu == EmptyView, Actions == EmptyView { + init( + @ViewBuilder leading: () -> Leading = { EmptyView() }, + @ViewBuilder trailing: () -> Trailing = { EmptyView() } + ) { + self.init( + addRemove: nil, + addMenu: EmptyView(), + actionsLabel: "", + actionsIdentifier: nil, + actions: EmptyView(), + leading: leading(), + trailing: trailing() + ) + } +} + +private struct SettingsListBarMenu: View { + let label: String + let systemImage: String + let help: String? + let identifier: String? + @ViewBuilder let items: Items + + var body: some View { Menu { - actions + items } label: { - Label(actionsLabel, systemImage: "ellipsis.circle") + Label(label, systemImage: systemImage) .labelStyle(.iconOnly) + .font(.system(size: NSFont.smallSystemFontSize)) + .foregroundStyle(.secondary) + .frame(width: ListBarMetrics.buttonWidth, height: ListBarMetrics.contentHeight) + .contentShape(Rectangle()) } + // Plain, not borderless: a borderless menu is an NSPopUpButton that ignores this label's font, color and frame. .menuStyle(.button) - .buttonStyle(.borderless) + .buttonStyle(.plain) .menuIndicator(.hidden) .fixedSize() - .help(actionsLabel) - .accessibilityElement(children: .contain) - .accessibilityLabel(actionsLabel) - .accessibilityIdentifier(actionsIdentifier ?? "") + .help(help ?? label) + .accessibilityLabel(label) + .accessibilityIdentifier(identifier ?? "") } } diff --git a/apple/TableProTests/Views/Settings/SettingsFullPageListTests.swift b/apple/TableProTests/Views/Settings/SettingsFullPageListTests.swift new file mode 100644 index 0000000000..573a29456e --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsFullPageListTests.swift @@ -0,0 +1,246 @@ +import AppKit +import ApplicationServices +@testable import TablePro +import SwiftUI +import TableProTestSupport +import Testing + +@MainActor +struct SettingsFullPageListTests { + private enum BarShape { + case none + case addMenu(canAdd: Bool) + case status + } + + private struct Page: View { + static let rowCount = 40 + + let shape: BarShape + @State private var selection: Int? + + var body: some View { + switch shape { + case .none: + SettingsFullPageList { list } + case .addMenu(let canAdd): + SettingsFullPageList { + list + } bar: { + SettingsListBar( + addLabel: "Add Row", + removeLabel: "Remove Row", + canAdd: canAdd, + addIdentifier: "list-bar-test-add", + removeIdentifier: "list-bar-test-remove", + addMenu: { Button(action: {}) { Text(verbatim: "Import") } }, + onRemove: {}, + actionsLabel: "Row Actions", + actionsIdentifier: "list-bar-test-actions" + ) { + Button(action: {}) { Text(verbatim: "Duplicate") } + } + } + case .status: + SettingsFullPageList { + list + } bar: { + SettingsListBar { + Text(verbatim: "3 customized") + } trailing: { + Button(action: {}) { Text(verbatim: "Restore Defaults") } + .accessibilityIdentifier("list-bar-test-restore") + } + } + } + } + + private var list: some View { + List(selection: $selection) { + ForEach(0.. NSRect { + let row = table.rect(ofRow: table.numberOfRows - 1) + return window.convertToScreen(table.convert(row, to: nil)) + } + } + + private static func host(_ shape: BarShape) async throws -> Hosted { + let size = NSSize(width: 480, height: 360) + let window = NSWindow( + contentRect: NSRect(origin: .zero, size: size), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + // A title of its own, so the accessibility lookup never reaches an earlier case's window. + window.title = "SettingsFullPageListTests \(UUID().uuidString)" + let hosting = NSHostingController(rootView: Page(shape: shape)) + hosting.sizingOptions = [] + window.contentViewController = hosting + window.setContentSize(size) + window.orderFront(nil) + + let content = try #require(window.contentView) + // The table fills its rows before its scroll view is laid out. + try await waitUntil { (listTable(in: content)?.enclosingScrollView?.frame.height ?? 0) > 0 } + let table = try #require(listTable(in: content)) + let scrollView = try #require(table.enclosingScrollView) + return Hosted(window: window, table: table, scrollView: scrollView) + } + + private static func listTable(in view: NSView) -> NSTableView? { + var pending = [view] + while let next = pending.popLast() { + if let table = next as? NSTableView, table.numberOfRows == Page.rowCount { + return table + } + pending.append(contentsOf: next.subviews) + } + return nil + } + + private static func attribute(_ name: String, of element: AXUIElement) -> CFTypeRef? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { return nil } + return value + } + + private static func element(_ identifier: String, under element: AXUIElement) -> AXUIElement? { + if attribute("AXIdentifier", of: element) as? String == identifier { + return element + } + for child in attribute(kAXChildrenAttribute, of: element) as? [AXUIElement] ?? [] { + if let match = Self.element(identifier, under: child) { + return match + } + } + return nil + } + + private static func element(_ identifier: String, inWindowTitled title: String) -> AXUIElement? { + let windows = attribute(kAXWindowsAttribute, of: AXUIElementCreateApplication(getpid())) as? [AXUIElement] ?? [] + guard let window = windows.first(where: { attribute(kAXTitleAttribute, of: $0) as? String == title }) else { + return nil + } + return element(identifier, under: window) + } + + private static func waitForElement(_ identifier: String, in hosted: Hosted) async throws -> AXUIElement { + let title = hosted.window.title + try await waitUntil { element(identifier, inWindowTitled: title) != nil } + return try #require(element(identifier, inWindowTitled: title)) + } + + private static func axValue(_ name: String, of element: AXUIElement) -> AXValue? { + guard let raw = attribute(name, of: element), CFGetTypeID(raw) == AXValueGetTypeID() else { return nil } + return unsafeDowncast(raw, to: AXValue.self) + } + + // AX counts y down from the top of the primary screen; AppKit counts up from its bottom. + private static func frame(of element: AXUIElement) throws -> NSRect { + let positionValue = try #require(axValue(kAXPositionAttribute, of: element)) + let sizeValue = try #require(axValue(kAXSizeAttribute, of: element)) + var position = CGPoint.zero + var size = CGSize.zero + let readPosition = AXValueGetValue(positionValue, .cgPoint, &position) + let readSize = AXValueGetValue(sizeValue, .cgSize, &size) + try #require(readPosition && readSize) + let screenHeight = try #require(NSScreen.screens.first).frame.height + return NSRect(x: position.x, y: screenHeight - position.y - size.height, width: size.width, height: size.height) + } + + private static func name(of element: AXUIElement) -> [String] { + [kAXTitleAttribute, kAXDescriptionAttribute].compactMap { attribute($0, of: element) as? String } + } + + @Test("The bar sits on the list's bottom edge, inside its border") + func barSitsInsideTheBorder() async throws { + let hosted = try await Self.host(.addMenu(canAdd: true)) + defer { hosted.window.orderOut(nil) } + + let removeElement = try await Self.waitForElement("list-bar-test-remove", in: hosted) + let remove = try Self.frame(of: removeElement) + let border = hosted.scrollViewFrame + #expect(border.insetBy(dx: -hosted.tolerance, dy: -hosted.tolerance).contains(remove), "\(remove) should sit inside \(border)") + #expect(remove.minY - border.minY < ListBarMetrics.height, "The bar should sit on the list's bottom edge") + #expect(hosted.scrollView.contentInsets.bottom >= ListBarMetrics.height) + } + + @Test("Scrolled to the end, the last row sits above the bar") + func lastRowScrollsClearOfTheBar() async throws { + let hosted = try await Self.host(.addMenu(canAdd: true)) + defer { hosted.window.orderOut(nil) } + + let removeElement = try await Self.waitForElement("list-bar-test-remove", in: hosted) + let remove = try Self.frame(of: removeElement) + hosted.scrollToEnd() + let lastRow = hosted.lastRowFrame() + #expect(lastRow.minY >= remove.maxY - hosted.tolerance, "Last row \(lastRow) runs under the bar at \(remove)") + } + + @Test("The add and actions menus are named menu buttons, and the add menu follows canAdd") + func glyphMenusAreNamedMenuButtons() async throws { + let hosted = try await Self.host(.addMenu(canAdd: false)) + defer { hosted.window.orderOut(nil) } + + let add = try await Self.waitForElement("list-bar-test-add", in: hosted) + #expect(Self.attribute(kAXRoleAttribute, of: add) as? String == kAXMenuButtonRole) + #expect(Self.name(of: add).contains("Add Row")) + #expect(Self.attribute(kAXEnabledAttribute, of: add) as? Bool == false) + + let actions = try await Self.waitForElement("list-bar-test-actions", in: hosted) + #expect(Self.attribute(kAXRoleAttribute, of: actions) as? String == kAXMenuButtonRole) + #expect(Self.name(of: actions).contains("Row Actions")) + #expect(Self.attribute(kAXEnabledAttribute, of: actions) as? Bool == true) + } + + @Test("A bar without + and − keeps its trailing button inside the border") + func statusBarKeepsItsButtonInside() async throws { + let hosted = try await Self.host(.status) + defer { hosted.window.orderOut(nil) } + + let restoreElement = try await Self.waitForElement("list-bar-test-restore", in: hosted) + let restore = try Self.frame(of: restoreElement) + let border = hosted.scrollViewFrame + #expect(border.insetBy(dx: -hosted.tolerance, dy: -hosted.tolerance).contains(restore), "\(restore) should sit inside \(border)") + #expect(restore.minY - border.minY < ListBarMetrics.height, "The button should sit in the bar") + } + + @Test("Without a bar, the last row scrolls down to the list's bottom edge") + func noBarLeavesNoGap() async throws { + let hosted = try await Self.host(.none) + defer { hosted.window.orderOut(nil) } + + hosted.scrollToEnd() + let gap = hosted.lastRowFrame().minY - hosted.scrollViewFrame.minY + #expect(gap < ListBarMetrics.height, "Scrolled to the end, \(gap)pt stays empty under the last row") + #expect(hosted.scrollView.contentInsets.bottom == 0) + } +} From 6078ba06945a3b4ebe7f98a88e92543020e6077e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 17:46:52 +0700 Subject: [PATCH 23/48] perf(settings): observe per-category settings slices app-wide Picking a {{body}} slash command from the chat menu now puts "/name " in the composer instead of running it with an empty body. --- .../WorkspaceRailViewController.swift | 193 ++++-------------- .../Models/UI/SidebarDisplayPreferences.swift | 38 ++++ .../Views/AIChat/AIChatPanelView.swift | 86 ++++---- .../Components/PaginationControlsView.swift | 60 ++---- .../Components/SQLStatementPreview.swift | 14 +- .../Panes/OptionsPaneView.swift | 37 +--- .../Editor/QueryEditorPaneController.swift | 14 +- .../Views/Import/SQLCodePreview.swift | 15 +- .../Main/Child/MainEditorContentView.swift | 48 +---- .../Results/ColumnVisibilityPopover.swift | 9 +- .../Results/ExecutionIndicatorView.swift | 42 +--- .../Views/Results/JSONCodeEditor.swift | 16 +- .../Views/Results/ResultStatusBar.swift | 104 ++-------- .../Views/Results/ValueSourceEditor.swift | 9 +- .../FieldEditors/MultiLineEditorView.swift | 9 +- .../Views/RowInspector/TableInfoView.swift | 9 +- .../RowInspector/TrailingPaneHeaderView.swift | 58 +----- .../Sidebar/DatabaseTreeFilterPopover.swift | 9 +- .../DatabaseTreeOutlineCoordinator.swift | 167 ++++----------- .../Views/Sidebar/DatabaseTreeRowView.swift | 76 +++---- .../Views/Sidebar/DatabaseTreeView.swift | 19 +- .../Views/Sidebar/FavoritesTabView.swift | 52 ++--- .../Views/Sidebar/RoutineRowView.swift | 10 +- .../Views/Sidebar/ServerObjectRowView.swift | 24 ++- .../Views/Sidebar/SidebarFilterBanner.swift | 13 +- .../Views/Sidebar/SidebarTreeView.swift | 17 +- .../TablePro/Views/Sidebar/SidebarView.swift | 49 ++--- .../TablePro/Views/Sidebar/TableRowView.swift | 22 +- .../Views/Sidebar/TriggerRowView.swift | 12 +- .../Views/Sidebar/UserTypeRowView.swift | 12 +- .../Views/Structure/DDLTextView.swift | 14 +- .../Views/Structure/TriggerEditorView.swift | 12 +- .../UI/SidebarDisplayPreferencesTests.swift | 90 ++++++++ .../AIChat/CustomSlashCommandPickTests.swift | 48 +++++ 34 files changed, 484 insertions(+), 923 deletions(-) create mode 100644 apple/TablePro/Models/UI/SidebarDisplayPreferences.swift create mode 100644 apple/TableProTests/Models/UI/SidebarDisplayPreferencesTests.swift create mode 100644 apple/TableProTests/Views/AIChat/CustomSlashCommandPickTests.swift diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift index d9fc7ad0cd..b952021515 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspaceRailViewController.swift @@ -1,8 +1,3 @@ -// -// WorkspaceRailViewController.swift -// TablePro -// - import AppKit import Combine import Observation @@ -10,11 +5,7 @@ import os import OSLog import TableProConnectionLibrary -/// The window a rail belongs to. A window hosts several connections and shows one at a time, so -/// which row the rail highlights is a question only the window can answer, and the answer changes. -/// The rail used to capture the connection its window was created for, which could name the right -/// row exactly once: after the window switched to a second connection the rail kept highlighting -/// the first, and clicking the row it was already standing on did nothing. +// Only the window knows which of its connections is on screen, so the rail asks rather than capturing one. @MainActor internal protocol WorkspaceRailHost: AnyObject { var hostedConnectionIds: [UUID] { get } @@ -22,20 +13,12 @@ internal protocol WorkspaceRailHost: AnyObject { func selectHostedConnection(_ connectionId: UUID) } -/// Middle-click closes the row under the pointer, which is what a list of open things does -/// everywhere it exists: browser tabs, and every database client surveyed. `NSTableView` routes no -/// action for the tertiary button, so the row is resolved from the click point the same way -/// `menu(for:)` resolves one. -/// -/// The table owns its own look, so a test hosting it gets the configuration the strip really ships -/// with: a source list rewrites cells and pads rows in ways a free-standing cell never shows. +// AppKit table on purpose: `NSTableView` routes no middle-click, and a source list pads rows a free cell never shows. @MainActor internal final class WorkspaceRailTableView: NSTableView { internal var onMiddleClick: ((Int) -> Void)? - /// Set by the window's rule the moment the strip is told to hide. AppKit hides a collapsing split - /// item only once its animation ends, and until then the list kept its full frame, so a window - /// first shown during that animation picked it as its first key view. + // Set the moment the strip hides: AppKit hides a collapsing item only after its animation, so the list could take first key view. internal var isStripShown = true override internal var canBecomeKeyView: Bool { @@ -53,8 +36,7 @@ internal final class WorkspaceRailTableView: NSTableView { backgroundColor = .clear allowsMultipleSelection = false allowsEmptySelection = true - /// A source list draws the selection over the spacing too, so spacing would only pad the - /// inside of the fill. The tile's own padding is what separates one entry from the next. + // A source list draws the selection over the spacing, so the tile's own padding separates entries. intercellSpacing = NSSize(width: 0, height: 0) } @@ -63,9 +45,7 @@ internal final class WorkspaceRailTableView: NSTableView { fatalError("WorkspaceRailTableView does not support NSCoder init") } - /// Read from the rows themselves, because where they start is the source list's to decide: it - /// pads the first one down from the document's top, and a model that assumed otherwise is what - /// left a slice of the previous tile showing. + // Read from the rows: the source list pads the first one down from the document's top. internal func scrollGeometry(viewportHeight: CGFloat) -> WorkspaceRailScrollGeometry { let first = numberOfRows > 0 ? rect(ofRow: 0) : .zero return WorkspaceRailScrollGeometry( @@ -113,10 +93,7 @@ internal final class WorkspaceRailViewController: NSViewController { private let scrollView = NSScrollView() private let tableView = WorkspaceRailTableView() - /// `rowSizeStyle` is the only route to the sidebar icon size preference, but any value - /// other than `.custom` makes the table impose the system row height and ignore - /// `heightOfRow`, which the rail's stacked cell needs. This unattached table lets AppKit - /// resolve the preference so the rail itself can stay `.custom`. + // Resolves the sidebar icon size; anything but `.custom` on the rail itself would ignore `heightOfRow`. private let rowSizeProbe = NSTableView() private var entries: [WorkspaceRailEntry] = [] @@ -131,22 +108,15 @@ internal final class WorkspaceRailViewController: NSViewController { private let scrollObserver = OSAllocatedUnfairLock<(any NSObjectProtocol)?>(uncheckedState: nil) private var contentTopConstraint: NSLayoutConstraint? - /// A scroll is settled once it has stopped changing, which is the only signal every input - /// device gives. `NSScrollViewWillStartLiveScroll`/`DidEndLiveScroll` would be the obvious pair, - /// and `NSScrollView.h` says outright that a legacy mouse is not bracketed by them, which is the - /// device most likely to leave the strip resting mid-tile. + // Settled once the scroll stops changing: a legacy mouse never posts the live-scroll pair. private var scrollSettle: DispatchWorkItem? - /// A reorder scrolls the strip itself as the pointer nears an edge, so settling during one would - /// fight the drag it is reacting to. + // A reorder autoscrolls the strip, so settling during one would fight the drag. private var isReordering = false private var needsSelectionReveal = false - /// What the rail last put on screen as selected, which after every `applySelection` is the - /// workspace the host is really showing. A commit for that same workspace has nothing to do, - /// and is the case the arrow keys hit constantly as they move the highlight across a row the - /// window is already on. + // A commit for the workspace already applied has nothing to do, which is what the arrow keys hit constantly. private var appliedSelection: WorkspaceID? internal init() { @@ -187,10 +157,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollView.autohidesScrollers = true scrollView.hasHorizontalScroller = false scrollView.drawsBackground = false - /// The bottom inset is the rail's own, and `contentInsets` and the automatic flag are one - /// property: writing the inset clears the flag anyway, so it is cleared here where it can be - /// read. Nothing is given up, because the automatic inset reads the scroll view's own safe - /// area, which `pinContentBelowTitleBar` has already reduced to nothing. + // Writing `contentInsets` clears the automatic flag anyway, and the safe area here is already zero. scrollView.automaticallyAdjustsContentInsets = false scrollView.contentView.postsBoundsChangedNotifications = true scrollView.translatesAutoresizingMaskIntoConstraints = false @@ -204,10 +171,7 @@ internal final class WorkspaceRailViewController: NSViewController { pinContentBelowTitleBar() } - /// The rail is a full-height sidebar, so AppKit gives it a top safe-area inset that - /// clears the window buttons and does not move when the native tab bar appears. - /// Anchoring to `NSWindow.contentLayoutGuide` instead tracked the tab bar and made the - /// rail jump between workspaces with different tab counts. + // The safe-area inset clears the window buttons and stays put when the native tab bar appears; the content layout guide did not. private func pinContentBelowTitleBar() { contentTopConstraint?.isActive = false let constraint = scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) @@ -227,9 +191,7 @@ internal final class WorkspaceRailViewController: NSViewController { .sink { [weak self] _ in self?.reload() } - /// Changing the Appearance setting means leaving TablePro and coming back, and AppKit - /// publishes that. `effectiveRowSizeStyle` is then re-read, which is the documented way to - /// ask what the system resolved. The undocumented defaults key this used to observe is gone. + // An Appearance change happens outside the app, so the system row size is re-read on return. let observer = NotificationCenter.default.addObserver( forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main ) { [weak self] _ in @@ -252,9 +214,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollObserver.withLockUnchecked { $0 = observer } } - /// Re-armed on every bounds change, so the strip settles once the scrolling stops rather than - /// once per frame of it. Settling itself changes the bounds, which comes back through here and - /// finds nothing left to do. + // Re-armed on every bounds change, so the strip settles once scrolling stops, not once per frame. private func scheduleScrollSettle() { scrollSettle?.cancel() let work = DispatchWorkItem { [weak self] in @@ -283,8 +243,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// Recomputed rather than set once, because the row count, the row height and the viewport all - /// move: an entry opens or closes, the sidebar icon size changes, the window resizes. + // Recomputed: the row count, the row height and the viewport all move. private var scrollGeometry: WorkspaceRailScrollGeometry { tableView.scrollGeometry(viewportHeight: scrollView.contentView.bounds.height) } @@ -295,12 +254,7 @@ internal final class WorkspaceRailViewController: NSViewController { scrollView.contentInsets = NSEdgeInsets(top: 0, left: 0, bottom: inset, right: 0) } - /// Asked for when the highlight moves, and held until the strip has a viewport to move inside. - /// - /// The rail is laid out after `viewDidLoad` has already applied the first selection, so the - /// clip view can still be zero high when the entry to show is below the fold. Nothing arrives - /// later to say so: `NSView.boundsDidChangeNotification` is not posted for a bounds change that - /// came from the frame resizing, and `NSTableView` does not reveal a selection it already holds. + // Held until the clip view has a height: no bounds notification follows a frame resize, and `NSTableView` never reveals a selection it already holds. private func requestSelectionReveal() { needsSelectionReveal = true revealSelectedRowIfNeeded() @@ -312,9 +266,7 @@ internal final class WorkspaceRailViewController: NSViewController { revealSelectedRow() } - /// Silent while the entry is already whole and on screen. Every rail lists every workspace, so - /// one window's change reloads all of them; the callers are the paths where the highlight - /// actually moved, so a strip whose own entry did not change stays where its window left it. + // Silent while the entry is whole on screen: every rail reloads on any window's change. private func revealSelectedRow() { let clipView = scrollView.contentView guard let origin = scrollGeometry.revealOrigin( @@ -340,8 +292,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// Reported from here rather than from the split view's resize callback, which runs before the - /// strip inside the item has taken its new width. + // Not the split view's resize callback, which runs before the strip has its new width. override func viewDidLayout() { super.viewDidLayout() tableView.sizeLastColumnToFit() @@ -352,8 +303,6 @@ internal final class WorkspaceRailViewController: NSViewController { onWidthChange?() } - // MARK: - Data - private func reload() { entries = WorkspaceRailStore.entries Self.logger.debug( @@ -386,19 +335,15 @@ internal final class WorkspaceRailViewController: NSViewController { "\(workspace.connectionId.uuidString.prefix(8)):\(workspace.container.isEmpty ? "-" : workspace.container)" } - /// Which window's rail a line came from. Every rail lists every workspace, so without this - /// a log of two connections switching back and forth cannot be attributed. + // Every rail lists every workspace, so a log line names which window's rail wrote it. private var railName: String { guard let connectionId = host?.selectedConnectionId else { return "none" } return String(connectionId.uuidString.prefix(8)) } - /// Re-arms itself, because `withObservationTracking` fires once per registration. private func observeRowSizePreference() { - /// `objectWillChange` covers every settings group, so the row size is compared here - /// to keep the rebuild as rare as the per-property tracking made it. var lastRowSize = AppSettingsManager.shared.general.sidebarRowSize - rowSizeObservation = AppSettingsManager.shared.onMainActorChange { [weak self] in + rowSizeObservation = AppSettingsManager.shared.generalSlice.onMainActorChange { [weak self] in let current = AppSettingsManager.shared.general.sidebarRowSize guard current != lastRowSize else { return } lastRowSize = current @@ -406,8 +351,7 @@ internal final class WorkspaceRailViewController: NSViewController { } } - /// The rail sits directly beside the object list, so it takes the same size. Following only the - /// system preference left the two disagreeing the moment the user set a size of their own. + // Same size as the object list beside it, including a size the user set. private var resolvedRowSizeStyle: NSTableView.RowSizeStyle { let preference = AppSettingsManager.shared.general.sidebarRowSize guard preference == .matchSystem else { @@ -424,19 +368,13 @@ internal final class WorkspaceRailViewController: NSViewController { tableView.reloadData() applyBottomInset() applySelection() - /// Every tile edge moved, and a scroll offset that moves nothing posts no bounds change, so - /// neither the settle nor the reveal would run on its own: the strip stayed mid-tile. + // A scroll offset that moves nothing posts no bounds change, so neither the settle nor the reveal would run on its own. requestSelectionReveal() scheduleScrollSettle() onLayoutChange?(resolved) } - /// Both halves move: the window switches which connection it shows, and that connection's tabs - /// switch which entry is in front. Neither can be captured at init. - /// - /// The entry this window shows, not the one the connection browses: a window a tab was torn off - /// into shares its connection's cursor with the window it came from, and highlighting the cursor - /// named an entry whose tabs that window was not showing. + // The entry this window shows, not the connection's browse cursor, which a torn-off window shares. private var activeWorkspace: WorkspaceID? { guard let connectionId = host?.selectedConnectionId else { return nil } if let shown = WindowManager.shared.coordinator(for: connectionId, in: view.window)? @@ -446,8 +384,7 @@ internal final class WorkspaceRailViewController: NSViewController { return WorkspaceRailStore.browsedWorkspace(for: connectionId) } - /// Called when the window changes which connection it is showing. The entry list is unchanged - /// by that, only which row is current, so this moves the highlight instead of reloading. + // The entry list is unchanged by a connection switch, so only the highlight moves. internal func refreshSelection() { applySelection() } @@ -483,32 +420,20 @@ internal final class WorkspaceRailViewController: NSViewController { requestSelectionReveal() } - // MARK: - Activation - @objc private func handleRowClick() { commit(row: tableView.clickedRow) } - /// Return opens the highlighted row, the same contract every AppKit list keeps. override func insertNewline(_ sender: Any?) { commit(row: tableView.selectedRow) } - /// Close means the entry highlighted here while the strip holds the keyboard, and the - /// connection when that entry is the only one it has. - /// - /// The selector is the window's, deliberately: `performClose:` reaching the responder chain - /// finds this implementation before the window's whenever the strip is focused, which is the - /// same mechanism that gives Cut and Copy a different meaning in each view. The window used to - /// ask whether the strip had focus and branch on the answer, which is this rule written out by - /// hand. + // Found before the window's `performClose:` whenever the strip is focused; closes the connection when the entry is its only one. @objc internal func performClose(_ sender: Any?) { guard let workspace = appliedSelection else { - /// Nothing highlighted means the strip has no entry to close, not that Close does - /// nothing: swallowing it here would leave the command dead in a window that has tabs, - /// which is the failure this whole route exists to prevent. + // Swallowing Close here would leave the command dead in a window that has tabs. view.window?.performClose(sender) return } @@ -518,8 +443,7 @@ internal final class WorkspaceRailViewController: NSViewController { private func commit(row: Int) { guard entries.indices.contains(row) else { return } let workspace = entries[row].workspace - /// The highlighted entry is clicked again to retry a switch that failed: its tabs are on - /// screen, but the object browser stayed where it was. + // Clicking the highlighted entry again retries a switch whose object browser stayed behind. guard workspace != appliedSelection || WorkspaceRailStore.browsedWorkspace(for: workspace.connectionId) != workspace else { @@ -581,19 +505,13 @@ internal final class WorkspaceRailViewController: NSViewController { return (window, host) } - /// Going to an entry of a connection: its tabs come forward, and the object tree follows to its - /// container once the switch lands. `BrowseCursorCoordinator.goToEntry` holds both halves, so the order cannot be got - /// wrong here. + // `BrowseCursorCoordinator.goToEntry` brings the tabs forward and moves the tree, in that order. private func moveBrowseCursor(of window: NSWindow, to workspace: WorkspaceID) { guard !workspace.container.isEmpty else { Self.logger.debug("moveBrowseCursor skipped: unnamed container") return } - /// Resolved by connection through the window that hosts it, never by window alone. - /// `coordinator(forWindow:)` answers with the window's selected workspace, so a row for any - /// other connection moved the browse cursor of the one on screen instead: it switched the - /// visible connection to a database named after a different one, or failed against a - /// database that connection does not have. + // By connection, never by window alone, which answers with the window's selected workspace. guard let coordinator = WindowManager.shared.coordinator(for: workspace.connectionId, in: window) else { Self.logger.error( """ @@ -607,8 +525,7 @@ internal final class WorkspaceRailViewController: NSViewController { coordinator.browseCursorCoordinator.goToEntry(workspace.container) } - /// The menu command is a commit, not a highlight: it names the workspace it goes to, so it - /// has to get there without a second keystroke. + // A commit, not a highlight: the command names where it goes. internal func activateWorkspace(offsetBy offset: Int) { guard let next = WorkspaceRailOrdering.cycled( in: entries.map(\.id), @@ -621,8 +538,6 @@ internal final class WorkspaceRailViewController: NSViewController { commit(row: row) } - // MARK: - Context Menu - private func contextMenu() -> NSMenu { let menu = NSMenu() menu.delegate = self @@ -683,12 +598,7 @@ internal final class WorkspaceRailViewController: NSViewController { close(workspace) } - /// Named for the rail rather than for the command, because `closeConnection(_:)` is the File - /// menu's own nil-target action on `MainSplitViewController`. `@objc` puts this in the - /// responder chain whatever its access level, and the rail sits ahead of the controller there, - /// so sharing the name meant the menu bar's Close Connection resolved here instead, found a - /// sender carrying no `representedObject`, and returned having done nothing at all. The rail's - /// own items set `target` explicitly, so nothing here depends on the selector's spelling. + // Not `closeConnection(_:)`: that is the File menu's nil-target action, and the rail sits ahead of its owner in the responder chain. @objc private func closeWorkspaceConnection(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID else { return } @@ -704,9 +614,7 @@ internal final class WorkspaceRailViewController: NSViewController { Task { await WorkspaceCloseAction.close(workspace) } } - /// Named after what the engine calls a container, not after the row. "Close “logs”" would read - /// as the connection on the one key the app already uses for exactly that, and its translations - /// say so: the Turkish for `Close “%@”` is "close %@'s connection". + // Named after the container: "Close %@" reads as closing the connection in some languages. internal static func containerCloseTitle(for entry: WorkspaceRailEntry) -> String { let format = entry.containerTarget == .schema ? String(localized: "Close Schema “%@”") @@ -714,7 +622,6 @@ internal final class WorkspaceRailViewController: NSViewController { return String(format: format, entry.container) } - /// Read from the entries this rail is showing, which is the list the user is looking at. private func closeScope(for workspace: WorkspaceID) -> WorkspaceCloseAction.Scope { guard !workspace.container.isEmpty else { return .connection } let count = entries.count { $0.workspace.connectionId == workspace.connectionId } @@ -725,9 +632,7 @@ internal final class WorkspaceRailViewController: NSViewController { Task { await ConnectionCloseAction.close(connectionId: connectionId) } } - /// Hands the connection's database file back to the rest of the machine and keeps the session, - /// so the tabs, the schema cache and the row the user was on all stay where they are. The next - /// query takes the file again. + // Releases the database file and keeps the session, so tabs, schema cache and position stay; the next query takes it again. @objc private func releaseWorkspaceFileLock(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID, @@ -756,16 +661,13 @@ internal final class WorkspaceRailViewController: NSViewController { shown.host.performConnectionAction(action, for: workspace.connectionId) } - /// Ends the session, which every workspace of the connection shares, so the other rows for it - /// go quiet too. No window closes: each one repaints from its own phase. + // Every workspace of the connection shares the session, so its other rows go quiet too; no window closes. @objc private func disconnectWorkspace(_ sender: NSMenuItem) { guard let workspace = sender.representedObject as? WorkspaceID, let entry = entries.first(where: { $0.workspace.connectionId == workspace.connectionId }) else { return } - /// The rail's own window, not the connection's most recent one: the user is looking at this - /// window, and the connection's most recent window can be behind it or miniaturized, which - /// would put the confirmation sheet somewhere they cannot see and read as a dead menu item. + // This window, not the connection's most recent one, which can be behind it or miniaturized. let presentingWindow = view.window Task { await ConnectionDisconnectAction.disconnect( @@ -777,14 +679,8 @@ internal final class WorkspaceRailViewController: NSViewController { } } -// MARK: - CloseCommandNaming - extension WorkspaceRailViewController: CloseCommandNaming { - /// The strip's own contextual menu names what it would close, and the menu bar has to agree with - /// it word for word: the command is the same one, so an entry that is its connection's only one - /// reads "Close Connection" in both, because that is what closing it takes. - /// nil while nothing is highlighted, so the resolver falls back to the window, which is where - /// the command goes in that state too. + // Matches the strip's own menu word for word; nil while nothing is highlighted, so the window's title applies. internal var closeCommandTitle: String? { guard let workspace = appliedSelection, let entry = entries.first(where: { $0.workspace == workspace }) @@ -796,8 +692,6 @@ extension WorkspaceRailViewController: CloseCommandNaming { } } -// MARK: - NSMenuDelegate - extension WorkspaceRailViewController: NSMenuDelegate { internal func menuNeedsUpdate(_ menu: NSMenu) { menu.removeAllItems() @@ -883,8 +777,6 @@ extension WorkspaceRailViewController: NSMenuDelegate { } } -// MARK: - NSTableViewDataSource - extension WorkspaceRailViewController: NSTableViewDataSource { internal func numberOfRows(in tableView: NSTableView) -> Int { entries.count @@ -948,8 +840,6 @@ extension WorkspaceRailViewController: NSTableViewDataSource { } } -// MARK: - NSTableViewDelegate - extension WorkspaceRailViewController: NSTableViewDelegate { internal func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { rowHeight @@ -985,20 +875,11 @@ extension WorkspaceRailViewController: NSTableViewDelegate { ) } - /// Selection is the highlight, not the commit. - /// - /// `NSTableView` selects on mouse-down, before the drag threshold, so committing here meant - /// grabbing an icon to reorder first switched to it and the rest of the drag happened in a - /// window that was no longer key. Arrow keys were worse: one press onto another connection's - /// row raised that window, so the rail lost key status and the next press went somewhere else - /// entirely. Commit belongs on the table's action, which fires after tracking ends, and on - /// Return, which is how every AppKit list opens the row the user arrowed to. + // Selection is the highlight, not the commit: `NSTableView` selects on mouse-down, before a reorder drag starts. internal func tableViewSelectionDidChange(_ notification: Notification) { let row = tableView.selectedRow guard entries.indices.contains(row) else { return } - /// The arrow keys move the highlight through `NSTableView` itself, which reveals the row it - /// lands on by scrolling the least it can and so stops between entries. Landing on the - /// boundary here keeps the strip from having to slide again once the scroll settles. + // `NSTableView` scrolls the least it can and stops between entries, so the reveal lands on a boundary. requestSelectionReveal() Self.logger.debug( """ diff --git a/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift b/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift new file mode 100644 index 0000000000..f5d05ad920 --- /dev/null +++ b/apple/TablePro/Models/UI/SidebarDisplayPreferences.swift @@ -0,0 +1,38 @@ +import Combine +import Foundation + +struct SidebarDisplayOptions: Equatable { + var showObjectIcons: Bool + var showObjectComments: Bool + var showSystemContainers: Bool + var showRecentTables: Bool + var showPartitions: Bool + var rowSize: SidebarRowSizePreference + + init(_ general: GeneralSettings) { + showObjectIcons = general.showObjectIcons + showObjectComments = general.showObjectComments + showSystemContainers = general.showSystemContainers + showRecentTables = general.showRecentTables + showPartitions = general.showPartitions + rowSize = general.sidebarRowSize + } +} + +// Publishes only when a General field the sidebar draws changes, so a query timeout or language write leaves every sidebar alone. +@MainActor +final class SidebarDisplayPreferences: ObservableObject { + static let shared = SidebarDisplayPreferences(general: AppSettingsManager.shared.generalSlice) + + @Published private(set) var options: SidebarDisplayOptions + private var subscription: AnyCancellable? + + init(general: SettingsSlice) { + options = SidebarDisplayOptions(general.value) + subscription = general.publisher + .map(SidebarDisplayOptions.init) + .removeDuplicates() + .dropFirst() + .sink { [weak self] in self?.options = $0 } + } +} diff --git a/apple/TablePro/Views/AIChat/AIChatPanelView.swift b/apple/TablePro/Views/AIChat/AIChatPanelView.swift index b830982a3b..929cb3f0ca 100644 --- a/apple/TablePro/Views/AIChat/AIChatPanelView.swift +++ b/apple/TablePro/Views/AIChat/AIChatPanelView.swift @@ -1,13 +1,5 @@ -// -// AIChatPanelView.swift -// TablePro -// -// AI chat panel view - right-side panel for conversing with AI about database queries. -// - import SwiftUI -/// AI chat panel displayed alongside the main editor content struct AIChatPanelView: View { @ObservedObject private var slashCommandStorage = CustomSlashCommandStorage.shared @@ -18,15 +10,14 @@ struct AIChatPanelView: View { var editorSnapshot: (() -> AssistantEditorSnapshot)? @ObservedObject var viewModel: AIChatViewModel - /// Fills its column in the trailing pane, and takes a reading measure in the window's content - /// column, where filling it would run a line the whole width of the window. + // A reading measure in the window's content column, where filling it would run a line the whole window wide. var contentWidth: ChatContentWidth = .pane - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice @ObservedObject private var copilotService = CopilotService.shared @StateObject private var mentionState = MentionPopoverState() private var hasConfiguredProvider: Bool { - settingsManager.ai.hasActiveProvider + aiSettings.value.hasActiveProvider } // Only a card a turn still waits on may take Return and Escape. @@ -75,7 +66,7 @@ struct AIChatPanelView: View { viewModel.connection = connection } .task(id: ModelListTrigger( - sources: settingsManager.ai.providers.map(AIModelListSource.init(config:)), + sources: aiSettings.value.providers.map(AIModelListSource.init(config:)), savedRevision: viewModel.providerSettingsRevision, isCopilotRunning: copilotService.status == .running )) { @@ -99,8 +90,6 @@ struct AIChatPanelView: View { } } - // MARK: - Empty States - private var emptyState: some View { EmptyStateView( icon: "sparkles", @@ -148,8 +137,6 @@ struct AIChatPanelView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - // MARK: - Error Banner - private func errorBanner(_ message: String) -> some View { PaneNoticeBar( severity: .warning, @@ -175,8 +162,6 @@ struct AIChatPanelView: View { .paneBarBackground() } - // MARK: - Input Area - private var inputArea: some View { VStack(spacing: 0) { Divider() @@ -191,7 +176,7 @@ struct AIChatPanelView: View { } let acceptsImages = viewModel.activeProviderSupportsImages - let highlightEnabled = settingsManager.ai.composerHighlightEnabled + let highlightEnabled = aiSettings.value.composerHighlightEnabled ChatComposerDraftReader(draft: viewModel.composerDraft) { text in composer(text: text, acceptsImages: acceptsImages, highlightEnabled: highlightEnabled) } @@ -205,14 +190,13 @@ struct AIChatPanelView: View { sendOrStopButton } } - /// Capped before the padding, the way the transcript above it is, so the composer's - /// leading edge lines up with the first character of the conversation. + // Capped before the padding, so the composer's leading edge lines up with the transcript's first character. .chatColumn(contentWidth) .padding(8) } } - /// Built by the draft reader on each keystroke, so it takes what it shows rather than looking it up again. + // Built by the draft reader on each keystroke, so it takes what it shows rather than looking it up again. private func composer(text: Binding, acceptsImages: Bool, highlightEnabled: Bool) -> some View { ChatComposerView( text: text, @@ -241,7 +225,7 @@ struct AIChatPanelView: View { }, highlightEnabled: highlightEnabled, onToggleHighlight: { - settingsManager.ai.composerHighlightEnabled.toggle() + aiSettings.value.composerHighlightEnabled.toggle() } ) } @@ -260,16 +244,8 @@ struct AIChatPanelView: View { } private var modeMenu: some View { - let binding = Binding( - get: { settingsManager.ai.chatMode }, - set: { newValue in - var settings = settingsManager.ai - settings.chatMode = newValue - settingsManager.ai = settings - } - ) - return Menu { - Picker(String(localized: "Mode"), selection: binding) { + Menu { + Picker(String(localized: "Mode"), selection: $aiSettings.value.chatMode) { ForEach(AIChatMode.allCases) { mode in Label(mode.displayName, systemImage: mode.symbolName) .tag(mode) @@ -279,8 +255,8 @@ struct AIChatPanelView: View { .labelsHidden() } label: { HStack(spacing: 4) { - Image(systemName: settingsManager.ai.chatMode.symbolName) - Text(settingsManager.ai.chatMode.displayName) + Image(systemName: aiSettings.value.chatMode.symbolName) + Text(aiSettings.value.chatMode.displayName) .lineLimit(1) } .font(.caption) @@ -289,7 +265,7 @@ struct AIChatPanelView: View { .menuStyle(.button) .buttonStyle(.borderless) .fixedSize() - .help(settingsManager.ai.chatMode.helpText) + .help(aiSettings.value.chatMode.helpText) } @ViewBuilder @@ -325,11 +301,11 @@ struct AIChatPanelView: View { // No frame and no .fixedSize(): a 44-character model name held a fixed-size button at 339 pt, 85 pt past a 240 pt pane (macOS 27). @ViewBuilder private var modelPicker: some View { - let providers = settingsManager.ai.providers + let providers = aiSettings.value.providers if providers.isEmpty { EmptyView() } else { - let activeProvider = settingsManager.ai.activeProvider + let activeProvider = aiSettings.value.activeProvider let selectedProviderId = viewModel.selectedProviderId ?? activeProvider?.id let selectedProvider = providers.first(where: { $0.id == selectedProviderId }) ?? activeProvider let resolvedModel = viewModel.selectedModel ?? selectedProvider?.model ?? "" @@ -435,8 +411,7 @@ struct AIChatPanelView: View { Section(String(localized: "Custom")) { ForEach(customCommands) { command in Button { - updateContext() - Task { await viewModel.runCustomSlashCommand(command) } + pick(command) } label: { if command.description.isEmpty { Text("/\(command.name)") @@ -509,8 +484,6 @@ struct AIChatPanelView: View { } } - // MARK: - Helpers - private func updateContext() { let live = editorSnapshot?() viewModel.currentQuery = live.map(\.currentQuery) ?? currentQuery @@ -518,6 +491,15 @@ struct AIChatPanelView: View { viewModel.editorTarget = live.map(\.target) ?? editorTarget } + private func pick(_ command: CustomSlashCommand) { + switch CustomSlashCommandPick.resolve(command, draft: viewModel.inputText) { + case .compose(let text): + viewModel.inputText = text + case .run: + updateContext() + Task { await viewModel.runCustomSlashCommand(command) } + } + } private func updateMentionState(text: String, caret: Int) { guard let match = MentionDetector.detect(in: text, caret: caret) else { @@ -598,3 +580,21 @@ private struct ModelListTrigger: Equatable { let savedRevision: Int let isCopilotRunning: Bool } + +enum CustomSlashCommandPick: Equatable { + case run + case compose(String) + + // A template that reads `{{body}}` would run on an empty body, so the command waits in the composer for it. + static func resolve(_ command: CustomSlashCommand, draft: String) -> Self { + guard command.promptTemplate.contains(CustomSlashCommandVariable.body.placeholder) else { return .run } + let body: String + if let invocation = SlashCommand.invocation(in: draft), + invocation.name.caseInsensitiveCompare(command.name) == .orderedSame { + body = invocation.body + } else { + body = draft.trimmingCharacters(in: .whitespacesAndNewlines) + } + return .compose("/\(command.name) " + body) + } +} diff --git a/apple/TablePro/Views/Components/PaginationControlsView.swift b/apple/TablePro/Views/Components/PaginationControlsView.swift index 14db7bf6aa..466b35ceb9 100644 --- a/apple/TablePro/Views/Components/PaginationControlsView.swift +++ b/apple/TablePro/Views/Components/PaginationControlsView.swift @@ -1,26 +1,16 @@ -// -// PaginationControlsView.swift -// TablePro -// - import SwiftUI struct PaginationControlsView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let pagination: PaginationState let loadedRowCount: Int - /// Identity of the tab these controls describe. Not used for display: a change to it is what - /// discards a half-typed page number so it cannot be submitted against the next tab. + // Not displayed: a change discards a half-typed page number so it cannot be submitted against the next tab. let tabId: UUID? var showsPageNavigation = true - /// First and Last. The Query menu carries all four page commands, so the two edges are the first - /// thing this cluster gives up when the bar runs out of room. + // The Query menu carries all four page commands, so First and Last go first when the bar runs out of room. var showsEdgePageButtons = true - /// Whether rows-per-page stands beside the page indicator or moves inside its menu. Rows-per-page - /// has no menu-bar home, so the narrow bar folds it in rather than dropping it, which is where - /// TablePlus and Sequel Ace both keep theirs. + // Rows-per-page has no menu-bar home, so a narrow bar folds it into the page menu rather than dropping it. var pageSizeIsInline = true - /// The most rows the engine returns from one statement, when it caps them. var maximumPageSize: Int? let onFirst: () -> Void let onPrevious: () -> Void @@ -39,8 +29,7 @@ struct PaginationControlsView: View { private static let pageSizePresets = [5, 10, 20, 100, 500, 1_000] - /// Anything past this is a mistake rather than an intent, and it used to be unbounded: pasting - /// `9223372036854775807` set the page size to `Int.max` and the next status-bar render trapped. + // Bounded: pasting `Int.max` as the page size trapped the next status bar render. static let maximumPageSize = 1_000_000 static func pageSizePresets(upTo maximum: Int?) -> [Int] { @@ -52,8 +41,7 @@ struct PaginationControlsView: View { min(maximumPageSize ?? Self.maximumPageSize, Self.maximumPageSize) } - /// An engine that cannot seek shows no page indicator, so there is nowhere to fold rows-per-page - /// into and it has to stand on its own however narrow the bar is. + // An engine that cannot seek has no page indicator to fold rows-per-page into. private var showsInlinePageSize: Bool { pageSizeIsInline || !showsPageNavigation } @@ -75,11 +63,7 @@ struct PaginationControlsView: View { } } - // MARK: - Page Size - - /// A bordered pull-down rather than a borderless one. Measured on macOS 27, a borderless - /// `NSPopUpButton` reports a 16pt fitting height and ignores `controlSize` at every size, so it - /// sat visibly shorter than the 20pt bordered controls beside it. + // Bordered: a borderless `NSPopUpButton` ignores `controlSize` and sat shorter than the controls beside it. private var pageSizeMenu: some View { Menu { pageSizeMenuItems @@ -100,8 +84,7 @@ struct PaginationControlsView: View { } } - /// Shared by the standalone pull-down and by the page indicator that swallows it when the bar is - /// narrow, so rows-per-page offers the same choices whichever control carries it. + // Shared, so rows-per-page offers the same choices whichever control carries it. @ViewBuilder private var pageSizeMenuItems: some View { Picker(String(localized: "Rows per page"), selection: pageSizeBinding) { @@ -127,11 +110,7 @@ struct PaginationControlsView: View { Binding(get: { pagination.pageSize }, set: { onPageSizeChange($0) }) } - // MARK: - Navigation - - /// A progress indicator never goes inside this cluster. Sitting between the page indicator and - /// Next, it would push both nav buttons sideways every time a page loaded, which is the reflow - /// the readout's own indicator already reports without moving anything. + // No progress indicator here: it would push the nav buttons sideways on every page load. private var navigationCluster: some View { HStack(spacing: 0) { if showsEdgePageButtons { @@ -189,12 +168,10 @@ struct PaginationControlsView: View { } private func helpText(_ label: String, for shortcut: ShortcutAction) -> String { - settingsManager.keyboard.shortcutHint(label, for: shortcut) + keyboard.value.shortcutHint(label, for: shortcut) } - /// A button straight to the jump popover while rows-per-page has its own control, and a menu - /// carrying both once it does not. The menu is what keeps rows-per-page reachable on a narrow - /// bar: it has no menu-bar equivalent, so it cannot simply be dropped. + // A menu once rows-per-page has no control of its own, so it stays reachable on a narrow bar. @ViewBuilder private var pageIndicator: some View { if showsInlinePageSize { @@ -213,9 +190,7 @@ struct PaginationControlsView: View { } } else { Menu { - /// The catalog's existing spelling, which is also this control's tooltip when it is - /// a plain button. A new string here would fall back to English in every translated - /// locale at exactly the width where the menu is the only route to these commands. + // The catalog's existing spelling: a new string would fall back to English where this menu is the only route. Button(String(localized: "Go to page")) { jumpPage = pagination.currentPage showJumpPopover = true @@ -250,8 +225,7 @@ struct PaginationControlsView: View { .frame(minWidth: 44) } - /// The total is marked when it came from a driver estimate, so a page count the user cannot - /// trust never looks like one they can. + // An estimated total is marked, so a page count the user cannot trust never looks exact. @ViewBuilder private var pageIndicatorText: some View { if pagination.hasExactRowCount { @@ -270,15 +244,12 @@ struct PaginationControlsView: View { return String(format: String(localized: "Page %d of %d"), pagination.currentPage, pagination.totalPages) } - // MARK: - Popovers - private var jumpPopover: some View { NumberEntryPopover( caption: String(localized: "Go to page"), value: $jumpPage, minimum: 1, - /// An estimated total is not a ceiling. Clamping to it here would put back the wall that - /// `PaginationState.goToPage` was opened up to remove. + // An estimated total is not a ceiling for `PaginationState.goToPage`. maximum: pagination.hasExactRowCount ? pagination.totalPages : nil, fieldWidth: 80, isFocused: $isJumpFocused, @@ -331,8 +302,7 @@ struct PaginationControlsView: View { } private extension View { - /// One home for the page indicator's accessibility, because XCUITest keys on the identifier and - /// the control is a button or a menu depending on how much room the bar has. + // XCUITest keys on the identifier, and the control is a button or a menu depending on the room. func pageIndicatorAccessibility(value: String) -> some View { accessibilityLabel(String(localized: "Page")) .accessibilityValue(value) diff --git a/apple/TablePro/Views/Components/SQLStatementPreview.swift b/apple/TablePro/Views/Components/SQLStatementPreview.swift index f9e6ca751f..1bae6a856a 100644 --- a/apple/TablePro/Views/Components/SQLStatementPreview.swift +++ b/apple/TablePro/Views/Components/SQLStatementPreview.swift @@ -1,18 +1,12 @@ -// -// SQLStatementPreview.swift -// TablePro -// - import AppKit import SwiftUI import TableProEditorKit import TableProGrammars import TableProPluginKit -/// One owner for the choice between the editor and the plain text view, so two surfaces never show the -/// same statement two ways. +// One owner for editor versus plain text, so two surfaces never show the same statement two ways. struct SQLStatementPreview: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice let prepared: SQLReviewSheet.Prepared let databaseType: DatabaseType @@ -43,7 +37,7 @@ struct SQLStatementPreview: View { .onReceive(AppEvents.shared.themeChanged) { _ in editorConfiguration = Self.makeConfiguration() } - .onChange(of: settingsManager.editor) { _ in + .onChange(of: editorSettings.value) { _ in editorConfiguration = Self.makeConfiguration() } .clipShape(RoundedRectangle(cornerRadius: 6)) @@ -53,7 +47,7 @@ struct SQLStatementPreview: View { ) } - /// A text view, since this path carries a statement of any length and a `Text` that size lays out for seconds. + // A text view: this path carries a statement of any length, and a `Text` that size lays out for seconds. private func plainTextEditor(_ text: String) -> some View { HighlightedSQLTextView(sql: text, databaseType: databaseType) .clipShape(RoundedRectangle(cornerRadius: 6)) diff --git a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift index fc86b88662..c97c39b866 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift @@ -1,19 +1,16 @@ -// -// OptionsPaneView.swift -// TablePro -// - import AppKit import SwiftUI import TableProAutocomplete import TableProPluginKit struct OptionsPaneView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice + @ObservedObject private var generalSettings = AppSettingsManager.shared.generalSlice + @ObservedObject private var syncSettings = AppSettingsManager.shared.syncSlice @ObservedObject var coordinator: ConnectionFormCoordinator private var databaseType: DatabaseType { coordinator.network.type } - private var aiIsEnabled: Bool { settingsManager.ai.enabled } + private var aiIsEnabled: Bool { aiSettings.value.enabled } // Nil until this connection is open as the type the form shows. private var liveDriverRunsReadOnly: Bool? { @@ -40,14 +37,12 @@ struct OptionsPaneView: View { if aiIsEnabled { aiRulesSection } - if settingsManager.sync.enabled { + if syncSettings.value.enabled { syncSection } } } - // MARK: - Timeouts - private var timeoutSection: some View { Section { LabeledContent(String(localized: "Connect timeout")) { @@ -118,7 +113,7 @@ struct OptionsPaneView: View { ) } - private var globalQueryTimeoutSeconds: Int { settingsManager.general.queryTimeoutSeconds } + private var globalQueryTimeoutSeconds: Int { generalSettings.value.queryTimeoutSeconds } // The field is 100 points wide beside a "seconds" label, so words go in the subtitle and the prompt stays short. nonisolated static func queryTimeoutPlaceholder(globalSeconds: Int) -> String { @@ -147,8 +142,6 @@ struct OptionsPaneView: View { return String(format: String(localized: "Leave blank to use Settings > Connections: %@."), duration) } - // MARK: - Binary values - @ViewBuilder private var binaryValuesSection: some View { if PluginManager.shared.binaryLengthFunction(for: databaseType) != nil { @@ -186,8 +179,6 @@ struct OptionsPaneView: View { String(format: String(localized: "Default (%d)"), UnloadedValuePlan.defaultInlineByteLimit / 1_024) } - // MARK: - Autocomplete - @ViewBuilder private var completionSection: some View { if databaseType.identifierRules != nil { @@ -224,8 +215,6 @@ struct OptionsPaneView: View { } } - // MARK: - Driver options - @ViewBuilder private var driverSection: some View { let fields = coordinator.advanced.advancedFields @@ -253,8 +242,6 @@ struct OptionsPaneView: View { ) } - // MARK: - Attached Databases - @ViewBuilder private var attachedDatabasesSection: some View { if let field = coordinator.advanced.attachedDatabaseListField { @@ -270,8 +257,6 @@ struct OptionsPaneView: View { } } - // MARK: - Extensions - @ViewBuilder private var extensionsSection: some View { if let field = coordinator.advanced.extensionListField { @@ -287,8 +272,6 @@ struct OptionsPaneView: View { } } - // MARK: - Startup - private var startupSection: some View { Section { StartupCommandsEditor(text: $coordinator.advanced.startupCommands, style: .code) @@ -356,8 +339,6 @@ struct OptionsPaneView: View { String(format: String(localized: "Default (%d)"), ConnectionScriptRunner.defaultTimeoutSeconds) } - // MARK: - Safety - private var safetySection: some View { Section { safeModeRow @@ -446,8 +427,6 @@ struct OptionsPaneView: View { .foregroundStyle(.secondary) } - // MARK: - AI rules - private var aiRulesSection: some View { Section { StartupCommandsEditor(text: $coordinator.aiRules.rules, style: .plain) @@ -461,8 +440,6 @@ struct OptionsPaneView: View { } } - // MARK: - Sync - private var syncSection: some View { Section { Toggle(String(localized: "Local only"), isOn: $coordinator.advanced.localOnly) @@ -481,7 +458,7 @@ struct OptionsPaneView: View { } } -/// Columns whose values TablePro hides, for this connection, in the grid, exports, the assistant and MCP. +// Columns whose values TablePro hides, for this connection, in the grid, exports, the assistant and MCP. private struct MaskingRulesSection: View { @ObservedObject var model: MaskingRulesPaneViewModel diff --git a/apple/TablePro/Views/Editor/QueryEditorPaneController.swift b/apple/TablePro/Views/Editor/QueryEditorPaneController.swift index 0e2ad9d64e..701e680d5d 100644 --- a/apple/TablePro/Views/Editor/QueryEditorPaneController.swift +++ b/apple/TablePro/Views/Editor/QueryEditorPaneController.swift @@ -1,16 +1,9 @@ -// -// QueryEditorPaneController.swift -// TablePro -// - import AppKit import Combine import SwiftUI import TableProEditorKit -/// What the query tab's editor pane shows: the header above the editor, and the editor's input. struct QueryEditorPaneInput { - /// The banner, the command bar and the parameter panel, given the Vim mode to show or nil. var header: (VimMode?) -> AnyView var editor: SQLEditorInput } @@ -21,17 +14,16 @@ final class QueryEditorPaneModel: ObservableObject { } struct QueryEditorHeader: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @ObservedObject var model: QueryEditorPaneModel let content: (VimMode?) -> AnyView var body: some View { - content(settingsManager.editor.keyBindings == .vim ? model.vimMode : nil) + content(editorSettings.value.keyBindings == .vim ? model.vimMode : nil) } } -/// The SQL editor under its command bar. The editor takes whatever height the header leaves, with no minimum of its -/// own: the pane bottoms out at the query split's top minimum, and an editor that also insisted on one overflowed it. +// No editor minimum: the pane bottoms out at the query split's top minimum, and a second one overflowed it. @MainActor final class QueryEditorPaneController: NSViewController { let editor: SQLEditorController diff --git a/apple/TablePro/Views/Import/SQLCodePreview.swift b/apple/TablePro/Views/Import/SQLCodePreview.swift index cd7aff1d2c..54c883ee8b 100644 --- a/apple/TablePro/Views/Import/SQLCodePreview.swift +++ b/apple/TablePro/Views/Import/SQLCodePreview.swift @@ -1,17 +1,9 @@ -// -// SQLCodePreview.swift -// TablePro -// -// Read-only SQL code preview with tree-sitter syntax highlighting -// - import SwiftUI import TableProEditorKit import TableProGrammars -/// Read-only SQL code preview with syntax highlighting powered by TableProEditorKit struct SQLCodePreview: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @Binding var text: String @State private var editorState = SourceEditorState() @@ -28,10 +20,11 @@ struct SQLCodePreview: View { .onReceive(AppEvents.shared.themeChanged) { _ in editorConfiguration = Self.makeConfiguration() } + .onChange(of: editorSettings.value) { _ in + editorConfiguration = Self.makeConfiguration() + } } - // MARK: - Configuration - private static func makeConfiguration() -> SourceEditorConfiguration { SourceEditorConfiguration( appearance: .init( diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index b923862b75..d6e71b3a62 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -1,11 +1,3 @@ -// -// MainEditorContentView.swift -// TablePro -// -// Main editor content view containing tab bar and tab content. -// Extracted from MainContentView for better separation. -// - import AppKit import SwiftUI import TableProEditorKit @@ -24,12 +16,10 @@ internal enum ContainerChangeRerunPolicy { struct MainEditorContentView: View { @ObservedObject private var featureAccess = FeatureAccess.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice // Must clear the nested editor/results split's required minimums, or dragging the drawer asks AppKit for an unreachable height. static let tabContentMinimumHeight = CollapsibleSplitController.combinedMinimumThickness - // MARK: - Dependencies - @ObservedObject var tabManager: QueryTabManager @ObservedObject var coordinator: MainContentCoordinator @@ -42,8 +32,6 @@ struct MainEditorContentView: View { let windowId: UUID let connectionId: UUID - // MARK: - Callbacks - let onFirstPage: () -> Void let onPreviousPage: () -> Void let onNextPage: () -> Void @@ -67,8 +55,6 @@ struct MainEditorContentView: View { return !historyState.isVisible && !historyState.isCapturePaused } - // MARK: - Body - var body: some View { EditorAreaHost(input: EditorAreaInput( content: editorAreaContent, @@ -168,8 +154,6 @@ struct MainEditorContentView: View { } } - // MARK: - Tab Content - private var selectedQueryTab: QueryTab? { guard let tab = tabManager.selectedTab, tab.tabType == .query else { return nil } return tab @@ -221,8 +205,6 @@ struct MainEditorContentView: View { } } - // MARK: - Table Listing Tab Content - private func tableListingContent(tab: QueryTab) -> some View { let model = tableListingModels.model(forTab: tab.id) { TableListingViewModel( @@ -242,8 +224,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Version History Tab Content - @ViewBuilder private func versionHistoryContent(tab: QueryTab) -> some View { if let subject = tab.display.versionHistorySubject { @@ -274,8 +254,6 @@ struct MainEditorContentView: View { } } - // MARK: - Object Source Tab Content - @ViewBuilder private func objectSourceContent(tab: QueryTab) -> some View { if let objectRef = tab.display.objectRef, objectRef.kind == .userType { @@ -299,8 +277,6 @@ struct MainEditorContentView: View { } } - // MARK: - Query Insights Tab Content - private func queryInsightsContent(tab: QueryTab) -> some View { Group { if let vm = queryInsightsViewModels[tab.id] { @@ -325,8 +301,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Table Health Tab Content - private func tableHealthContent(tab: QueryTab) -> some View { Group { if let model = coordinator.tableHealthModels[tab.id] { @@ -345,8 +319,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Users & Roles Tab Content - @ViewBuilder private func usersRolesContent(tab: QueryTab) -> some View { Group { @@ -368,8 +340,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - Server Dashboard Tab Content - @ViewBuilder private func serverDashboardContent(tab: QueryTab) -> some View { Group { @@ -395,8 +365,6 @@ struct MainEditorContentView: View { .id(tab.id) } - // MARK: - ER Diagram Tab Content - @ViewBuilder private func erDiagramContent(tab: QueryTab) -> some View { Group { @@ -430,8 +398,6 @@ struct MainEditorContentView: View { } } - // MARK: - Per-tab container picker - private var containerSwitchTarget: ContainerSwitchTarget? { PluginManager.shared.containerSwitchTarget(for: connection.type) } @@ -536,8 +502,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Table Tab Content - @ViewBuilder private func tableTabContent(tab: QueryTab) -> some View { VStack(spacing: 0) { @@ -548,8 +512,6 @@ struct MainEditorContentView: View { } } - // MARK: - Results Section - @ViewBuilder private func executionErrorBanner(tab: QueryTab) -> some View { if let error = tab.shownError { @@ -923,8 +885,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Status Bar - private func statusBar(tab: QueryTab, selectedRowCount: Int) -> some View { let resolvedRows = resolvedTableRows(for: tab) let isExecuting = coordinator.tabExecution.isBusy(tab.id) @@ -1059,8 +1019,6 @@ struct MainEditorContentView: View { ) } - // MARK: - Empty State - private var emptyStateView: some View { VStack(spacing: 20) { Image(systemName: "tablecells") @@ -1136,7 +1094,7 @@ extension MainEditorContentView { supportsFormatting: QueryFormatterFactory.supportsFormatting(coordinator.connection.type), aiActions: coordinator.aiQueryActionAvailability(for: tab), shortcutHint: { label, action in - settingsManager.keyboard.shortcutHint(label, for: action) + keyboard.value.shortcutHint(label, for: action) } ) } @@ -1174,8 +1132,6 @@ fileprivate extension MainEditorContentView { } } -// MARK: - Query Tab Content - extension MainEditorContentView { private func queryTabInput(tab: QueryTab) -> QueryTabInput { let claimFocus = coordinator.tabManager.pendingFocusTabId == tab.id diff --git a/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift b/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift index 3755e81ea8..0b7a1eaac0 100644 --- a/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift +++ b/apple/TablePro/Views/Results/ColumnVisibilityPopover.swift @@ -1,12 +1,7 @@ -// -// ColumnVisibilityPopover.swift -// TablePro -// - import SwiftUI struct ColumnVisibilityPopover: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let columns: [GridColumnEntry] let hiddenColumns: Set let onToggleColumn: (String) -> Void @@ -42,7 +37,7 @@ struct ColumnVisibilityPopover: View { Button("Jump to Column…") { onJumpToColumn(searchText) } .buttonStyle(.link) .controlSize(.small) - .help(settingsManager.keyboard.shortcutHint( + .help(keyboard.value.shortcutHint( String(localized: "Scroll to a column and put the cell cursor in it"), for: .jumpToColumn )) diff --git a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift index 9c7c120b3b..decdbda73a 100644 --- a/apple/TablePro/Views/Results/ExecutionIndicatorView.swift +++ b/apple/TablePro/Views/Results/ExecutionIndicatorView.swift @@ -1,40 +1,19 @@ -// -// ExecutionIndicatorView.swift -// TablePro -// - import SwiftUI import TableProPluginKit import TableProUtilities -/// What the query is doing, in the bar under the result it produces. -/// -/// It used to sit in the centred toolbar item, where it reported the window rather than the tab and -/// where AppKit dropped it whole as soon as the window narrowed. Every comparable client puts this -/// in a bottom bar, and so does the rest of what this bar already reports. struct ExecutionIndicatorView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared - /// Held back rather than the spinner inside it, so a query too fast to report leaves the - /// previous duration standing instead of emptying the readout and changing its width twice. - /// Clicking a table on a local database runs in single-digit milliseconds, and "Executing…" - /// appearing and going in that time is churn the user reads as a flicker. - /// - /// The Stop button goes with it. Nothing needs cancelling inside the grace, and past it the - /// button is there, which is what the HIG asks: "When it's feasible, let people halt - /// processing." + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice + // Held back as a whole, Stop included, so a query too fast to report leaves the previous duration standing. let report: ExecutionSlot.Report let isExecuting: Bool - /// Defaulted so a preview and a caller with nothing to protect read the same as before. A batch - /// whose commit is on the wire passes false: the spinner stays and the button dims, rather than - /// offering a cancel that cannot reach the server. + // False while a batch's commit is on the wire: a cancel then cannot reach the server. var canStop = true var onCancel: (() -> Void)? @State private var showsBreakdown = false - /// Why the two numbers differ, in the popover's own words. A client-measured first row carries - /// one network round trip and a server-reported figure does not, and a reader comparing them - /// has no other way to know that. + // A client-measured first row includes one network round trip; a server figure does not. private static let clientExplanation = String(localized: """ Time to the first row is measured here, so it includes one network round trip. """) @@ -43,10 +22,9 @@ struct ExecutionIndicatorView: View { The server figure is the engine's own report, so it excludes network time. """) - /// Resolved from the user's own binding rather than written into the string. A hint naming a - /// key nobody bound is the same defect as a toolbar tooltip that outlived a rebind (#2185). + // From the user's own binding, so the hint never names a key nobody bound (#2185). private var cancelHint: String { - settingsManager.keyboard.shortcutHint(String(localized: "Cancel Query"), for: .cancelQuery) + keyboard.value.shortcutHint(String(localized: "Cancel Query"), for: .cancelQuery) } var body: some View { @@ -81,11 +59,7 @@ struct ExecutionIndicatorView: View { } } - // MARK: - Readout - - /// The elapsed number stays the label, because that is what a reader already knows how to read. - /// The split lives one click away rather than widening the bar with a second figure whose - /// meaning nothing on screen explains. + // The split lives one click away rather than widening the bar with a second unexplained figure. @ViewBuilder private func durationReadout(_ timing: PluginQueryTiming) -> some View { let text = QueryDurationFormatter.string(from: timing.total) @@ -123,8 +97,6 @@ struct ExecutionIndicatorView: View { } } -// MARK: - Preview - #Preview("Executing") { ExecutionIndicatorView(report: .running, isExecuting: true) .padding() diff --git a/apple/TablePro/Views/Results/JSONCodeEditor.swift b/apple/TablePro/Views/Results/JSONCodeEditor.swift index 1b310abff9..e9850d3007 100644 --- a/apple/TablePro/Views/Results/JSONCodeEditor.swift +++ b/apple/TablePro/Views/Results/JSONCodeEditor.swift @@ -1,18 +1,10 @@ -// -// JSONCodeEditor.swift -// TablePro -// -// JSON text view backed by TableProEditorKit (tree-sitter), sharing the -// app's editor theme and font with the SQL editor. -// - import AppKit import SwiftUI import TableProEditorKit import TableProGrammars internal struct JSONCodeEditor: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice @ObservedObject private var themeEngine = ThemeEngine.shared @Binding var text: String let isEditable: Bool @@ -21,9 +13,7 @@ internal struct JSONCodeEditor: View { @State private var editorState = SourceEditorState() @State private var configuration: SourceEditorConfiguration - /// Held in `@State` so the editor is handed the same coordinator on every update. It names the - /// text view itself, which is where an accessibility identifier has to land: the SwiftUI - /// modifier names the representable and never reaches it. + // One coordinator across updates; it names the text view, which the SwiftUI accessibility modifier never reaches. @State private var coordinators: [any TextViewCoordinator] init( @@ -58,7 +48,7 @@ internal struct JSONCodeEditor: View { .onChange(of: isEditable) { _ in rebuildConfiguration() } - .onChange(of: settingsManager.editor) { _ in + .onChange(of: editorSettings.value) { _ in rebuildConfiguration() } .onReceive(AppEvents.shared.accessibilityTextSizeChanged) { _ in diff --git a/apple/TablePro/Views/Results/ResultStatusBar.swift b/apple/TablePro/Views/Results/ResultStatusBar.swift index dbea74b74b..82fb81aa72 100644 --- a/apple/TablePro/Views/Results/ResultStatusBar.swift +++ b/apple/TablePro/Views/Results/ResultStatusBar.swift @@ -1,38 +1,9 @@ -// -// ResultStatusBar.swift -// TablePro -// - import AppKit import SwiftUI -/// The window's bottom bar: what the result is, and the controls that change what of it you see. -/// -/// Two zones, never three. Centring a variable-width sentence between two variable-width clusters -/// only holds while the clusters happen to match, which is why the row count sat visibly left of -/// centre. Anchoring the readout to the leading edge and the controls to the trailing edge also -/// keeps the controls still when a mode change removes one of them. -/// -/// The view switcher leads the bar. It was briefly a strip of its own above the result, which cost -/// a band of height in every mode and left the structure editor with two segmented rows stacked, -/// the child louder than the parent. -/// -/// Adding a row still belongs to the toolbar: it changes the document. The structure editor's -/// add and remove pair is this bar's trailing cluster while the structure editor is the content, -/// because a second bar underneath it would be the stacking problem again, one bar lower. -/// -/// The bar gives up chrome rather than overflowing its pane. Its clusters used to be pinned at full -/// width, which made the bar's own minimum wider than the pane and clipped the data grid along with -/// it; see `StatusBarTier`. `ViewThatFits` picks the widest tier whose ideal width fits, and the -/// narrowest tier holds its shape down to 280pt, measured, against a pane whose own floor is 400pt. -/// Two rules keep that true. No candidate row carries `.fixedSize()`: the clusters carry their own, -/// and the readout's constant `idealWidth` is what makes a candidate's ideal width equal its floor, -/// so the mounted row still grows to fill the pane and anchor the controls to the trailing edge. And -/// no tier drops a control that opens a popover: one anchored to a button that has left the view -/// tree cannot present, so giving up the Highlight Rules button would have made -/// `View > Highlight Rules…` do nothing. See `StatusBarTier` for what a tier may give up. +// Two zones: `ViewThatFits` picks the widest `StatusBarTier` that fits, and no tier drops a control that anchors a popover. struct ResultStatusBar: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var keyboard = AppSettingsManager.shared.keyboardSlice let model: ResultStatusModel let snapshot: StatusBarSnapshot let filterState: TabFilterState @@ -40,10 +11,8 @@ struct ResultStatusBar: View { let highlightState: StatusBarHighlightState let paginationCallbacks: PaginationCallbacks let execution: ExecutionReadout - /// Held, not observed: only the readout inside the report slot re-renders when it changes. + // Held, not observed: only the readout inside the report slot re-renders when it changes. let selectionSummary: SelectionSummaryState - /// The object tree's own reload, reported where every other piece of background activity in - /// this window is. It had no surface at all between the centred toolbar item going and this. let isRefreshingSchema: Bool @Binding var viewMode: ResultsViewMode // Empty unless the tab holds exactly one result: two or more are chosen from the tab row above the result. @@ -55,10 +24,7 @@ struct ResultStatusBar: View { @State private var showColumnPopover = false @State private var showHighlightPopover = false - /// The tab the rules popover was opened for. Switching tab closes the popover, and by the time - /// the close is seen this view already belongs to the tab that was switched to, so pruning - /// "the selected tab" pruned the wrong one and left an unfinished rule saved on the tab the - /// user actually opened it from. + // By the time the close is seen this view belongs to the new tab, so pruning "the selected tab" pruned the wrong one. @State private var highlightPopoverTabId: UUID? @State private var revealedExecutionTabId: UUID? @State private var showSelectionSummaryPopover = false @@ -97,8 +63,7 @@ struct ResultStatusBar: View { } } - /// One row of the bar, drawn the way its tier says. `ViewThatFits` measures each of these and - /// mounts the first that fits, so this is both the measurement and the result. + // `ViewThatFits` measures each row and mounts the first that fits. @ViewBuilder private func row(_ tier: StatusBarTier) -> some View { let presentation = ResultStatusPresentation(tier: tier) @@ -122,9 +87,7 @@ struct ResultStatusBar: View { } } - /// Segmented while the modes fit, and a pull-down naming the current one once they do not. The - /// pull-down is capped, because it takes the width of its widest item and a long locale would - /// otherwise decide the narrow tier's floor. + // Capped: the pull-down takes its widest item's width, and a long locale would set the narrow tier's floor. @ViewBuilder private func modeSwitcher(_ presentation: ResultStatusPresentation) -> some View { let picker = Picker(String(localized: "View Mode"), selection: $viewMode) { @@ -147,11 +110,7 @@ struct ResultStatusBar: View { } } - // MARK: - Readout - - /// The zone that absorbs the bar's slack, which is why `row` gives it the flexible frame and the - /// clusters on either side keep their intrinsic widths. Its three parts are the slots - /// `ReadoutZoneLayout` sizes: the sentence, the actions beside it, and the report after them. + // Takes the bar's slack; the clusters on either side keep their intrinsic widths. private var readoutCluster: some View { ReadoutZoneLayout(spacing: StatusBarChrome.clusterSpacing, sentenceIdealWidth: StatusBarLayoutMetrics.readoutIdealWidth) { HStack(spacing: Self.readoutSpacing) { @@ -204,9 +163,7 @@ struct ResultStatusBar: View { } } - /// Drawn at the bar's small control size, as every other control on the bar is, and never - /// truncated: the sentence beside them gives way first, and `ReadoutZoneLayout` counts their - /// width into the tier choice so the bar drops a tier before either has to. + // Never truncated: `ReadoutZoneLayout` counts their width, so the bar drops a tier first. @ViewBuilder private var readoutActions: some View { if model.controls.showsExactCountAction { @@ -234,10 +191,7 @@ struct ResultStatusBar: View { @ViewBuilder private var readoutMessage: some View { if let statusMessage = model.statusMessage { - /// Yields its width before the execution report beside it does, so a wordy driver - /// message truncates instead of squeezing anything else out. Which tier the bar draws - /// is not its business: `ReadoutZoneLayout` leaves it out of the ideal width, so no - /// message length can change that choice. + // Truncates first, and `ReadoutZoneLayout` leaves it out of the ideal width, so no message changes the tier. Text(statusMessage) .font(.caption) .foregroundStyle(.secondary) @@ -273,16 +227,13 @@ struct ResultStatusBar: View { model.selectionSummaryCoversLoadedRowsOnly ? String(localized: "Covers the loaded rows only.") : nil } - /// No `idealWidth` here: `ReadoutZoneLayout` reports the zone's ideal itself, and a frame that - /// named one would replace it. + // No `idealWidth`: `ReadoutZoneLayout` reports the zone's ideal, and a frame naming one would replace it. private func readoutZone(_ content: some View) -> some View { content.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) } private static let readoutSpacing: CGFloat = 6 - // MARK: - Controls - @ViewBuilder private func controlCluster(_ presentation: ResultStatusPresentation) -> some View { HStack(spacing: StatusBarChrome.clusterSpacing) { @@ -305,10 +256,7 @@ struct ResultStatusBar: View { .fixedSize() } - /// The tab identity is passed in rather than applied as `.id()`. Keying the view by tab did stop - /// a page number typed for one tab being submitted against the next, but it also tore the whole - /// cluster down and rebuilt it on every switch, which is a second source of the churn this bar - /// exists to avoid. The view resets the same `@State` on the same signal instead. + // The tab id is passed, not applied as `.id()`, which rebuilt the cluster on every switch. private func paginationControls(_ presentation: ResultStatusPresentation) -> some View { PaginationControlsView( pagination: snapshot.pagination, @@ -341,8 +289,7 @@ struct ResultStatusBar: View { } .statusBarLabelStyle(showsTitle: presentation.showsControlTitles) .controlSize(.small) - /// Present but inert until the result names its columns, so a reload dims the button rather - /// than removing it and shifting everything beside it. + // Dimmed, not removed, while columns load, so nothing beside it shifts. .disabled(columnState.columns.isEmpty) .help(String(localized: "Choose which columns the grid shows")) .accessibilityLabel(String(localized: "Columns")) @@ -377,9 +324,7 @@ struct ResultStatusBar: View { .statusBarControlIcon(besideTitle: false) } } - /// A glyph at every tier. Its title would add 88pt, and measured at the window's default - /// 1200pt with the sidebar open the regular tier then no longer fits, so drawing it would - /// take the titles off Columns and Filters at the size most windows are. + // A glyph at every tier: its title would cost the regular tier at the default 1200pt window. .labelStyle(.iconOnly) .controlSize(.small) .disabled(highlightState.columns.isEmpty) @@ -466,7 +411,7 @@ struct ResultStatusBar: View { .statusBarLabelStyle(showsTitle: presentation.showsControlTitles) .toggleStyle(.button) .controlSize(.small) - .help(settingsManager.keyboard.shortcutHint(String(localized: "Filters"), for: .toggleFilters)) + .help(keyboard.value.shortcutHint(String(localized: "Filters"), for: .toggleFilters)) .accessibilityLabel(String(localized: "Filters")) .accessibilityValue(filtersAccessibilityValue) .accessibilityAddTraits(filterState.isVisible ? .isSelected : []) @@ -477,8 +422,7 @@ struct ResultStatusBar: View { !columnState.hidden.isEmpty } - /// The count is a value, not part of the name. Folding it into the label made VoiceOver read a - /// different control name depending on how many columns happened to be hidden. + // A value, not part of the name, so VoiceOver reads one control name however many columns are hidden. private var columnsAccessibilityValue: String { guard hasHiddenColumns else { return String(localized: "All columns visible") } let total = columnState.visibilityColumns.count @@ -491,18 +435,7 @@ struct ResultStatusBar: View { } } -/// The readout zone: the sentence, the actions beside it, and the report after them, left to right. -/// -/// It exists for the ideal width it reports, which is the width `ViewThatFits` picks a tier by. The -/// sentence and the report count as one constant, `StatusBarLayoutMetrics.readoutIdealWidth`, so -/// neither a long count, a wordy driver message nor a selection summary drops the bar a tier by -/// itself. The actions add their own width on top. Counted inside the constant, they left a table -/// with an estimate on the regular tier with no room for both, and the bar drew "1-22 of ~22 r…" -/// beside "Count Ex…". -/// -/// Placed, the actions keep their width and the report keeps what it cannot give up. The sentence -/// takes the rest up to its own width, and whatever is left after that goes to the report, whose -/// driver message truncates into it. +// Reports the ideal width `ViewThatFits` picks a tier by: the sentence and report count as one constant, the actions on top. private struct ReadoutZoneLayout: Layout { let spacing: CGFloat let sentenceIdealWidth: CGFloat @@ -550,7 +483,6 @@ private struct ReadoutZoneLayout: Layout { ] } - /// The width of slots laid side by side, with one gap between each pair that draws anything. private func span(of widths: [CGFloat]) -> CGFloat { let drawn = widths.filter { $0 > 0 } return drawn.reduce(0, +) + spacing * CGFloat(max(0, drawn.count - 1)) @@ -558,9 +490,7 @@ private struct ReadoutZoneLayout: Layout { } private extension View { - /// `titleAndIcon` and `iconOnly` are different types, so a tier choosing between them cannot do - /// it with a ternary. Branching here keeps each control's modifier chain written once, and keeps - /// the system's own label metrics rather than a hand-rolled stack's. + // `titleAndIcon` and `iconOnly` are different types, so a ternary cannot choose between them. @ViewBuilder func statusBarLabelStyle(showsTitle: Bool) -> some View { if showsTitle { diff --git a/apple/TablePro/Views/Results/ValueSourceEditor.swift b/apple/TablePro/Views/Results/ValueSourceEditor.swift index 21cfa3124d..0e3fdf92c0 100644 --- a/apple/TablePro/Views/Results/ValueSourceEditor.swift +++ b/apple/TablePro/Views/Results/ValueSourceEditor.swift @@ -1,14 +1,9 @@ -// -// ValueSourceEditor.swift -// TablePro -// - import AppKit import SwiftUI internal struct ValueSourceEditor: View { @ObservedObject private var themeEngine = ThemeEngine.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var dataGridSettings = AppSettingsManager.shared.dataGridSlice @Binding var text: String var isEditable: Bool var textContainerInset = NSSize(width: 4, height: 6) @@ -20,7 +15,7 @@ internal struct ValueSourceEditor: View { font: themeEngine.valueFont, textContainerInset: textContainerInset, style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters + marksInvisibleCharacters: dataGridSettings.value.showInvisibleCharacters ) } } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift index 9e392e782b..b762c48990 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift @@ -1,13 +1,8 @@ -// -// MultiLineEditorView.swift -// TablePro -// - import SwiftUI internal struct MultiLineEditorView: View { @ObservedObject private var themeEngine = ThemeEngine.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var dataGridSettings = AppSettingsManager.shared.dataGridSlice let context: FieldEditorContext var onPopOut: ((String) -> Void)? var isExpanded = false @@ -29,7 +24,7 @@ internal struct MultiLineEditorView: View { font: themeEngine.valueFont, movesFocusOnTab: true, style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters, + marksInvisibleCharacters: dataGridSettings.value.showInvisibleCharacters, documentID: context.documentID.map { AnyHashable($0) } ) .valueWell(clipsContent: true) diff --git a/apple/TablePro/Views/RowInspector/TableInfoView.swift b/apple/TablePro/Views/RowInspector/TableInfoView.swift index 1927087b00..9c88cbd7c0 100644 --- a/apple/TablePro/Views/RowInspector/TableInfoView.swift +++ b/apple/TablePro/Views/RowInspector/TableInfoView.swift @@ -1,8 +1,3 @@ -// -// TableInfoView.swift -// TablePro -// - import SwiftUI // The table's own statistics, when the inspector has a table but no row selected. Not a grouped `Form`: its 30pt @@ -22,7 +17,7 @@ internal struct TableInfoView: View { // The statistics alone, for a pane that scrolls them with its own content. internal struct TableInfoSections: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var generalSettings = AppSettingsManager.shared.generalSlice internal let metadata: TableMetadata internal var includesComment = true @@ -33,7 +28,7 @@ internal struct TableInfoSections: View { var body: some View { VStack(alignment: .leading, spacing: 14) { - if includesComment, settingsManager.general.showObjectComments, + if includesComment, generalSettings.value.showObjectComments, let comment = metadata.comment, !comment.isEmpty { section(String(localized: "Comment")) { Text(comment) diff --git a/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift b/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift index 9fe7349c6e..f823cd68a8 100644 --- a/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift +++ b/apple/TablePro/Views/RowInspector/TrailingPaneHeaderView.swift @@ -1,26 +1,11 @@ -// -// TrailingPaneHeaderView.swift -// TablePro -// - import SwiftUI -/// One height for the header on every surface, so switching surface moves nothing beneath it. -/// -/// Fixed rather than grown from padding, because the leading slot is a picker on one surface and a -/// title on another and the two are not the same height: measured on macOS 27, the small segmented -/// control is 20pt and a headline 18pt, beside a menu whose hit target is 22pt. Grown from its -/// content, the header changed height with the surface, which is the jump this view exists to remove. +// Fixed, not grown from content: the picker, a headline and the menu differ in height, and the header jumped with the surface. internal enum TrailingPaneHeaderMetrics { internal static let height: CGFloat = 30 } -/// The trailing pane's header, drawn by each surface at its own top. -/// -/// A picker between the surfaces the user may choose, or the surface's name where there is nothing to -/// choose, and one menu of that surface's commands. `TrailingPaneHeaderModel` decides all of it, so -/// the three surfaces cannot draw it three ways again; this view only draws what the model says, and -/// each surface supplies the commands in the menu sections the model names. +// `TrailingPaneHeaderModel` decides the picker, title and menu, so the three surfaces cannot draw it three ways. internal struct TrailingPaneHeaderView: View { private let surface: TrailingPaneSurface private let contentMode: ConnectionWorkspaceContentMode @@ -29,14 +14,10 @@ internal struct TrailingPaneHeaderView: View { private let hasContent: Bool private let menuSection: (TrailingPaneMenuSection) -> MenuSectionContent - /// Read live rather than captured when the pane was built. Turning the assistant off changes - /// nothing the pane's render key holds while browsing, so a captured value would go on offering - /// the assistant's segment over a pane that can no longer draw it. - @ObservedObject private var settings = AppSettingsManager.shared + // Live: turning the assistant off changes nothing the pane's render key holds while browsing. + @ObservedObject private var aiSettings = AppSettingsManager.shared.aiSlice - /// `paneState` is nil for the result column, whose surface the mode chose, and for a connection - /// whose session went and took its pane state with it. Either way there is no stored surface to - /// write, so the header names its surface instead of offering a picker that could not answer. + // `paneState` is nil for the result column and for a session that went; there is no stored surface to write. internal init( surface: TrailingPaneSurface, contentMode: ConnectionWorkspaceContentMode, @@ -57,7 +38,7 @@ internal struct TrailingPaneHeaderView: View { TrailingPaneHeaderModel( surface: surface, contentMode: contentMode, - isAIEnabled: settings.ai.enabled, + isAIEnabled: aiSettings.value.enabled, inspectorRendering: inspectorRendering, hasContent: hasContent ) @@ -91,18 +72,7 @@ internal struct TrailingPaneHeaderView: View { } } - /// The ellipsis draws no text, so the only name VoiceOver has for this control is the one the - /// accessibility modifiers give it, and it takes all three of them. - /// - /// Measured on macOS 27, naming it through the label does not work in any arrangement. A `Label` - /// whose title `.labelStyle(.iconOnly)` has resolved away carries no name, whichever view the - /// style sits on, and `.accessibilityLabel` inside the label closure, which is how - /// `ResultSetMenu` names a pull-down that also draws text, does not reach this one either. - /// `.accessibilityLabel` on the `Menu` alone is likewise ignored. In all three the control falls - /// back to AppKit's own name for an unnamed pull-down, which reads "More" locally and the empty - /// string on the CI runner. Only `.accessibilityElement` publishes the name, and it has to be - /// `.contain`: `.ignore` names the button and then takes the menu's own items out of the tree - /// with it, so nothing can reach Fields, JSON or any other command in it. + // Only `.accessibilityElement(children: .contain)` publishes the name here; label-based naming is ignored on macOS 27. private func menu(_ model: TrailingPaneHeaderModel) -> some View { Menu { ForEach(Array(model.menuSections.enumerated()), id: \.element) { index, section in @@ -132,8 +102,7 @@ internal struct TrailingPaneHeaderView: View { } } -/// The surface picker, observing the connection's pane state itself so that the segment it draws is -/// the surface the controller parents next rather than the one the pane was built with. +// Observes the pane state itself, so the segment is the surface the controller parents next. private struct TrailingPaneSurfacePicker: View { @ObservedObject var state: TrailingPaneState let segments: [TrailingPaneSurface] @@ -152,10 +121,7 @@ private struct TrailingPaneSurfacePicker: View { .accessibilityIdentifier("trailing-pane-surface") } - /// The segment's name travels in the symbol image's own description. Measured on macOS 27, a - /// segmented picker names each segment from the image it was handed and never reads - /// `.accessibilityLabel` on the view, so `Image(systemName:)` published "info" and "sparkle" to - /// VoiceOver whatever label it carried. The image is the same template at the same size. + // A segmented picker names each segment from its image and never reads `.accessibilityLabel`. private static func symbol(for segment: TrailingPaneSurface) -> Image { guard let image = NSImage( systemSymbolName: segment.symbolName, @@ -166,11 +132,7 @@ private struct TrailingPaneSurfacePicker: View { return Image(nsImage: image) } - /// Writes the stored surface and nothing else. A segment is a choice the user made, so it is - /// remembered for the connection, which a suggestion such as a grid click never is. The controller - /// watches the state of the connection on screen and parents the new surface on the next turn of - /// the run loop, so the view whose segment was clicked leaves the window after its action has - /// returned rather than from inside it. + // Writes the stored surface only; the controller parents it a turn later, after this action returns. private var selection: Binding { Binding( get: { state.surface }, diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeFilterPopover.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeFilterPopover.swift index 23716c6bda..d0478199d0 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeFilterPopover.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeFilterPopover.swift @@ -1,8 +1,3 @@ -// -// DatabaseTreeFilterPopover.swift -// TablePro -// - import SwiftUI import TableProUtilities @@ -18,7 +13,7 @@ struct DatabaseTreeFilterPopover: View { @ObservedObject private var treeService = DatabaseTreeMetadataService.shared @ObservedObject private var schemaService = SchemaService.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared @State private var selection: Set @State private var searchText: String = "" @@ -37,7 +32,7 @@ struct DatabaseTreeFilterPopover: View { } private var showsSystemContainers: Bool { - settingsManager.general.showSystemContainers + sidebarDisplay.options.showSystemContainers } private var databases: [DatabaseMetadata] { diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift index 6563a9bbb4..de263fdcc8 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator.swift @@ -1,8 +1,3 @@ -// -// DatabaseTreeOutlineCoordinator.swift -// TablePro -// - import AppKit import Combine import Observation @@ -50,24 +45,19 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { internal var bucketMemo = DatabaseTreeBucketMemo() internal var loadedContentMemo = DatabaseTreeBucketMemo() internal var tableRowMemo: [CatalogName: DatabaseTreeTableRows] = [:] - /// Whether a routine row shows its signature depends on the other rows in its own section, so - /// the label is decided where the section is built and looked up here when the row draws. + // Decided where the section is built: whether a routine shows its signature depends on its siblings. internal var routineDisplayLabels: [String: String] = [:] - /// Built once per refresh for each container, because the container, its folders and its kind - /// sections all read the same plan and AppKit asks for each of them separately. + // Built once per refresh: the container, its folders and its kind sections all read the same plan. internal var flatFolderPlan: TableFolderPlan? internal var containerFolderPlans: [DatabaseTreeContainerKey: TableFolderPlan] = [:] - /// The folder whose name is being typed, which a search must not hide out from under the field. + // The folder being renamed, which a search must not hide out from under the field. internal var revealedFolderId: UUID? - /// A reload ends a drag in flight and drops the field a name is being typed into, so one asked - /// for during either waits for it to finish. The Welcome list holds its reloads the same way. + // A reload ends a drag and drops a rename field, so one asked for during either waits for it to finish. internal var isDragging = false internal var isReloadDeferred = false - /// The tables and views a drag carries, resolved once when it starts rather than on every move - /// of the pointer. Nil for a drag that started in another window. + // Resolved once when the drag starts; nil for a drag from another window. internal var draggedFolderItems: [TableFolderDragItem]? - /// A rename in progress, held as identity only. See `DatabaseTreeOutlineCoordinator+Rename`. internal var renameSession: DatabaseTreeRenameSession? private var cachedRowContext: DatabaseTreeRowContext? private var cachedRowActions: DatabaseTreeRowActions? @@ -124,8 +114,6 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { Set(PluginManager.shared.systemSchemaNames(for: databaseType)) } - // MARK: - Attach / input - func attach(outlineView: NSOutlineView) { self.outlineView = outlineView let tableObserver = NotificationCenter.default.addObserver( @@ -163,23 +151,14 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { observeObjectListAppearance() } - /// The rows repaint from the setting rather than from the command that wrote it, so the same - /// change arrives whether it came from the View Options control in the filter row, the - /// empty-area menu, or Settings. Toggling Show Object Icons in Settings used to repaint - /// nothing, because only the contextual menu's own handler called `refreshVisibleRows`. - /// - /// Re-arms itself, because `withObservationTracking` fires once per registration. - /// - /// The macro registers access on the stored `general` property rather than on the two fields - /// read inside it, so this wakes on every `GeneralSettings` write, the query timeout and the - /// sync write-back included. `refreshVisibleRows` reconfigures every row of every open window, - /// so the two values are compared before it runs. + // Follows the setting, not the command that wrote it, so the filter row, the empty-area menu and Settings all repaint. private func observeObjectListAppearance() { - appearanceObservation = AppSettingsManager.shared.onMainActorChange { [weak self] in + appearanceObservation = AppSettingsManager.shared.generalSlice.onMainActorChange { [weak self] in guard let self else { return } let appearance = Self.objectListAppearance() guard appearance != self.observedAppearance else { return } self.observedAppearance = appearance + self.cachedRowContext = nil self.refreshVisibleRows() } } @@ -259,8 +238,6 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { } } - // MARK: - Observation - private func beginObserving() { observationGeneration += 1 let generation = observationGeneration @@ -373,16 +350,14 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { tableRowMemo = tableRowMemo.filter { childrenCache[$0.key] != nil } } - /// Coalesced with any reload already scheduled, because the edit that ended the hold usually - /// posts a change of its own that asks for one too. + // Coalesced: the edit that ended the hold usually posts a change that asks for a reload too. internal func applyDeferredReloadIfNeeded() { guard isReloadDeferred, !isDragging, renameSession == nil else { return } isReloadDeferred = false scheduleReconcile(forcing: true) } - /// A star toggling on or off changes no row and no ordering, so the rows are reconfigured in - /// place. Reloading would throw away every hosted SwiftUI view to repaint one glyph. + // Reconfigures in place: a reload would throw away every hosted SwiftUI view to repaint one glyph. internal func refreshVisibleRows() { guard let outlineView else { return } outlineView.enumerateAvailableRowViews { _, row in @@ -449,8 +424,6 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { ) } - // MARK: - Selection / open - internal func selectedRefs() -> [DatabaseTreeTableRef] { DatabaseTreeSelection.tableRefs(of: selectedNodes()) } @@ -481,20 +454,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { isSyncingSelection = false } - /// The window writes `selectedTables` whenever the active editor tab moves, so the highlight has - /// to follow it the way the `List(selection:)` binding this outline replaced did. Reading it back - /// is also what keeps a click on the row that is still highlighted from being swallowed: AppKit - /// posts no selection change when the selection already holds that row, so a highlight left - /// behind on a table the user has since navigated away from becomes a dead row. - /// - /// A table can be drawn twice, once under Recent and once in its own section. Only the section - /// row is adopted, because that is the row the model's `TableInfo` stands for. - /// - /// Nothing is adopted while this coordinator is opening a row the user clicked. `activate(_:)` - /// moves the browse database before `publishSelection()` runs, so through that window the model - /// still names the previous database's table. Adopting it would deselect the clicked row and - /// then publish the empty selection over it. The depth counts, because a second click can land - /// while the first switch is still in flight. + // Adopts only a table's section row, and never while a clicked open is still moving the browse database. private func adoptModelSelection() { guard let windowState, openSelectionDepth == 0 else { return } let selectedTables = windowState.selectedTables @@ -506,19 +466,14 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { publishedTables = selectedTables publishedSelectionDatabase = selectionDatabase - /// Matched on the object and scoped to the database on screen, in that order, rather than - /// on the whole reference. The model holds the row the user picked, database included, but - /// browsing elsewhere is meant to move the highlight onto that database's copy of the same - /// object; comparing references pins it to the database it was picked in and leaves the - /// tree with nothing selected the moment the browse cursor moves. + // By object, not reference, so browsing another database moves the highlight to its copy of the table. let selectedObjects = Set(selectedTables.map(\.table)) let nodes = nodeCache.nodes(drawing: selectedObjects).filter { node in selectionDatabase == nil || node.tableRef?.database == selectionDatabase } lastSelectedNodeIds = nodes.map(\.id) lastSelection = Set(DatabaseTreeSelection.tableRefs(of: nodes)) - /// Still pending while a selected table has no row in the database being browsed: the row is - /// usually one that has not been built yet, and the next sync adopts it. + // Pending while a selected table has no row yet in the browsed database; the next sync adopts it. isModelSelectionAdoptionPending = Set(lastSelection.map(\.table)) != selectedObjects } @@ -528,11 +483,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { return activeDatabase } - /// Opens run one after another, because a double-click is two opens of the same row and the - /// second lands while the first is still inside `activate(_:)`. Both would then read the same - /// stale `activeDatabase` and switch the database twice for one gesture, which on an engine - /// that reconnects to switch means two reconnects and two schema invalidations. Waiting for the - /// one in flight lets the second see the database it already moved to, so it only promotes. + // Serialized: a double-click is two opens, and two reads of a stale `activeDatabase` would switch twice. private func open( _ ref: DatabaseTreeTableRef, activateGridFocus: Bool, @@ -557,13 +508,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { } } - /// The Table menu reads `windowState.selectedTables`, so the tree has to put its own selection - /// there or every command that acts on a selection does nothing in tree layout. - /// - /// Timing is the whole trick. The shared navigation observer also watches this property, and it - /// opens whatever single table appeared. Publishing before the tree's own open landed would race - /// it into opening the table twice, so a selection that navigates publishes only once the tab is - /// already the clicked table, which is exactly the case that observer resolves to skip. + // Published only once the tab is the clicked table, or the window's navigation observer opens it twice. private func publishSelection() { guard let windowState else { return } let nodes = selectedNodes() @@ -571,8 +516,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { publishedTables = tables publishedSelectionDatabase = modelSelectionDatabase isModelSelectionAdoptionPending = false - /// The row count goes with the tables, because this is the one list that can select a row - /// which is not a table. One table selected beside a schema must not read as a pick. + // This list can select rows that are not tables, so one table beside a schema must not read as a pick. windowState.select(tables: tables, rowCount: nodes.count) } @@ -617,10 +561,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { } } - /// Every visible row is handed the same context and the same action set, and both are pure - /// functions of the inputs `update(from:)` already tracks, so they are built once per refresh - /// instead of once per row. Rebuilding them in `viewFor` allocated a fresh set of closures for - /// every row the outline drew, on every reload and every scroll. + // Built once per refresh, not per row: `viewFor` allocated fresh closures for every row it drew. private var rowContext: DatabaseTreeRowContext { if let cachedRowContext { return cachedRowContext } let context = makeRowContext() @@ -663,7 +604,9 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { self?.routineDisplayLabels[ref.id] ?? ref.routine.name }, showsPartitions: showsPartitions, - listsAttachedSchemas: listsAttachedSchemas + listsAttachedSchemas: listsAttachedSchemas, + showsObjectIcons: observedAppearance.showsIcons, + showsObjectComments: observedAppearance.showsComments ) } @@ -674,8 +617,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { ) } - /// A namespace rescopes the browse pattern and a key opens; neither goes through the - /// double-click window a table open needs, because there is no preview tab to promote. + // No double-click window: there is no preview tab to promote. private func openRedis(_ node: RedisKeyNode) { switch node { case .namespace(_, let fullPrefix, _, _): @@ -772,13 +714,9 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { perform(DatabaseTreeDoubleClickResolver.resolve(node: node), on: node, in: outlineView) } - /// Return does what a double-click does, because a keyboard user arrowing through the tree has - /// already opened every row they passed and needs the same way to keep one. `NSOutlineView` - /// routes neither gesture on its own. + // Return keeps the row the way a double-click does; `NSOutlineView` routes neither on its own. internal func performPrimaryAction() { - /// One row only, for the same reason `DatabaseTreeSelection.navigationTarget` refuses to - /// navigate on an extended selection: that selection is a batch about to be exported or - /// truncated, and opening one of its rows would move the browsed database out from under it. + // An extended selection is a batch; opening one of its rows would move the database out from under it. guard let outlineView, outlineView.numberOfSelectedRows == 1, outlineView.selectedRow >= 0, let node = outlineView.item(atRow: outlineView.selectedRow) as? DatabaseTreeNode @@ -814,8 +752,7 @@ final class DatabaseTreeOutlineCoordinator: NSObject, NSTextFieldDelegate { } extension DatabaseTreeOutlineCoordinator: DatabaseTreeSelectionClearing { - /// Deselecting runs the normal delegate path, which publishes the now empty selection, so the - /// Table menu and the outline agree without a second write. + // The delegate path publishes the empty selection, so the Table menu agrees without a second write. func clearSelection() { guard let outlineView, !outlineView.selectedRowIndexes.isEmpty else { return } outlineView.deselectAll(nil) @@ -831,9 +768,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDataSource { resolvedChildren(of: item)[index] } - /// `DatabaseTreeNode.isExpandable` answers from the node's kind alone and has no settings to - /// read, so the hide-partitions gate has to be applied here as well as in the node builder. - /// Without it a hidden table kept a disclosure triangle that opened on nothing. + // `isExpandable` cannot read settings, so the hide-partitions gate is applied here too. func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { guard let node = item as? DatabaseTreeNode, node.isExpandable else { return false } switch node.kind { @@ -848,16 +783,13 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDataSource { } extension DatabaseTreeOutlineCoordinator { - // MARK: - NSTextFieldDelegate - - /// The rename editor's callbacks. They live here rather than in the rename extension because - /// they are `@objc` and an extension cannot supply them for the conformance. + // Here, not in the rename extension: an extension cannot supply `@objc` requirements for the conformance. internal func controlTextDidChange(_ obj: Notification) { guard let field = obj.object as? NSTextField else { return } renameSession?.pendingName = field.stringValue } - /// The click-away path, which commits the way Finder and the Xcode navigator do. + // Click-away commits, as Finder and the Xcode navigator do. internal func controlTextDidEndEditing(_ obj: Notification) { guard renameSession != nil else { return } endRename(commit: true) @@ -873,8 +805,7 @@ extension DatabaseTreeOutlineCoordinator { return true } if selector == #selector(NSResponder.cancelOperation(_:)) { - /// `abortEditing` discards the edit without posting `controlTextDidEndEditing`, so the - /// cancel does not immediately arrive back as a commit. + // `abortEditing` posts no `controlTextDidEndEditing`, so the cancel is not read back as a commit. (control as? NSTextField)?.abortEditing() endRename(commit: false) return true @@ -902,11 +833,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { return DatabaseTreeSelection.isSelectable(node.kind) } - /// Hands the section headers to AppKit. In `.sourceList` a group row is drawn at its own - /// height with its own background and collapse control, and its children are laid out at the - /// depth the group itself sits at rather than one level in. That last part is what makes a - /// table under "Tables" line up with a database, the way a package lines up with the project - /// in Xcode's navigator. + // A source list lays a group's children at the group's depth, so a table under Tables lines up with a database. func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool { (item as? DatabaseTreeNode)?.isGroupRow ?? false } @@ -923,9 +850,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { ) } - /// The load has to run before AppKit asks for the children, which is what `will` is for. The - /// recording is the opposite: `will` fires before the state flips, so a disclosure recorded - /// there is describing the state the row is leaving. + // Loads in `will`, before AppKit asks for children; the disclosure is recorded in `did`, once the state flipped. func outlineViewItemWillExpand(_ notification: Notification) { guard let node = notification.userInfo?["NSObject"] as? DatabaseTreeNode else { return } beginExpansionTrace(for: node) @@ -957,14 +882,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { } } - /// A collapse that hides the selected row makes AppKit rewrite the outline's selection, and that - /// rewrite is not a pick. Publishing it wrote an empty `selectedTables` the tree could never take - /// back: an empty model against an empty published set leaves `adoptModelSelection()` nothing to - /// restore when the row comes back. - /// - /// AppKit posts that selection change outside the will/did pair, so the suppression is raised at - /// both ends and lowered a main-actor hop later, which is also when the highlight is driven back - /// from the model. + // AppKit rewrites the selection a collapse hides, outside the will/did pair; that is not a pick, so publishing waits a hop. func outlineViewItemWillCollapse(_ notification: Notification) { isCollapsingItem = true } @@ -983,23 +901,12 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { scheduleSelectionSync(force: true) } - /// A filtered tree discloses whatever matches, so while the field has text the disclosure on - /// screen is the search's, not the user's. A gesture against it is an edit of the search view - /// and must stay out of the saved state: recording it made the row spring back open on the next - /// keystroke and then, once the filter cleared, took the layout the user had built with it. + // While filtering, disclosure belongs to the search, so gestures stay out of the saved state. private var isRecordingExpansion: Bool { !isApplyingExpansion && searchText.isEmpty } - /// Selection drives the content, which is how a source list works: the navigator picks, the - /// detail follows. Both the mouse and the keyboard land here, so there is one entry point. - /// - /// This deliberately does not use `NSTableView.action`. AppKit sends the action on mouse up, - /// which is a whole gesture later than the selection the user already sees. - /// - /// Nothing is published when a single table was added, because the open publishes it once the - /// tab is already that table. Publishing here would hand the same table to the window's - /// navigation observer first and open it twice. + // Selection drives the content, not `action`, which arrives on mouse up; a single added table is published by its open. func outlineViewSelectionDidChange(_ notification: Notification) { guard !isSyncingSelection, !isReloading, !isCollapsingItem else { return } let nodes = selectedNodes() @@ -1009,8 +916,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { selectedNodes: nodes, previousRefs: lastSelection, newRefs: refs ) if let target { - /// Only a repeating key is a burst to wait out. A discrete press is the whole gesture - /// and opens now, the way a click does. + // Only a repeating key is a burst to wait out; a discrete press opens now. if isAutorepeatingSelection { scheduleOpen(target, after: NSEvent.keyRepeatInterval) } else { @@ -1037,10 +943,7 @@ extension DatabaseTreeOutlineCoordinator: NSOutlineViewDelegate { return DatabaseTreeTypeSelect.isAutorepeatingArrowNavigation(event) } - /// A held arrow key is one gesture, not one open per row it travels over, so a repeating key - /// waits out `NSEvent.keyRepeatInterval` and each new selection cancels the pending one. The - /// burst collapses to the row the user stopped on. Without it, arrowing down a schema ran a - /// query and opened a tab for every row in between. + // A held arrow key is one gesture: each repeat cancels the pending open, so only the row it stops on opens. private func scheduleOpen(_ ref: DatabaseTreeTableRef, after delay: TimeInterval) { pendingOpenWork?.cancel() let work = DispatchWorkItem { [weak self] in diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift index 85da448667..f1e7c137f3 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeRowView.swift @@ -1,28 +1,20 @@ -// -// DatabaseTreeRowView.swift -// TablePro -// - import SwiftUI import TableProPluginKit -/// What a row can do on its own. Everything a menu item does now goes through -/// `SidebarMenuCommand`, so this is only the star, which is a control inside the row. +// Only the star: every menu item goes through `SidebarMenuCommand`. struct DatabaseTreeRowActions { let toggleFavorite: (DatabaseTreeTableRef) -> Void let toggleFavoriteDatabase: (String) -> Void } -/// Row labels are built here rather than inline so the database row reads to VoiceOver in the same -/// shape `TableRowLogic` already uses for a table, instead of inventing a second phrasing. +// Same "Kind: Name" shape `TableRowLogic` gives a table, so VoiceOver reads one phrasing. enum DatabaseTreeRowLabel { static func database(name: String, isFavorite: Bool) -> String { guard isFavorite else { return name } return name + ", " + String(localized: "favorite") } - /// Read in the "Kind: Name" shape a table row uses. The count takes two keys rather than - /// inflection markup, which `String(localized:)` leaves unprocessed. + // Two keys rather than inflection markup, which `String(localized:)` leaves unprocessed. static func folder(name: String, memberCount: Int) -> String { let row = String(format: String(localized: "%@: %@"), String(localized: "Folder"), name) let count = memberCount == 1 @@ -39,26 +31,21 @@ struct DatabaseTreeRowContext { let systemSchemas: Set let pendingTruncates: Set let pendingDeletes: Set - /// AppKit sizes the row, but it lays out `NSTableCellView.textField` and `imageView` to do it, - /// and this cell hosts SwiftUI instead. The size has to reach the content or the text stays one - /// size inside three different row heights. + // The cell hosts SwiftUI, so AppKit's row size never reaches the text unless it is passed in. var rowSize: SidebarRowSize = .medium var isExternalSchema: @MainActor (String, String) -> Bool = { _, _ in false } - /// The plugin decides what a table is called, so a section header cannot hardcode "Tables". var objectKindTitle: @MainActor (SidebarObjectKind) -> String = { $0.pluralDisplayName } - /// Whether a routine's row shows its bare name or its signature depends on the other rows in - /// its section, which only the node builder can see, so the row asks rather than deciding. + // Bare name or signature depends on the other rows in the section, which only the node builder sees. var routineDisplayLabel: @MainActor (DatabaseTreeRoutineRef) -> String = { $0.routine.name } - /// Whether a partitioned table's row shows its partition count. It follows the same setting - /// that decides whether partitions are listed at all, so a hidden set of partitions does not - /// leave a number behind on the parent. + // Follows the setting that lists partitions, so hidden partitions leave no count on the parent. var showsPartitions: Bool = true - /// The engine's schema rows are databases attached beside the opened file, never one to switch to. + // The engine's schema rows are databases attached beside the opened file, never one to switch to. var listsAttachedSchemas: Bool = false + var showsObjectIcons: Bool = true + var showsObjectComments: Bool = true } struct DatabaseTreeRowView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let node: DatabaseTreeNode let isFavorite: Bool let context: DatabaseTreeRowContext @@ -66,10 +53,7 @@ struct DatabaseTreeRowView: View { @State private var isHovered = false - /// No `.contextMenu` here. A menu on the hosted view answers the right-click before the outline - /// view ever sees it, which cost the clicked-row highlight, `clickedRow`, and any menu at all in - /// the empty area below the last row. The outline owns the menu now; see - /// `DatabaseTreeOutlineCoordinator+Menu`. + // No `.contextMenu`: a menu on the hosted view takes the right-click before the outline sets `clickedRow`. var body: some View { row } @@ -94,6 +78,8 @@ struct DatabaseTreeRowView: View { case .temporaryTable(let ref): TableRow( table: ref.table, + showsIcon: context.showsObjectIcons, + showsComment: context.showsObjectComments, isPendingTruncate: false, isPendingDelete: false, showsPartitionCount: context.showsPartitions, @@ -120,13 +106,17 @@ struct DatabaseTreeRowView: View { case .partition(let ref): partitionRow(ref) case .routine(let ref): - RoutineRowView(routine: ref.routine, displayLabel: context.routineDisplayLabel(ref)) + RoutineRowView( + routine: ref.routine, + displayLabel: context.routineDisplayLabel(ref), + showsIcon: context.showsObjectIcons + ) case .trigger(let ref): - TriggerRowView(trigger: ref.trigger) + TriggerRowView(trigger: ref.trigger, showsIcon: context.showsObjectIcons) case .userType(let ref): - UserTypeRowView(type: ref.type) + UserTypeRowView(type: ref.type, showsIcon: context.showsObjectIcons) case .serverObject(let ref): - ServerObjectRowView(object: ref.object, kind: ref.kind) + ServerObjectRowView(object: ref.object, kind: ref.kind, showsIcon: context.showsObjectIcons) case .status(let status): statusRow(status) case .objectKindSection(let kind): @@ -147,9 +137,7 @@ struct DatabaseTreeRowView: View { } } - /// A source list section title carries no icon and no chevron of its own: AppKit draws the - /// group row's background and its collapse control, and an icon here would be a second glyph - /// competing with the one on every object below it. + // No icon: AppKit draws the group row and its collapse control, and a glyph here would compete with the rows'. private func sectionHeader(_ text: String) -> some View { Text(text) .font(.caption.weight(.semibold)) @@ -169,14 +157,14 @@ struct DatabaseTreeRowView: View { } icon: { Image(systemName: "folder") } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: context.showsObjectIcons) .accessibilityElement(children: .combine) .accessibilityLabel(DatabaseTreeRowLabel.folder(name: ref.folder.name, memberCount: ref.memberCount)) } private func objectGroupRow(_ kind: SidebarObjectKind) -> some View { Label(context.objectKindTitle(kind), systemImage: kind.iconName) - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: context.showsObjectIcons) .lineLimit(1) } @@ -201,6 +189,8 @@ struct DatabaseTreeRowView: View { private func tableRow(_ ref: DatabaseTreeTableRef) -> some View { TableRow( table: ref.table, + showsIcon: context.showsObjectIcons, + showsComment: context.showsObjectComments, isPendingTruncate: context.pendingTruncates.contains(ref), isPendingDelete: context.pendingDeletes.contains(ref), isFavorite: isFavorite, @@ -209,12 +199,7 @@ struct DatabaseTreeRowView: View { ) } - /// A partition that is a relation draws as the table it is, so a staged Drop or Truncate, a - /// favourite star and the accessibility status all keep working, with its bound in the caption - /// slot beside the name. One that is not a relation has none of those states to show. - /// - /// The bound truncates from the middle, not the tail: a range bound puts the value that tells - /// one partition from the next at both ends, and tail truncation keeps only the opening one. + // A range bound puts the value that tells partitions apart at both ends, so the caption truncates in the middle. @ViewBuilder private func partitionRow(_ ref: DatabaseTreePartitionRef) -> some View { let caption = SidebarPartitionRow.caption( @@ -224,6 +209,8 @@ struct DatabaseTreeRowView: View { if let tableRef = ref.tableRef { TableRow( table: tableRef.table, + showsIcon: context.showsObjectIcons, + showsComment: context.showsObjectComments, isPendingTruncate: context.pendingTruncates.contains(tableRef), isPendingDelete: context.pendingDeletes.contains(tableRef), isFavorite: isFavorite, @@ -251,7 +238,7 @@ struct DatabaseTreeRowView: View { .selectionAwareTint(Color.accentColor) .frame(width: 16) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: context.showsObjectIcons) .accessibilityElement(children: .combine) .accessibilityLabel( SidebarPartitionRow.accessibilityLabel( @@ -263,8 +250,7 @@ struct DatabaseTreeRowView: View { } } - /// Redis rows carry their own count and type rather than reusing `TableRow`, which is built - /// around a `TableInfo` a key does not have. + // Not `TableRow`: that is built around a `TableInfo` a key does not have. @ViewBuilder private func redisRow(_ node: RedisKeyNode) -> some View { switch node { @@ -318,7 +304,7 @@ struct DatabaseTreeRowView: View { } icon: { Image(systemName: systemImage) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: context.showsObjectIcons) .lineLimit(1) .sidebarRowForeground(isActive: isActive, isSystem: isSystem) } diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift index 637da97808..4be89c79ad 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeView.swift @@ -1,8 +1,3 @@ -// -// DatabaseTreeView.swift -// TablePro -// - import SwiftUI import TableProPluginKit @@ -75,14 +70,12 @@ struct DatabaseTreeView: View { @Binding var pendingDeletes: Set let coordinator: MainContentCoordinator? - /// The publisher behind `activeDatabase` and `activeSchema` is the toolbar state, not the - /// coordinator, and `@ObservedObject` cannot wrap an optional. The coordinator holds it as - /// a stable `let`, so the view observes it directly. + // `@ObservedObject` cannot wrap an optional, and the coordinator holds the toolbar state as a stable `let`. @ObservedObject var toolbarState: ConnectionToolbarState @ObservedObject var sidebarState: SharedSidebarState @ObservedObject var catalog: ConnectionSidebarCatalog - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared @State private var showsDatabaseProgress = false private var activeDatabase: String? { @@ -103,7 +96,7 @@ struct DatabaseTreeView: View { } private var showsSystemContainers: Bool { - settingsManager.general.showSystemContainers + sidebarDisplay.options.showSystemContainers } private var filteredDatabases: [DatabaseMetadata] { @@ -202,10 +195,10 @@ struct DatabaseTreeView: View { activeDatabase: activeDatabase, activeSchema: activeSchema, selectedTables: windowState.selectedTables, - showRecentTables: settingsManager.general.showRecentTables, + showRecentTables: sidebarDisplay.options.showRecentTables, showSystemContainers: showsSystemContainers, - showsPartitions: settingsManager.general.showPartitions, - rowSizePreference: settingsManager.general.sidebarRowSize + showsPartitions: sidebarDisplay.options.showPartitions, + rowSizePreference: sidebarDisplay.options.rowSize ) } diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index af1b296352..edaaf46b89 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -6,7 +6,7 @@ import TableProUtilities internal struct FavoritesTabView: View { @ObservedObject private var teamLibrarySync = TeamLibrarySync.shared @ObservedObject private var featureAccess = FeatureAccess.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared @ObservedObject private var gitStatusStore = LinkedFolderGitStatusStore.shared @ObservedObject private var gitActions = LinkedFolderGitActions.shared @ObservedObject private var catalog: ConnectionSidebarCatalog @@ -253,11 +253,7 @@ internal struct FavoritesTabView: View { } } - // MARK: - List - - /// Every team query this license can see, before the filter field has had a word to say about - /// it. The empty state asks whether the user owns anything, and the filtered list cannot answer - /// that question. + // Before the filter: the empty state asks whether the user owns anything, which the filtered list cannot answer. private var allTeamLibraryQueries: [TeamLibraryQuery] { guard featureAccess.isAvailable(.teamLibrary) else { return [] } return teamLibrarySync.content.queries @@ -357,7 +353,7 @@ internal struct FavoritesTabView: View { linkedFolderGitStates: linkedFolderGitStates ), selection: $sharedSidebarState.selectedFavorite, - rowSizePreference: settingsManager.general.sidebarRowSize, + rowSizePreference: sidebarDisplay.options.rowSize, actions: FavoritesOutlineActions( primaryAction: { handlePrimaryAction($0) }, deleteSelection: { deleteNode($0) }, @@ -369,9 +365,7 @@ internal struct FavoritesTabView: View { ) } - /// The cell pins its hosted view to the full row width, and `NSHostingView` centers a root view - /// narrower than its bounds, so the row has to claim that width itself or short content drifts - /// to the middle. + // `NSHostingView` centers a narrower root view, so the row claims the full width or short content drifts. private func outlineRow(_ node: FavoritesOutlineNode) -> some View { rowContent(node) .font(resolvedRowSize.rowFont) @@ -380,18 +374,15 @@ internal struct FavoritesTabView: View { .contentShape(Rectangle()) } - /// AppKit sizes the row from `rowSizeStyle`, but it does that by laying out - /// `NSTableCellView.textField`, and these cells host SwiftUI instead. Without this the object - /// list grew with the sidebar size and the Favorites list beside it did not. + // The cells host SwiftUI, so AppKit's row size never reaches the text unless it is passed in. private var resolvedRowSize: SidebarRowSize { SidebarRowSizeResolver.resolve( - preference: settingsManager.general.sidebarRowSize, + preference: sidebarDisplay.options.rowSize, system: systemRowSize ) } - /// No `.contextMenu` on any row: the outline view owns the menu, so AppKit sets `clickedRow`, - /// highlights the clicked row and answers a right-click below the last one. + // No `.contextMenu`: the outline owns the menu, so AppKit sets `clickedRow` and answers below the last row. @ViewBuilder private func rowContent(_ node: FavoritesOutlineNode) -> some View { switch node.kind { @@ -428,12 +419,12 @@ internal struct FavoritesTabView: View { } icon: { Image(systemName: group.environment.iconName) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: sidebarDisplay.options.showObjectIcons) } private func favoriteDatabaseRow(_ entry: FavoriteDatabaseEntry) -> some View { Label(entry.database, systemImage: "cylinder") - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: sidebarDisplay.options.showObjectIcons) .lineLimit(1) .accessibilityLabel(String( format: String(localized: "%@: %@"), @@ -473,8 +464,7 @@ internal struct FavoritesTabView: View { } } - /// One line, not two. The outline draws a uniform 24pt row, and the stacked publisher caption - /// the SwiftUI list used would be clipped. + // One line: the outline draws a uniform row, and a stacked caption would be clipped. private func teamQueryRow(name: String, detail: String?) -> some View { Label { HStack(spacing: 6) { @@ -510,7 +500,7 @@ internal struct FavoritesTabView: View { Image(systemName: TableRowLogic.iconName(for: row.table.type)) .selectionAwareTint(Color.accentColor) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: sidebarDisplay.options.showObjectIcons) .accessibilityLabel( [ TableRowLogic.accessibilityLabel(table: row.table, isPendingDelete: false, isPendingTruncate: false), @@ -543,9 +533,7 @@ internal struct FavoritesTabView: View { } } - /// Selecting a favourite does not open it, so every open from this list is a deliberate one: - /// a double-click, Return, or a menu item. None of them may hand back a tab the next sidebar - /// click throws away. + // Every open here is deliberate, so none may hand back a tab the next sidebar click throws away. private func handlePrimaryAction(_ kind: FavoritesOutlineNode.Kind) { switch kind { case .header: @@ -596,10 +584,7 @@ internal struct FavoritesTabView: View { } } - // MARK: - Menu commands - - /// Runs what a contextual menu item described. The commands that end in a confirmation set the - /// state this view already owns, so the alert stays where the rest of the presentation is. + // Confirmations set state this view owns, so the alert stays with the rest of the presentation. private func perform(_ command: FavoritesMenuCommand) { switch command { case .useDatabase(let entry): @@ -724,13 +709,7 @@ internal struct FavoritesTabView: View { Task { await coordinator?.switchDatabase(to: entry.database) } } - // MARK: - Empty States - - /// An empty list has no row to right-click, so the background menu's commands are here too. - /// - /// The actions are stacked, not left to `ContentUnavailableView`'s default row. On macOS 15 the - /// row of three buttons is wider than the sidebar, and the view sizes its whole content to that - /// row, so the description and the buttons ran past both edges and were cut off. + // Stacked: on macOS 15 the default row of three buttons is wider than the sidebar and got cut off. private var emptyState: some View { UnavailableStateView { Label(String(localized: "No Favorites"), systemImage: "star") @@ -775,8 +754,7 @@ internal struct FavoritesTabView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - /// A filter miss is not a failed search, so it never borrows the search placeholder's "check - /// the spelling" advice. The filter control stays on screen above this, which is the reset. + // A filter miss is not a failed search, so no "check the spelling" advice; the filter control above is the reset. private var noFilterMatchState: some View { UnavailableStateView { Label(String(localized: "No Matching Favorites"), systemImage: "line.3.horizontal.decrease.circle") diff --git a/apple/TablePro/Views/Sidebar/RoutineRowView.swift b/apple/TablePro/Views/Sidebar/RoutineRowView.swift index cc4515a5e2..643eab37f6 100644 --- a/apple/TablePro/Views/Sidebar/RoutineRowView.swift +++ b/apple/TablePro/Views/Sidebar/RoutineRowView.swift @@ -1,8 +1,3 @@ -// -// RoutineRowView.swift -// TablePro -// - import SwiftUI enum RoutineRowLogic { @@ -22,7 +17,6 @@ enum RoutineRowLogic { } } - /// The parts the row could not show: its full identity, then whatever the engine said about it. static func tooltip(for routine: RoutineInfo) -> String { var lines = [RoutineDisplayLabel.copyableSignature(for: routine)] if let returnType = routine.returnType, !returnType.isEmpty { @@ -37,9 +31,9 @@ enum RoutineRowLogic { } struct RoutineRowView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let routine: RoutineInfo let displayLabel: String + let showsIcon: Bool var body: some View { Label { @@ -51,7 +45,7 @@ struct RoutineRowView: View { .selectionAwareTint(Color.accentColor) .frame(width: 16) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: showsIcon) .accessibilityElement(children: .combine) .accessibilityLabel(RoutineRowLogic.accessibilityLabel(for: routine, displayLabel: displayLabel)) .help(RoutineRowLogic.tooltip(for: routine)) diff --git a/apple/TablePro/Views/Sidebar/ServerObjectRowView.swift b/apple/TablePro/Views/Sidebar/ServerObjectRowView.swift index cd9b583400..d3a9c7bbb1 100644 --- a/apple/TablePro/Views/Sidebar/ServerObjectRowView.swift +++ b/apple/TablePro/Views/Sidebar/ServerObjectRowView.swift @@ -1,8 +1,3 @@ -// -// ServerObjectRowView.swift -// TablePro -// - import SwiftUI enum ServerObjectRowLogic { @@ -27,28 +22,37 @@ enum ServerObjectRowLogic { // Plain drawn values: `ServerObjectInfo` compares by id, so a refreshed version or state would read as unchanged. struct ServerObjectRowView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let name: String let detail: String? let iconName: String let tooltip: String let accessibilityLabel: String + let showsIcon: Bool - init(name: String, detail: String?, iconName: String, tooltip: String, accessibilityLabel: String) { + init( + name: String, + detail: String?, + iconName: String, + tooltip: String, + accessibilityLabel: String, + showsIcon: Bool + ) { self.name = name self.detail = detail self.iconName = iconName self.tooltip = tooltip self.accessibilityLabel = accessibilityLabel + self.showsIcon = showsIcon } - init(object: ServerObjectInfo, kind: SidebarServerObjectKind) { + init(object: ServerObjectInfo, kind: SidebarServerObjectKind, showsIcon: Bool = true) { self.init( name: object.name, detail: object.detail, iconName: kind.iconName, tooltip: ServerObjectRowLogic.tooltip(for: object, kind: kind), - accessibilityLabel: ServerObjectRowLogic.accessibilityLabel(for: object, kind: kind) + accessibilityLabel: ServerObjectRowLogic.accessibilityLabel(for: object, kind: kind), + showsIcon: showsIcon ) } @@ -71,7 +75,7 @@ struct ServerObjectRowView: View { .selectionAwareTint(Color.accentColor) .frame(width: 16) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: showsIcon) .accessibilityElement(children: .combine) .accessibilityLabel(accessibilityLabel) .help(tooltip) diff --git a/apple/TablePro/Views/Sidebar/SidebarFilterBanner.swift b/apple/TablePro/Views/Sidebar/SidebarFilterBanner.swift index b470da2ed9..f1f6fa4a38 100644 --- a/apple/TablePro/Views/Sidebar/SidebarFilterBanner.swift +++ b/apple/TablePro/Views/Sidebar/SidebarFilterBanner.swift @@ -1,11 +1,6 @@ -// -// SidebarFilterBanner.swift -// TablePro -// - import SwiftUI -/// A filtered list looks exactly like a short one, so the sidebar says it is filtered. +// A filtered list looks exactly like a short one, so the sidebar says it is filtered. struct SidebarFilterBanner: View { let label: String let showAll: () -> Void @@ -27,7 +22,7 @@ struct SidebarFilterBanner: View { } } -/// The schema filter's banner for one database, shown while the filter keeps anything at all. +// Shown while the schema filter keeps anything at all. struct SidebarSchemaFilterBanner: View { let connectionId: UUID let database: String? @@ -35,7 +30,7 @@ struct SidebarSchemaFilterBanner: View { @ObservedObject var sidebarState: SharedSidebarState @ObservedObject var catalog: ConnectionSidebarCatalog - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared private var summary: DatabaseTreeVisibility.Summary? { let selected = sidebarState.schemaFilter(for: database) @@ -43,7 +38,7 @@ struct SidebarSchemaFilterBanner: View { let schemas = SidebarSchemaFilter().schemaList(connectionId: connectionId, database: database ?? "") else { return nil } let systemSchemas = Set(PluginManager.shared.systemSchemaNames(for: databaseType)) - let showsSystem = settingsManager.general.showSystemContainers + let showsSystem = sidebarDisplay.options.showSystemContainers guard DatabaseTreeVisibility.isFilteringSchemas( selected: selected, schemas: schemas, systemSchemas: systemSchemas, showsSystem: showsSystem ) else { return nil } diff --git a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift index d2d00350c1..eac683d2c2 100644 --- a/apple/TablePro/Views/Sidebar/SidebarTreeView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarTreeView.swift @@ -15,7 +15,7 @@ struct SidebarTreeView: View { // Also carries the all-schema listing the view model's scan reads, so a listing that lands redraws the verdicts. @ObservedObject var catalog: ConnectionSidebarCatalog - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared private var activeDatabase: String? { let name = coordinator?.browseDatabaseName ?? "" @@ -35,7 +35,7 @@ struct SidebarTreeView: View { schemaService.schemas(for: connectionId), systemSchemas: systemSchemas, activeSchema: coordinator?.toolbarState.currentSchema, - showsSystem: settingsManager.general.showSystemContainers, + showsSystem: sidebarDisplay.options.showSystemContainers, selected: sidebarState.schemaFilter(for: activeDatabase), pinned: Set(pendingTruncates.union(pendingDeletes).compactMap(\.qualifyingSchema)) ) @@ -45,8 +45,7 @@ struct SidebarTreeView: View { viewModel.filterQuery } - /// The same verdict the outline applies, so the empty state and the rows can never disagree about - /// whether a schema survived the filter. + // The outline's own verdict, so the empty state and the rows never disagree. private var visibleSchemas: [String] { guard !searchText.isEmpty else { return schemas } // The listing of the database the schemas were read from, which during a switch is the one being left. @@ -92,8 +91,6 @@ struct SidebarTreeView: View { } } - /// Same outline the other two sidebar shapes use. See `SidebarView.tableList` for why a SwiftUI - /// `List` cannot serve here. private var treeList: some View { DatabaseTreeOutlineView( connectionId: connectionId, @@ -109,10 +106,10 @@ struct SidebarTreeView: View { activeDatabase: activeDatabase, activeSchema: coordinator?.toolbarState.currentSchema, selectedTables: windowState.selectedTables, - showRecentTables: settingsManager.general.showRecentTables, - showSystemContainers: settingsManager.general.showSystemContainers, - showsPartitions: settingsManager.general.showPartitions, - rowSizePreference: settingsManager.general.sidebarRowSize + showRecentTables: sidebarDisplay.options.showRecentTables, + showSystemContainers: sidebarDisplay.options.showSystemContainers, + showsPartitions: sidebarDisplay.options.showPartitions, + rowSizePreference: sidebarDisplay.options.rowSize ) } diff --git a/apple/TablePro/Views/Sidebar/SidebarView.swift b/apple/TablePro/Views/Sidebar/SidebarView.swift index a82344867e..3ebb98627e 100644 --- a/apple/TablePro/Views/Sidebar/SidebarView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarView.swift @@ -1,10 +1,3 @@ -// -// SidebarView.swift -// TablePro -// -// Created by Ngo Quoc Dat on 16/12/25. -// - import SwiftUI import TableProPluginKit import TableProUtilities @@ -12,9 +5,8 @@ import TableProUtilities struct SidebarView: View { @ObservedObject private var featureAccess = FeatureAccess.shared @StateObject private var viewModel: SidebarViewModel - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var sidebarDisplay = SidebarDisplayPreferences.shared @State private var showsSchemaProgress = false - /// See `presentedSchemaState`. @State private var showsLoadedCatalog = false @ObservedObject private var catalog: ConnectionSidebarCatalog @@ -83,9 +75,7 @@ struct SidebarView: View { } } - /// The schemas the flat outline lists below its own sections. Counted here too, or a search - /// whose only matches are in another schema is shown as "No Results" and the outline that would - /// have listed them is never drawn. + // Counted too, or a search matching only another schema shows No Results and never draws the outline. private var otherSchemaMatches: [String] { guard rootShape == .flat, !viewModel.filterQuery.isEmpty, let database = activeDatabase, DatabaseTreeMetadataService.listsTablesPerSchema(groupingStrategy) else { return [] } @@ -98,7 +88,7 @@ struct SidebarView: View { database: database, browsedSchema: coordinator?.toolbarState.currentSchema, searchText: searchText, - hiddenSchemas: settingsManager.general.showSystemContainers ? [] : systemSchemas, + hiddenSchemas: sidebarDisplay.options.showSystemContainers ? [] : systemSchemas, listingMatches: viewModel.schemaListingMatches(database: database, searchText: searchText), keptSchemas: SidebarSchemaFilter().keptSchemas(connectionId: connectionId, database: database)? .union(pending), @@ -119,16 +109,13 @@ struct SidebarView: View { PluginManager.shared.databaseGroupingStrategy(for: viewModel.databaseType) } - /// Only the flat list is scoped to one schema. The tree already shows every schema as a node, - /// so a picker there would name a schema the list is not filtered by. + // The tree shows every schema as a node, so a picker there would name a schema the list is not filtered by. private var supportsSchemaFooter: Bool { guard PluginManager.shared.supportsSchemaSwitching(for: viewModel.databaseType) else { return false } return rootShape == .flat } - /// The one derivation of the sidebar's shape. The outline's coordinator calls the same resolver - /// with the same inputs, so the wrapper this view picks and the root the outline builds can - /// never describe different sidebars. + // The outline's coordinator calls the same resolver, so the wrapper and the root never describe different sidebars. private var rootShape: SidebarRootShape { SidebarRootShapeResolver.resolve( groupingStrategy: groupingStrategy, @@ -167,8 +154,6 @@ struct SidebarView: View { ) } - // MARK: - Body - var body: some View { VStack(spacing: 0) { switch sidebarState.selectedSidebarTab { @@ -193,7 +178,7 @@ struct SidebarView: View { sidebarFooter } - .onChange(of: settingsManager.general.showRecentTables) { _ in + .onChange(of: sidebarDisplay.options.showRecentTables) { _ in sidebarState.reloadRecentTablesFromStore() } // A new session, or a database whose session is another connection, holds its own temporary tables. @@ -241,9 +226,7 @@ struct SidebarView: View { } } - // MARK: - Footer - - /// The Tables tab's bar. Favorites draws its own, because its commands belong to that view. + // Favorites draws its own bar, because its commands belong to that view. @ViewBuilder private var sidebarFooter: some View { if sidebarState.selectedSidebarTab == .tables { @@ -284,8 +267,6 @@ struct SidebarView: View { ) } - // MARK: - Tables Content - @ViewBuilder private var tablesContent: some View { switch rootShape { @@ -385,9 +366,7 @@ struct SidebarView: View { viewModel.databaseType.browsingRequiresSelectedDatabase && activeDatabase == nil } - /// Asked above the switch rather than inside its loading branch, so which of the two the - /// column renders stays a decision of the pure resolver that already owns every other one, - /// and is tested there rather than buried in a view. + // Resolved above the switch, so the pure, tested resolver decides every branch. @ViewBuilder private var flatContent: some View { let presentation = objectListPresentation @@ -454,8 +433,6 @@ struct SidebarView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - // MARK: - Table List - private var activeDatabase: String? { let name = coordinator?.browseDatabaseName ?? "" return name.isEmpty ? nil : name @@ -480,10 +457,10 @@ struct SidebarView: View { activeDatabase: activeDatabase, activeSchema: coordinator?.toolbarState.currentSchema, selectedTables: windowState.selectedTables, - showRecentTables: settingsManager.general.showRecentTables, - showSystemContainers: settingsManager.general.showSystemContainers, - showsPartitions: settingsManager.general.showPartitions, - rowSizePreference: settingsManager.general.sidebarRowSize + showRecentTables: sidebarDisplay.options.showRecentTables, + showSystemContainers: sidebarDisplay.options.showSystemContainers, + showsPartitions: sidebarDisplay.options.showPartitions, + rowSizePreference: sidebarDisplay.options.rowSize ) } @@ -509,8 +486,6 @@ private struct TemporaryTableReadKey: Hashable { let isConnected: Bool } -// MARK: - Preview - #Preview { SidebarView( sidebarState: SharedSidebarState(), diff --git a/apple/TablePro/Views/Sidebar/TableRowView.swift b/apple/TablePro/Views/Sidebar/TableRowView.swift index 22f4ec55ab..a372a7a32d 100644 --- a/apple/TablePro/Views/Sidebar/TableRowView.swift +++ b/apple/TablePro/Views/Sidebar/TableRowView.swift @@ -1,8 +1,3 @@ -// -// TableRowView.swift -// TablePro -// - import SwiftUI enum TableRowLogic { @@ -72,15 +67,14 @@ enum TableRowLogic { } struct TableRow: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let table: TableInfo + let showsIcon: Bool + let showsComment: Bool let isPendingTruncate: Bool let isPendingDelete: Bool var isFavorite: Bool = false var showsPartitionCount: Bool = false - /// Set when the row stands for a partition that is a relation of its own. It draws beside the - /// name like a comment does, and it is not the comment: the comment is what the server stores - /// against the object, and it is hidden behind its own setting. + // A partition that is a relation: drawn beside the name like a comment, and never hidden by the comment setting. var partitionBound: String? var accessibilityKind: String? var onToggleFavorite: (() -> Void)? @@ -93,19 +87,15 @@ struct TableRow: View { } private var visibleComment: String? { - guard settingsManager.general.showObjectComments, + guard showsComment, let comment = table.comment, !comment.isEmpty else { return nil } return comment } - private var showsObjectIcon: Bool { - settingsManager.general.showObjectIcons - } - private var showsLeadingIcon: Bool { TableRowLogic.showsLeadingIcon( - showObjectIcons: showsObjectIcon, + showObjectIcons: showsIcon, isPendingTruncate: isPendingTruncate, isPendingDelete: isPendingDelete ) @@ -155,7 +145,7 @@ struct TableRow: View { } } } icon: { - if showsObjectIcon { + if showsIcon { Image(systemName: TableRowLogic.iconName(for: table.type)) .selectionAwareTint(Color.accentColor) .frame(width: 16) diff --git a/apple/TablePro/Views/Sidebar/TriggerRowView.swift b/apple/TablePro/Views/Sidebar/TriggerRowView.swift index 660fff5af4..f8e99302c4 100644 --- a/apple/TablePro/Views/Sidebar/TriggerRowView.swift +++ b/apple/TablePro/Views/Sidebar/TriggerRowView.swift @@ -1,8 +1,3 @@ -// -// TriggerRowView.swift -// TablePro -// - import SwiftUI enum TriggerRowLogic { @@ -12,8 +7,7 @@ enum TriggerRowLogic { return String(format: String(localized: "%1$@ on %2$@"), base, table) } - /// The row shows the name; the table it fires for, its timing and its event go here, because - /// those are what tell two same-named triggers apart in a database-wide list. + // The table, timing and event are what tell two same-named triggers apart in a database-wide list. static func tooltip(for trigger: TriggerInfo) -> String { var lines: [String] = [trigger.qualifiedName] let firing = [trigger.timing, trigger.event, trigger.orientation] @@ -29,8 +23,8 @@ enum TriggerRowLogic { } struct TriggerRowView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let trigger: TriggerInfo + let showsIcon: Bool var body: some View { Label { @@ -51,7 +45,7 @@ struct TriggerRowView: View { .selectionAwareTint(Color.accentColor) .frame(width: 16) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: showsIcon) .accessibilityElement(children: .combine) .accessibilityLabel(TriggerRowLogic.accessibilityLabel(for: trigger)) .help(TriggerRowLogic.tooltip(for: trigger)) diff --git a/apple/TablePro/Views/Sidebar/UserTypeRowView.swift b/apple/TablePro/Views/Sidebar/UserTypeRowView.swift index 9b3bf88ead..cce0051d72 100644 --- a/apple/TablePro/Views/Sidebar/UserTypeRowView.swift +++ b/apple/TablePro/Views/Sidebar/UserTypeRowView.swift @@ -1,8 +1,3 @@ -// -// UserTypeRowView.swift -// TablePro -// - import SwiftUI enum UserTypeRowLogic { @@ -10,8 +5,7 @@ enum UserTypeRowLogic { "\(type.kind.displayName): \(type.name)" } - /// The row shows the name; what the type is made of goes here, because that is what tells an - /// enum from a domain before the reader opens either. + // What the type is made of tells an enum from a domain before the reader opens either. static func tooltip(for type: UserDefinedTypeInfo) -> String { var lines = [type.qualifiedName, type.kind.displayName] switch type.kind { @@ -32,8 +26,8 @@ enum UserTypeRowLogic { } struct UserTypeRowView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared let type: UserDefinedTypeInfo + let showsIcon: Bool var body: some View { Label { @@ -45,7 +39,7 @@ struct UserTypeRowView: View { .selectionAwareTint(Color.accentColor) .frame(width: 16) } - .sidebarRowIcon(visible: settingsManager.general.showObjectIcons) + .sidebarRowIcon(visible: showsIcon) .accessibilityElement(children: .combine) .accessibilityLabel(UserTypeRowLogic.accessibilityLabel(for: type)) .help(UserTypeRowLogic.tooltip(for: type)) diff --git a/apple/TablePro/Views/Structure/DDLTextView.swift b/apple/TablePro/Views/Structure/DDLTextView.swift index 8df3363b4c..ec2ed98c99 100644 --- a/apple/TablePro/Views/Structure/DDLTextView.swift +++ b/apple/TablePro/Views/Structure/DDLTextView.swift @@ -1,18 +1,10 @@ -// -// DDLTextView.swift -// TablePro -// -// Read-only DDL view with tree-sitter syntax highlighting via TableProEditorKit -// - import SwiftUI import TableProEditorKit import TableProGrammars import TableProPluginKit -/// Read-only DDL display with syntax highlighting powered by TableProEditorKit struct DDLTextView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice let ddl: String @Binding var fontSize: Double var databaseType: DatabaseType? @@ -21,7 +13,6 @@ struct DDLTextView: View { @State private var editorState = SourceEditorState() @State private var editorConfiguration: SourceEditorConfiguration - /// Primary initializer accepting DDL as a value (read-only display) init(ddl: String, fontSize: Binding, databaseType: DatabaseType? = nil) { self.ddl = ddl self._text = State(wrappedValue: ddl) @@ -47,6 +38,9 @@ struct DDLTextView: View { .onChange(of: fontSize) { newSize in editorConfiguration = Self.makeConfiguration(fontSize: newSize) } + .onChange(of: editorSettings.value) { _ in + editorConfiguration = Self.makeConfiguration(fontSize: fontSize) + } } private var foldProvider: LineFoldProvider? { diff --git a/apple/TablePro/Views/Structure/TriggerEditorView.swift b/apple/TablePro/Views/Structure/TriggerEditorView.swift index ef9b441168..6caa88bc5a 100644 --- a/apple/TablePro/Views/Structure/TriggerEditorView.swift +++ b/apple/TablePro/Views/Structure/TriggerEditorView.swift @@ -1,17 +1,10 @@ -// -// TriggerEditorView.swift -// TablePro -// -// DDL-first editor sheet for creating and editing triggers. -// - import SwiftUI import TableProEditorKit import TableProGrammars import TableProPluginKit struct TriggerEditorView: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var editorSettings = AppSettingsManager.shared.editorSlice enum Mode { case create case edit(originalName: String, originalDefinition: String) @@ -100,6 +93,9 @@ struct TriggerEditorView: View { .onChange(of: fontSize) { newSize in editorConfiguration = Self.makeConfiguration(fontSize: newSize) } + .onChange(of: editorSettings.value) { _ in + editorConfiguration = Self.makeConfiguration(fontSize: fontSize) + } } private var header: some View { diff --git a/apple/TableProTests/Models/UI/SidebarDisplayPreferencesTests.swift b/apple/TableProTests/Models/UI/SidebarDisplayPreferencesTests.swift new file mode 100644 index 0000000000..f02efee1c8 --- /dev/null +++ b/apple/TableProTests/Models/UI/SidebarDisplayPreferencesTests.swift @@ -0,0 +1,90 @@ +import Combine +import Foundation +@testable import TablePro +import Testing + +@MainActor +private final class WillChangeCounter { + private(set) var count = 0 + private var subscription: AnyCancellable? + + init(_ publisher: ObservableObjectPublisher) { + subscription = publisher.sink { [weak self] _ in self?.count += 1 } + } +} + +@MainActor +struct SidebarDisplayPreferencesTests { + @Test("Starts from the slice's current value") + func seedsFromSlice() { + var general = GeneralSettings.default + general.sidebarRowSize = .large + general.showSystemContainers = true + general.showObjectComments = false + let preferences = SidebarDisplayPreferences(general: SettingsSlice(general)) + + #expect(preferences.options.rowSize == .large) + #expect(preferences.options.showSystemContainers) + #expect(!preferences.options.showObjectComments) + #expect(preferences.options.showObjectIcons) + } + + @Test("A General write the sidebar does not draw publishes nothing") + func unrelatedWriteIsSilent() { + let slice = SettingsSlice(GeneralSettings.default) + let preferences = SidebarDisplayPreferences(general: slice) + let counter = WillChangeCounter(preferences.objectWillChange) + + slice.update { + $0.queryTimeoutSeconds = 120 + $0.shareAnalytics = false + $0.showWorkspaceRail = false + } + + #expect(counter.count == 0) + #expect(preferences.options == SidebarDisplayOptions(GeneralSettings.default)) + } + + @Test("One write of two sidebar fields publishes once, with both values") + func sidebarWritePublishesOnce() { + let slice = SettingsSlice(GeneralSettings.default) + let preferences = SidebarDisplayPreferences(general: slice) + let counter = WillChangeCounter(preferences.objectWillChange) + + slice.update { + $0.showObjectIcons = false + $0.showObjectComments = false + } + + #expect(counter.count == 1) + #expect(!preferences.options.showObjectIcons) + #expect(!preferences.options.showObjectComments) + } + + @Test("Each listing field reaches the options") + func everyListingFieldIsCarried() { + let slice = SettingsSlice(GeneralSettings.default) + let preferences = SidebarDisplayPreferences(general: slice) + let counter = WillChangeCounter(preferences.objectWillChange) + + slice.update { $0.showRecentTables.toggle() } + slice.update { $0.showSystemContainers.toggle() } + slice.update { $0.showPartitions.toggle() } + + let expected = SidebarDisplayOptions(slice.value) + #expect(counter.count == 3) + #expect(preferences.options == expected) + } + + @Test("A row size change publishes") + func rowSizeChangePublishes() { + let slice = SettingsSlice(GeneralSettings.default) + let preferences = SidebarDisplayPreferences(general: slice) + let counter = WillChangeCounter(preferences.objectWillChange) + + slice.update { $0.sidebarRowSize = .small } + + #expect(counter.count == 1) + #expect(preferences.options.rowSize == .small) + } +} diff --git a/apple/TableProTests/Views/AIChat/CustomSlashCommandPickTests.swift b/apple/TableProTests/Views/AIChat/CustomSlashCommandPickTests.swift new file mode 100644 index 0000000000..bffd07f0f3 --- /dev/null +++ b/apple/TableProTests/Views/AIChat/CustomSlashCommandPickTests.swift @@ -0,0 +1,48 @@ +import Foundation +@testable import TablePro +import Testing + +struct CustomSlashCommandPickTests { + private let summarize = CustomSlashCommand(name: "summarize", promptTemplate: "Summarize {{body}} using {{schema}}") + + @Test("A template without {{body}} runs at once") + func runsWithoutBody() { + let audit = CustomSlashCommand(name: "audit", promptTemplate: "Audit {{query}} on {{database}}") + #expect(CustomSlashCommandPick.resolve(audit, draft: "") == .run) + #expect(CustomSlashCommandPick.resolve(audit, draft: "some text") == .run) + } + + @Test("A template with {{body}} waits in an empty composer") + func composesIntoEmptyDraft() { + #expect(CustomSlashCommandPick.resolve(summarize, draft: "") == .compose("/summarize ")) + #expect(CustomSlashCommandPick.resolve(summarize, draft: " \n") == .compose("/summarize ")) + } + + @Test("Text already typed becomes the body") + func keepsDraftAsBody() { + #expect( + CustomSlashCommandPick.resolve(summarize, draft: " orders by month\n") + == .compose("/summarize orders by month") + ) + } + + @Test("Picking the command already typed keeps its body once") + func sameCommandKeepsBody() { + #expect( + CustomSlashCommandPick.resolve(summarize, draft: "/Summarize last week") + == .compose("/summarize last week") + ) + #expect(CustomSlashCommandPick.resolve(summarize, draft: "/summarize") == .compose("/summarize ")) + } + + @Test("A body typed after the composed command is what Send passes to the template") + func composedTextParsesBack() throws { + guard case .compose(let text) = CustomSlashCommandPick.resolve(summarize, draft: "") else { + Issue.record("expected the command to wait in the composer") + return + } + let invocation = try #require(SlashCommand.invocation(in: text + "orders by month")) + #expect(invocation.name == "summarize") + #expect(invocation.body == "orders by month") + } +} From 5c7f9c7ea31b3cb624356f00fdc6efab7dedcdd4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 17:46:53 +0700 Subject: [PATCH 24/48] feat(settings): AppKit sidebar shell with back/forward history, native title and page deep links --- apple/TablePro/AppDelegate.swift | 2 +- .../ConnectionRecoveryPerformer.swift | 13 +- .../Infrastructure/DeeplinkParser.swift | 25 +- .../Infrastructure/LaunchIntent.swift | 9 +- .../Infrastructure/LaunchIntentRouter.swift | 6 +- .../Infrastructure/WindowOpener.swift | 39 +- .../PluginNotificationService.swift | 6 +- .../Settings/Entries/AISettingsEntry.swift | 38 ++ .../Entries/AccountSettingsEntry.swift | 41 ++ .../Entries/AppearanceSettingsEntry.swift | 38 ++ .../Entries/ConnectionsSettingsEntry.swift | 41 ++ .../Settings/Entries/DataSettingsEntry.swift | 59 +++ .../Entries/EditorSettingsEntry.swift | 49 ++ .../Entries/ExtensionsSettingsEntry.swift | 26 + .../Entries/GeneralSettingsEntry.swift | 42 ++ .../Entries/KeyboardSettingsEntry.swift | 32 ++ .../Settings/Entries/MCPSettingsEntry.swift | 38 ++ .../Entries/NotificationsSettingsEntry.swift | 32 ++ .../Entries/ProfilesSettingsEntry.swift | 26 + .../Entries/SidebarTabsSettingsEntry.swift | 34 ++ .../Settings/Entries/SyncSettingsEntry.swift | 26 + .../SettingsDetailViewController.swift | 83 ++++ .../Settings/SettingsDrillInChrome.swift | 20 +- .../Views/Settings/SettingsPaneContext.swift | 77 +++ .../Views/Settings/SettingsPaneRouter.swift | 167 +++++++ .../SettingsSidebarViewController.swift | 385 +++++++++++++++ .../SettingsSplitViewController.swift | 195 ++++++++ .../Settings/SettingsTitleResolver.swift | 89 ++++ .../Settings/SettingsWindowController.swift | 456 ++++++------------ .../Settings/SettingsWindowToolbar.swift | 242 +++++++--- .../Views/Sidebar/NativeSearchField.swift | 15 - .../AppActivationPolicyTests.swift | 13 +- .../DeeplinkSettingsParsingTests.swift | 58 ++- .../Infrastructure/WindowOpenerTests.swift | 33 +- .../PluginNotificationServiceTests.swift | 9 + .../ConnectionRecoveryPresentationTests.swift | 36 +- .../Settings/SettingsWindowSizingTests.swift | 96 ++++ .../Settings/SettingsWindowTitleTests.swift | 315 +++++++++--- .../SettingsDeeplinkUITests.swift | 18 + .../SettingsWindowUITests.swift | 77 +++ .../Support/UITestCase+Settings.swift | 42 ++ 41 files changed, 2436 insertions(+), 612 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift create mode 100644 apple/TablePro/Views/Settings/SettingsDetailViewController.swift create mode 100644 apple/TablePro/Views/Settings/SettingsPaneContext.swift create mode 100644 apple/TablePro/Views/Settings/SettingsPaneRouter.swift create mode 100644 apple/TablePro/Views/Settings/SettingsSidebarViewController.swift create mode 100644 apple/TablePro/Views/Settings/SettingsSplitViewController.swift create mode 100644 apple/TablePro/Views/Settings/SettingsTitleResolver.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsWindowSizingTests.swift create mode 100644 apple/TableProUITests/SettingsWindowUITests.swift create mode 100644 apple/TableProUITests/Support/UITestCase+Settings.swift diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index 84e4e68a66..30de3144d1 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -76,7 +76,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { WindowOpener.shared.setWelcomePresenter { WelcomeWindowController.present() } WindowOpener.shared.setConnectionFormPresenter { ConnectionFormWindowController.present($0) } WindowOpener.shared.setIntegrationsActivityPresenter { IntegrationsActivityWindowController.present() } - WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present(pane: $0) } + WindowOpener.shared.setSettingsPresenter { SettingsWindowController.present($0) } KeyRepeatFilter.shared.install() TableClickFocus.shared.install() RecentTabSwitcherController.installEditorKeyClaim() diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift index 11be701b3c..6a4eaffc30 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionRecoveryPerformer.swift @@ -1,8 +1,3 @@ -// -// ConnectionRecoveryPerformer.swift -// TablePro -// - import AppKit internal struct PendingConnectionRecovery { @@ -23,16 +18,16 @@ internal enum ConnectionRecoveryPerformer { internal static func perform( _ action: ConnectionRecoveryAction, - for connection: DatabaseConnection + for connection: DatabaseConnection, + opener: WindowOpener = .shared ) { switch action { case .installPlugin: WelcomeRouter.shared.routePluginInstall(connection) case .openPluginSettings(let pluginId): - PluginsSettingsNavigation.shared.reveal(pluginId: pluginId) - WindowOpener.shared.openSettings(tab: .plugins) + opener.openSettings(revealingPlugin: pluginId) case .editConnection: - WindowOpener.shared.openConnectionForm(editing: connection.id) + opener.openConnectionForm(editing: connection.id) case .openLocalNetworkSettings: guard let url = localNetworkSettingsURL else { return } NSWorkspace.shared.open(url) diff --git a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift index 9b8723395b..61612e68e7 100644 --- a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift +++ b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift @@ -1,8 +1,3 @@ -// -// DeeplinkParser.swift -// TablePro -// - import Foundation import os import TableProImport @@ -83,17 +78,15 @@ internal enum DeeplinkParser { return .success(.openSharedLink(token: token)) } - /// Never fails: an unknown id or extra segments open the last-used pane, so a link to a pane - /// or section added later still opens Settings on an older app. + // Never fails, so a link to a pane or page added later still opens Settings on an older app. + // It only navigates: opening a page performs nothing and grants nothing. private static func parseSettings(_ url: URL) -> Result { - guard let identifier = pathSegments(url).first else { - return .success(.openSettings(nil)) - } - guard let pane = SettingsPane(urlIdentifier: identifier) else { + let segments = pathSegments(url) + let location = SettingsLocation(urlPathSegments: segments) + if location == nil, let identifier = segments.first { logger.notice("Unknown settings pane id \(identifier, privacy: .public), opening the last-used pane") - return .success(.openSettings(nil)) } - return .success(.openSettings(pane)) + return .success(.openSettings(location)) } private static func parseConnect(_ url: URL) -> Result { @@ -256,11 +249,7 @@ internal enum DeeplinkParser { responseMode = .legacy } - /// Only an absent parameter means every connection. Naming the parameter and then handing - /// over something unreadable used to fall back to absent, which turned a request scoped to - /// one connection into a request for all of them with the sheet pre-ticked to All - /// Connections. So presence is the test, not a non-empty value, and an empty field is kept - /// rather than dropped so it has to answer the same guard. (#2930) + // Only an absent parameter means every connection; an empty or unreadable one must not widen to all (#2930). let connectionIds: Set? if queryItems.contains(where: { $0.name == "connection-ids" }) { let csv = value("connection-ids") ?? "" diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift index 37ba828a0c..0ef70be726 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift @@ -1,8 +1,3 @@ -// -// LaunchIntent.swift -// TablePro -// - import Foundation import TableProImport @@ -26,8 +21,8 @@ internal enum LaunchIntent: @unchecked Sendable { case openSharedLink(token: String) case pairIntegration(PairingRequest) case startMCPServer - /// nil opens the last-used pane. - case openSettings(SettingsPane?) + // nil opens the last-used pane. + case openSettings(SettingsLocation?) case openDatabaseURL(URL) case installPlugin(URL) case reopenClosedTab(RecentlyClosedTabEntry) diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index 0e7f89087a..595b43d497 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -42,8 +42,8 @@ internal final class LaunchIntentRouter { case .startMCPServer: await startMCPServer() - case .openSettings(let pane): - WindowOpener.shared.openSettings(tab: pane) + case .openSettings(let location): + WindowOpener.shared.openSettings(location) case .installPlugin(let url): try await installPlugin(url) @@ -106,7 +106,7 @@ internal final class LaunchIntentRouter { private func installPlugin(_ url: URL) async throws { let entry = try await PluginManager.shared.installPlugin(from: url) Self.logger.info("Installed plugin '\(entry.name, privacy: .public)' from Finder") - WindowOpener.shared.openSettings(tab: .plugins) + WindowOpener.shared.openSettings(revealingPlugin: entry.id) } private func presentRecoverableError(_ error: Error, for intent: LaunchIntent, title: String) -> Bool { diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift index 366c740e00..2ebc42a0da 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowOpener.swift @@ -1,12 +1,14 @@ -// -// WindowOpener.swift -// TablePro -// - import AppKit import Combine import os +internal enum SettingsRequest: Equatable, Sendable { + // nil opens the last-used pane. + case open(SettingsLocation?) + // A nil id asks for the first plugin that needs an update. + case revealPlugin(String?) +} + @MainActor internal final class WindowOpener: ObservableObject { internal static let shared = WindowOpener() @@ -16,12 +18,11 @@ internal final class WindowOpener: ObservableObject { private var openWelcomeAction: (() -> Void)? private var openConnectionFormAction: ((ConnectionFormRequest) -> Void)? private var openIntegrationsActivityAction: (() -> Void)? - private var openSettingsAction: ((SettingsPane?) -> Void)? + private var openSettingsAction: ((SettingsRequest) -> Void)? private var stagedDraftId: UUID? private var pendingCalls: [() -> Void] = [] - /// Not private so a test can exercise the queue on an instance with no presenters - /// registered. Production code uses `shared`. + // Not private so a test can exercise the queue on an instance with no presenters registered. internal init() {} internal func openWelcome() { @@ -33,10 +34,22 @@ internal final class WindowOpener: ObservableObject { } } - internal func openSettings(tab: SettingsPane? = nil) { + internal func openSettings(_ location: SettingsLocation? = nil) { + requestSettings(.open(location)) + } + + internal func openSettings(tab pane: SettingsPane?) { + openSettings(pane.map { SettingsLocation.root($0) }) + } + + internal func openSettings(revealingPlugin pluginId: String?) { + requestSettings(.revealPlugin(pluginId)) + } + + private func requestSettings(_ request: SettingsRequest) { perform { opener in guard let present = opener.openSettingsAction else { return false } - present(tab) + present(request) return true } } @@ -115,14 +128,12 @@ internal final class WindowOpener: ObservableObject { drainPendingCalls() } - internal func setSettingsPresenter(_ present: @escaping (SettingsPane?) -> Void) { + internal func setSettingsPresenter(_ present: @escaping (SettingsRequest) -> Void) { openSettingsAction = present drainPendingCalls() } - /// Returns false when the presenter for that window has not been registered yet, which - /// queues the call. Each window registers independently, so one that has already migrated - /// to AppKit never waits on one that has not. + // A block returns false while its window has no presenter yet, which queues the call. private func perform(_ block: @escaping (WindowOpener) -> Bool) { AppActivationPolicyController.shared.enterForeground() guard !block(self) else { return } diff --git a/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift b/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift index aef854ffc1..9fb08f85f1 100644 --- a/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift +++ b/apple/TablePro/Core/Services/Notifications/PluginNotificationService.swift @@ -132,6 +132,7 @@ final class PluginNotificationService { let content = UNMutableNotificationContent() content.title = title content.body = body + content.sound = .default content.categoryIdentifier = Self.updateFailedCategoryId if let pluginId { content.userInfo = [Self.pluginIdKey: pluginId] @@ -165,7 +166,7 @@ final class PluginNotificationService { extension PluginNotificationService: NotificationHandling { func presentationOptions(for notification: UNNotification) -> UNNotificationPresentationOptions { - [.banner, .list] + [.banner, .list, .sound] } func handle(_ response: UNNotificationResponse) { @@ -173,7 +174,6 @@ extension PluginNotificationService: NotificationHandling { guard action == Self.openPluginSettingsActionId || action == UNNotificationDefaultActionIdentifier else { return } let pluginId = response.notification.request.content.userInfo[Self.pluginIdKey] as? String - PluginsSettingsNavigation.shared.reveal(pluginId: pluginId) - WindowOpener.shared.openSettings(tab: .plugins) + WindowOpener.shared.openSettings(revealingPlugin: pluginId) } } diff --git a/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift new file mode 100644 index 0000000000..2b72d9629f --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift @@ -0,0 +1,38 @@ +import SwiftUI + +internal struct AISettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var ai: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._ai = ObservedObject(wrappedValue: context.settings.aiSlice) + } + + internal var body: some View { + AISettingsView(settings: $ai.value) + } +} + +internal struct AISettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.slashCommands): + Form { CustomSlashCommandsSection(storage: CustomSlashCommandStorage.shared) } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct AIStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift new file mode 100644 index 0000000000..5d98a879fc --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift @@ -0,0 +1,41 @@ +import SwiftUI + +internal struct AccountSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + AccountSettingsView(model: context.models.account) + } +} + +internal struct AccountSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + @ObservedObject private var account: AccountSettingsModel + + internal init(route: SettingsRoute, context: SettingsPaneContext) { + self.route = route + self.context = context + self._account = ObservedObject(wrappedValue: context.models.account) + } + + internal var body: some View { + switch route { + case .page(.accountFeatures): + Form { + AccountFeaturesSection(access: account.access, offersPurchase: account.content.identity == .signedOut) + } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct AccountStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift new file mode 100644 index 0000000000..2381d23d68 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift @@ -0,0 +1,38 @@ +import SwiftUI + +internal struct AppearanceSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var appearance: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._appearance = ObservedObject(wrappedValue: context.settings.appearanceSlice) + } + + internal var body: some View { + AppearanceSettingsView(settings: $appearance.value) + } +} + +internal struct AppearanceSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.manageThemes): + // Not in a Form: a List inside a grouped Form does not scroll on macOS. + ThemeLibrarySection() + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct AppearanceStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift new file mode 100644 index 0000000000..6053b1a588 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift @@ -0,0 +1,41 @@ +import SwiftUI + +internal struct ConnectionsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var general: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._general = ObservedObject(wrappedValue: context.settings.generalSlice) + } + + internal var body: some View { + ConnectionsSettingsView(settings: $general.value) + } +} + +internal struct ConnectionsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.linkedFolders): + Form { LinkedFoldersSection() } + .formStyle(.grouped) + case .page(.trustedLinks): + Form { TrustedExternalConnectionsSection() } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct ConnectionsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift new file mode 100644 index 0000000000..4a7d190d4e --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift @@ -0,0 +1,59 @@ +import SwiftUI + +internal struct DataSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var dataGrid: SettingsSlice + @ObservedObject private var valueColors: SettingsSlice + @ObservedObject private var editor: SettingsSlice + @ObservedObject private var typography: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._dataGrid = ObservedObject(wrappedValue: context.settings.dataGridSlice) + self._valueColors = ObservedObject(wrappedValue: context.settings.valueColorsSlice) + self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) + self._typography = ObservedObject(wrappedValue: context.settings.typographySlice) + } + + internal var body: some View { + DataResultsSettingsView( + dataGrid: $dataGrid.value, + valueColors: $valueColors.value, + editor: $editor.value, + typography: $typography.value + ) + } +} + +internal struct DataSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + @ObservedObject private var history: SettingsSlice + + internal init(route: SettingsRoute, context: SettingsPaneContext) { + self.route = route + self.context = context + self._history = ObservedObject(wrappedValue: context.settings.historySlice) + } + + internal var body: some View { + switch route { + case .page(.queryHistory): + Form { HistorySection(settings: $history.value) } + .formStyle(.grouped) + case .page(.dataRewind): + Form { DataRewindSection(settings: $history.value) } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct DataStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift new file mode 100644 index 0000000000..229fe6b47e --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift @@ -0,0 +1,49 @@ +import SwiftUI + +internal struct EditorSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var editor: SettingsSlice + @ObservedObject private var typography: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) + self._typography = ObservedObject(wrappedValue: context.settings.typographySlice) + } + + internal var body: some View { + EditorSettingsView(settings: $editor.value, typography: $typography.value) + } +} + +internal struct EditorSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + @ObservedObject private var formatter: SettingsSlice + @ObservedObject private var editor: SettingsSlice + + internal init(route: SettingsRoute, context: SettingsPaneContext) { + self.route = route + self.context = context + self._formatter = ObservedObject(wrappedValue: context.settings.formatterSlice) + self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) + } + + internal var body: some View { + switch route { + case .page(.sqlFormatting): + Form { FormatterSection(settings: $formatter.value, editor: editor.value) } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct EditorStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift new file mode 100644 index 0000000000..35c552b48a --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift @@ -0,0 +1,26 @@ +import SwiftUI + +internal struct ExtensionsSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + InstalledPluginsView(registryClient: context.registryClient) + } +} + +internal struct ExtensionsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct ExtensionsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift new file mode 100644 index 0000000000..c8a3fe7e1f --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift @@ -0,0 +1,42 @@ +import SwiftUI + +internal struct GeneralSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var general: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._general = ObservedObject(wrappedValue: context.settings.generalSlice) + } + + internal var body: some View { + let settings = context.settings + GeneralSettingsView(settings: $general.value, onResetAll: { settings.resetToDefaults() }) + } +} + +internal struct GeneralSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.softwareUpdate): + Form { SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) } + .formStyle(.grouped) + case .page(.commandLineTool): + Form { CommandLineToolSection() } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct GeneralStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift new file mode 100644 index 0000000000..c076b89608 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift @@ -0,0 +1,32 @@ +import SwiftUI + +internal struct KeyboardSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var keyboard: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._keyboard = ObservedObject(wrappedValue: context.settings.keyboardSlice) + } + + internal var body: some View { + KeyboardSettingsView(settings: $keyboard.value) + } +} + +internal struct KeyboardSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct KeyboardStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift new file mode 100644 index 0000000000..2114e7aeb6 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift @@ -0,0 +1,38 @@ +import SwiftUI + +internal struct MCPSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var mcp: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._mcp = ObservedObject(wrappedValue: context.settings.mcpSlice) + } + + internal var body: some View { + MCPSettingsView(settings: $mcp.value) + } +} + +internal struct MCPSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + switch route { + case .page(.mcpApprovals): + Form { Section { MCPGrantListView() } } + .formStyle(.grouped) + default: + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } + } +} + +internal struct MCPStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift new file mode 100644 index 0000000000..0c12c2a3ae --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift @@ -0,0 +1,32 @@ +import SwiftUI + +internal struct NotificationsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var notifications: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._notifications = ObservedObject(wrappedValue: context.settings.notificationsSlice) + } + + internal var body: some View { + NotificationsSettingsView(settings: $notifications.value) + } +} + +internal struct NotificationsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct NotificationsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift new file mode 100644 index 0000000000..e37d226012 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift @@ -0,0 +1,26 @@ +import SwiftUI + +internal struct ProfilesSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + ProfilesSettingsView() + } +} + +internal struct ProfilesSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct ProfilesStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift new file mode 100644 index 0000000000..41cfb6afc0 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift @@ -0,0 +1,34 @@ +import SwiftUI + +internal struct SidebarTabsSettingsEntry: View { + internal let context: SettingsPaneContext + @ObservedObject private var general: SettingsSlice + @ObservedObject private var tabs: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._general = ObservedObject(wrappedValue: context.settings.generalSlice) + self._tabs = ObservedObject(wrappedValue: context.settings.tabsSlice) + } + + internal var body: some View { + SidebarTabsSettingsView(settings: $general.value, tabSettings: $tabs.value) + } +} + +internal struct SidebarTabsSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct SidebarTabsStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift new file mode 100644 index 0000000000..4625f19016 --- /dev/null +++ b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift @@ -0,0 +1,26 @@ +import SwiftUI + +internal struct SyncSettingsEntry: View { + internal let context: SettingsPaneContext + + internal var body: some View { + SyncSettingsView() + } +} + +internal struct SyncSettingsPageEntry: View { + internal let route: SettingsRoute + internal let context: SettingsPaneContext + + internal var body: some View { + SettingsPagePlaceholder(title: context.navigation.title(for: route)) + } +} + +internal struct SyncStackPresentations: ViewModifier { + internal let context: SettingsPaneContext + + internal func body(content: Content) -> some View { + content + } +} diff --git a/apple/TablePro/Views/Settings/SettingsDetailViewController.swift b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift new file mode 100644 index 0000000000..12d4beab3a --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift @@ -0,0 +1,83 @@ +import AppKit +import SwiftUI + +@MainActor +internal protocol SettingsPaneContextProviding: AnyObject { + func context(for pane: SettingsPane) -> SettingsPaneContext +} + +// Keeps one hosting controller per visited pane while the window is open: rebuilding a pane on +// every sidebar click cost 136 to 374 ms and dropped its scroll position and @State. +@MainActor +internal final class SettingsDetailViewController: NSViewController { + internal weak var provider: SettingsPaneContextProviding? + private var hosts: [SettingsPane: NSHostingController] = [:] + internal private(set) var shownPane: SettingsPane? + + internal init() { + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("SettingsDetailViewController does not support NSCoder init") + } + + override internal func loadView() { + view = NSView() + } + + internal func host(for pane: SettingsPane) -> NSHostingController? { + hosts[pane] + } + + internal func show(_ pane: SettingsPane) { + guard isViewLoaded, let provider else { return } + let existing = hosts[pane] + guard pane != shownPane || existing == nil else { return } + let host = existing ?? makeHost(for: provider.context(for: pane)) + for (other, hidden) in hosts where other != pane { + // Hidden hosts leave the key view loop and the accessibility tree, and add nothing to a live resize. + hidden.view.isHidden = true + hidden.view.autoresizingMask = [] + } + host.view.frame = view.bounds + host.view.autoresizingMask = [.width, .height] + host.view.isHidden = false + shownPane = pane + // A show before the window is key counts when it becomes key, so opening counts once. + if view.window?.isKeyWindow == true { + provider.context(for: pane).visit.bump() + } + } + + internal func windowDidBecomeKey() { + guard let shownPane, let provider else { return } + provider.context(for: shownPane).visit.bump() + } + + // After a close, so no pane observer or task outlives the window. + internal func releaseHosts() { + for host in hosts.values { + host.view.removeFromSuperview() + host.removeFromParent() + } + hosts.removeAll() + shownPane = nil + } + + private func makeHost(for context: SettingsPaneContext) -> NSHostingController { + let host = NSHostingController(rootView: SettingsPaneHost(context: context)) + // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. + host.sizingOptions = [] + if #available(macOS 14.0, *) { + // The window title and toolbar belong to the shell; a pane's navigationTitle must not reach them. + host.sceneBridgingOptions = [] + } + addChild(host) + host.view.frame = view.bounds + view.addSubview(host.view) + hosts[context.pane] = host + return host + } +} diff --git a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift index fecac11d6b..badb4e5198 100644 --- a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift +++ b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift @@ -1,24 +1,8 @@ -// -// SettingsDrillInChrome.swift -// TablePro -// - import SwiftUI -// A pushed Settings page reports its title up to the pane's NavigationStack, which hands it to the -// window toolbar (shown next to the Back control, System Settings style). The Back button and the -// title live in the toolbar, so a drill-in page adds no chrome of its own. -struct SettingsPageTitleKey: PreferenceKey { - static var defaultValue: String? { nil } - - static func reduce(value: inout String?, nextValue: () -> String?) { - if let next = nextValue() { value = next } - } -} - +// The shell titles pushed pages from their route; this stays only until the pane rewrites drop their calls. extension View { func settingsDrillIn(title: String) -> some View { - navigationTitle(title) - .preference(key: SettingsPageTitleKey.self, value: title) + self } } diff --git a/apple/TablePro/Views/Settings/SettingsPaneContext.swift b/apple/TablePro/Views/Settings/SettingsPaneContext.swift new file mode 100644 index 0000000000..f7272f8c22 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsPaneContext.swift @@ -0,0 +1,77 @@ +import Combine +import Foundation + +// Counts shows of a pane and key-window returns while it is shown, so a pane reloads with .task(id: visit.count). +@MainActor +internal final class SettingsPaneVisit: ObservableObject { + @Published internal private(set) var count = 0 + + internal func bump() { + count += 1 + } +} + +// The toolbar search field of a pane that filters its own list (Keyboard, Extensions). +@MainActor +internal final class SettingsPaneFilter: ObservableObject { + @Published internal var query = "" +} + +// Live for the window controller's lifetime, so a pane switch or a close never drops their state. +@MainActor +internal final class SettingsWindowModels { + internal private(set) lazy var themeLibrary = ThemeLibraryModel( + catalog: .shared, + selection: AppSettingsManager.shared, + editors: ThemeEditorWindows.shared + ) + + internal private(set) lazy var account = AccountSettingsModel(services: .shared) +} + +// A class, so a pane entry holding it compares equal across renders and keeps its body. +@MainActor +internal final class SettingsPaneContext { + internal let pane: SettingsPane + internal let settings: AppSettingsManager + internal let navigation: SettingsNavigationModel + internal let models: SettingsWindowModels + internal let registryClient: RegistryClient + internal let visit = SettingsPaneVisit() + internal let filter: SettingsPaneFilter? + private let errorPresenter: (_ title: String, _ message: String) -> Void + + internal init( + pane: SettingsPane, + settings: AppSettingsManager, + navigation: SettingsNavigationModel, + models: SettingsWindowModels, + registryClient: RegistryClient, + presentError: @escaping (_ title: String, _ message: String) -> Void + ) { + self.pane = pane + self.settings = settings + self.navigation = navigation + self.models = models + self.registryClient = registryClient + self.filter = Self.filtersItsList(pane) ? SettingsPaneFilter() : nil + self.errorPresenter = presentError + } + + internal var path: SettingsPanePath { + navigation.path(for: pane) + } + + internal var isCurrent: Bool { + navigation.location.pane == pane + } + + // For errors raised while the page that caused them is not on screen. + internal func presentError(title: String, message: String) { + errorPresenter(title, message) + } + + internal static func filtersItsList(_ pane: SettingsPane) -> Bool { + pane == .keyboard || pane == .plugins + } +} diff --git a/apple/TablePro/Views/Settings/SettingsPaneRouter.swift b/apple/TablePro/Views/Settings/SettingsPaneRouter.swift new file mode 100644 index 0000000000..7bfefff48f --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsPaneRouter.swift @@ -0,0 +1,167 @@ +import SwiftUI + +// The root of one retained pane host: the pane's own stack, its pages and its stack-level presentations. +internal struct SettingsPaneHost: View { + internal let context: SettingsPaneContext + + internal var body: some View { + content + .environment(\.appServices, .live) + } + + @ViewBuilder private var content: some View { + switch context.pane { + case .general: + SettingsPaneStack(context: context) { + GeneralSettingsEntry(context: context) + } page: { + GeneralSettingsPageEntry(route: $0, context: context) + } + .modifier(GeneralStackPresentations(context: context)) + case .appearance: + SettingsPaneStack(context: context) { + AppearanceSettingsEntry(context: context) + } page: { + AppearanceSettingsPageEntry(route: $0, context: context) + } + .modifier(AppearanceStackPresentations(context: context)) + case .notifications: + SettingsPaneStack(context: context) { + NotificationsSettingsEntry(context: context) + } page: { + NotificationsSettingsPageEntry(route: $0, context: context) + } + .modifier(NotificationsStackPresentations(context: context)) + case .keyboard: + SettingsPaneStack(context: context) { + KeyboardSettingsEntry(context: context) + } page: { + KeyboardSettingsPageEntry(route: $0, context: context) + } + .modifier(KeyboardStackPresentations(context: context)) + case .connections: + SettingsPaneStack(context: context) { + ConnectionsSettingsEntry(context: context) + } page: { + ConnectionsSettingsPageEntry(route: $0, context: context) + } + .modifier(ConnectionsStackPresentations(context: context)) + case .profiles: + SettingsPaneStack(context: context) { + ProfilesSettingsEntry(context: context) + } page: { + ProfilesSettingsPageEntry(route: $0, context: context) + } + .modifier(ProfilesStackPresentations(context: context)) + case .sidebar: + SettingsPaneStack(context: context) { + SidebarTabsSettingsEntry(context: context) + } page: { + SidebarTabsSettingsPageEntry(route: $0, context: context) + } + .modifier(SidebarTabsStackPresentations(context: context)) + case .editor: + SettingsPaneStack(context: context) { + EditorSettingsEntry(context: context) + } page: { + EditorSettingsPageEntry(route: $0, context: context) + } + .modifier(EditorStackPresentations(context: context)) + case .data: + SettingsPaneStack(context: context) { + DataSettingsEntry(context: context) + } page: { + DataSettingsPageEntry(route: $0, context: context) + } + .modifier(DataStackPresentations(context: context)) + case .ai: + SettingsPaneStack(context: context) { + AISettingsEntry(context: context) + } page: { + AISettingsPageEntry(route: $0, context: context) + } + .modifier(AIStackPresentations(context: context)) + case .mcp: + SettingsPaneStack(context: context) { + MCPSettingsEntry(context: context) + } page: { + MCPSettingsPageEntry(route: $0, context: context) + } + .modifier(MCPStackPresentations(context: context)) + case .plugins: + SettingsPaneStack(context: context) { + ExtensionsSettingsEntry(context: context) + } page: { + ExtensionsSettingsPageEntry(route: $0, context: context) + } + .modifier(ExtensionsStackPresentations(context: context)) + case .sync: + SettingsPaneStack(context: context) { + SyncSettingsEntry(context: context) + } page: { + SyncSettingsPageEntry(route: $0, context: context) + } + .modifier(SyncStackPresentations(context: context)) + case .account: + SettingsPaneStack(context: context) { + AccountSettingsEntry(context: context) + } page: { + AccountSettingsPageEntry(route: $0, context: context) + } + .modifier(AccountStackPresentations(context: context)) + } + } +} + +// One navigationDestination per stack, outside any Form or List, so every SettingsRoute link resolves. +private struct SettingsPaneStack: View { + private let context: SettingsPaneContext + @ObservedObject private var path: SettingsPanePath + private let root: Root + private let page: (SettingsRoute) -> Page + + init( + context: SettingsPaneContext, + @ViewBuilder root: () -> Root, + @ViewBuilder page: @escaping (SettingsRoute) -> Page + ) { + self.context = context + self._path = ObservedObject(wrappedValue: context.path) + self.root = root() + self.page = page + } + + var body: some View { + NavigationStack(path: routes) { + root + .frame(maxWidth: .infinity, maxHeight: .infinity) + .navigationDestination(for: SettingsRoute.self) { route in + page(route) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + + private var routes: Binding<[SettingsRoute]> { + let context = context + return Binding( + get: { context.path.routes }, + set: { context.navigation.setRoutes($0, for: context.pane) } + ) + } +} + +// Stands in for a page whose pane has not moved to the route-based pages yet. +internal struct SettingsPagePlaceholder: View { + internal let title: String + + internal var body: some View { + Form { + Section { + Text(verbatim: title) + .foregroundStyle(.secondary) + } + } + .formStyle(.grouped) + } +} diff --git a/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift b/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift new file mode 100644 index 0000000000..ca22970587 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift @@ -0,0 +1,385 @@ +import AppKit + +// AppKit on purpose: a SwiftUI sidebar List keeps the previous row's emphasized label after a +// programmatic selection change while it is not first responder, and making it first responder +// steals focus from the search field or a detail field. +@MainActor +internal final class SettingsSidebarViewController: NSViewController { + internal static let searchIdentifier = "settings-sidebar-search" + internal static let listIdentifier = "settings-sidebar" + private static let spacerHeight: CGFloat = 12 + private static let paneCellIdentifier = NSUserInterfaceItemIdentifier("SettingsSidebarPaneCell") + private static let pageCellIdentifier = NSUserInterfaceItemIdentifier("SettingsSidebarPageCell") + + internal let searchField = NSSearchField() + internal let tableView = NSTableView() + private let scrollView = NSScrollView() + private let noResultsLabel = NSTextField(labelWithString: "") + + internal var onSelectPane: ((SettingsPane) -> Void)? + internal var onOpenLocation: ((SettingsLocation) -> Void)? + internal var searchEntries: () -> [SettingsSearchEntry] = { [] } + + internal private(set) var rows: [SettingsSidebarRow] = SettingsNavigation.rows(matching: "") + private var query = "" + private var location: SettingsLocation + private var isReflecting = false + + internal init(location: SettingsLocation) { + self.location = location + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("SettingsSidebarViewController does not support NSCoder init") + } + + override internal func loadView() { + let root = NSView() + configureSearchField() + configureTable() + configureNoResultsLabel() + + for subview in [searchField, scrollView, noResultsLabel] { + subview.translatesAutoresizingMaskIntoConstraints = false + root.addSubview(subview) + } + NSLayoutConstraint.activate([ + searchField.topAnchor.constraint(equalTo: root.safeAreaLayoutGuide.topAnchor, constant: 8), + searchField.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 10), + searchField.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -10), + scrollView.topAnchor.constraint(equalTo: searchField.bottomAnchor, constant: 8), + scrollView.leadingAnchor.constraint(equalTo: root.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: root.trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: root.bottomAnchor), + noResultsLabel.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor), + noResultsLabel.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor), + noResultsLabel.leadingAnchor.constraint(greaterThanOrEqualTo: root.leadingAnchor, constant: 16), + noResultsLabel.trailingAnchor.constraint(lessThanOrEqualTo: root.trailingAnchor, constant: -16), + ]) + view = root + } + + override internal func viewDidLoad() { + super.viewDidLoad() + tableView.reloadData() + reflect(location) + } + + private func configureSearchField() { + searchField.placeholderString = String(localized: "Search") + searchField.sendsSearchStringImmediately = true + searchField.delegate = self + searchField.target = self + searchField.action = #selector(searchFieldChanged(_:)) + searchField.setAccessibilityIdentifier(Self.searchIdentifier) + if #available(macOS 26.0, *) { + searchField.controlSize = .large + } else { + searchField.controlSize = .regular + } + } + + private func configureTable() { + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("pane")) + column.resizingMask = .autoresizingMask + tableView.addTableColumn(column) + tableView.headerView = nil + tableView.style = .sourceList + tableView.rowSizeStyle = .default + tableView.backgroundColor = .clear + tableView.allowsMultipleSelection = false + // A query that hides the current pane leaves nothing selected; allowsEmptySelection false + // would select row 0 on every reload and navigate on each keystroke. + tableView.allowsEmptySelection = true + tableView.allowsTypeSelect = true + tableView.dataSource = self + tableView.delegate = self + tableView.target = self + tableView.action = #selector(rowClicked(_:)) + tableView.setAccessibilityIdentifier(Self.listIdentifier) + tableView.setAccessibilityLabel(String(localized: "Settings sections")) + + scrollView.documentView = tableView + scrollView.drawsBackground = false + scrollView.hasVerticalScroller = true + scrollView.hasHorizontalScroller = false + scrollView.autohidesScrollers = true + } + + private func configureNoResultsLabel() { + noResultsLabel.textColor = .secondaryLabelColor + noResultsLabel.alignment = .center + noResultsLabel.lineBreakMode = .byWordWrapping + noResultsLabel.maximumNumberOfLines = 0 + noResultsLabel.isHidden = true + } + + // MARK: - Location + + internal func reflect(_ location: SettingsLocation) { + self.location = location + guard isViewLoaded else { return } + let index = row(for: location) + isReflecting = true + defer { isReflecting = false } + if let index { + if tableView.selectedRow != index { + tableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) + } + tableView.scrollRowToVisible(index) + } else if tableView.selectedRow >= 0 { + tableView.deselectAll(nil) + } + } + + private func row(for location: SettingsLocation) -> Int? { + let pageRow = rows.firstIndex { + if case .page(_, let rowLocation) = $0 { return rowLocation == location } + return false + } + return pageRow ?? rows.firstIndex(of: .pane(location.pane)) + } + + // MARK: - Search + + internal var isFiltering: Bool { + SettingsSearchIndex.isFiltering(query) + } + + internal func filter(by text: String) { + if searchField.stringValue != text { + searchField.stringValue = text + } + applyQuery(text) + } + + internal func clearSearch() { + filter(by: "") + } + + // Dynamic names changed (a plugin loaded, a provider was renamed), so a visible result list is stale. + internal func reloadSearchResults() { + guard isFiltering else { return } + reloadRows() + } + + @objc private func searchFieldChanged(_ sender: NSSearchField) { + applyQuery(sender.stringValue) + } + + private func applyQuery(_ text: String) { + guard text != query else { return } + query = text + reloadRows() + } + + private func reloadRows() { + rows = SettingsNavigation.rows(matching: query, adding: isFiltering ? searchEntries() : []) + isReflecting = true + tableView.reloadData() + isReflecting = false + updateNoResults() + reflect(location) + } + + private func updateNoResults() { + let isEmpty = rows.isEmpty && isFiltering + noResultsLabel.isHidden = !isEmpty + guard isEmpty else { return } + noResultsLabel.stringValue = String(format: String(localized: "No Results for “%@”"), query) + } + + // Return or Down in the field goes to the first match, the way the System Settings search does. + private func pickFirstMatch() -> Bool { + guard let index = rows.firstIndex(where: \.isSelectable) else { + NSSound.beep() + return true + } + pick(rows[index]) + view.window?.makeFirstResponder(tableView) + return true + } + + // MARK: - Picking + + private func pick(_ row: SettingsSidebarRow) { + switch row { + case .pane(let pane): + onSelectPane?(pane) + case .page(_, let location): + onOpenLocation?(location) + case .spacer: + break + } + } + + // A click on the row already selected sends no selection change, so it arrives here; on a + // pane drilled into a page it returns to the pane's root. + @objc private func rowClicked(_ sender: Any?) { + let index = tableView.clickedRow + guard index >= 0, index == tableView.selectedRow, rows.indices.contains(index) else { return } + pick(rows[index]) + } +} + +extension SettingsSidebarViewController: NSTableViewDataSource, NSTableViewDelegate { + internal func numberOfRows(in tableView: NSTableView) -> Int { + rows.count + } + + internal func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { + guard rows.indices.contains(row), case .spacer = rows[row] else { return tableView.rowHeight } + return Self.spacerHeight + } + + internal func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool { + rows.indices.contains(row) && rows[row].isSelectable + } + + internal func tableView(_ tableView: NSTableView, typeSelectStringFor tableColumn: NSTableColumn?, row: Int) -> String? { + guard rows.indices.contains(row) else { return nil } + switch rows[row] { + case .pane(let pane): return pane.title + case .page(let title, _): return title + case .spacer: return nil + } + } + + internal func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + guard rows.indices.contains(row) else { return nil } + switch rows[row] { + case .pane(let pane): + let cell = tableView.makeView(withIdentifier: Self.paneCellIdentifier, owner: self) as? SettingsSidebarPaneCell + ?? SettingsSidebarPaneCell(identifier: Self.paneCellIdentifier) + cell.configure(pane) + return cell + case .page(let title, let location): + let cell = tableView.makeView(withIdentifier: Self.pageCellIdentifier, owner: self) as? SettingsSidebarPageCell + ?? SettingsSidebarPageCell(identifier: Self.pageCellIdentifier) + cell.configure(title: title, location: location) + return cell + case .spacer: + return nil + } + } + + internal func tableViewSelectionDidChange(_ notification: Notification) { + guard !isReflecting else { return } + let index = tableView.selectedRow + guard rows.indices.contains(index) else { + reflect(location) + return + } + pick(rows[index]) + } +} + +extension SettingsSidebarViewController: NSSearchFieldDelegate { + internal func controlTextDidChange(_ notification: Notification) { + guard (notification.object as? NSSearchField) === searchField else { return } + applyQuery(searchField.stringValue) + } + + internal func searchFieldDidEndSearching(_ sender: NSSearchField) { + applyQuery("") + } + + internal func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { + guard control === searchField else { return false } + switch commandSelector { + case #selector(NSResponder.moveDown(_:)), #selector(NSResponder.insertNewline(_:)): + return pickFirstMatch() + case #selector(NSResponder.cancelOperation(_:)) where searchField.stringValue.isEmpty: + view.window?.makeFirstResponder(tableView) + return true + default: + return false + } + } +} + +private extension SettingsSidebarRow { + var isSelectable: Bool { + if case .spacer = self { return false } + return true + } +} + +// Keeps the imageView and textField outlets: the source list then emphasizes the selected label +// and turns the template glyph white. +private final class SettingsSidebarPaneCell: NSTableCellView { + private let glyph = NSImageView() + private let label = NSTextField(labelWithString: "") + + init(identifier: NSUserInterfaceItemIdentifier) { + super.init(frame: .zero) + self.identifier = identifier + glyph.imageScaling = .scaleNone + glyph.setAccessibilityElement(false) + label.lineBreakMode = .byTruncatingTail + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + for subview in [glyph, label] { + subview.translatesAutoresizingMaskIntoConstraints = false + addSubview(subview) + } + imageView = glyph + textField = label + NSLayoutConstraint.activate([ + glyph.centerXAnchor.constraint(equalTo: leadingAnchor, constant: 13), + glyph.centerYAnchor.constraint(equalTo: centerYAnchor), + label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 28.5), + label.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor), + label.centerYAnchor.constraint(equalTo: centerYAnchor), + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("SettingsSidebarPaneCell does not support NSCoder init") + } + + func configure(_ pane: SettingsPane) { + // The table overwrites imageView.symbolConfiguration, so the size is baked into the image. + let image = NSImage(systemSymbolName: pane.symbol, accessibilityDescription: nil)? + .withSymbolConfiguration(NSImage.SymbolConfiguration(textStyle: .body, scale: .large)) + // An empty description, not nil: nil still reads the symbol name ("Gear shape") to VoiceOver. + image?.accessibilityDescription = "" + glyph.image = image + label.stringValue = pane.title + setAccessibilityIdentifier("settings-sidebar-\(pane.rawValue)") + setAccessibilityLabel(pane.title) + } +} + +private final class SettingsSidebarPageCell: NSTableCellView { + private let label = NSTextField(labelWithString: "") + + init(identifier: NSUserInterfaceItemIdentifier) { + super.init(frame: .zero) + self.identifier = identifier + label.lineBreakMode = .byTruncatingTail + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + label.translatesAutoresizingMaskIntoConstraints = false + addSubview(label) + textField = label + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 28.5), + label.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor), + label.centerYAnchor.constraint(equalTo: centerYAnchor), + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("SettingsSidebarPageCell does not support NSCoder init") + } + + func configure(title: String, location: SettingsLocation) { + label.stringValue = title + setAccessibilityLabel(title) + let pageIdentifier = location.routes.last?.page.map(\.urlIdentifier) + setAccessibilityIdentifier(pageIdentifier.map { "settings-sidebar-page-\($0)" } ?? "") + } +} diff --git a/apple/TablePro/Views/Settings/SettingsSplitViewController.swift b/apple/TablePro/Views/Settings/SettingsSplitViewController.swift new file mode 100644 index 0000000000..f6a8dc0f32 --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsSplitViewController.swift @@ -0,0 +1,195 @@ +import AppKit +import os + +// Settings is chrome: no theme slot and no ThemeBackdropState, only the system sidebar material +// and each Form's own background. +@MainActor +internal final class SettingsSplitViewController: NSSplitViewController, SettingsPaneContextProviding { + internal static let sidebarWidth: CGFloat = 220 + internal static let detailWidth: CGFloat = 520 + internal static let contentWidth: CGFloat = sidebarWidth + detailWidth + internal static let minimumContentSize = NSSize(width: contentWidth, height: 480) + + private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") + + internal let model: SettingsNavigationModel + internal let toolbarController = SettingsWindowToolbar() + internal let models = SettingsWindowModels() + internal let sidebar: SettingsSidebarViewController + internal let detail = SettingsDetailViewController() + + private let registryClient: RegistryClient + private let titles: SettingsTitleResolver + private var contexts: [SettingsPane: SettingsPaneContext] = [:] + private var panesReleased = false + + internal init( + registryClient: RegistryClient = .shared, + initial: SettingsLocation? = nil, + titles: SettingsTitleResolver = SettingsTitleResolver() + ) { + self.registryClient = registryClient + self.titles = titles + let start = initial ?? .root(Self.persistedPane) + self.model = SettingsNavigationModel( + initial: start, + isRouteAvailable: { titles.isAvailable($0) }, + titleResolver: { titles.title(for: $0) } + ) + self.sidebar = SettingsSidebarViewController(location: start) + super.init(nibName: nil, bundle: nil) + detail.provider = self + title = model.title + + model.onLocationChange = { [weak self] _ in self?.syncChrome() } + model.onUserPick = { Self.persist($0) } + sidebar.searchEntries = { titles.searchEntries } + sidebar.onSelectPane = { [weak self] pane in + self?.endEditing() + self?.model.select(pane) + } + sidebar.onOpenLocation = { [weak self] location in + self?.endEditing() + self?.model.open(location, recordsHistory: true) + // A search result is still a pick in the sidebar, so it sets the last-used pane like a row click. + Self.persist(location.pane) + } + toolbarController.onBack = { [weak self] in self?.goBack() } + toolbarController.onForward = { [weak self] in self?.goForward() } + } + + @available(*, unavailable) + internal required init?(coder: NSCoder) { + fatalError("SettingsSplitViewController does not support NSCoder init") + } + + internal static var persistedPane: SettingsPane { + let stored = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) + return stored.flatMap(SettingsPane.init(rawValue:)) ?? SettingsNavigation.defaultPane + } + + private static func persist(_ pane: SettingsPane) { + AppStorageEnvironment.shared.defaults.set(pane.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name) + } + + override internal func viewDidLoad() { + super.viewDidLoad() + + let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) + sidebarItem.minimumThickness = Self.sidebarWidth + sidebarItem.maximumThickness = Self.sidebarWidth + sidebarItem.canCollapse = false + addSplitViewItem(sidebarItem) + + let detailItem = NSSplitViewItem(viewController: detail) + // The divider comes out of the fixed width, so the detail minimum leaves room for it. + detailItem.minimumThickness = Self.detailWidth - splitView.dividerThickness + detailItem.holdingPriority = .splitPaneHolding + addSplitViewItem(detailItem) + + syncChrome() + } + + // MARK: - Navigation + + internal func navigate(to pane: SettingsPane) { + navigate(to: .root(pane), recordsHistory: true) + } + + internal func navigate(to location: SettingsLocation, recordsHistory: Bool) { + _ = view + model.open(location, recordsHistory: recordsHistory) + } + + internal func goBack() { + endEditing() + model.goBack() + } + + internal func goForward() { + endEditing() + model.goForward() + } + + // Commits a field being edited before the shell moves away from it; AppKit ends editing on resign. + internal func endEditing() { + guard let window = view.window, window.firstResponder is NSTextView else { return } + window.makeFirstResponder(nil) + } + + internal func focusSearch() { + guard !toolbarController.focusFilter() else { return } + focusSidebarSearch() + } + + internal func focusSidebarSearch() { + view.window?.makeFirstResponder(sidebar.searchField) + } + + // MARK: - Window lifetime + + internal func windowWillOpen() { + panesReleased = false + titles.startObserving { [weak self] in self?.namesDidChange() } + model.refresh() + syncChrome() + } + + internal func windowDidClose() { + titles.stopObserving() + sidebar.clearSearch() + model.resetHistory() + } + + internal func releasePanes() { + panesReleased = true + detail.releaseHosts() + contexts.removeAll() + } + + private func namesDidChange() { + model.refresh() + sidebar.reloadSearchResults() + } + + // MARK: - Chrome + + // The one place a location change reaches the window: title, toolbar, sidebar row and detail host. + internal func syncChrome() { + let location = model.location + title = model.title + toolbarController.update(canGoBack: model.canGoBack, canGoForward: model.canGoForward) + guard isViewLoaded else { return } + sidebar.reflect(location) + guard !panesReleased else { return } + toolbarController.showFilter(for: location.pane, filter: filter(for: location.pane)) + detail.show(location.pane) + } + + private func filter(for pane: SettingsPane) -> SettingsPaneFilter? { + guard SettingsPaneContext.filtersItsList(pane) else { return nil } + return context(for: pane).filter + } + + internal func context(for pane: SettingsPane) -> SettingsPaneContext { + if let context = contexts[pane] { return context } + let context = SettingsPaneContext( + pane: pane, + settings: .shared, + navigation: model, + models: models, + registryClient: registryClient, + presentError: { [weak self] title, message in self?.presentError(title: title, message: message) } + ) + contexts[pane] = context + return context + } + + private func presentError(title: String, message: String) { + guard let window = view.window, window.isVisible else { + Self.logger.notice("Settings error not shown, the window is closed: \(title, privacy: .public)") + return + } + AlertHelper.showErrorSheet(title: title, message: message, window: window) + } +} diff --git a/apple/TablePro/Views/Settings/SettingsTitleResolver.swift b/apple/TablePro/Views/Settings/SettingsTitleResolver.swift new file mode 100644 index 0000000000..4c5802f09d --- /dev/null +++ b/apple/TablePro/Views/Settings/SettingsTitleResolver.swift @@ -0,0 +1,89 @@ +import Combine +import Foundation + +// Answers the navigation model's two questions about routes whose subject lives outside Settings: +// does it still exist, and what is it called. It also feeds those names to the sidebar search. +@MainActor +internal final class SettingsTitleResolver { + internal struct Sources { + internal var plugins: @MainActor () -> [PluginEntry] + internal var rejectedPlugins: @MainActor () -> [RejectedPlugin] + internal var providers: @MainActor () -> [AIProviderConfig] + internal var isSignedIn: @MainActor () -> Bool + internal var changes: @MainActor () -> [AnyPublisher] + + internal static var live: Sources { + Sources( + plugins: { PluginManager.shared.plugins }, + rejectedPlugins: { PluginManager.shared.rejectedPlugins }, + providers: { AppSettingsManager.shared.ai.providers }, + isSignedIn: { FeatureAccess.shared.state.isSignedIn }, + changes: { + [ + PluginManager.shared.objectWillChange.map { _ in () }.eraseToAnyPublisher(), + AppSettingsManager.shared.aiSlice.objectWillChange.map { _ in () }.eraseToAnyPublisher(), + FeatureAccess.shared.objectWillChange.map { _ in () }.eraseToAnyPublisher(), + ] + } + ) + } + } + + private let sources: Sources + private var subscription: AnyCancellable? + + internal init(sources: Sources = .live) { + self.sources = sources + } + + internal func isAvailable(_ route: SettingsRoute) -> Bool { + switch route { + case .page(.accountDevices), .page(.accountTeams): + sources.isSignedIn() + case .page: + true + case .plugin(let id): + sources.plugins().contains { $0.id == id } + case .rejectedPlugin(let url): + sources.rejectedPlugins().contains { $0.url == url } + case .aiProvider(let id): + sources.providers().contains { $0.id == id } + } + } + + internal func title(for route: SettingsRoute) -> String? { + switch route { + case .page: + nil + case .plugin(let id): + sources.plugins().first { $0.id == id }?.name + case .rejectedPlugin(let url): + sources.rejectedPlugins().first { $0.url == url }?.name + case .aiProvider(let id): + sources.providers().first { $0.id == id }?.displayName + } + } + + internal var searchEntries: [SettingsSearchEntry] { + let plugins = sources.plugins().map { + SettingsSearchEntry(title: $0.name, location: SettingsLocation(route: .plugin(id: $0.id))) + } + let providers = sources.providers().map { + SettingsSearchEntry(title: $0.displayName, location: SettingsLocation(route: .aiProvider($0.id))) + } + return plugins + providers + } + + // Delivered a run-loop turn later: objectWillChange fires before the new value lands. + internal func startObserving(_ onChange: @escaping @MainActor () -> Void) { + subscription = Publishers.MergeMany(sources.changes()) + .receive(on: RunLoop.main) + .sink { _ in + MainActor.assumeIsolated { onChange() } + } + } + + internal func stopObserving() { + subscription = nil + } +} diff --git a/apple/TablePro/Views/Settings/SettingsWindowController.swift b/apple/TablePro/Views/Settings/SettingsWindowController.swift index 8d482b0b45..9da0df40a8 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowController.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowController.swift @@ -1,360 +1,202 @@ -// -// SettingsWindowController.swift -// TablePro -// - import AppKit -import Combine -import os -import SwiftUI // An AppKit window, so the app needs no SwiftUI Settings scene (which would rewrite NSApp.mainMenu). @MainActor -internal final class SettingsWindowController: NSWindowController { +internal final class SettingsWindowController: NSWindowController, NSWindowDelegate { + // A new name: the old one holds 768 and 800 wide frames and heights shrunk by contentLayoutRect. + internal static let frameAutosaveName = "settings-sidebar" + internal static let styleMask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] + private static let preferredContentHeight: CGFloat = 700 + private static let screenMargin: CGFloat = 80 + private static var shared: SettingsWindowController? - internal static func present(pane: SettingsPane? = nil) { - let controller = shared ?? SettingsWindowController() - shared = controller - controller.split?.navigate(to: pane) - controller.showWindow(nil) - controller.window?.makeKeyAndOrderFront(nil) - AppActivationPolicyController.shared.activate() + internal let split: SettingsSplitViewController + + internal static func present(_ request: SettingsRequest) { + switch request { + case .open(let location): + present(location) + case .revealPlugin(let pluginId): + presentPlugin(revealing: pluginId) + } + } + + // Cmd-, on a visible window only brings it forward; a location navigates unless a sheet is up. + internal static func present(_ location: SettingsLocation? = nil) { + let controller = sharedController(opening: location) + controller.prepareToShow(location) + controller.showAndActivate() } - private var split: SettingsSplitViewController? { - contentViewController as? SettingsSplitViewController + // A loaded plugin opens its page; anything else asks the Extensions pane to find it once its list loads. + internal static func presentPlugin(revealing pluginId: String?) { + let location = pluginId.map { SettingsLocation(route: .plugin(id: $0)) } ?? .root(.plugins) + let controller = sharedController(opening: location) + if controller.prepareToShow(location), pluginId == nil { + controller.split.model.requestPluginReveal(nil) + } + controller.showAndActivate() + } + + private static func sharedController(opening location: SettingsLocation?) -> SettingsWindowController { + if let shared { return shared } + let controller = SettingsWindowController( + registryClient: .shared, + initial: .root(location?.pane ?? SettingsSplitViewController.persistedPane) + ) + shared = controller + return controller } - // A defaulted parameter would let `SettingsWindowController()` resolve to the inherited `init()`, which builds no window. + // A defaulted parameter alone would let `SettingsWindowController()` resolve to an inherited init that builds no window. internal convenience init() { self.init(registryClient: .shared) } - internal convenience init(registryClient: RegistryClient) { - let split = SettingsSplitViewController(registryClient: registryClient) + internal init(registryClient: RegistryClient, initial: SettingsLocation? = nil) { + let split = SettingsSplitViewController(registryClient: registryClient, initial: initial) + self.split = split + // This init binds window.title to split.title, so the Window menu and VoiceOver read the page. let window = NSWindow(contentViewController: split) window.identifier = NSUserInterfaceItemIdentifier(WindowIdentifier.settings) + window.styleMask = Self.styleMask window.keepsKeyViewLoopCurrent() - // fullSizeContentView lets the sidebar material run the full window height, behind the - // traffic lights, like System Settings and other native sidebar windows. - window.styleMask = [.titled, .closable, .resizable, .fullSizeContentView] - // No centered window title; the pane name lives in the toolbar beside Back. - window.titleVisibility = .hidden - window.titlebarAppearsTransparent = true + window.isRestorable = false + window.tabbingMode = .disallowed + window.collectionBehavior.insert([.fullScreenNone, .fullScreenDisallowsTiling]) + window.titleVisibility = .visible window.toolbarStyle = .unified window.toolbar = split.toolbarController.makeToolbar() - window.isRestorable = false - // Width fixed (sidebar + detail); height resizes. - window.contentMinSize = SettingsSplitViewController.minimumContentSize - window.contentMaxSize = NSSize(width: SettingsSplitViewController.minimumContentSize.width, height: .greatestFiniteMagnitude) - window.setContentSize(SettingsSplitViewController.defaultContentSize) - window.applyAutosaveName(WindowIdentifier.settings) - window.setContentSize( - NSSize( - width: SettingsSplitViewController.minimumContentSize.width, - height: max(window.contentLayoutRect.height, SettingsSplitViewController.minimumContentSize.height) - ) + window.standardWindowButton(.zoomButton)?.isEnabled = false + window.initialFirstResponder = split.sidebar.tableView + Self.applyFrame(to: window, autosaveName: SplitViewAutosaveName.current(Self.frameAutosaveName)) + + super.init(window: window) + window.delegate = self + split.syncChrome() + NotificationCenter.default.addObserver( + self, + selector: #selector(applicationWillTerminate(_:)), + name: NSApplication.willTerminateNotification, + object: nil ) - self.init(window: window) - } -} - -// The sidebar list + detail pane. Replaces the twelve-item .preference toolbar; a scrolling -// sidebar has no item cap, and the detail hosts a NavigationStack so a row can push sub-pages. -internal final class SettingsSplitViewController: NSSplitViewController { - // System Settings keeps a fixed width and resizes in height only. - internal static let minimumContentSize = NSSize(width: sidebarWidth + detailMinWidth, height: 480) - internal static let defaultContentSize = NSSize(width: sidebarWidth + detailMinWidth, height: 700) - private static let sidebarWidth: CGFloat = 248 - private static let detailMinWidth: CGFloat = 520 - - private static let logger = Logger(subsystem: "com.TablePro", category: "SettingsWindow") - - internal let model: LegacySettingsNavigationModel - internal let toolbarController: SettingsWindowToolbar - private let registryClient: RegistryClient - private var cancellables: Set = [] - - internal init(registryClient: RegistryClient = .shared) { - self.registryClient = registryClient - let model = LegacySettingsNavigationModel(initial: Self.persistedPane) - self.model = model - self.toolbarController = SettingsWindowToolbar(model: model) - super.init(nibName: nil, bundle: nil) } + @available(*, unavailable) internal required init?(coder: NSCoder) { - fatalError("SettingsSplitViewController does not support NSCoder init") - } - - private static var persistedPane: SettingsPane { - let stored = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) - guard let stored, let pane = SettingsPane(rawValue: stored) else { return SettingsNavigation.defaultPane } - return pane - } - - // A user click persists as the new last-used pane; a programmatic jump (openSettings, deep link) - // navigates without clobbering it. - internal func navigate(to pane: SettingsPane?) { - _ = view // loads the view on every supported macOS, which attaches the selection observer - model.applyProgrammatic(pane ?? Self.persistedPane) - } - - override func viewDidLoad() { - super.viewDidLoad() - - let sidebar = NSHostingController(rootView: SettingsSidebarView(model: model)) - let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebar) - sidebarItem.minimumThickness = Self.sidebarWidth - sidebarItem.maximumThickness = Self.sidebarWidth - sidebarItem.canCollapse = false - addSplitViewItem(sidebarItem) - - let detail = NSHostingController(rootView: SettingsDetailView(model: model, registryClient: registryClient)) - // A split item's hosting controller fixes its fitting size as a required minimum unless this is cleared. - detail.sizingOptions = [] - let detailItem = NSSplitViewItem(viewController: detail) - detailItem.minimumThickness = Self.detailMinWidth - detailItem.holdingPriority = NSLayoutConstraint.Priority(260) // below dragThatCannotResizeWindow (490) - addSplitViewItem(detailItem) - - model.$selection - .removeDuplicates() - .sink { [weak self] pane in - self?.persistUserSelection(pane) - } - .store(in: &cancellables) - } - - private func persistUserSelection(_ pane: SettingsPane) { - guard !model.isApplyingProgrammatic else { return } - AppStorageEnvironment.shared.defaults.set(pane.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name) + fatalError("SettingsWindowController does not support NSCoder init") + } + + // Returns false when nothing navigated: an attached sheet, or no location for a window already on screen. + @discardableResult + internal func prepareToShow(_ location: SettingsLocation?) -> Bool { + guard let window, window.attachedSheet == nil else { return false } + if window.isVisible || window.isMiniaturized { + guard let location else { return false } + split.endEditing() + split.navigate(to: location, recordsHistory: true) + return true + } + split.navigate(to: location ?? .root(SettingsSplitViewController.persistedPane), recordsHistory: false) + split.windowWillOpen() + window.makeFirstResponder(split.sidebar.tableView) + return true } -} - -// Goes away with this shell once it moves to SettingsNavigationModel. -@MainActor -internal final class LegacySettingsNavigationModel: ObservableObject { - @Published internal var selection: SettingsPane - // The detail's NavigationStack path, owned here so the window toolbar can read depth and drive Back. - @Published internal var path = NavigationPath() - // The pushed page's title, reported by the drill-in modifier; nil at a pane root. - @Published internal var drillTitle: String? - internal private(set) var isApplyingProgrammatic = false - - internal var currentTitle: String { drillTitle ?? selection.title } - internal var canGoBack: Bool { !path.isEmpty } - internal init(initial: SettingsPane) { - self.selection = initial + private func showAndActivate() { + if window?.isMiniaturized == true { + window?.deminiaturize(nil) + } + showWindow(nil) + window?.makeKeyAndOrderFront(nil) + AppActivationPolicyController.shared.activate() } - // From the sidebar list: the user picked a row, so it becomes the last-used pane. - internal func userSelect(_ pane: SettingsPane) { - resetDepth() - isApplyingProgrammatic = false - selection = pane + internal static func defaultContentSize(on screen: NSScreen?) -> NSSize { + let available = (screen?.visibleFrame.height ?? 800) - screenMargin + let height = max(SettingsSplitViewController.minimumContentSize.height, min(preferredContentHeight, available)) + return NSSize(width: SettingsSplitViewController.contentWidth, height: height) } - // From openSettings / a deep link: show the pane but do not rewrite the last-used pane. - internal func applyProgrammatic(_ pane: SettingsPane) { - resetDepth() - isApplyingProgrammatic = true - selection = pane - isApplyingProgrammatic = false - } + // Reads the content size from contentRect(forFrameRect:): contentLayoutRect leaves out the toolbar + // band, and writing it back shrank the window on every launch. + internal static func applyFrame(to window: NSWindow, autosaveName: NSWindow.FrameAutosaveName?) { + let width = SettingsSplitViewController.contentWidth + let minimumHeight = SettingsSplitViewController.minimumContentSize.height + let preferred = defaultContentSize(on: window.screen ?? NSScreen.main) + window.setContentSize(preferred) - internal func goBack() { - guard !path.isEmpty else { return } - path.removeLast() + // Restored before the size limits go on: AppKit clamps a restored frame to them, which hides an older width. + var restored = false + if let autosaveName { + window.setFrameAutosaveName(autosaveName) + restored = window.setFrameUsingName(autosaveName) + } + let content = window.contentRect(forFrameRect: window.frame).size + window.contentMinSize = SettingsSplitViewController.minimumContentSize + window.contentMaxSize = NSSize(width: width, height: .greatestFiniteMagnitude) + if !restored || abs(content.width - width) > 0.5 { + window.setContentSize(preferred) + window.center() + } else if content.height < minimumHeight { + window.setContentSize(NSSize(width: width, height: minimumHeight)) + } } - private func resetDepth() { - path = NavigationPath() - drillTitle = nil + internal func windowShouldClose(_ sender: NSWindow) -> Bool { + split.endEditing() + return true } -} - -private struct SettingsSidebarView: View { - @ObservedObject fileprivate var model: LegacySettingsNavigationModel - // Search lives here, not on the nav model, so typing re-renders only the sidebar list and never - // the detail pane or the toolbar. - @State private var searchText = "" - private var selectionBinding: Binding { - Binding( - get: { model.selection }, - set: { if let pane = $0 { model.userSelect(pane) } } - ) - } - - fileprivate var body: some View { - let matches = Set(SettingsNavigation.panes(matching: searchText)) - return VStack(spacing: 0) { - NativeSearchField( - text: $searchText, - placeholder: String(localized: "Search"), - fixedHeight: 28, - accessibilityIdentifier: "settings-sidebar-search" - ) - .padding(.horizontal, 10) - .padding(.top, 10) - .padding(.bottom, 8) - - List(selection: selectionBinding) { - ForEach(SettingsNavigation.sections, id: \.id) { section in - let panes = section.panes.filter(matches.contains) - if !panes.isEmpty { - Section { - ForEach(panes, id: \.self) { pane in - // The sidebar tints the symbol with the accent and inverts it on - // selection (Xcode's Settings sidebar), so no custom icon view. - Label(pane.title, systemImage: pane.symbol) - .tag(Optional(pane)) - } - } - } - } - } - .listStyle(.sidebar) + internal func windowWillClose(_ notification: Notification) { + split.endEditing() + split.windowDidClose() + // Next turn, after AppKit finishes closing; a window reopened in the meantime keeps its panes. + DispatchQueue.main.async { [weak self] in + guard let self, self.window?.isVisible != true, self.window?.isMiniaturized != true else { return } + self.split.releasePanes() } } -} - -private struct SettingsDetailView: View { - @ObservedObject fileprivate var model: LegacySettingsNavigationModel - fileprivate let registryClient: RegistryClient - fileprivate var body: some View { - // Each pane owns its own stack, keyed by selection, so switching panes resets its depth. - SettingsPaneStack(model: model, pane: model.selection, registryClient: registryClient) - .id(model.selection) - .environment(\.appServices, .live) + internal func windowDidBecomeKey(_ notification: Notification) { + split.detail.windowDidBecomeKey() } -} - -private struct SettingsPaneStack: View { - @ObservedObject fileprivate var model: LegacySettingsNavigationModel - fileprivate let pane: SettingsPane - fileprivate let registryClient: RegistryClient - fileprivate var body: some View { - NavigationStack(path: $model.path) { - SettingsPaneContent(pane: pane, registryClient: registryClient, path: $model.path) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - .onPreferenceChange(SettingsPageTitleKey.self) { title in - MainActor.assumeIsolated { model.drillTitle = title } - } + @objc private func applicationWillTerminate(_ notification: Notification) { + split.endEditing() } -} - -// A pushed drill-in page. Back button and title come from the NavigationStack. -private struct SettingsSubpageView: View { - @ObservedObject fileprivate var settingsManager: AppSettingsManager - fileprivate let subpage: SettingsSubpage - fileprivate var body: some View { - content - .settingsDrillIn(title: subpage.title) + @objc internal func navigateBack(_ sender: Any?) { + split.goBack() } - @ViewBuilder private var content: some View { - switch subpage { - case .softwareUpdate: - Form { SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) } - .formStyle(.grouped) - case .commandLine: - Form { CommandLineToolSection() } - .formStyle(.grouped) - case .manageThemes: - // Not wrapped in a Form: a List inside a grouped Form does not scroll on macOS. - ThemeLibrarySection() - .frame(maxWidth: .infinity, maxHeight: .infinity) - case .sqlFormatting: - Form { FormatterSection(settings: $settingsManager.formatter, editor: settingsManager.editor) } - .formStyle(.grouped) - case .queryHistory: - Form { HistorySection(settings: $settingsManager.history) } - .formStyle(.grouped) - case .dataRewind: - Form { DataRewindSection(settings: $settingsManager.history) } - .formStyle(.grouped) - case .whatSyncs: - Form { SyncCategoriesSection(settingsManager: settingsManager) } - .formStyle(.grouped) - } + @objc internal func navigateForward(_ sender: Any?) { + split.goForward() } -} -private struct SettingsPaneContent: View { - @ObservedObject private var settingsManager = AppSettingsManager.shared - - private let pane: SettingsPane - private let registryClient: RegistryClient - private let path: Binding - - fileprivate init(pane: SettingsPane, registryClient: RegistryClient, path: Binding) { - self.pane = pane - self.registryClient = registryClient - self.path = path + @objc internal func performFind(_ sender: Any?) { + split.focusSearch() } - fileprivate var body: some View { - paneContent - .navigationDestination(for: SettingsSubpage.self) { subpage in - SettingsSubpageView(settingsManager: settingsManager, subpage: subpage) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } + @objc internal func focusSidebarFilter(_ sender: Any?) { + split.focusSidebarSearch() } +} - @ViewBuilder private var paneContent: some View { - switch pane { - case .general: - GeneralSettingsView( - settings: $settingsManager.general, - onResetAll: { settingsManager.resetToDefaults() } - ) - case .sidebar: - SidebarTabsSettingsView( - settings: $settingsManager.general, - tabSettings: $settingsManager.tabs - ) - case .connections: - ConnectionsSettingsView(settings: $settingsManager.general) - case .appearance: - AppearanceSettingsView(settings: $settingsManager.appearance) - case .editor: - EditorSettingsView( - settings: $settingsManager.editor, - typography: $settingsManager.typography - ) - case .data: - DataResultsSettingsView( - dataGrid: $settingsManager.dataGrid, - valueColors: $settingsManager.valueColors, - editor: $settingsManager.editor, - typography: $settingsManager.typography - ) - case .keyboard: - KeyboardSettingsView(settings: $settingsManager.keyboard) - case .profiles: - ProfilesSettingsView() - case .notifications: - NotificationsSettingsView(settings: $settingsManager.notifications) - case .ai: - AISettingsView(settings: $settingsManager.ai) - case .mcp: - MCPSettingsView(settings: $settingsManager.mcp) - case .plugins: - InstalledPluginsView(registryClient: registryClient, path: path) - .frame(maxWidth: .infinity, maxHeight: .infinity) - case .sync: - SyncSettingsView() - case .account: - AccountSettingsView(model: AccountSettingsModel(services: .shared)) +extension SettingsWindowController: NSMenuItemValidation { + internal func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + let isFree = window?.attachedSheet == nil + switch menuItem.action { + case #selector(navigateBack(_:)): + return isFree && split.model.canGoBack + case #selector(navigateForward(_:)): + return isFree && split.model.canGoForward + case #selector(performFind(_:)), #selector(focusSidebarFilter(_:)): + return isFree + default: + return true } } } diff --git a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift index 245b523675..7d0991f574 100644 --- a/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift +++ b/apple/TablePro/Views/Settings/SettingsWindowToolbar.swift @@ -1,48 +1,87 @@ -// -// SettingsWindowToolbar.swift -// TablePro -// - import AppKit -import Combine -// The System Settings toolbar: a back/forward navigation group pinned to the leading edge of the -// detail region, then the current page title in bold. AppKit draws the sidebar/detail tracking -// separator. Forward stays disabled (a NavigationStack is back-only), which matches the reference's -// idle state. No centered window title. +// Back and Forward as one navigational group, so AppKit draws the window title right after it +// (System Settings). A pane that filters its own list gets a search item at the trailing edge. @MainActor internal final class SettingsWindowToolbar: NSObject, NSToolbarDelegate { - private static let backForward = NSToolbarItem.Identifier("com.TablePro.settings.backForward") - private static let pageTitle = NSToolbarItem.Identifier("com.TablePro.settings.title") - - private let model: LegacySettingsNavigationModel - private weak var backItem: NSToolbarItem? - private weak var titleField: NSTextField? - private var cancellable: AnyCancellable? - - internal init(model: LegacySettingsNavigationModel) { - self.model = model - super.init() - cancellable = model.objectWillChange.sink { [weak self] in - // objectWillChange fires before the value updates; read it on the next runloop turn. - Task { @MainActor in self?.sync() } - } - } + internal static let navigationIdentifier = NSToolbarItem.Identifier("com.TablePro.settings.backForward") + internal static let keyboardSearchIdentifier = NSToolbarItem.Identifier("com.TablePro.settings.keyboardSearch") + internal static let extensionsFilterIdentifier = NSToolbarItem.Identifier("com.TablePro.settings.extensionsFilter") + private static let filterWidth: CGFloat = 180 + + internal var onBack: (() -> Void)? + internal var onForward: (() -> Void)? + + private weak var toolbar: NSToolbar? + private weak var navigationGroup: NSToolbarItemGroup? + private var canGoBack = false + private var canGoForward = false + private var filterPane: SettingsPane? + private var filter: SettingsPaneFilter? internal func makeToolbar() -> NSToolbar { - let toolbar = NSToolbar(identifier: "com.TablePro.settings.toolbar") + // AppKit mirrors an insert or remove into every toolbar sharing the identifier, and a closed + // window's toolbar can outlive it with a different item count, which throws. + let toolbar = NSToolbar(identifier: "com.TablePro.settings.toolbar.\(UUID().uuidString)") toolbar.delegate = self toolbar.displayMode = .iconOnly toolbar.allowsUserCustomization = false + toolbar.autosavesConfiguration = false + if #available(macOS 15.0, *) { + toolbar.allowsDisplayModeCustomization = false + } + self.toolbar = toolbar return toolbar } + internal var isBackEnabled: Bool { + navigationGroup?.subitems.first?.isEnabled ?? canGoBack + } + + internal var isForwardEnabled: Bool { + navigationGroup?.subitems.last?.isEnabled ?? canGoForward + } + + internal func update(canGoBack: Bool, canGoForward: Bool) { + self.canGoBack = canGoBack + self.canGoForward = canGoForward + applyNavigationState() + } + + // Inserted and removed by identifier, only when the wanted item differs, so a navigation never flickers it. + internal func showFilter(for pane: SettingsPane, filter: SettingsPaneFilter?) { + let wanted = filter == nil ? nil : Self.filterIdentifier(for: pane) + filterPane = wanted == nil ? nil : pane + self.filter = wanted == nil ? nil : filter + guard let toolbar else { return } + for (index, item) in toolbar.items.enumerated().reversed() + where Self.isFilterIdentifier(item.itemIdentifier) && item.itemIdentifier != wanted { + toolbar.removeItem(at: index) + } + guard let wanted else { return } + if let item = toolbar.items.first(where: { $0.itemIdentifier == wanted }) as? NSSearchToolbarItem { + syncField(item.searchField) + } else { + toolbar.insertItem(withItemIdentifier: wanted, at: toolbar.items.count) + } + } + + // Returns false when the current pane has no filter, so Find falls back to the sidebar search. + internal func focusFilter() -> Bool { + guard let filterPane, + let identifier = Self.filterIdentifier(for: filterPane), + let item = toolbar?.items.first(where: { $0.itemIdentifier == identifier }) as? NSSearchToolbarItem + else { return false } + item.beginSearchInteraction() + return true + } + internal func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { - [.sidebarTrackingSeparator, Self.backForward, Self.pageTitle, .flexibleSpace] + [.sidebarTrackingSeparator, Self.navigationIdentifier, .flexibleSpace] } internal func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { - toolbarDefaultItemIdentifiers(toolbar) + toolbarDefaultItemIdentifiers(toolbar) + [Self.keyboardSearchIdentifier, Self.extensionsFilterIdentifier] } internal func toolbar( @@ -51,58 +90,117 @@ internal final class SettingsWindowToolbar: NSObject, NSToolbarDelegate { willBeInsertedIntoToolbar flag: Bool ) -> NSToolbarItem? { switch identifier { - case Self.backForward: - let back = chevron(id: "com.TablePro.settings.back", symbol: "chevron.backward", label: String(localized: "Back")) - back.target = self - back.action = #selector(goBack(_:)) - back.isEnabled = model.canGoBack - backItem = back - - let forward = chevron(id: "com.TablePro.settings.forward", symbol: "chevron.forward", label: String(localized: "Forward")) - forward.isEnabled = false - - // isNavigational pins the pair to the leading edge of the detail region (Finder/Safari/System Settings). - let group = NSToolbarItemGroup(itemIdentifier: identifier) - group.label = String(localized: "Navigation") - group.paletteLabel = String(localized: "Navigation") - group.subitems = [back, forward] - group.isNavigational = true - return group - - case Self.pageTitle: - let item = NSToolbarItem(itemIdentifier: identifier) - let field = NSTextField(labelWithString: model.currentTitle) - field.font = .systemFont(ofSize: NSFont.systemFontSize + 1, weight: .bold) - field.lineBreakMode = .byTruncatingTail - field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - item.view = field - item.visibilityPriority = .high - titleField = field - return item - + case Self.navigationIdentifier: + return makeNavigationGroup() + case Self.keyboardSearchIdentifier: + return makeFilterItem( + identifier: identifier, + placeholder: String(localized: "Search Shortcuts"), + accessibilityIdentifier: "shortcut-search" + ) + case Self.extensionsFilterIdentifier: + return makeFilterItem( + identifier: identifier, + placeholder: String(localized: "Filter"), + accessibilityIdentifier: "extensions-filter" + ) default: return nil } } - private func chevron(id: String, symbol: String, label: String) -> NSToolbarItem { - let item = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(id)) - item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label) - item.label = label - item.paletteLabel = label - item.isBordered = true - // Enablement is driven by canGoBack; without this AppKit auto-enables Back because its - // target responds to the action, so it would never dim at a pane root. - item.autovalidates = false + private func makeNavigationGroup() -> NSToolbarItemGroup { + let back = String(localized: "Back") + let forward = String(localized: "Forward") + let images = [ + NSImage(systemSymbolName: "chevron.backward", accessibilityDescription: back), + NSImage(systemSymbolName: "chevron.forward", accessibilityDescription: forward), + ].compactMap { $0 } + let group = NSToolbarItemGroup( + itemIdentifier: Self.navigationIdentifier, + images: images, + selectionMode: .momentary, + labels: [back, forward], + target: self, + action: #selector(navigate(_:)) + ) + group.isNavigational = true + group.label = String(localized: "Navigation") + group.paletteLabel = String(localized: "Navigation") + // Enablement comes from history; autovalidation would enable both because the target answers the action. + group.autovalidates = false + for item in group.subitems { + item.autovalidates = false + } + navigationGroup = group + applyNavigationState() + return group + } + + private func applyNavigationState() { + guard let subitems = navigationGroup?.subitems, subitems.count == 2 else { return } + subitems[0].isEnabled = canGoBack + subitems[1].isEnabled = canGoForward + subitems[0].toolTip = Self.toolTip(String(localized: "Back"), action: .navigateBack) + subitems[1].toolTip = Self.toolTip(String(localized: "Forward"), action: .navigateForward) + } + + private static func toolTip(_ title: String, action: ShortcutAction) -> String { + guard let key = AppSettingsManager.shared.keyboard.shortcut(for: action) else { return title } + return String(format: String(localized: "%@ (%@)"), title, key.displayString) + } + + @objc private func navigate(_ sender: Any?) { + guard let group = sender as? NSToolbarItemGroup else { return } + switch group.selectedIndex { + case 0: onBack?() + case 1: onForward?() + default: break + } + } + + private func makeFilterItem( + identifier: NSToolbarItem.Identifier, + placeholder: String, + accessibilityIdentifier: String + ) -> NSSearchToolbarItem { + let field = NSSearchField() + field.placeholderString = placeholder + field.sendsSearchStringImmediately = true + field.target = self + field.action = #selector(filterChanged(_:)) + field.setAccessibilityIdentifier(accessibilityIdentifier) + field.widthAnchor.constraint(lessThanOrEqualToConstant: Self.filterWidth).isActive = true + syncField(field) + + let item = NSSearchToolbarItem(itemIdentifier: identifier) + item.searchField = field + item.preferredWidthForSearchField = Self.filterWidth + item.label = placeholder return item } - private func sync() { - titleField?.stringValue = model.currentTitle - backItem?.isEnabled = model.canGoBack + private func syncField(_ field: NSSearchField) { + let query = filter?.query ?? "" + if field.stringValue != query { + field.stringValue = query + } + } + + @objc private func filterChanged(_ sender: NSSearchField) { + guard let filter, filter.query != sender.stringValue else { return } + filter.query = sender.stringValue + } + + private static func filterIdentifier(for pane: SettingsPane) -> NSToolbarItem.Identifier? { + switch pane { + case .keyboard: keyboardSearchIdentifier + case .plugins: extensionsFilterIdentifier + default: nil + } } - @objc private func goBack(_ sender: Any?) { - model.goBack() + private static func isFilterIdentifier(_ identifier: NSToolbarItem.Identifier) -> Bool { + identifier == keyboardSearchIdentifier || identifier == extensionsFilterIdentifier } } diff --git a/apple/TablePro/Views/Sidebar/NativeSearchField.swift b/apple/TablePro/Views/Sidebar/NativeSearchField.swift index 25dac44ce5..51a72bbae5 100644 --- a/apple/TablePro/Views/Sidebar/NativeSearchField.swift +++ b/apple/TablePro/Views/Sidebar/NativeSearchField.swift @@ -1,25 +1,12 @@ -// -// NativeSearchField.swift -// TablePro -// -// Native NSSearchField wrapped for SwiftUI. -// - import AppKit import os import SwiftUI private final class IntrinsicHeightSearchField: NSSearchField { var focusOnAppear = false - // When set, the field reports this height instead of the text-cell height; the Settings sidebar - // uses it to reach the taller System Settings search pill. - var fixedHeight: CGFloat? private let windowKeyObserver = OSAllocatedUnfairLock<(any NSObjectProtocol)?>(uncheckedState: nil) override var intrinsicContentSize: NSSize { - if let fixedHeight { - return NSSize(width: NSView.noIntrinsicMetric, height: fixedHeight) - } let cellHeight = cell?.cellSize.height ?? super.intrinsicContentSize.height return NSSize(width: NSView.noIntrinsicMetric, height: cellHeight) } @@ -69,7 +56,6 @@ struct NativeSearchField: NSViewRepresentable { var focusOnAppear: Bool = false var focusTrigger: Int = 0 var maxWidth: CGFloat? - var fixedHeight: CGFloat? var accessibilityIdentifier: String = "sidebar-filter" func makeNSView(context: Context) -> NSSearchField { @@ -77,7 +63,6 @@ struct NativeSearchField: NSViewRepresentable { field.placeholderString = placeholder field.delegate = context.coordinator field.controlSize = controlSize - field.fixedHeight = fixedHeight field.sendsSearchStringImmediately = true field.setAccessibilityIdentifier(accessibilityIdentifier) field.cell?.usesSingleLineMode = true diff --git a/apple/TableProTests/Core/Services/Infrastructure/AppActivationPolicyTests.swift b/apple/TableProTests/Core/Services/Infrastructure/AppActivationPolicyTests.swift index 214760287f..3db74dd272 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/AppActivationPolicyTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/AppActivationPolicyTests.swift @@ -1,11 +1,4 @@ -// -// AppActivationPolicyTests.swift -// TableProTests -// -// The MCP bridge launches TablePro to answer a client, and that launch opens no window. The app -// used to take a Dock icon and an app-switcher entry for it anyway, which is a process claiming to -// be something the person never started. -// +// The MCP bridge's launch opens no window, so it must not take a Dock icon or an app-switcher entry. import Foundation @testable import TablePro @@ -34,7 +27,7 @@ struct AppActivationPolicyTests { #expect(LaunchIntent.openDataFile(URL(fileURLWithPath: "/tmp/rows.csv")).impliesUserInterface) #expect(LaunchIntent.openConnectionShare(URL(string: "tablepro://share")!).impliesUserInterface) #expect(LaunchIntent.installPlugin(URL(string: "tablepro://plugin")!).impliesUserInterface) - #expect(LaunchIntent.openSettings(.mcp).impliesUserInterface) + #expect(LaunchIntent.openSettings(.root(.mcp)).impliesUserInterface) #expect(LaunchIntent.openSettings(nil).impliesUserInterface) #expect( LaunchIntent.openTable( @@ -91,7 +84,7 @@ struct AppActivationPolicyTests { func settingsLinkLaunchIsUser() { #expect( AppActivationPolicyDecision.origin( - adopting: [.openSettings(.mcp)], current: .machine, isLaunching: true + adopting: [.openSettings(.root(.mcp))], current: .machine, isLaunching: true ) == .user ) } diff --git a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSettingsParsingTests.swift b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSettingsParsingTests.swift index 7dd44cb6d1..9c2b50f228 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSettingsParsingTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSettingsParsingTests.swift @@ -1,58 +1,70 @@ -// -// DeeplinkSettingsParsingTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @MainActor struct DeeplinkSettingsParsingTests { - private func pane(for link: String) throws -> SettingsPane? { + private func location(for link: String) throws -> SettingsLocation? { let url = try #require(URL(string: link)) let outcome = URLClassifier.classify(url) - guard case .some(.success(.openSettings(let pane))) = outcome else { + guard case .some(.success(.openSettings(let location))) = outcome else { Issue.record("Expected .openSettings for \(link), got \(String(describing: outcome))") return nil } - return pane + return location } - @Test("A bare link asks for no pane", arguments: ["tablepro://settings", "tablepro://settings/"]) + @Test("A bare link asks for the last-used pane", arguments: ["tablepro://settings", "tablepro://settings/"]) func bareLinkAsksForNoPane(link: String) throws { - #expect(try pane(for: link) == nil) + #expect(try location(for: link) == nil) } - @Test("A known id opens its pane") + @Test("A known id opens its pane root") func knownIdOpensItsPane() throws { - #expect(try pane(for: "tablepro://settings/mcp") == .mcp) - #expect(try pane(for: "tablepro://settings/plugins") == .plugins) - #expect(try pane(for: "tablepro://settings/license") == .account) + #expect(try location(for: "tablepro://settings/mcp") == .root(.mcp)) + #expect(try location(for: "tablepro://settings/plugins") == .root(.plugins)) + #expect(try location(for: "tablepro://settings/license") == .root(.account)) } @Test( - "An unknown id asks for no pane instead of failing", + "An unknown pane id asks for the last-used pane instead of failing", arguments: ["tablepro://settings/nope", "tablepro://settings/MCP", "tablepro://settings/account"] ) func unknownIdAsksForNoPane(link: String) throws { - #expect(try pane(for: link) == nil) + #expect(try location(for: link) == nil) + } + + @Test("A page id opens that page", arguments: SettingsPage.allCases) + func pageIdOpensThePage(page: SettingsPage) throws { + let link = "tablepro://settings/\(page.parent.urlIdentifier)/\(page.urlIdentifier)" + #expect(try location(for: link) == SettingsLocation(page: page)) + } + + @Test("An unknown second segment or a page of another pane opens the pane root") + func unknownSecondSegmentOpensThePaneRoot() throws { + #expect(try location(for: "tablepro://settings/mcp/authentication") == .root(.mcp)) + #expect(try location(for: "tablepro://settings/ai/providers/openai/") == .root(.ai)) + #expect(try location(for: "tablepro://settings/general/themes") == .root(.general)) + #expect(try location(for: "tablepro://settings/editor/SQL-Formatting") == .root(.editor)) } - @Test("Path segments after the pane are ignored") - func extraSegmentsAreIgnored() throws { - #expect(try pane(for: "tablepro://settings/mcp/authentication") == .mcp) - #expect(try pane(for: "tablepro://settings/ai/providers/openai/") == .ai) + @Test("plugins/ opens that plugin's page, and an id that cannot be one opens Extensions") + func pluginIdOpensItsPage() throws { + #expect( + try location(for: "tablepro://settings/plugins/com.TablePro.PostgreSQLDriver") + == SettingsLocation(route: .plugin(id: "com.TablePro.PostgreSQLDriver")) + ) + #expect(try location(for: "tablepro://settings/plugins/bad%20id") == .root(.plugins)) } @Test("Query items are ignored") func queryIsIgnored() throws { - #expect(try pane(for: "tablepro://settings/sync?section=status") == .sync) - #expect(try pane(for: "tablepro://settings?pane=mcp") == nil) + #expect(try location(for: "tablepro://settings/sync?section=status") == .root(.sync)) + #expect(try location(for: "tablepro://settings?pane=mcp") == nil) } @Test("A percent-encoded id is decoded before matching") func percentEncodedIdIsDecoded() throws { - #expect(try pane(for: "tablepro://settings/%6Dcp") == .mcp) + #expect(try location(for: "tablepro://settings/%6Dcp") == .root(.mcp)) } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift index 4df579f945..e8398a116e 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WindowOpenerTests.swift @@ -1,28 +1,23 @@ -// -// WindowOpenerTests.swift -// TableProTests -// - @testable import TablePro import XCTest @MainActor final class WindowOpenerTests: XCTestCase { private var openedRequests: [ConnectionFormRequest] = [] - private var openedSettingsPanes: [SettingsPane?] = [] + private var openedSettings: [SettingsRequest] = [] override func setUp() async throws { try await super.setUp() _ = WelcomeRouter.shared.consumePendingRequest() openedRequests = [] - openedSettingsPanes = [] + openedSettings = [] WindowOpener.shared.setWelcomePresenter {} WindowOpener.shared.setConnectionFormPresenter { [weak self] request in self?.openedRequests.append(request) } WindowOpener.shared.setIntegrationsActivityPresenter {} - WindowOpener.shared.setSettingsPresenter { [weak self] pane in - self?.openedSettingsPanes.append(pane) + WindowOpener.shared.setSettingsPresenter { [weak self] request in + self?.openedSettings.append(request) } } @@ -143,8 +138,7 @@ final class WindowOpenerTests: XCTestCase { XCTAssertEqual(opened, [.edit(connectionId: connectionId)]) } - /// Registering one window's presenter must not drop another window's queued call, which is - /// what lets the windows migrate to AppKit one at a time. + // Lets the windows migrate to AppKit one at a time. func testRegisteringOneWindowDoesNotDiscardAnotherWindowsQueuedCall() { let opener = WindowOpener() var opened: [ConnectionFormRequest] = [] @@ -162,39 +156,38 @@ final class WindowOpenerTests: XCTestCase { func testTheRequestedSettingsPaneReachesThePresenter() { WindowOpener.shared.openSettings(tab: .plugins) - XCTAssertEqual(openedSettingsPanes, [.plugins]) + XCTAssertEqual(openedSettings, [.open(.root(.plugins))]) } func testOpeningSettingsWithoutAPaneAsksForNone() { WindowOpener.shared.openSettings() - XCTAssertEqual(openedSettingsPanes, [SettingsPane?.none]) + XCTAssertEqual(openedSettings, [.open(nil)]) } - /// The pane used to travel through UserDefaults, so a call made before the presenter existed - /// wrote the preference and then opened on whatever was stored. + // The pane used to travel through UserDefaults, so a queued call opened on whatever was stored. func testASettingsCallQueuedBeforeItsPresenterKeepsItsPane() { let opener = WindowOpener() - var opened: [SettingsPane?] = [] + var opened: [SettingsRequest] = [] opener.openSettings(tab: .ai) XCTAssertTrue(opened.isEmpty, "No presenter yet, so the call has to wait") opener.setSettingsPresenter { opened.append($0) } - XCTAssertEqual(opened, [.ai]) + XCTAssertEqual(opened, [.open(.root(.ai))]) } func testASettingsLinkRoutesItsPaneToThePresenter() async { - await LaunchIntentRouter.shared.route(.openSettings(.mcp)) + await LaunchIntentRouter.shared.route(.openSettings(.root(.mcp))) - XCTAssertEqual(openedSettingsPanes, [.mcp]) + XCTAssertEqual(openedSettings, [.open(.root(.mcp))]) } func testABareSettingsLinkAsksForNoPane() async { await LaunchIntentRouter.shared.route(.openSettings(nil)) - XCTAssertEqual(openedSettingsPanes, [SettingsPane?.none]) + XCTAssertEqual(openedSettings, [.open(nil)]) } func testEditingTheSameConnectionTwiceRequestsTheSameWindow() { diff --git a/apple/TableProTests/Core/Services/Notifications/PluginNotificationServiceTests.swift b/apple/TableProTests/Core/Services/Notifications/PluginNotificationServiceTests.swift index 652f608ced..a8dc3792af 100644 --- a/apple/TableProTests/Core/Services/Notifications/PluginNotificationServiceTests.swift +++ b/apple/TableProTests/Core/Services/Notifications/PluginNotificationServiceTests.swift @@ -85,6 +85,15 @@ struct PluginNotificationServiceTests { withExtendedLifetime(service) {} } + @Test("A plugin notification carries the default sound, so the system Play sound switch decides") + func notificationCarriesDefaultSound() async throws { + let service = makeService() + await service.notifyRejected([rejected("com.example.rejected")]) + + let request = try #require(presenter.posted.first) + #expect(request.content.sound == .default) + } + @Test("A manual retry and a later successful install clear the delivered failure") func manualRetryClearsTheFailure() async throws { let service = makeService() diff --git a/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift b/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift index 3cc19cd334..2c52fe8d6a 100644 --- a/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift +++ b/apple/TableProTests/Views/Connection/ConnectionRecoveryPresentationTests.swift @@ -1,11 +1,3 @@ -// -// ConnectionRecoveryPresentationTests.swift -// TableProTests -// -// The inline failure pane is where a reporter looked for the way to their Plugins window and -// found only Try Again, which repeats a connect that cannot succeed. -// - import Foundation @testable import TablePro import Testing @@ -57,26 +49,16 @@ struct ConnectionRecoveryPresentationTests { ) } - @Test("A request to show a plugin is answered once") - func navigationRequestIsConsumedOnce() { - let navigation = PluginsSettingsNavigation() - navigation.reveal(pluginId: "com.TablePro.SQLiteDriver") - - #expect(navigation.consumePendingRequest()?.pluginId == "com.TablePro.SQLiteDriver") - #expect(navigation.consumePendingRequest() == nil) - #expect(navigation.pendingRequest == nil) - } + @Test("Opening plugin settings asks Settings to reveal the plugin the failure names, or the first one to update") + func openPluginSettingsRevealsThePlugin() { + let opener = WindowOpener() + var requests: [SettingsRequest] = [] + opener.setSettingsPresenter { requests.append($0) } + let connection = TestFixtures.makeConnection() - @Test("Asking twice for the same plugin is two requests, so the list reselects it") - func repeatedRequestsAreDistinct() { - let navigation = PluginsSettingsNavigation() - navigation.reveal(pluginId: "p") - let first = navigation.consumePendingRequest() - navigation.reveal(pluginId: "p") - let second = navigation.consumePendingRequest() + ConnectionRecoveryPerformer.perform(.openPluginSettings(pluginId: "com.TablePro.SQLiteDriver"), for: connection, opener: opener) + ConnectionRecoveryPerformer.perform(.openPluginSettings(pluginId: nil), for: connection, opener: opener) - #expect(first != nil) - #expect(second != nil) - #expect(first != second) + #expect(requests == [.revealPlugin("com.TablePro.SQLiteDriver"), .revealPlugin(nil)]) } } diff --git a/apple/TableProTests/Views/Settings/SettingsWindowSizingTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowSizingTests.swift new file mode 100644 index 0000000000..5c9352666e --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsWindowSizingTests.swift @@ -0,0 +1,96 @@ +import AppKit +@testable import TablePro +import Testing + +// The app's autosave name is nil in the unit host, so each case passes its own name and removes it. +@MainActor +struct SettingsWindowSizingTests { + private static let width = SettingsSplitViewController.contentWidth + + private func makeWindow() -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), + styleMask: SettingsWindowController.styleMask, + backing: .buffered, + defer: true + ) + window.isReleasedWhenClosed = false + return window + } + + private func contentSize(of window: NSWindow) -> NSSize { + window.contentRect(forFrameRect: window.frame).size + } + + private func defaultSize(for window: NSWindow) -> NSSize { + SettingsWindowController.defaultContentSize(on: window.screen ?? NSScreen.main) + } + + private func withAutosaveName(_ body: (String) -> Void) { + let name = "TableProTests.SettingsWindow.\(UUID().uuidString)" + body(name) + NSWindow.removeFrame(usingName: name) + } + + @Test("The default is 700 points tall, or less on a short screen, never under the minimum") + func defaultHeightFitsTheScreen() { + #expect(SettingsWindowController.defaultContentSize(on: nil) == NSSize(width: Self.width, height: 700)) + let size = SettingsWindowController.defaultContentSize(on: NSScreen.main) + #expect(size.width == Self.width) + #expect(size.height <= 700) + #expect(size.height >= SettingsSplitViewController.minimumContentSize.height) + } + + @Test("With no saved frame the window opens at the default size") + func noSavedFrameUsesTheDefault() { + let window = makeWindow() + SettingsWindowController.applyFrame(to: window, autosaveName: nil) + #expect(contentSize(of: window) == defaultSize(for: window)) + } + + @Test("A saved height survives two reconstructions unchanged") + func savedHeightSurvivesTwoReconstructions() { + withAutosaveName { name in + let first = makeWindow() + SettingsWindowController.applyFrame(to: first, autosaveName: name) + first.setContentSize(NSSize(width: Self.width, height: 600)) + first.saveFrame(usingName: name) + first.setFrameAutosaveName("") + + for _ in 0..<2 { + let next = makeWindow() + SettingsWindowController.applyFrame(to: next, autosaveName: name) + #expect(contentSize(of: next) == NSSize(width: Self.width, height: 600)) + next.setFrameAutosaveName("") + } + } + } + + @Test("A frame saved at an older width falls back to the default size") + func olderWidthFallsBackToTheDefault() { + withAutosaveName { name in + let old = makeWindow() + old.setContentSize(NSSize(width: 768, height: 480)) + old.saveFrame(usingName: name) + + let window = makeWindow() + SettingsWindowController.applyFrame(to: window, autosaveName: name) + #expect(contentSize(of: window) == defaultSize(for: window)) + window.setFrameAutosaveName("") + } + } + + @Test("A saved frame shorter than the minimum grows to the minimum") + func shortFrameGrowsToTheMinimum() { + withAutosaveName { name in + let old = makeWindow() + old.setContentSize(NSSize(width: Self.width, height: 300)) + old.saveFrame(usingName: name) + + let window = makeWindow() + SettingsWindowController.applyFrame(to: window, autosaveName: name) + #expect(contentSize(of: window) == SettingsSplitViewController.minimumContentSize) + window.setFrameAutosaveName("") + } + } +} diff --git a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift index 31e7859261..53466a33bd 100644 --- a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift @@ -1,22 +1,16 @@ -// -// SettingsWindowTitleTests.swift -// TableProTests -// - import AppKit -import SwiftUI @testable import TablePro import TableProTestSupport import Testing extension GlobalStateSuites { - // The sidebar window reads and writes the selected-pane default, so it nests here for serialized - // access to that process-wide value. + // The window reads and writes the last-used pane default, so it nests here for serialized access to it. @MainActor struct SettingsWindowNavigationTests { @MainActor private final class Host { var windows: [NSWindow] = [] + var controllers: [SettingsWindowController] = [] let registry: OfflineRegistry let storedPane: String? @@ -25,6 +19,14 @@ extension GlobalStateSuites { storedPane = AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) } + var persistedPane: String? { + AppStorageEnvironment.shared.defaults.string(forKey: PreferenceKeys.selectedSettingsPane.name) + } + + func storePane(_ pane: SettingsPane) { + AppStorageEnvironment.shared.defaults.set(pane.rawValue, forKey: PreferenceKeys.selectedSettingsPane.name) + } + func makeSplit() -> (SettingsSplitViewController, NSWindow) { let split = SettingsSplitViewController(registryClient: registry.client) let window = NSWindow(contentViewController: split) @@ -33,12 +35,28 @@ extension GlobalStateSuites { return (split, window) } + func makeController() throws -> (SettingsWindowController, NSWindow) { + let controller = SettingsWindowController(registryClient: registry.client) + let window = try #require(controller.window, "The controller must build a window") + window.isReleasedWhenClosed = false + windows.append(window) + controllers.append(controller) + return (controller, window) + } + func tearDown() async { + for controller in controllers { + controller.split.windowDidClose() + } for window in windows { - window.contentViewController = nil + if let sheet = window.attachedSheet { + window.endSheet(sheet) + } window.orderOut(nil) + window.contentViewController = nil } windows = [] + controllers = [] await registry.settle() let key = PreferenceKeys.selectedSettingsPane.name if let storedPane { @@ -49,42 +67,57 @@ extension GlobalStateSuites { } } + private static func toolbarIdentifiers(of window: NSWindow) -> [NSToolbarItem.Identifier] { + window.toolbar?.items.map { $0.itemIdentifier } ?? [] + } + @Test("The sidebar order is every pane exactly once") func everyPaneIsReachableExactlyOnce() { #expect(SettingsNavigation.orderedPanes.count == SettingsPane.allCases.count) #expect(Set(SettingsNavigation.orderedPanes) == Set(SettingsPane.allCases)) } - @Test("The toolbar title follows the selected pane") - func toolbarTitleFollowsTheSelectedPane() async throws { + @Test("The window title follows every pane") + func windowTitleFollowsEveryPane() async throws { let host = try Host() - let (split, _) = host.makeSplit() + let (split, window) = host.makeSplit() for pane in SettingsPane.allCases { split.navigate(to: pane) - #expect(split.model.currentTitle == pane.title) + #expect(window.title == pane.title) } await host.tearDown() } - @Test("A fresh controller opens on the persisted pane") + @Test("A pushed page titles the window, and Back returns the pane title") + func pushedPageTitlesTheWindow() async throws { + let host = try Host() + let (split, window) = host.makeSplit() + split.navigate(to: .appearance) + + #expect(split.model.push(.page(.manageThemes), in: .appearance)) + #expect(window.title == SettingsPage.manageThemes.title) + + split.goBack() + #expect(window.title == SettingsPane.appearance.title) + await host.tearDown() + } + + @Test("A fresh window titles itself from the persisted pane") func freshControllerOpensOnThePersistedPane() async throws { let host = try Host() - AppStorageEnvironment.shared.defaults.set( - SettingsPane.keyboard.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name - ) - let (split, _) = host.makeSplit() - #expect(split.model.currentTitle == SettingsPane.keyboard.title) + host.storePane(.keyboard) + let (_, window) = host.makeSplit() + #expect(window.title == SettingsPane.keyboard.title) await host.tearDown() } - @Test("A stored MCP pane restores the pane titled MCP") + @Test("A stored MCP pane restores the window titled MCP") func storedMCPPaneRestoresTheMCPTitle() async throws { let host = try Host() AppStorageEnvironment.shared.defaults.set("mcp", forKey: PreferenceKeys.selectedSettingsPane.name) - let (split, _) = host.makeSplit() - #expect(split.model.currentTitle == "MCP") + let (_, window) = host.makeSplit() + #expect(window.title == "MCP") await host.tearDown() } @@ -96,82 +129,234 @@ extension GlobalStateSuites { #expect(SettingsPane.account.urlIdentifier == "license") } - @Test("Navigating with no pane reads the stored pane rather than staying put") - func navigatingWithNoPaneReadsTheStoredPane() async throws { + // Replaces "Navigating with no pane reads the stored pane": Cmd-, on an open window only brings it forward. + @Test("No location leaves a visible window where it is, and opens a closed one on the last-used pane") + func noLocationKeepsAVisibleWindowInPlace() async throws { let host = try Host() - let (split, _) = host.makeSplit() - split.navigate(to: .plugins) - #expect(split.model.currentTitle == SettingsPane.plugins.title) + let (controller, window) = try host.makeController() + #expect(controller.prepareToShow(.root(.plugins))) + window.orderFront(nil) + + host.storePane(.editor) + #expect(!controller.prepareToShow(nil)) + #expect(window.title == SettingsPane.plugins.title) - AppStorageEnvironment.shared.defaults.set( - SettingsPane.editor.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name + window.orderOut(nil) + #expect(controller.prepareToShow(nil)) + #expect(window.title == SettingsPane.editor.title) + await host.tearDown() + } + + @Test("A location never navigates under an attached sheet, and the menu items are off") + func attachedSheetBlocksNavigation() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + controller.prepareToShow(.root(.general)) + window.orderFront(nil) + let sheet = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 120), + styleMask: [.titled], + backing: .buffered, + defer: false ) - split.navigate(to: nil) - #expect(split.model.currentTitle == SettingsPane.editor.title) + sheet.isReleasedWhenClosed = false + controller.split.model.select(.data) + window.beginSheet(sheet, completionHandler: nil) + try await waitUntil { window.attachedSheet === sheet } + + #expect(!controller.prepareToShow(.root(.ai))) + #expect(window.title == SettingsPane.data.title) + let back = NSMenuItem(title: "Back", action: #selector(SettingsWindowController.navigateBack(_:)), keyEquivalent: "") + #expect(!controller.validateMenuItem(back)) + + window.endSheet(sheet) await host.tearDown() } - // A deep link / openSettings jump must not overwrite the user's last-used pane. @Test("A programmatic jump does not clobber the persisted pane") func programmaticJumpDoesNotClobberThePersistedPane() async throws { let host = try Host() - let key = PreferenceKeys.selectedSettingsPane.name - AppStorageEnvironment.shared.defaults.set(SettingsPane.editor.rawValue, forKey: key) + host.storePane(.editor) let (split, _) = host.makeSplit() split.navigate(to: .ai) - #expect(AppStorageEnvironment.shared.defaults.string(forKey: key) == SettingsPane.editor.rawValue) + split.navigate(to: SettingsLocation(page: .slashCommands), recordsHistory: true) + split.goBack() + #expect(host.persistedPane == SettingsPane.editor.rawValue) - // A user click, by contrast, persists. - split.model.userSelect(.mcp) - #expect(AppStorageEnvironment.shared.defaults.string(forKey: key) == SettingsPane.mcp.rawValue) + // A pick in the sidebar, by contrast, persists. + split.model.select(.mcp) + #expect(host.persistedPane == SettingsPane.mcp.rawValue) await host.tearDown() } - // The toolbar reads these: Back is enabled only while the detail stack has a pushed page, - // and a pane switch pops back to the pane's own title. - @Test("Back enablement and title track the detail stack depth") - func backEnablementTracksDepth() { - let model = LegacySettingsNavigationModel(initial: .appearance) - #expect(!model.canGoBack) - #expect(model.currentTitle == SettingsPane.appearance.title) + @Test("A sidebar click navigates, persists its pane and enables Back") + func sidebarClickNavigatesAndPersists() async throws { + let host = try Host() + host.storePane(.general) + let (split, window) = host.makeSplit() + let row = try #require(split.sidebar.rows.firstIndex(of: .pane(.data))) + + split.sidebar.tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) + + #expect(window.title == SettingsPane.data.title) + #expect(host.persistedPane == SettingsPane.data.rawValue) + #expect(split.model.canGoBack) + #expect(split.toolbarController.isBackEnabled) + await host.tearDown() + } - model.path.append(SettingsSubpage.manageThemes) - #expect(model.canGoBack) + @Test("A page found by the sidebar search opens with its pane selected and persisted") + func searchResultOpensThePage() async throws { + let host = try Host() + host.storePane(.general) + let (split, window) = host.makeSplit() + let target = SettingsLocation(page: .sqlFormatting) + + split.sidebar.filter(by: "formatting") + let row = try #require(split.sidebar.rows.firstIndex(of: .page(title: SettingsPage.sqlFormatting.title, location: target))) + split.sidebar.tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) - model.goBack() - #expect(!model.canGoBack) + #expect(window.title == SettingsPage.sqlFormatting.title) + #expect(split.model.location == target) + #expect(host.persistedPane == SettingsPane.editor.rawValue) + #expect(split.sidebar.tableView.selectedRow == row) - model.path.append(SettingsSubpage.manageThemes) - model.userSelect(.editor) - #expect(!model.canGoBack) - #expect(model.currentTitle == SettingsPane.editor.title) + split.sidebar.clearSearch() + #expect(split.sidebar.tableView.selectedRow == split.sidebar.rows.firstIndex(of: .pane(.editor))) + await host.tearDown() } - @Test("The window refuses to shrink below the sidebar plus detail minimum") - func theWindowRefusesToShrinkBelowTheMinimum() async throws { + // Updated on purpose: Back used to track only the pushed depth of one pane; it now follows + // history across panes, as System Settings does. + @Test("Back and Forward follow history across panes") + func backEnablementTracksDepth() async throws { let host = try Host() - let controller = SettingsWindowController(registryClient: host.registry.client) - let window = try #require(controller.window, "The controller must build a window") - window.isReleasedWhenClosed = false - host.windows.append(window) + host.storePane(.appearance) + let (split, window) = host.makeSplit() + #expect(!split.model.canGoBack) + #expect(!split.toolbarController.isBackEnabled) + + split.model.select(.editor) + #expect(split.toolbarController.isBackEnabled) + #expect(!split.toolbarController.isForwardEnabled) + + split.goBack() + #expect(window.title == SettingsPane.appearance.title) + #expect(split.toolbarController.isForwardEnabled) + + split.goForward() + #expect(window.title == SettingsPane.editor.title) + #expect(!split.toolbarController.isForwardEnabled) + await host.tearDown() + } + + @Test("A deep link to a page in a closed window enables Back to the pane root") + func deepLinkIntoAClosedWindowSeedsThePaneRoot() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + + controller.prepareToShow(SettingsLocation(page: .sqlFormatting)) + #expect(window.title == SettingsPage.sqlFormatting.title) + let back = NSMenuItem(title: "Back", action: #selector(SettingsWindowController.navigateBack(_:)), keyEquivalent: "") + #expect(controller.validateMenuItem(back)) + + controller.navigateBack(nil) + #expect(window.title == SettingsPane.editor.title) + #expect(controller.split.model.location == .root(.editor)) + await host.tearDown() + } + + @Test("A link to a plugin that is not loaded opens Extensions and leaves a reveal for the pane") + func unloadedPluginLinkBecomesAReveal() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + + controller.prepareToShow(SettingsLocation(route: .plugin(id: "com.example.missing"))) + + #expect(window.title == SettingsPane.plugins.title) + #expect(controller.split.model.pendingPluginReveal?.pluginId == "com.example.missing") + await host.tearDown() + } + + @Test("Opening the window gives the sidebar list the keyboard, never the search field") + func sidebarListHoldsFocusOnOpen() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + + controller.prepareToShow(nil) + + #expect(window.initialFirstResponder === controller.split.sidebar.tableView) + #expect(window.firstResponder === controller.split.sidebar.tableView) + await host.tearDown() + } + + @Test("A visited pane keeps its host while the window is open, and closing releases it") + func paneHostsAreRetainedUntilClose() async throws { + let host = try Host() + let (controller, _) = try host.makeController() + let split = controller.split + controller.prepareToShow(.root(.editor)) + let editor = try #require(split.detail.host(for: .editor)) + + split.model.select(.data) + #expect(editor.view.isHidden) + split.model.select(.editor) + #expect(split.detail.host(for: .editor) === editor) + #expect(split.detail.host(for: .data)?.view.isHidden == true) + + controller.windowWillClose(Notification(name: NSWindow.willCloseNotification)) + #expect(!split.model.canGoBack) + try await waitUntil { split.detail.host(for: .editor) == nil } + await host.tearDown() + } + + @Test("Only Keyboard and Extensions put a filter in the toolbar") + func paneFilterFollowsThePane() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + controller.prepareToShow(.root(.general)) + let filters = [SettingsWindowToolbar.keyboardSearchIdentifier, SettingsWindowToolbar.extensionsFilterIdentifier] + + #expect(Self.toolbarIdentifiers(of: window).filter { filters.contains($0) }.isEmpty) + + controller.split.model.select(.keyboard) + #expect(Self.toolbarIdentifiers(of: window).filter { filters.contains($0) } == [SettingsWindowToolbar.keyboardSearchIdentifier]) + + controller.split.model.select(.plugins) + #expect(Self.toolbarIdentifiers(of: window).filter { filters.contains($0) } == [SettingsWindowToolbar.extensionsFilterIdentifier]) + + controller.split.model.select(.data) + #expect(Self.toolbarIdentifiers(of: window).filter { filters.contains($0) }.isEmpty) + await host.tearDown() + } + + @Test("The window has a fixed width, can be minimized and never zooms, tabs or restores") + func windowShape() async throws { + let host = try Host() + let (_, window) = try host.makeController() + + #expect(window.identifier?.rawValue == WindowIdentifier.settings) #expect(window.contentMinSize == SettingsSplitViewController.minimumContentSize) + #expect(window.contentMaxSize.width == SettingsSplitViewController.contentWidth) + #expect(window.styleMask.contains(.miniaturizable)) + #expect(window.standardWindowButton(.zoomButton)?.isEnabled == false) + #expect(window.tabbingMode == .disallowed) + #expect(!window.isRestorable) + #expect(window.titleVisibility == .visible) await host.tearDown() } @Test("present() builds the settings window with its identifier") func presentBuildsTheSettingsWindow() async throws { let host = try Host() - AppStorageEnvironment.shared.defaults.set( - SettingsPane.general.rawValue, - forKey: PreferenceKeys.selectedSettingsPane.name - ) + host.storePane(.general) let controller = SettingsWindowController() let window = try #require(controller.window, "Cmd-comma and settings links present this controller") window.isReleasedWhenClosed = false host.windows.append(window) #expect(window.identifier?.rawValue == WindowIdentifier.settings) + #expect(window.title == SettingsPane.general.title) await host.tearDown() } } diff --git a/apple/TableProUITests/SettingsDeeplinkUITests.swift b/apple/TableProUITests/SettingsDeeplinkUITests.swift index 10d79caa05..f900e4494b 100644 --- a/apple/TableProUITests/SettingsDeeplinkUITests.swift +++ b/apple/TableProUITests/SettingsDeeplinkUITests.swift @@ -11,4 +11,22 @@ final class SettingsDeeplinkUITests: UITestCase { "The link must open the Account pane, the window is titled \(settings.title)" ) } + + func testASettingsPageLinkOpensThePageWithBackToItsPane() throws { + let app = try launchOpeningURL("tablepro://settings/appearance/themes") + + let settings = settingsWindow(in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "A settings link must open the settings window") + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Manage Themes" }, + "The link must open Manage Themes, the window is titled \(settings.title)" + ) + let back = settingsNavigationButton("Back", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 5) { back.exists && back.isEnabled }, "A page link must leave Back to its pane") + back.click() + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Appearance" }, + "Back must return to the Appearance pane, the window is titled \(settings.title)" + ) + } } diff --git a/apple/TableProUITests/SettingsWindowUITests.swift b/apple/TableProUITests/SettingsWindowUITests.swift new file mode 100644 index 0000000000..c419d283f6 --- /dev/null +++ b/apple/TableProUITests/SettingsWindowUITests.swift @@ -0,0 +1,77 @@ +import XCTest + +final class SettingsWindowUITests: UITestCase { + private static let panes: [(id: String, title: String)] = [ + ("appearance", "Appearance"), + ("notifications", "Notifications"), + ("keyboard", "Keyboard"), + ("connections", "Connections"), + ("profiles", "Profiles"), + ("sidebar", "Sidebar & Tabs"), + ("editor", "Editor"), + ("data", "Data"), + ("ai", "AI"), + ("mcp", "MCP"), + ("plugins", "Extensions"), + ("sync", "iCloud Sync"), + ("account", "Account"), + ("general", "General"), + ] + + // One launch for the whole walk: the UI plan pays for every launch. + func testEveryPaneTitlesTheWindowAndHistoryWalksBack() throws { + let app = try launchApp() + let settings = openSettings(in: app) + + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "General" }, + "A new sandbox opens Settings on General, the window is titled \(settings.title)" + ) + let list = settings.tables.matching(identifier: "settings-sidebar").firstMatch + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(list) }, + "The sidebar list must hold the keyboard when Settings opens" + ) + XCTAssertFalse( + holdsKeyboardFocus(settings.searchFields.matching(identifier: "settings-sidebar-search").firstMatch), + "The sidebar search must not take focus when Settings opens" + ) + attachScreenshot(of: settings, named: "settings-general") + + let back = settingsNavigationButton("Back", in: settings) + let forward = settingsNavigationButton("Forward", in: settings) + XCTAssertTrue(back.waitToExist(timeout: 5), "The toolbar must carry Back") + XCTAssertFalse(back.isEnabled, "Back has nothing to return to on a fresh window") + + for pane in Self.panes { + selectSettingsPane(pane.id, in: settings) + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == pane.title }, + "Picking \(pane.id) must title the window \(pane.title), it is \(settings.title)" + ) + attachScreenshot(of: settings, named: "settings-\(pane.id)") + } + XCTAssertTrue(back.isEnabled, "A sidebar switch must enable Back") + + back.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Account" }, "Back must return to Account") + XCTAssertTrue(waitForPredicate(timeout: 5) { forward.isEnabled }, "Back must enable Forward") + + // View > Back and View > Forward, through their default key equivalents. + settings.typeKey("[", modifierFlags: [.command, .control]) + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "iCloud Sync" }, "View > Back must return to iCloud Sync") + settings.typeKey("]", modifierFlags: [.command, .control]) + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Account" }, "View > Forward must return to Account") + } + + func testDarkAppearanceScreenshots() throws { + let app = try launchApp(arguments: ["-AppleInterfaceStyle", "Dark"]) + let settings = openSettings(in: app) + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "General" }, "Settings must open on General") + attachScreenshot(of: settings, named: "settings-general-dark") + + selectSettingsPane("appearance", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Appearance" }, "Picking Appearance must title the window") + attachScreenshot(of: settings, named: "settings-appearance-dark") + } +} diff --git a/apple/TableProUITests/Support/UITestCase+Settings.swift b/apple/TableProUITests/Support/UITestCase+Settings.swift new file mode 100644 index 0000000000..01c09f85c5 --- /dev/null +++ b/apple/TableProUITests/Support/UITestCase+Settings.swift @@ -0,0 +1,42 @@ +import XCTest + +extension UITestCase { + internal func settingsWindow(in app: XCUIApplication) -> XCUIElement { + window("settings", in: app) + } + + internal func openSettings(in app: XCUIApplication) -> XCUIElement { + app.typeShortcut(.settings) + let settings = settingsWindow(in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "Cmd+, must open Settings") + return settings + } + + internal func settingsSidebarRow(_ pane: String, in settings: XCUIElement) -> XCUIElement { + settings.descendants(matching: .any).matching(identifier: "settings-sidebar-\(pane)").firstMatch + } + + // `pane` is the stored pane id (General is "general", Extensions "plugins"); `page` is a page's + // URL id, such as "software-update", reached through its settings-drill- row. + internal func selectSettingsPane(_ pane: String, page: String? = nil, in settings: XCUIElement) { + let row = settingsSidebarRow(pane, in: settings) + XCTAssertTrue(waitUntilHittable(row, timeout: 10), "The Settings sidebar must list \(pane)") + row.click() + guard let page else { return } + let drill = settings.descendants(matching: .any).matching(identifier: "settings-drill-\(page)").firstMatch + XCTAssertTrue(scrollUntilHittable(drill, in: settings, timeout: 10), "The \(pane) pane must link to \(page)") + drill.click() + } + + // The toolbar's navigation group publishes Back and Forward as buttons with their enabled state. + internal func settingsNavigationButton(_ label: String, in settings: XCUIElement) -> XCUIElement { + settings.toolbars.buttons.matching(NSPredicate(format: "label == %@", label)).firstMatch + } + + internal func attachScreenshot(of element: XCUIElement, named name: String) { + let attachment = XCTAttachment(screenshot: element.screenshot()) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} From beeec2d790913305550d91f5022e7758695543c1 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:51 +0700 Subject: [PATCH 25/48] fix(settings): expose sidebar row identifiers to accessibility --- .../Views/Settings/SettingsSidebarViewController.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift b/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift index ca22970587..b56d259e0b 100644 --- a/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift +++ b/apple/TablePro/Views/Settings/SettingsSidebarViewController.swift @@ -348,7 +348,8 @@ private final class SettingsSidebarPaneCell: NSTableCellView { image?.accessibilityDescription = "" glyph.image = image label.stringValue = pane.title - setAccessibilityIdentifier("settings-sidebar-\(pane.rawValue)") + // The table publishes its own AXCell for this view and drops the view's identifier, so the label carries it. + label.setAccessibilityIdentifier("settings-sidebar-\(pane.rawValue)") setAccessibilityLabel(pane.title) } } @@ -380,6 +381,6 @@ private final class SettingsSidebarPageCell: NSTableCellView { label.stringValue = title setAccessibilityLabel(title) let pageIdentifier = location.routes.last?.page.map(\.urlIdentifier) - setAccessibilityIdentifier(pageIdentifier.map { "settings-sidebar-page-\($0)" } ?? "") + label.setAccessibilityIdentifier(pageIdentifier.map { "settings-sidebar-page-\($0)" } ?? "") } } From c3b74efdb176c6e92ff0121a6937a22f078406e2 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:51 +0700 Subject: [PATCH 26/48] feat(settings): General pane with Software Update and Command Line Tool pages --- .../Entries/GeneralSettingsEntry.swift | 16 +-- .../Views/Settings/GeneralSettingsView.swift | 112 ++++++++++-------- .../Sections/CommandLineToolSection.swift | 85 +++++++------ .../Settings/SoftwareUpdateSection.swift | 77 ++++++------ .../WelcomeWindowUITests.swift | 11 +- 5 files changed, 165 insertions(+), 136 deletions(-) diff --git a/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift index c8a3fe7e1f..0f7367dad6 100644 --- a/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/GeneralSettingsEntry.swift @@ -2,16 +2,10 @@ import SwiftUI internal struct GeneralSettingsEntry: View { internal let context: SettingsPaneContext - @ObservedObject private var general: SettingsSlice - - internal init(context: SettingsPaneContext) { - self.context = context - self._general = ObservedObject(wrappedValue: context.settings.generalSlice) - } internal var body: some View { let settings = context.settings - GeneralSettingsView(settings: $general.value, onResetAll: { settings.resetToDefaults() }) + GeneralSettingsView(settings: settings.generalSlice, onResetAll: { settings.resetToDefaults() }) } } @@ -22,13 +16,11 @@ internal struct GeneralSettingsPageEntry: View { internal var body: some View { switch route { case .page(.softwareUpdate): - Form { SoftwareUpdateSection(updater: SoftwareUpdater.shared, updates: .shared) } - .formStyle(.grouped) + SoftwareUpdatePage(updater: .shared, updates: .shared) case .page(.commandLineTool): - Form { CommandLineToolSection() } - .formStyle(.grouped) + CommandLineToolPage(visit: context.visit) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index dd47e2c88d..a519169a11 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -1,86 +1,100 @@ -import AppKit import SwiftUI struct GeneralSettingsView: View { - @Binding var settings: GeneralSettings - var onResetAll: () -> Void + @ObservedObject var settings: SettingsSlice + let onResetAll: () -> Void @State private var showResetConfirmation = false var body: some View { Form { - Picker("Language:", selection: $settings.language) { - ForEach(AppLanguage.allCases) { lang in - Text(lang.displayName).tag(lang) + Section { + Picker("Language", selection: $settings.value.language) { + ForEach(AppLanguage.allCases) { language in + Text(language.displayName).tag(language) + } } - } + .accessibilityIdentifier("general-language-picker") - if settings.language != LanguageLaunchState.language { - LabeledContent { - Button(String(localized: "Relaunch")) { - UpdateCenter.shared.relaunch() + if settings.value.language != LanguageLaunchState.language { + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() + } + .accessibilityIdentifier("language-relaunch-button") + } label: { + Text("Relaunch TablePro to finish switching languages.") } - .accessibilityIdentifier("language-relaunch-button") - } label: { - Text("Relaunch TablePro to finish switching languages.") - .font(.caption) - .foregroundStyle(.secondary) } - } - Picker("When TablePro starts:", selection: $settings.startupBehavior) { - ForEach(StartupBehavior.allCases) { behavior in - Text(behavior.displayName).tag(behavior) + Picker("When TablePro starts", selection: $settings.value.startupBehavior) { + ForEach(StartupBehavior.allCases) { behavior in + Text(behavior.displayName).tag(behavior) + } } + .accessibilityIdentifier("general-startup-picker") } Section { - NavigationLink(value: SettingsSubpage.commandLine) { - Label("Command Line Tool", systemImage: "terminal") - } - NavigationLink(value: SettingsSubpage.softwareUpdate) { - Label("Software Update", systemImage: "arrow.down.circle") - } + SoftwareUpdateDrillRow() + SettingsDrillRow(route: SettingsRoute.page(.commandLineTool), title: SettingsPage.commandLineTool.title) } - LinkedFoldersSection() - - TrustedExternalConnectionsSection() - Section { - Toggle("Share usage data", isOn: $settings.shareAnalytics) + Toggle(isOn: $settings.value.shareAnalytics) { + Text("Share usage data") + Text( + """ + Sent to PostHog: app and macOS versions, Mac model, screen size, architecture, language, time zone, \ + database types, connection count, first connection and query, plan prompts, sign-in and sign-out, \ + and your account ID once you sign in. Never hostnames, credentials, queries, or rows. + """ + ) + } + .accessibilityIdentifier("general-share-usage-toggle") } header: { Text("Privacy") - } footer: { - Text( - """ - Sent to PostHog: app and macOS versions, Mac model, screen size, architecture, language, time zone, \ - database types, connection count, first connection and query, plan prompts, sign-in and sign-out, \ - and your account ID once you sign in. Never hostnames, credentials, queries, or rows. - """ - ) } Section { - Button(String(localized: "Reset All Settings to Defaults"), role: .destructive) { - showResetConfirmation = true + LabeledContent { + Button(String(localized: "Reset…"), role: .destructive) { + showResetConfirmation = true + } + .accessibilityLabel(String(localized: "Reset All Settings…")) + .accessibilityIdentifier("general-reset-all-button") + } label: { + Text("Reset all settings") + Text("Returns every section to its defaults.") } } } .formStyle(.grouped) - .alert(String(localized: "Reset All Settings"), isPresented: $showResetConfirmation) { + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-general") + .alert(String(localized: "Reset all settings?"), isPresented: $showResetConfirmation) { Button(String(localized: "Reset"), role: .destructive) { onResetAll() } Button(String(localized: "Cancel"), role: .cancel) {} } message: { - Text("This will reset all settings across every section to their default values. AI providers, their API keys and Enable AI Features are kept.") + Text( + """ + Every section returns to its default values. AI providers and their API keys, Enable AI features, \ + Share usage data, linked folders, trusted links, connections and history are kept. + """ + ) } } } -#Preview { - GeneralSettingsView( - settings: .constant(.default), - onResetAll: {} - ) - .frame(width: 450, height: 500) +// Only this row re-renders when the update status changes. +private struct SoftwareUpdateDrillRow: View { + @ObservedObject private var updates = UpdateCenter.shared + + var body: some View { + SettingsDrillRow( + route: SettingsRoute.page(.softwareUpdate), + title: SettingsPage.softwareUpdate.title, + value: updates.status.indicatorTitle + ) + } } diff --git a/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift b/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift index 5cda970d70..025005f609 100644 --- a/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift +++ b/apple/TablePro/Views/Settings/Sections/CommandLineToolSection.swift @@ -1,49 +1,73 @@ import AppKit import SwiftUI -struct CommandLineToolSection: View { +struct CommandLineToolPage: View { private let tool: CommandLineShim + @ObservedObject private var visit: SettingsPaneVisit - @State private var status: CommandLineShimStatus = .notLinked - @State private var command: String? + @State private var link: CommandLineToolLink? - init(tool: CommandLineShim = CommandLineShim()) { + init(visit: SettingsPaneVisit, tool: CommandLineShim = CommandLineShim()) { self.tool = tool - _command = State(initialValue: tool.linkCommand) + self._visit = ObservedObject(wrappedValue: visit) } var body: some View { - Section { - LabeledContent { - Text(statusText) - .foregroundStyle(.secondary) - } label: { - Text("tablepro command") - Text(tool.linkPath) - .font(.system(.caption, design: .monospaced)) - } + Form { + Section { + LabeledContent { + if let link { + Text(link.statusText) + .foregroundStyle(.secondary) + .accessibilityIdentifier("command-line-status") + } + } label: { + Text("tablepro command") + Text("Opens database URLs and files, runs queries and exports tables from the terminal. Run `tablepro help` to see every command.") + } - VStack(alignment: .leading, spacing: 6) { - Text(instruction) - .font(.caption) - .foregroundStyle(.secondary) + LabeledContent("Location") { + Text(verbatim: tool.linkPath) + .font(.system(.body, design: .monospaced)) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } - if let command { - CopyableCodeBlock(text: command) + if let link { + VStack(alignment: .leading, spacing: 6) { + Text(link.instruction) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + if let command = link.command { + CopyableCodeBlock(text: command) + } + } } } - } header: { - Text("Command Line") - } footer: { - Text("Opens database URLs and files, runs queries and exports tables from the terminal. Run `tablepro help` to see every command.") } - .onAppear(perform: syncStatus) + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.commandLineTool.pageIdentifier) + .task(id: visit.count) { refresh() } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in - syncStatus() + refresh() } } - private var statusText: String { + // The link changes from Terminal, so it is read on every show and every return to the app. + private func refresh() { + let status = tool.status() + link = CommandLineToolLink(status: status, command: tool.command(for: status)) + } +} + +private struct CommandLineToolLink: Equatable { + let status: CommandLineShimStatus + let command: String? + + var statusText: String { switch status { case .linked: String(localized: "Linked") @@ -54,7 +78,7 @@ struct CommandLineToolSection: View { } } - private var instruction: String { + var instruction: String { guard command != nil else { return String(localized: "TablePro is running from a disk image or a temporary location. Move it to the Applications folder first, then open it from there.") } @@ -67,9 +91,4 @@ struct CommandLineToolSection: View { return String(localized: "To replace that file with a link to this app, run this in Terminal:") } } - - private func syncStatus() { - status = tool.status() - command = tool.command(for: status) - } } diff --git a/apple/TablePro/Views/Settings/SoftwareUpdateSection.swift b/apple/TablePro/Views/Settings/SoftwareUpdateSection.swift index a4c93237cd..ad8620ebe0 100644 --- a/apple/TablePro/Views/Settings/SoftwareUpdateSection.swift +++ b/apple/TablePro/Views/Settings/SoftwareUpdateSection.swift @@ -1,7 +1,7 @@ import AppKit import SwiftUI -struct SoftwareUpdateSection: View { +struct SoftwareUpdatePage: View { @ObservedObject var updater: SoftwareUpdater @ObservedObject var updates: UpdateCenter @@ -32,47 +32,56 @@ struct SoftwareUpdateSection: View { } var body: some View { - Section { - LabeledContent { - Button(summary.actionTitle) { - updates.performPrimaryAction() + Form { + Section { + LabeledContent { + Button(summary.actionTitle) { + updates.performPrimaryAction() + } + .disabled(!updates.isPrimaryActionEnabled) + .accessibilityIdentifier("software-update-action") + } label: { + Text(summary.headline) + .accessibilityIdentifier("software-update-headline") + Text(summary.detail) + .accessibilityIdentifier("software-update-detail") } - .disabled(!updates.isPrimaryActionEnabled) - .accessibilityIdentifier("software-update-action") - } label: { - Text(summary.headline) - .accessibilityIdentifier("software-update-headline") - Text(summary.detail) - .foregroundStyle(.secondary) - .accessibilityIdentifier("software-update-detail") - } - .accessibilityElement(children: .contain) + .accessibilityElement(children: .contain) - Picker("Update channel:", selection: channel) { - Text("Stable").tag(UpdateChannel.stable) - Text("Beta").tag(UpdateChannel.beta) + Button(String(localized: "What's New")) { + NSApp.sendAction(#selector(AppDelegate.openChangelog(_:)), to: nil, from: nil) + } + .buttonStyle(.link) + .accessibilityIdentifier("whats-new-link") } - .accessibilityIdentifier("update-channel-picker") - Toggle("Automatically check for updates", isOn: automaticallyChecksForUpdates) - .accessibilityIdentifier("automatic-update-check-toggle") + Section { + Toggle("Automatically check for updates", isOn: automaticallyChecksForUpdates) + .accessibilityIdentifier("automatic-update-check-toggle") - Toggle("Download and install updates automatically", isOn: automaticallyDownloadsUpdates) - .disabled(!updater.allowsAutomaticUpdates) + Toggle(isOn: automaticallyDownloadsUpdates) { + Text("Download and install updates automatically") + Text("A new version downloads in the background and installs the next time you quit TablePro.") + } + .disabled(!updater.allowsAutomaticUpdates || !updater.automaticallyChecksForUpdates) .accessibilityIdentifier("automatic-update-install-toggle") - .help(String(localized: "A new version downloads in the background and installs the next time you quit TablePro.")) + } header: { + Text("Automatic Updates") + } - Button { - NSApp.sendAction(#selector(AppDelegate.openChangelog(_:)), to: nil, from: nil) - } label: { - Text(String(localized: "What's New")) + Section { + Picker(selection: channel) { + Text("Stable").tag(UpdateChannel.stable) + Text("Beta").tag(UpdateChannel.beta) + } label: { + Text("Update channel") + Text("Betas get new features first. Switching back to Stable keeps the beta you have until a newer release ships.") + } + .accessibilityIdentifier("update-channel-picker") } - .buttonStyle(.link) - .accessibilityIdentifier("whats-new-link") - } header: { - Text("Software Update") - } footer: { - Text("Betas get new features first. Switching back to Stable keeps the beta you have until a newer release ships.") } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.softwareUpdate.pageIdentifier) } } diff --git a/apple/TableProUITests/WelcomeWindowUITests.swift b/apple/TableProUITests/WelcomeWindowUITests.swift index 9193bdd3ac..746dbce74d 100644 --- a/apple/TableProUITests/WelcomeWindowUITests.swift +++ b/apple/TableProUITests/WelcomeWindowUITests.swift @@ -66,16 +66,11 @@ final class WelcomeWindowUITests: UITestCase { let updateLink = welcome.descendants(matching: .any).matching(identifier: "welcome-update-link").firstMatch XCTAssertFalse(updateLink.exists, "With nothing pending the welcome window offers no update link") - app.typeShortcut(.settings) - let settings = window("settings", in: app) - XCTAssertTrue(settings.waitToExist(timeout: 10), "Command-comma must open Settings") - let generalPaneButton = settings.toolbars.buttons["General"] - XCTAssertTrue(generalPaneButton.waitToExist(timeout: 10)) - generalPaneButton.click() + let settings = openSettings(in: app) + selectSettingsPane("general", page: "software-update", in: settings) - // The Form builds every row, so the row reads without scrolling to it. let action = settings.descendants(matching: .any).matching(identifier: "software-update-action").firstMatch - XCTAssertTrue(action.waitToExist(timeout: 10), "General must show the Software Update row") + XCTAssertTrue(action.waitToExist(timeout: 10), "The Software Update page must show its status row") XCTAssertEqual(action.label, "Check Now") let headline = settings.descendants(matching: .any).matching(identifier: "software-update-headline").firstMatch From 8ff979a0da815545f43448886b7f4d4fa0382476 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:51 +0700 Subject: [PATCH 27/48] feat(settings): Sidebar & Tabs pane --- .../Models/UI/SharedSidebarState.swift | 41 +++------ .../Entries/SidebarTabsSettingsEntry.swift | 3 +- .../Settings/SidebarTabsSettingsView.swift | 83 +++++++++-------- .../Settings/SidebarTabsSettingsTests.swift | 88 +++++++++++++++++++ 4 files changed, 147 insertions(+), 68 deletions(-) create mode 100644 apple/TableProTests/Views/Settings/SidebarTabsSettingsTests.swift diff --git a/apple/TablePro/Models/UI/SharedSidebarState.swift b/apple/TablePro/Models/UI/SharedSidebarState.swift index 3b8d902ced..0f1ee2d55d 100644 --- a/apple/TablePro/Models/UI/SharedSidebarState.swift +++ b/apple/TablePro/Models/UI/SharedSidebarState.swift @@ -1,17 +1,7 @@ -// -// SharedSidebarState.swift -// TablePro -// -// Connection-scoped sidebar state shared across all windows of the same -// connection. Window-scoped state (table selection) lives in -// `WindowSidebarState`. -// - import Combine import Foundation import TableProUtilities -/// Which sidebar tab is active internal enum SidebarTab: String, CaseIterable { case tables case favorites @@ -20,8 +10,11 @@ internal enum SidebarTab: String, CaseIterable { internal enum SidebarLayout: String, CaseIterable, Sendable { case flat case tree + + static let fallback: SidebarLayout = .flat } +// Shared by every window of one connection; window-scoped state lives in WindowSidebarState. @MainActor final class SharedSidebarState: ObservableObject { @Published var redisKeyTreeViewModel: RedisKeyTreeViewModel? @@ -38,8 +31,7 @@ final class SharedSidebarState: ObservableObject { recentTables.filter { $0.database == normalizedDatabase(database) } } - /// `objectType` is what the object actually is, where the caller knew it. `isView` stays - /// beside it for the callers that know only that much, and is what an older build reads. + // isView stays beside objectType for callers that know only that much, and is what an older build reads. func recordTableOpen( database: String?, schema: String?, @@ -106,8 +98,7 @@ final class SharedSidebarState: ObservableObject { ) } - /// Removal matches on the entry's id, which is its database, schema and name, so the kind it - /// was recorded with is not part of the lookup. + // Matches on the id (database, schema, name), so the kind recorded with the entry is not part of the lookup. func removeRecentTable(database: String?, schema: String?, name: String) { let entry = RecentTableEntry( database: normalizedDatabase(database), schema: schema, name: name, @@ -116,9 +107,7 @@ final class SharedSidebarState: ObservableObject { recentTables = RecentTablesStore.shared.remove(connectionId: connectionId, entry: entry) } - /// A renamed table keeps its place in Recent. The store is asked directly rather than the live - /// list, because that list is empty while Show Recent Tables is off and the entry is still on - /// disk: renaming only what is on screen left a dead entry to reappear under the old name. + // Asks the store, not the live list: that list is empty while Show Recent Tables is off, and the entry is still on disk. func renameRecentTable(database: String?, schema: String?, from oldName: String, to newName: String) { let scope = normalizedDatabase(database) let existing = RecentTablesStore.shared.entries(connectionId: connectionId).first { @@ -128,8 +117,7 @@ final class SharedSidebarState: ObservableObject { publish(RecentTablesStore.shared.rename(connectionId: connectionId, entry: existing, to: newName)) } - /// Every Recent entry in a renamed container follows it, because the entries are keyed by the - /// container's name and would otherwise all point at one that has gone. + // Entries are keyed by the container's name, so each one has to follow the rename. func renameRecentDatabase(from oldName: String, to newName: String) { publish(RecentTablesStore.shared.renameDatabase( connectionId: connectionId, from: oldName, to: newName @@ -142,9 +130,7 @@ final class SharedSidebarState: ObservableObject { )) } - /// A table opened before the session knew its schema is recorded without one, and clicking that - /// entry opens the same name in whichever schema is browsed by then. It takes the schema the tab - /// resolved, in place. + // An entry recorded before the session knew its schema would open the name in whichever schema is browsed. func resolveRecentSchema(database: String?, name: String, to schema: String) { publish(RecentTablesStore.shared.resolveSchema( connectionId: connectionId, database: normalizedDatabase(database), name: name, to: schema @@ -206,8 +192,7 @@ final class SharedSidebarState: ObservableObject { } } - /// Keyed by database name, "" for an engine browsed without one. Written only through the - /// methods below, which keep the stored copy in step. + // Keyed by database name, "" without one. Written only through the methods below, which keep the stored copy in step. @Published private(set) var schemaFilterSelected: [String: Set] func schemaFilter(for database: String?) -> Set { @@ -237,8 +222,7 @@ final class SharedSidebarState: ObservableObject { setSchemaFilter(selected, for: database) } - /// A filter whose last schema was dropped is cleared rather than left naming nothing: an empty - /// selection is no filter, which is the list the user saw before picking the dropped one. + // An empty selection is no filter, which is the list the user saw before picking the dropped schema. func removeSchemaFromFilter(database: String?, schema: String) { var selected = schemaFilter(for: database) guard selected.remove(schema) != nil else { return } @@ -288,7 +272,7 @@ final class SharedSidebarState: ObservableObject { get { guard let raw = AppStorageEnvironment.shared.defaults.string(forKey: SidebarPersistenceKey.defaultLayout), let layout = SidebarLayout(rawValue: raw) else { - return .flat + return .fallback } return layout } @@ -329,11 +313,10 @@ final class SharedSidebarState: ObservableObject { } } - /// Default init for previews and tests init() { self.connectionId = UUID() self.selectedSidebarTab = .tables - self.sidebarLayout = .flat + self.sidebarLayout = .fallback self.databaseFilterSelected = [] self.schemaFilterSelected = [:] self.favoriteDatabaseEnvironmentFilter = .all diff --git a/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift index 41cfb6afc0..1fa5a03445 100644 --- a/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/SidebarTabsSettingsEntry.swift @@ -16,12 +16,13 @@ internal struct SidebarTabsSettingsEntry: View { } } +// No SettingsPage has Sidebar & Tabs as its parent, so nothing reaches this. internal struct SidebarTabsSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } diff --git a/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift b/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift index d55492fe4e..a61e91c407 100644 --- a/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift +++ b/apple/TablePro/Views/Settings/SidebarTabsSettingsView.swift @@ -1,8 +1,3 @@ -// -// SidebarTabsSettingsView.swift -// TablePro -// - import SwiftUI struct SidebarTabsSettingsView: View { @@ -10,64 +5,76 @@ struct SidebarTabsSettingsView: View { @Binding var tabSettings: TabSettings @AppStorage(SidebarPersistenceKey.defaultLayout, store: AppStorageEnvironment.shared.defaults) - private var defaultSidebarLayout: SidebarLayout = .flat + private var defaultSidebarLayout: SidebarLayout = .fallback var body: some View { Form { - Section("Tabs") { - Toggle("Enable preview tabs", isOn: $tabSettings.enablePreviewTabs) - .help("Single-clicking a table opens a temporary tab that gets replaced on next click.") - } - Section("Sidebar") { - Toggle("Show connections", isOn: $settings.showWorkspaceRail) - .help("Adds a narrow strip on the window's leading edge listing every connection and database you have open, so one click switches to it.") + Toggle(isOn: $settings.showWorkspaceRail) { + Text("Show connections") + Text("A strip on the window's leading edge with each open connection and database. It appears once more than one is open.") + } + .accessibilityIdentifier("show-connections-toggle") Toggle("Show recent tables", isOn: $settings.showRecentTables) - .help("Adds a Recent section at the top of the Tables sidebar with the last tables you opened per connection and database.") + .accessibilityIdentifier("show-recent-tables-toggle") + + Picker(selection: $defaultSidebarLayout) { + Text("List").tag(SidebarLayout.flat) + Text("Tree").tag(SidebarLayout.tree) + } label: { + Text("Default layout") + Text("Used when a connection opens, unless you picked a layout for it from the View menu. For servers with a database tree.") + } + .accessibilityIdentifier("sidebar-default-layout-picker") + } - Toggle("Show object icons", isOn: $settings.showObjectIcons) - .help("Shows a type icon before each object name in the sidebar. Turn it off for a plain list of names.") + // Same set and order as the sidebar's View Options menu, so the two map one to one. + Section("Objects") { + Toggle("Show icons", isOn: $settings.showObjectIcons) + .accessibilityIdentifier("show-object-icons-toggle") - Toggle("Show object comments", isOn: $settings.showObjectComments) - .help("Shows database object comments next to tables in the sidebar and in grid column headers.") + Toggle(isOn: $settings.showObjectComments) { + Text("Show comments") + Text("In the sidebar, the inspector and data grid column header tooltips.") + } + .accessibilityIdentifier("show-object-comments-toggle") - Toggle("Show system databases and schemas", isOn: $settings.showSystemContainers) - .accessibilityIdentifier("show-system-containers-toggle") - .help(String(localized: """ - Lists system databases such as mysql and information_schema, and system schemas, \ - in the sidebar tree and the database filter. Switchers always list them. - """)) + Toggle(isOn: $settings.showSystemContainers) { + Text("Show system databases and schemas") + Text("Such as mysql and information_schema, in the sidebar and its database filter. The database switcher always lists them.") + } + .accessibilityIdentifier("show-system-containers-toggle") Toggle("Show partitions", isOn: $settings.showPartitions) .accessibilityIdentifier("show-partitions-toggle") - .help(String(localized: """ - Lists a partitioned table's partitions under it in the sidebar, with how many \ - it holds. Turn it off to keep partitioned tables as single rows. - """)) - Picker("Row size:", selection: $settings.sidebarRowSize) { + Picker(selection: $settings.sidebarRowSize) { ForEach(SidebarRowSizePreference.allCases, id: \.self) { size in Text(size.title).tag(size) } + } label: { + Text("Row size") + Text("Match System follows Sidebar icon size in System Settings.") } - .help(String(localized: """ - Match System follows Sidebar icon size in System Settings > Appearance. \ - Choose a size to fit more objects on screen than the rest of the system shows. - """)) + .accessibilityIdentifier("sidebar-row-size-picker") + } - Picker("Default layout for new connections:", selection: $defaultSidebarLayout) { - Text("List").tag(SidebarLayout.flat) - Text("Tree").tag(SidebarLayout.tree) + Section("Tabs") { + Toggle(isOn: $tabSettings.enablePreviewTabs) { + Text("Enable preview tabs") + Text("Clicking a table opens it in a preview tab that the next click reuses. Double-click a table or press Return to keep its tab.") } - .help(String(localized: "Layout for new connections on servers that support a database tree. Switch the current connection from the View menu.")) + .accessibilityIdentifier("preview-tabs-toggle") } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-sidebar") } } #Preview { SidebarTabsSettingsView(settings: .constant(.default), tabSettings: .constant(.default)) - .frame(width: 520, height: 500) + .frame(width: 520, height: 760) } diff --git a/apple/TableProTests/Views/Settings/SidebarTabsSettingsTests.swift b/apple/TableProTests/Views/Settings/SidebarTabsSettingsTests.swift new file mode 100644 index 0000000000..8dda4d64c4 --- /dev/null +++ b/apple/TableProTests/Views/Settings/SidebarTabsSettingsTests.swift @@ -0,0 +1,88 @@ +import Combine +import Foundation +@testable import TablePro +import SwiftUI +import Testing + +@MainActor +private final class PublishCounter { + private(set) var count = 0 + private var subscription: AnyCancellable? + + init(_ publisher: ObservableObjectPublisher) { + subscription = publisher.sink { [weak self] _ in self?.count += 1 } + } +} + +@MainActor +struct SidebarTabsSettingsTests { + @Test("The default sidebar layout is List") + func fallbackIsList() { + #expect(SidebarLayout.fallback == .flat) + #expect(SharedSidebarState().sidebarLayout == .fallback) + } + + @Test("An unset or unknown default layout reads as the fallback, a stored one as itself") + func defaultLayoutReadsTheStoredValue() { + let defaults = AppStorageEnvironment.shared.defaults + let key = SidebarPersistenceKey.defaultLayout + let saved = defaults.string(forKey: key) + defer { + if let saved { + defaults.set(saved, forKey: key) + } else { + defaults.removeObject(forKey: key) + } + } + + defaults.removeObject(forKey: key) + #expect(SharedSidebarState.defaultLayout == .fallback) + + defaults.set("outline", forKey: key) + #expect(SharedSidebarState.defaultLayout == .fallback) + + SharedSidebarState.defaultLayout = .tree + #expect(defaults.string(forKey: key) == SidebarLayout.tree.rawValue) + #expect(SharedSidebarState.defaultLayout == .tree) + } + + @Test("A pane control is one General write, and only a sidebar field redraws the sidebar") + func paneWritesPublishOnce() { + let slice = SettingsSlice(GeneralSettings.default) + let preferences = SidebarDisplayPreferences(general: slice) + let sliceWrites = PublishCounter(slice.objectWillChange) + let sidebarRedraws = PublishCounter(preferences.objectWillChange) + // The same shape as the entry's `$general.value`. + let settings = Binding(get: { slice.value }, set: { slice.value = $0 }) + + settings.showObjectComments.wrappedValue.toggle() + #expect(sliceWrites.count == 1) + #expect(sidebarRedraws.count == 1) + #expect(preferences.options.showObjectComments == !GeneralSettings.default.showObjectComments) + + settings.showWorkspaceRail.wrappedValue.toggle() + #expect(sliceWrites.count == 2) + #expect(sidebarRedraws.count == 1) + + settings.sidebarRowSize.wrappedValue = .small + #expect(sliceWrites.count == 3) + #expect(sidebarRedraws.count == 2) + #expect(preferences.options.rowSize == .small) + + settings.sidebarRowSize.wrappedValue = .small + #expect(sliceWrites.count == 3) + #expect(sidebarRedraws.count == 2) + } + + @Test("The preview tabs switch writes the Tabs slice") + func previewTabsWritesTabs() { + let slice = SettingsSlice(TabSettings.default) + let writes = PublishCounter(slice.objectWillChange) + let tabs = Binding(get: { slice.value }, set: { slice.value = $0 }) + + tabs.enablePreviewTabs.wrappedValue.toggle() + + #expect(writes.count == 1) + #expect(slice.value.enablePreviewTabs == !TabSettings.default.enablePreviewTabs) + } +} From 471bfc3cf68053df132c300d6b2fddfcf8445756 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:52 +0700 Subject: [PATCH 28/48] feat(settings): Appearance pane with a Manage Themes page --- .../Settings/Appearance/ThemeEditorView.swift | 12 +- .../Appearance/ThemeLibraryModel.swift | 202 ++++++++--- .../Appearance/ThemeLibrarySection.swift | 340 ++++++++---------- .../Settings/AppearanceSettingsView.swift | 31 +- .../Entries/AppearanceSettingsEntry.swift | 21 +- .../Settings/AppearancePaneListTests.swift | 13 +- .../Settings/ThemeLibraryModelTests.swift | 117 +++++- .../ThemeLibraryUndoLifetimeTests.swift | 97 +++++ .../AppearanceSettingsUITests.swift | 57 ++- 9 files changed, 589 insertions(+), 301 deletions(-) create mode 100644 apple/TableProTests/Views/Settings/ThemeLibraryUndoLifetimeTests.swift diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift index 709db8dc4e..a7dc89f3a8 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift @@ -55,8 +55,6 @@ internal struct ThemeEditorView: View { } } - // MARK: - Sections - private var builtInSection: some View { Section { HStack { @@ -148,8 +146,6 @@ internal struct ThemeEditorView: View { ) } - // MARK: - Alerts - @ViewBuilder private func alertButtons(for alert: ThemeEditorModel.Alert) -> some View { switch alert { @@ -164,15 +160,15 @@ internal struct ThemeEditorView: View { } } -// Observes the settings itself, so a settings change re-renders this footer and not the editor or its preview. +// Observes the value colors slice itself, so a change re-renders this footer and not the editor or its preview. private struct ThemeValuesSectionFooter: View { let contrastNote: String? - @ObservedObject private var settingsManager = AppSettingsManager.shared + @ObservedObject private var valueColors = AppSettingsManager.shared.valueColorsSlice var body: some View { let settingNote = ThemeValueColorsNote.message( for: .values, - colorsValuesByType: settingsManager.valueColors.colorsValuesByType + colorsValuesByType: valueColors.value.colorsValuesByType ) if contrastNote != nil || settingNote != nil { VStack(alignment: .leading, spacing: 4) { @@ -206,7 +202,7 @@ internal extension ThemeEditorModel.Alert { case .changedOnDisk: return String(localized: "It was changed outside TablePro. The editor now shows the newer version.") case .unreadableOnDisk: - return String(localized: "It was changed outside TablePro and no longer loads. Settings > Appearance lists it under Not Loaded with the reason.") + return String(localized: "It was changed outside TablePro and no longer loads. Settings > Appearance > Manage Themes lists it under Couldn't Load with the reason.") case .deletedOnDisk: return String(localized: "The file was removed outside TablePro, possibly on another Mac.") case let .saveFailed(_, reason): diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift index 1d12ffda57..1698d19d9c 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift @@ -14,12 +14,23 @@ internal enum ThemeLibraryItem: Hashable, Sendable { @MainActor internal protocol ThemeSelectionStore: AnyObject { var themeSelection: AppearanceSettings { get set } + var themeSelectionWillChange: AnyPublisher { get } +} + +extension ThemeSelectionStore { + internal var themeSelectionWillChange: AnyPublisher { + Empty().eraseToAnyPublisher() + } } extension AppSettingsManager: ThemeSelectionStore { internal var themeSelection: AppearanceSettings { - get { appearance } - set { appearance = newValue } + get { appearanceSlice.value } + set { appearanceSlice.value = newValue } + } + + internal var themeSelectionWillChange: AnyPublisher { + appearanceSlice.objectWillChange.eraseToAnyPublisher() } } @@ -63,8 +74,7 @@ internal struct ThemeImportReport: Equatable { internal var imported: [ThemeDefinition] = [] internal var failures: [ThemeImportFailure] = [] - /// A clean import needs no alert: the new row is selected. Anything else is one alert for the - /// whole drop, so ten files never mean ten alerts. + // One alert for a whole drop, and none for a clean one: the new row is selected. internal var alert: ThemeLibraryAlert? { guard !failures.isEmpty else { return nil } let lines = failures.map { @@ -76,16 +86,53 @@ internal struct ThemeImportReport: Equatable { message: only.reason ) } - let title: String - switch imported.count { - case 0: title = String(localized: "No Themes Imported") - case 1: title = String(localized: "Imported 1 theme.") - default: title = String(format: String(localized: "Imported %d themes."), imported.count) - } + let title = imported.isEmpty + ? String(localized: "No Themes Imported") + : String(format: String(localized: "Imported %lld Themes"), imported.count) return ThemeLibraryAlert(title: title, message: lines.joined(separator: "\n")) } } +internal enum ThemeLibraryAction: Hashable, Sendable { + case edit + case showInEditor + case duplicate + case rename + case export + case use(ThemeAppearance) + case showInFinder + case tryAgain + case moveToTrash + + internal var title: String { + switch self { + case .edit: return String(localized: "Edit…") + case .showInEditor: return String(localized: "Show in Theme Editor") + case .duplicate: return String(localized: "Duplicate") + case .rename: return String(localized: "Rename") + case .export: return String(localized: "Export…") + case .use(.light): return String(localized: "Use for Light Appearance") + case .use(.dark): return String(localized: "Use for Dark Appearance") + case .showInFinder: return String(localized: "Show in Finder") + case .tryAgain: return String(localized: "Try Again") + case .moveToTrash: return String(localized: "Move to Trash") + } + } +} + +internal struct ThemeLibraryMenuEntry: Hashable, Sendable { + internal let action: ThemeLibraryAction + internal let isEnabled: Bool + // A separator goes before it when anything shows above it. + internal let startsGroup: Bool + + internal init(_ action: ThemeLibraryAction, isEnabled: Bool, startsGroup: Bool = false) { + self.action = action + self.isEnabled = isEnabled + self.startsGroup = startsGroup + } +} + internal struct ThemeFileDocument: FileDocument { internal static var readableContentTypes: [UTType] { [.json] } @@ -105,19 +152,22 @@ internal struct ThemeFileDocument: FileDocument { } } -/// Every action of the Appearance pane's theme list. Views call it and show what it publishes; it -/// never reaches the engine, which follows the catalog by itself. An action on a theme whose editor -/// is open goes through that editor, so the window and the list cannot write over each other. +// Never reaches the engine, which follows the catalog itself. An action on a theme whose editor is +// open goes through that editor, so the window and the list cannot write over each other. @MainActor internal final class ThemeLibraryModel: ObservableObject { @Published internal var alert: ThemeLibraryAlert? + // The Settings window sets this. It shows an alert raised while the Manage Themes page is off + // screen, an undo from another page for one, and returns true; false leaves it to the page. + internal var presentOffPage: (@MainActor (ThemeLibraryAlert) -> Bool)? + internal let catalog: ThemeCatalog private let selection: ThemeSelectionStore private let editors: ThemeEditorPresenting private let revealInFinder: @MainActor ([URL]) -> Void private let dragDirectory: URL - private var catalogCancellable: AnyCancellable? + private var cancellables: Set = [] private static let logger = Logger(subsystem: "com.TablePro", category: "ThemeLibrary") @@ -134,13 +184,15 @@ internal final class ThemeLibraryModel: ObservableObject { self.editors = editors self.dragDirectory = dragDirectory self.revealInFinder = revealInFinder - catalogCancellable = catalog.objectWillChange.sink { [weak self] _ in - self?.objectWillChange.send() - } + catalog.objectWillChange + .sink { [weak self] _ in self?.objectWillChange.send() } + .store(in: &cancellables) + // The in-use subtitles follow the slots, which sync and the theme editor also write. + selection.themeSelectionWillChange + .sink { [weak self] _ in self?.objectWillChange.send() } + .store(in: &cancellables) } - // MARK: - Contents - internal var builtInThemes: [ThemeDefinition] { catalog.themes.filter(\.isBuiltIn) } @@ -168,7 +220,12 @@ internal final class ThemeLibraryModel: ObservableObject { return record(for: item) != nil } - /// The slot a theme can still be chosen for, or nil when it is already the choice there. + internal func hasFile(_ item: ThemeLibraryItem?) -> Bool { + if case let .theme(id) = item { return catalog.fileURL(for: id) != nil } + return record(for: item) != nil + } + + // The slot a theme can still be chosen for, or nil when it is already the choice there. internal func availableSlot(for theme: ThemeDefinition) -> ThemeAppearance? { let current = selection.themeSelection switch theme.appearance { @@ -177,6 +234,16 @@ internal final class ThemeLibraryModel: ObservableObject { } } + // The themes the windows draw with, resolved as the pop-ups resolve them. + internal var inUseThemeIds: Set { + let current = selection.themeSelection + let themes = catalog.themes + return [ + ThemeSlotChoice(slot: .light, savedId: current.preferredLightThemeId, themes: themes).selectedId, + ThemeSlotChoice(slot: .dark, savedId: current.preferredDarkThemeId, themes: themes).selectedId, + ] + } + internal static func appearanceLabel(_ appearance: ThemeAppearance) -> String { switch appearance { case .light: return String(localized: "Light") @@ -184,8 +251,40 @@ internal final class ThemeLibraryModel: ObservableObject { } } - // MARK: - Opening and choosing + internal static func rowSubtitle(_ appearance: ThemeAppearance, isInUse: Bool) -> String { + guard isInUse else { return appearanceLabel(appearance) } + switch appearance { + case .light: return String(localized: "Light, in use") + case .dark: return String(localized: "Dark, in use") + } + } + // One list for the context menu, which leaves out a disabled entry, and the pull-down, which dims it. + internal func menuEntries(for item: ThemeLibraryItem?) -> [ThemeLibraryMenuEntry] { + if record(for: item) != nil { + return [ + ThemeLibraryMenuEntry(.showInFinder, isEnabled: true), + ThemeLibraryMenuEntry(.tryAgain, isEnabled: true), + ThemeLibraryMenuEntry(.moveToTrash, isEnabled: true, startsGroup: true), + ] + } + guard let theme = theme(for: item) else { + let actions: [ThemeLibraryAction] = [.edit, .duplicate, .rename, .export, .showInFinder] + return actions.map { ThemeLibraryMenuEntry($0, isEnabled: false) } + + [ThemeLibraryMenuEntry(.moveToTrash, isEnabled: false, startsGroup: true)] + } + return [ + ThemeLibraryMenuEntry(theme.isEditable ? .edit : .showInEditor, isEnabled: true), + ThemeLibraryMenuEntry(.duplicate, isEnabled: true), + ThemeLibraryMenuEntry(.rename, isEnabled: theme.isEditable), + ThemeLibraryMenuEntry(.export, isEnabled: true), + ThemeLibraryMenuEntry(.use(theme.appearance), isEnabled: availableSlot(for: theme) != nil), + ThemeLibraryMenuEntry(.showInFinder, isEnabled: hasFile(item)), + ThemeLibraryMenuEntry(.moveToTrash, isEnabled: theme.isEditable, startsGroup: true), + ] + } + + // A built-in opens read-only, with Duplicate. internal func edit(_ id: String) { guard catalog.theme(id: id) != nil else { return } editors.openEditor(for: id) @@ -201,14 +300,12 @@ internal final class ThemeLibraryModel: ObservableObject { selection.themeSelection = updated } - // MARK: - Creating - @discardableResult internal func duplicate(_ id: String, undoManager: UndoManager?) -> ThemeDefinition? { makeCopy(of: id, actionName: String(localized: "Duplicate"), undoManager: undoManager) } - /// A theme made to be edited, so its editor opens with it. + // A theme made to be edited, so its editor opens with it. @discardableResult internal func createTheme(basedOn id: String, undoManager: UndoManager?) -> ThemeDefinition? { guard let copy = makeCopy(of: id, actionName: String(localized: "New Theme"), undoManager: undoManager) else { @@ -243,15 +340,13 @@ internal final class ThemeLibraryModel: ObservableObject { } registerCreation(of: report.imported.map(\.id), actionName: String(localized: "Import"), undoManager: undoManager) if let alert = report.alert { - self.alert = alert + raise(alert) } return report } - // MARK: - Renaming - - /// The name the rename field starts from: the file's own, not the "Ocean 2" the list shows for - /// the second of two "Ocean" themes, so committing it untouched changes nothing. + // The file's own name, not the "Ocean 2" the list shows for the second of two "Ocean" themes, + // so committing it untouched changes nothing. internal func nameForRenaming(_ id: String) -> String? { catalog.storedTheme(id: id)?.name } @@ -299,15 +394,13 @@ internal final class ThemeLibraryModel: ObservableObject { register(on: undoManager, actionName: String(localized: "Rename")) { model in guard let current = model.catalog.storedTheme(id: id)?.name else { return } if case let .rejected(reason) = model.applyRename(id, to: name) { - model.alert = ThemeLibraryAlert(title: String(localized: "Couldn't Rename the Theme"), message: reason) + model.raise(ThemeLibraryAlert(title: String(localized: "Couldn't Rename the Theme"), message: reason)) return } model.registerRename(id, back: current, undoManager: undoManager) } } - // MARK: - Export - internal func exportDocument(for id: String) -> ThemeFileDocument? { editors.editor(for: id)?.flush() guard let theme = catalog.storedTheme(id: id) else { return nil } @@ -322,12 +415,15 @@ internal final class ThemeLibraryModel: ObservableObject { return cleaned.isEmpty ? theme.id : cleaned } - /// A copy in a folder of its own rather than the theme's file, because Finder may move a dragged - /// file instead of copying it, and a built-in theme has no file. + // A copy, because Finder may move a dragged file rather than copy it, and a built-in has no file. + // One folder per theme, emptied on each drag, so drags never pile up copies. internal func dragExportURL(for id: String) throws -> URL { editors.editor(for: id)?.flush() guard let theme = catalog.storedTheme(id: id) else { throw CocoaError(.fileNoSuchFile) } - let folder = dragDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let folder = dragDirectory.appendingPathComponent(id, isDirectory: true) + if FileManager.default.fileExists(atPath: folder.path) { + try FileManager.default.removeItem(at: folder) + } try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) let url = folder.appendingPathComponent(Self.exportFileName(for: theme) + ".json", isDirectory: false) try ThemeFileFormat.encode(theme).write(to: url, options: .atomic) @@ -348,26 +444,23 @@ internal final class ThemeLibraryModel: ObservableObject { url.standardizedFileURL.path.hasPrefix(dragDirectory.standardizedFileURL.path + "/") } - // MARK: - Finder - internal func revealInFinder(_ item: ThemeLibraryItem?) { if case let .theme(id) = item, let url = catalog.fileURL(for: id) { revealInFinder([url]) } else if let record = record(for: item) { revealInFinder([URL(fileURLWithPath: record.path)]) - } else { - revealInFinder([catalog.themesDirectory]) } } + internal func revealThemesFolder() { + revealInFinder([catalog.themesDirectory]) + } + internal func retryLoading() { catalog.reloadSynchronously() } - // MARK: - Trash - - /// Asked only when the trash changes what the windows draw. Moving a theme nothing uses is undone - /// from the Edit menu, so it needs no alert. + // Asked only when the trash changes what the windows draw; any other trash is undone from the Edit menu. internal func trashConfirmation(for item: ThemeLibraryItem) -> ThemeTrashConfirmation? { guard let theme = theme(for: item), theme.isEditable else { return nil } let current = selection.themeSelection @@ -392,7 +485,7 @@ internal final class ThemeLibraryModel: ObservableObject { } return ThemeTrashConfirmation( item: item, - title: String(format: String(localized: "Delete “%@”?"), theme.name), + title: String(format: String(localized: "Move “%@” to the Trash?"), theme.name), message: message ) } @@ -458,9 +551,7 @@ internal final class ThemeLibraryModel: ObservableObject { } } - // MARK: - Undoing a creation - - /// The way Finder undoes a duplicate: the new file goes to the Trash, and Redo brings it back. + // As Finder undoes a duplicate: the new file goes to the Trash, and Redo brings it back. private func registerCreation(of ids: [String], actionName: String, undoManager: UndoManager?) { guard let undoManager, !ids.isEmpty else { return } register(on: undoManager, actionName: actionName) { model in @@ -497,7 +588,7 @@ internal final class ThemeLibraryModel: ObservableObject { registerCreation(of: ids, actionName: actionName, undoManager: undoManager) } - /// A group of its own, so each action is one undo whether or not the manager groups by event. + // A group of its own, so each action is one undo whether or not the manager groups by event. private func register( on undoManager: UndoManager, actionName: String, @@ -513,8 +604,6 @@ internal final class ThemeLibraryModel: ObservableObject { undoManager.endUndoGrouping() } - // MARK: - Failures - private func perform(_ title: String, _ work: () throws -> Value) -> Value? { do { return try work() @@ -526,13 +615,17 @@ internal final class ThemeLibraryModel: ObservableObject { private func fail(_ title: String, _ error: Error) { Self.logger.error("Theme action failed: \(error.publicLogShape, privacy: .public)") - alert = ThemeLibraryAlert(title: title, message: error.localizedDescription) + raise(ThemeLibraryAlert(title: title, message: error.localizedDescription)) + } + + private func raise(_ alert: ThemeLibraryAlert) { + if presentOffPage?(alert) == true { return } + self.alert = alert } } internal extension AppearanceSettings { - /// A slot that held a theme the user just trashed goes back to its built-in, so the popup does - /// not then report that theme as missing. + // A slot that held a trashed theme goes back to its built-in, so the pop-up does not report it missing. func releasing(themeId: String) -> AppearanceSettings { var updated = self if updated.preferredLightThemeId == themeId { @@ -544,8 +637,7 @@ internal extension AppearanceSettings { return updated } - /// Undo of a trash puts the theme back only into the slots the trash released and nothing has - /// chosen since. + // Undo of a trash refills only the slots the trash released and nothing has chosen since. func reclaiming(themeId: String, from before: AppearanceSettings) -> AppearanceSettings { var updated = self if before.preferredLightThemeId == themeId, updated.preferredLightThemeId == BuiltInThemes.defaultLightId { diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift index e5da101404..c771368268 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift @@ -3,15 +3,9 @@ import SwiftUI import TableProTheme import UniformTypeIdentifiers -/// Every theme on this Mac in one list: the built-ins, the user's own, and the files that did not -/// load. The add and remove pair and the action pull-down sit under it the way macOS puts them under -/// a list. A context menu acts on the row under the pointer, which is not always the selected one. +// A context menu acts on the row under the pointer, which is not always the selected one. internal struct ThemeLibrarySection: View { - @StateObject private var model = ThemeLibraryModel( - catalog: .shared, - selection: AppSettingsManager.shared, - editors: ThemeEditorWindows.shared - ) + @ObservedObject private var model: ThemeLibraryModel @Environment(\.undoManager) private var undoManager @@ -33,80 +27,73 @@ internal struct ThemeLibrarySection: View { // A two-line theme row. The table sizes a row it has not measured at this estimate, and an // accessibility read makes it drop and remeasure off-screen rows, so any other value moves the rows. private static let rowHeight: CGFloat = 42 - /// A grouped Form centers its sections at most this wide (measured on macOS 27), so the list keeps - /// the edges of the sections above it. - private static let formContentWidth: CGFloat = 704 - private static let formMargin: CGFloat = 20 - /// How far a grouped Form indents its section headers from the section's edge. - private static let headerInset: CGFloat = 10 + + internal init(model: ThemeLibraryModel) { + self._model = ObservedObject(wrappedValue: model) + } internal var body: some View { - VStack(alignment: .leading, spacing: 8) { - Text("Themes") - .font(.headline) - .padding(.horizontal, Self.headerInset) - .accessibilityAddTraits(.isHeader) + SettingsFullPageList { list - .alert( - model.alert?.title ?? "", - isPresented: isPresented($model.alert), - presenting: model.alert - ) { _ in - Button(String(localized: "OK")) {} - } message: { alert in - Text(alert.message) - } - .alert( - pendingTrash?.title ?? "", - isPresented: isPresented($pendingTrash), - presenting: pendingTrash - ) { confirmation in - Button(String(localized: "Move to Trash"), role: .destructive) { - trash(confirmation.item) - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { confirmation in - Text(confirmation.message) - } - .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json], allowsMultipleSelection: true) { result in - guard case let .success(urls) = result else { return } - importThemes(urls) - } - .fileExporter( - isPresented: isPresented($exporting), - document: exporting?.document, - contentType: .json, - defaultFilename: exporting?.fileName - ) { _ in } + } bar: { + bar + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.manageThemes.pageIdentifier) + .alert( + model.alert?.title ?? "", + isPresented: isPresented($model.alert), + presenting: model.alert + ) { _ in + Button(String(localized: "OK")) {} + } message: { alert in + Text(alert.message) + } + .alert( + pendingTrash?.title ?? "", + isPresented: isPresented($pendingTrash), + presenting: pendingTrash + ) { confirmation in + Button(String(localized: "Move to Trash"), role: .destructive) { + trash(confirmation.item) + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(confirmation.message) + } + .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json], allowsMultipleSelection: true) { result in + guard case let .success(urls) = result else { return } + importThemes(urls) } - .frame(maxWidth: Self.formContentWidth) - .padding(.horizontal, Self.formMargin) - .padding(.bottom, Self.formMargin) - .frame(maxWidth: .infinity) + .fileExporter( + isPresented: isPresented($exporting), + document: exporting?.document, + contentType: .json, + defaultFilename: exporting?.fileName + ) { _ in } } - // MARK: - List - - /// The user's own themes come first: fourteen built-ins above them would push the rows a person - /// creates, renames and trashes out of sight. + // The user's own themes come first: the built-ins above them would push the rows a person + // creates, renames and trashes out of sight. private var list: some View { - ScrollViewReader { proxy in + let inUse = model.inUseThemeIds + return ScrollViewReader { proxy in List(selection: $selection) { Section(String(localized: "Custom")) { if model.customThemes.isEmpty { - Text("Duplicate a theme or import one to customize colors.") + Text("Click + to add a theme, or drop a TablePro or VS Code theme file here.") .foregroundStyle(.secondary) .accessibilityIdentifier("appearance-themes-custom-empty") } ForEach(model.customThemes) { theme in - themeRow(theme) + themeRow(theme, isInUse: inUse.contains(theme.id)) .tag(ThemeLibraryItem.theme(theme.id)) .id(ThemeLibraryItem.theme(theme.id)) } } if !model.notLoaded.isEmpty { - Section(String(localized: "Not Loaded")) { + Section(String(localized: "Couldn't Load")) { ForEach(model.notLoaded) { record in notLoadedRow(record) .tag(ThemeLibraryItem.notLoaded(path: record.path)) @@ -117,49 +104,57 @@ internal struct ThemeLibrarySection: View { Section(String(localized: "Built-in")) { ForEach(model.builtInThemes) { theme in - themeRow(theme) + themeRow(theme, isInUse: inUse.contains(theme.id)) .tag(ThemeLibraryItem.theme(theme.id)) .id(ThemeLibraryItem.theme(theme.id)) } } } - .listStyle(.bordered(alternatesRowBackgrounds: false)) .environment(\.defaultMinListRowHeight, Self.rowHeight) - .frame(minHeight: Self.minimumListHeight, maxHeight: .infinity) - .accessibilityIdentifier("appearance-themes-list") .contextMenu(forSelectionType: ThemeLibraryItem.self) { items in - rowMenu(for: items.first) + if let item = items.first { + menuItems(for: item, dimsUnavailable: false) + } else { + emptyAreaMenu + } } primaryAction: { items in guard case let .theme(id) = items.first else { return } model.edit(id) } - .onDeleteCommand { requestTrash(selection) } + .onDeleteCommand { + if model.canTrash(selection) { + requestTrash(selection) + } else { + NSSound.beep() + } + } .dropDestination(for: URL.self) { urls, _ in let files = urls.filter(\.isFileURL) guard !files.isEmpty else { return false } importThemes(files) return true } - .safeAreaInset(edge: .bottom, spacing: 0) { - footer - } .onChange(of: selection) { item in guard let item else { return } proxy.scrollTo(item) } + .frame(minHeight: Self.minimumListHeight, maxHeight: .infinity) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("appearance-themes-list") } } @ViewBuilder - private func themeRow(_ theme: ThemeDefinition) -> some View { + private func themeRow(_ theme: ThemeDefinition, isInUse: Bool) -> some View { if renamingId == theme.id { renameField(for: theme) } else { + // No combined element: the UI tests find a row by its name's text. VStack(alignment: .leading, spacing: 1) { Text(theme.name) .lineLimit(1) - Text(ThemeLibraryModel.appearanceLabel(theme.appearance)) - .font(.caption) + Text(ThemeLibraryModel.rowSubtitle(theme.appearance, isInUse: isInUse)) + .font(.subheadline) .foregroundStyle(.secondary) } .padding(.vertical, 2) @@ -181,7 +176,7 @@ internal struct ThemeLibrarySection: View { .accessibilityIdentifier("appearance-theme-rename-field") if let renameError { NoticeLabel(renameError, severity: .error) - .font(.caption) + .font(.subheadline) .accessibilityIdentifier("appearance-theme-rename-error") } } @@ -193,7 +188,7 @@ internal struct ThemeLibrarySection: View { Text(record.fileName) .lineLimit(1) Text(record.reason) - .font(.caption) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(3) .fixedSize(horizontal: false, vertical: true) @@ -202,137 +197,104 @@ internal struct ThemeLibrarySection: View { .help(record.reason) } - /// A contextual menu leaves out what does not apply; the pull-down below dims it instead. - @ViewBuilder - private func rowMenu(for item: ThemeLibraryItem?) -> some View { - if let theme = model.theme(for: item) { - if theme.isEditable { - Button(String(localized: "Edit…")) { model.edit(theme.id) } - } - Button(String(localized: "Duplicate")) { duplicate(theme.id) } - if theme.isEditable { - RenameButton() - .renameAction { beginRename(theme) } - } - Button(String(localized: "Export…")) { export(theme.id) } - if let slot = model.availableSlot(for: theme) { - Button(useTitle(for: slot)) { model.use(theme.id, for: slot) } - } - if theme.isEditable { - Button(String(localized: "Show in Finder")) { model.revealInFinder(item) } + private var bar: some View { + SettingsListBar( + addLabel: String(localized: "Add Theme"), + removeLabel: String(localized: "Move to Trash"), + canRemove: model.canTrash(selection), + addIdentifier: "appearance-theme-add", + removeIdentifier: "appearance-theme-remove", + addMenu: { addMenuItems }, + onRemove: { requestTrash(selection) }, + actionsLabel: String(localized: "Theme Actions"), + actionsIdentifier: "appearance-theme-actions", + actions: { + menuItems(for: selection, dimsUnavailable: true) Divider() - Button(String(localized: "Move to Trash")) { requestTrash(item) } + showThemesFolderButton } - } else if let item, model.record(for: item) != nil { - Button(String(localized: "Show in Finder")) { model.revealInFinder(item) } - Button(String(localized: "Try Again")) { model.retryLoading() } - Divider() - Button(String(localized: "Move to Trash")) { requestTrash(item) } - } + ) } - private func useTitle(for slot: ThemeAppearance) -> String { - switch slot { - case .light: return String(localized: "Use for Light Appearance") - case .dark: return String(localized: "Use for Dark Appearance") - } + @ViewBuilder + private var addMenuItems: some View { + newThemeMenu + Divider() + importButton } - // MARK: - Footer - - private var footer: some View { - VStack(spacing: 0) { - Divider() - HStack(spacing: 0) { - ControlGroup { - addMenu - - Button { - requestTrash(selection) - } label: { - Label(String(localized: "Move to Trash"), systemImage: "minus") - .labelStyle(.iconOnly) - } - .help(String(localized: "Move to Trash")) - .accessibilityLabel(String(localized: "Move to Trash")) - .accessibilityIdentifier("appearance-theme-remove") - .disabled(!model.canTrash(selection)) - - actionsMenu - } - .controlGroupStyle(.navigation) - .controlSize(.small) - .fixedSize() - - Spacer() - } - .padding(.horizontal, 4) - .padding(.vertical, 2) - } - .background(.bar) + @ViewBuilder + private var emptyAreaMenu: some View { + newThemeMenu + importButton + Divider() + showThemesFolderButton } - /// An icon-only `Menu` is named only through `.contain` plus a label on the menu itself; a - /// label inside its label closure leaves VoiceOver reading "More", or nothing on CI. - private var addMenu: some View { - Menu { - Menu(String(localized: "New Theme Based On")) { - ForEach(model.builtInThemes) { theme in + private var newThemeMenu: some View { + Menu(String(localized: "New Theme Based On")) { + ForEach(model.builtInThemes) { theme in + Button(theme.name) { createTheme(basedOn: theme.id) } + } + if !model.customThemes.isEmpty { + Divider() + ForEach(model.customThemes) { theme in Button(theme.name) { createTheme(basedOn: theme.id) } } - if !model.customThemes.isEmpty { - Divider() - ForEach(model.customThemes) { theme in - Button(theme.name) { createTheme(basedOn: theme.id) } - } - } } - Divider() - Button(String(localized: "Import…")) { isImporting = true } - } label: { - Label(String(localized: "Add Theme"), systemImage: "plus") - .labelStyle(.iconOnly) } - .menuIndicator(.hidden) - .help(String(localized: "Add Theme")) - .accessibilityElement(children: .contain) - .accessibilityLabel(String(localized: "Add Theme")) - .accessibilityIdentifier("appearance-theme-add") } - private var actionsMenu: some View { - let theme = model.theme(for: selection) - return Menu { - Button(String(localized: "Edit…")) { - if let theme { model.edit(theme.id) } - } - .disabled(theme == nil) - Button(String(localized: "Duplicate")) { - if let theme { duplicate(theme.id) } - } - .disabled(theme == nil) - Button(String(localized: "Rename")) { - if let theme { beginRename(theme) } + private var importButton: some View { + Button(String(localized: "Import…")) { isImporting = true } + } + + private var showThemesFolderButton: some View { + Button(String(localized: "Show Themes Folder in Finder")) { model.revealThemesFolder() } + } + + // The context menu leaves out what does not apply; the pull-down dims it. + private func menuItems(for item: ThemeLibraryItem?, dimsUnavailable: Bool) -> some View { + let entries = model.menuEntries(for: item).filter { dimsUnavailable || $0.isEnabled } + return ForEach(Array(entries.enumerated()), id: \.element.action) { index, entry in + if entry.startsGroup, index > 0 { + Divider() } - .disabled(theme?.isEditable != true) - Button(String(localized: "Export…")) { - if let theme { export(theme.id) } + if entry.action == .rename, !dimsUnavailable { + RenameButton() + .renameAction { perform(.rename, on: item) } + } else { + Button(entry.action.title) { perform(entry.action, on: item) } + .disabled(!entry.isEnabled) } - .disabled(theme == nil) - Divider() - Button(String(localized: "Show in Finder")) { model.revealInFinder(selection) } - } label: { - Label(String(localized: "Theme Actions"), systemImage: "ellipsis.circle") - .labelStyle(.iconOnly) } - .menuIndicator(.hidden) - .help(String(localized: "Theme Actions")) - .accessibilityElement(children: .contain) - .accessibilityLabel(String(localized: "Theme Actions")) - .accessibilityIdentifier("appearance-theme-actions") } - // MARK: - Actions + private func perform(_ action: ThemeLibraryAction, on item: ThemeLibraryItem?) { + switch action { + case .edit, .showInEditor: + guard case let .theme(id) = item else { return } + model.edit(id) + case .duplicate: + guard case let .theme(id) = item else { return } + duplicate(id) + case .rename: + guard let theme = model.theme(for: item) else { return } + beginRename(theme) + case .export: + guard case let .theme(id) = item else { return } + export(id) + case let .use(slot): + guard case let .theme(id) = item else { return } + model.use(id, for: slot) + case .showInFinder: + model.revealInFinder(item) + case .tryAgain: + model.retryLoading() + case .moveToTrash: + requestTrash(item) + } + } private func duplicate(_ id: String) { guard let copy = model.duplicate(id, undoManager: undoManager) else { return } @@ -364,7 +326,7 @@ internal struct ThemeLibrarySection: View { renamingId = theme.id } - /// A taken name keeps the field open with the reason, the way Finder refuses one. + // A taken name keeps the field open with the reason, the way Finder refuses one. private func commitRename(_ id: String) { guard renamingId == id else { return } switch model.rename(id, to: renameText, undoManager: undoManager) { diff --git a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift index d54f3f5686..18b7ed86dc 100644 --- a/apple/TablePro/Views/Settings/AppearanceSettingsView.swift +++ b/apple/TablePro/Views/Settings/AppearanceSettingsView.swift @@ -3,40 +3,36 @@ import TableProTheme internal struct AppearanceSettingsView: View { @Binding internal var settings: AppearanceSettings + @Binding internal var appearanceMode: AppAppearanceMode @ObservedObject private var catalog = ThemeCatalog.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared private static let modes: [AppAppearanceMode] = [.auto, .light, .dark] internal var body: some View { Form { Section { - Picker(String(localized: "Appearance"), selection: $settingsManager.appearanceMode) { + Picker(selection: $appearanceMode) { ForEach(Self.modes, id: \.self) { mode in Text(Self.title(for: mode)).tag(mode) } + } label: { + Text("Appearance") + Text("Controls, sidebars and Settings follow this. Applies to this Mac.") } .pickerStyle(.segmented) .accessibilityIdentifier("appearance-mode-picker") - } footer: { - Text("Applies to this Mac.") } - Section { + Section("Themes") { themePicker(ThemeSlotChoice(slot: .light, savedId: settings.preferredLightThemeId, themes: catalog.themes)) themePicker(ThemeSlotChoice(slot: .dark, savedId: settings.preferredDarkThemeId, themes: catalog.themes)) - } footer: { - Text("Themes color the editor, the data grid, other content views and the window background. Controls, sidebars and Settings follow the system appearance.") - } - - Section { - NavigationLink(value: SettingsSubpage.manageThemes) { - Label("Manage Themes", systemImage: "paintpalette") - } + SettingsDrillRow(route: SettingsRoute.page(.manageThemes), title: SettingsPage.manageThemes.title) } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-appearance") } private static func title(for mode: AppAppearanceMode) -> String { @@ -65,11 +61,12 @@ internal struct AppearanceSettingsView: View { .accessibilityIdentifier("appearance-\(choice.slot.rawValue)-theme-note") } } + .pickerStyle(.menu) .accessibilityIdentifier("appearance-\(choice.slot.rawValue)-theme") } - /// The popup shows the theme in use, but only a pick writes the setting: a saved id this Mac - /// cannot resolve stays saved for the Mac that has the theme. + // Shows the theme in use, but only a pick writes: a saved id this Mac cannot resolve stays saved + // for the Mac that has the theme. private func selectionBinding(for choice: ThemeSlotChoice) -> Binding { Binding( get: { choice.selectedId }, @@ -86,6 +83,6 @@ internal struct AppearanceSettingsView: View { } #Preview { - AppearanceSettingsView(settings: .constant(.default)) - .frame(width: 720, height: 560) + AppearanceSettingsView(settings: .constant(.default), appearanceMode: .constant(.auto)) + .frame(width: 520, height: 480) } diff --git a/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift index 2381d23d68..b7a89eebcb 100644 --- a/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/AppearanceSettingsEntry.swift @@ -3,14 +3,16 @@ import SwiftUI internal struct AppearanceSettingsEntry: View { internal let context: SettingsPaneContext @ObservedObject private var appearance: SettingsSlice + @ObservedObject private var appearanceMode: SettingsSlice internal init(context: SettingsPaneContext) { self.context = context self._appearance = ObservedObject(wrappedValue: context.settings.appearanceSlice) + self._appearanceMode = ObservedObject(wrappedValue: context.settings.appearanceModeSlice) } internal var body: some View { - AppearanceSettingsView(settings: $appearance.value) + AppearanceSettingsView(settings: $appearance.value, appearanceMode: $appearanceMode.value) } } @@ -21,10 +23,9 @@ internal struct AppearanceSettingsPageEntry: View { internal var body: some View { switch route { case .page(.manageThemes): - // Not in a Form: a List inside a grouped Form does not scroll on macOS. - ThemeLibrarySection() + ThemeLibrarySection(model: context.models.themeLibrary) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } @@ -34,5 +35,17 @@ internal struct AppearanceStackPresentations: ViewModifier { internal func body(content: Content) -> some View { content + .onAppear { + Self.routeOffPageAlerts(of: context.models.themeLibrary, to: context) + } + } + + // A theme undo from the root page or another pane fails with no Manage Themes page to show it. + internal static func routeOffPageAlerts(of model: ThemeLibraryModel, to context: SettingsPaneContext) { + model.presentOffPage = { [weak context] alert in + guard let context, context.path.routes.last != .page(.manageThemes) else { return false } + context.presentError(title: alert.title, message: alert.message) + return true + } } } diff --git a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift index b5b875c556..7ba6b5508e 100644 --- a/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift +++ b/apple/TableProTests/Views/Settings/AppearancePaneListTests.swift @@ -4,14 +4,14 @@ import ApplicationServices import SwiftUI import Testing -/// The Themes list lives in the Manage Themes drill-in, free of the grouped Form that used to -/// disable its scrolling. It must scroll on its own and hold still while accessibility reads it. +// The Manage Themes list sits outside a grouped Form, which used to disable its scrolling. @MainActor struct AppearancePaneListTests { private struct HostedPane { let window: NSWindow let table: NSTableView let scrollView: NSScrollView + let model: ThemeLibraryModel } private static let windowTitle = "AppearancePaneListTests" @@ -43,8 +43,7 @@ struct AppearancePaneListTests { } private static func hostPane() throws -> HostedPane { - // The size of the Settings detail pane that hosts the Appearance view. - let paneSize = NSSize(width: 560, height: 480) + let paneSize = NSSize(width: SettingsSplitViewController.detailWidth, height: SettingsSplitViewController.minimumContentSize.height) let window = NSWindow( contentRect: NSRect(origin: .zero, size: paneSize), styleMask: [.titled], @@ -53,8 +52,10 @@ struct AppearancePaneListTests { ) window.isReleasedWhenClosed = false window.title = windowTitle + // The shared catalog's built-ins overflow the list; the slots and editors are stand-ins. + let model = ThemeLibraryModel(catalog: .shared, selection: InMemoryThemeSelection(), editors: StubThemeEditors()) // As the Settings window hosts a pane: the window keeps its size whatever the content asks. - let hosting = NSHostingController(rootView: ThemeLibrarySection()) + let hosting = NSHostingController(rootView: ThemeLibrarySection(model: model)) hosting.sizingOptions = [] window.contentViewController = hosting window.setContentSize(paneSize) @@ -67,7 +68,7 @@ struct AppearancePaneListTests { "The pane should show the Themes list" ) let scrollView = try #require(table.enclosingScrollView) - return HostedPane(window: window, table: table, scrollView: scrollView) + return HostedPane(window: window, table: table, scrollView: scrollView, model: model) } private static func elements(_ attribute: String, of element: AXUIElement) -> [AXUIElement] { diff --git a/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift b/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift index 7691aa16ed..d29dd4afcb 100644 --- a/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift +++ b/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift @@ -42,8 +42,7 @@ struct ThemeLibraryModelTests { #expect(fixture.editors.opened == [created.id]) } - /// A copy of a default has no syntax colors of its own, so it keeps Xcode's Increase Contrast - /// palette instead of freezing the standard one into the file. + // A copy of a default has no syntax colors of its own, so it keeps Xcode's Increase Contrast palette. @Test("A duplicate of a default keeps the adaptive syntax palette") func duplicateOfDefaultKeepsAdaptiveSyntax() throws { let fixture = try Fixture() @@ -70,7 +69,7 @@ struct ThemeLibraryModelTests { undoManager.groupsByEvent = false let confirmation = try #require(library.trashConfirmation(for: .theme("user.aaaa0002"))) - #expect(confirmation.title == "Delete “Midnight”?") + #expect(confirmation.title == "Move “Midnight” to the Trash?") #expect(confirmation.message == "The file moves to the Trash. Dark windows switch to Default Dark.") undoManager.beginUndoGrouping() @@ -166,7 +165,7 @@ struct ThemeLibraryModelTests { #expect(report.imported.allSatisfy { $0.id != "user.11111111" && $0.id != "user.22222222" }) #expect(report.failures.map(\.fileName) == ["Monokai.json"]) let alert = try #require(library.alert) - #expect(alert.title == "Imported 2 themes.") + #expect(alert.title == "Imported 2 Themes") #expect(alert.message.hasPrefix("Monokai.json could not be read: ")) #expect(library.customThemes.map(\.name) == ["Ocean", "Paper"]) } @@ -305,8 +304,7 @@ struct ThemeLibraryModelTests { #expect(editor.alert == nil) } - /// The list shows the second of two "Ocean" themes as "Ocean 2". The rename field started from that - /// shown name, and committing it untouched reported a rename and left an Undo step that did nothing. + // The rename field used to start from the shown "Ocean 2", so an untouched commit left an empty Undo step. @Test("Renaming the second of two same-named themes starts from its stored name, with or without its editor") func renameOfADisambiguatedTheme() throws { let fixture = try Fixture() @@ -334,8 +332,7 @@ struct ThemeLibraryModelTests { editor.close() } - /// Typed on purpose, the shown name becomes the file's name. It used to be a silent no-op without - /// an editor open and a write with one. + // It used to be a silent no-op without an editor open and a write with one. @Test("Typing the shown name renames the file the same way with or without its editor", arguments: [false, true]) func typedShownNameRenamesTheFile(isEditorOpen: Bool) throws { let fixture = try Fixture() @@ -378,4 +375,108 @@ struct ThemeLibraryModelTests { #expect(settings.releasing(themeId: "user.other") == settings) #expect(released.reclaiming(themeId: "user.aaaa0002", from: settings) == settings) } + + @Test("One item list feeds both menus: the context menu leaves out what the pull-down dims") + func menuEntriesPerItem() throws { + let fixture = try Fixture() + try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + try Data("{".utf8).write(to: fixture.themes.appendingPathComponent("Broken.json")) + fixture.catalog.reloadSynchronously() + let library = fixture.makeLibrary() + let broken = try #require(library.notLoaded.first) + + let custom = library.menuEntries(for: .theme("user.aaaa0002")) + let customActions = custom.map { $0.action } + let allThemeActions: [ThemeLibraryAction] = [.edit, .duplicate, .rename, .export, .use(.dark), .showInFinder, .moveToTrash] + #expect(customActions == allThemeActions) + #expect(custom.allSatisfy { $0.isEnabled }) + + let builtIn = library.menuEntries(for: .theme(BuiltInThemes.defaultDarkId)) + let builtInActions = builtIn.map { $0.action } + let builtInShown = builtIn.filter { $0.isEnabled }.map { $0.action } + let builtInExpected: [ThemeLibraryAction] = [.showInEditor, .duplicate, .rename, .export, .use(.dark), .showInFinder, .moveToTrash] + let builtInShownExpected: [ThemeLibraryAction] = [.showInEditor, .duplicate, .export] + #expect(builtInActions == builtInExpected) + #expect(builtInShown == builtInShownExpected) + + let record = library.menuEntries(for: .notLoaded(path: broken.path)) + let recordActions = record.map { $0.action } + let recordExpected: [ThemeLibraryAction] = [.showInFinder, .tryAgain, .moveToTrash] + #expect(recordActions == recordExpected) + #expect(record.allSatisfy { $0.isEnabled }) + + let nothing = library.menuEntries(for: nil) + #expect(nothing.allSatisfy { !$0.isEnabled }) + let trash = try #require(nothing.last) + #expect(trash.action == .moveToTrash) + #expect(trash.startsGroup) + } + + @Test("A theme the windows draw with says so under its name, resolved as the pop-up resolves it") + func inUseFollowsTheResolvedSlots() throws { + let fixture = try Fixture() + try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + let library = fixture.makeLibrary() + #expect(library.inUseThemeIds == Set([BuiltInThemes.defaultLightId, BuiltInThemes.defaultDarkId])) + + fixture.selection.themeSelection.preferredDarkThemeId = "user.aaaa0002" + #expect(library.inUseThemeIds == Set([BuiltInThemes.defaultLightId, "user.aaaa0002"])) + + // A dark theme saved for the light slot draws the default light. + fixture.selection.themeSelection.preferredLightThemeId = "user.aaaa0002" + #expect(library.inUseThemeIds == Set([BuiltInThemes.defaultLightId, "user.aaaa0002"])) + + fixture.selection.themeSelection.preferredDarkThemeId = "user.gone" + #expect(library.inUseThemeIds == Set([BuiltInThemes.defaultLightId, BuiltInThemes.defaultDarkId])) + + #expect(ThemeLibraryModel.rowSubtitle(.dark, isInUse: true) == "Dark, in use") + #expect(ThemeLibraryModel.rowSubtitle(.light, isInUse: true) == "Light, in use") + #expect(ThemeLibraryModel.rowSubtitle(.light, isInUse: false) == "Light") + } + + @Test("Each drag of a theme rewrites the one folder named for it") + func dragReusesOneFolderPerTheme() throws { + let fixture = try Fixture() + try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + let library = fixture.makeLibrary() + + let first = try library.dragExportURL(for: "user.aaaa0002") + #expect(first.deletingLastPathComponent().lastPathComponent == "user.aaaa0002") + #expect(library.rename("user.aaaa0002", to: "Night Owl", undoManager: nil) == .renamed("Night Owl")) + let second = try library.dragExportURL(for: "user.aaaa0002") + let folder = second.deletingLastPathComponent() + + #expect(folder.standardizedFileURL.path == first.deletingLastPathComponent().standardizedFileURL.path) + #expect(try FileManager.default.contentsOfDirectory(atPath: folder.path) == ["Night Owl.json"]) + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.drags.path) == ["user.aaaa0002"]) + } + + @Test("Show in Finder reveals only a theme's file, and the folder item reveals the Themes folder") + func revealInFinder() throws { + let fixture = try Fixture() + let file = try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + let recorder = RevealRecorder() + let library = ThemeLibraryModel( + catalog: fixture.catalog, + selection: fixture.selection, + editors: fixture.editors, + dragDirectory: fixture.drags, + revealInFinder: { recorder.revealed.append($0) } + ) + + #expect(library.hasFile(.theme("user.aaaa0002"))) + #expect(!library.hasFile(.theme(BuiltInThemes.defaultDarkId))) + library.revealInFinder(.theme("user.aaaa0002")) + library.revealInFinder(.theme(BuiltInThemes.defaultDarkId)) + library.revealThemesFolder() + + let revealed = recorder.revealed.map { urls in urls.map { $0.resolvingSymlinksInPath().path } } + let expected = [[file.resolvingSymlinksInPath().path], [fixture.themes.resolvingSymlinksInPath().path]] + #expect(revealed == expected) + } +} + +@MainActor +private final class RevealRecorder { + var revealed: [[URL]] = [] } diff --git a/apple/TableProTests/Views/Settings/ThemeLibraryUndoLifetimeTests.swift b/apple/TableProTests/Views/Settings/ThemeLibraryUndoLifetimeTests.swift new file mode 100644 index 0000000000..5fc8ed12e2 --- /dev/null +++ b/apple/TableProTests/Views/Settings/ThemeLibraryUndoLifetimeTests.swift @@ -0,0 +1,97 @@ +import AppKit +@testable import TablePro +import SwiftUI +import TableProTheme +import Testing + +// The Manage Themes page used to own its model, so Cmd-Z after Back reached a released undo target. +@MainActor +struct ThemeLibraryUndoLifetimeTests { + private typealias Fixture = ThemeLibraryTestFixture + + @Test("Undo of a trash made on Manage Themes restores the theme and its slot after the page is gone") + func undoAfterThePageIsReleased() throws { + let fixture = try Fixture() + try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + fixture.selection.themeSelection.preferredDarkThemeId = "user.aaaa0002" + let library = fixture.makeLibrary() + + let window = NSWindow( + contentRect: NSRect( + x: 0, + y: 0, + width: SettingsSplitViewController.detailWidth, + height: SettingsSplitViewController.minimumContentSize.height + ), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + defer { window.orderOut(nil) } + let undoManager = try #require(window.undoManager) + undoManager.groupsByEvent = false + + window.contentViewController = NSHostingController(rootView: ThemeLibrarySection(model: library)) + window.layoutIfNeeded() + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.2)) + + undoManager.beginUndoGrouping() + #expect(library.moveToTrash(.theme("user.aaaa0002"), undoManager: undoManager)) + undoManager.endUndoGrouping() + #expect(fixture.catalog.theme(id: "user.aaaa0002") == nil) + #expect(fixture.selection.themeSelection.preferredDarkThemeId == BuiltInThemes.defaultDarkId) + + // Releasing the host stands in for Back popping the page. + window.contentViewController = nil + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.2)) + + #expect(undoManager.canUndo) + undoManager.undo() + #expect(fixture.catalog.theme(id: "user.aaaa0002")?.name == "Midnight") + #expect(try fixture.fileNames() == ["user.aaaa0002.json"]) + #expect(fixture.selection.themeSelection.preferredDarkThemeId == "user.aaaa0002") + #expect(library.alert == nil) + } + + @Test("A theme undo that fails off the Manage Themes page shows its error on the Settings window") + func offPageErrorReachesTheWindow() throws { + let fixture = try Fixture() + try fixture.install(Fixture.theme("user.aaaa0001", "Paper", appearance: .light)) + try fixture.install(Fixture.theme("user.aaaa0002", "Midnight")) + let library = fixture.makeLibrary() + let registry = try OfflineRegistry() + let navigation = SettingsNavigationModel(initial: .root(.appearance)) + let shown = PresentedErrors() + let context = SettingsPaneContext( + pane: .appearance, + settings: .shared, + navigation: navigation, + models: SettingsWindowModels(), + registryClient: registry.client, + presentError: { title, _ in shown.titles.append(title) } + ) + AppearanceStackPresentations.routeOffPageAlerts(of: library, to: context) + let undoManager = UndoManager() + undoManager.groupsByEvent = false + + undoManager.beginUndoGrouping() + #expect(library.rename("user.aaaa0002", to: "Night Owl", undoManager: undoManager) == .renamed("Night Owl")) + undoManager.endUndoGrouping() + #expect(library.rename("user.aaaa0001", to: "Midnight", undoManager: nil) == .renamed("Midnight")) + undoManager.undo() + #expect(shown.titles == ["Couldn't Rename the Theme"]) + #expect(library.alert == nil) + + #expect(navigation.push(.page(.manageThemes), in: .appearance)) + let broken = try fixture.writeIncoming("Monokai.json", contents: Data("[]".utf8)) + _ = library.importThemes(from: [broken], undoManager: nil) + #expect(library.alert?.title == "Couldn't Import “Monokai.json”") + #expect(shown.titles.count == 1) + } +} + +@MainActor +private final class PresentedErrors { + var titles: [String] = [] +} diff --git a/apple/TableProUITests/AppearanceSettingsUITests.swift b/apple/TableProUITests/AppearanceSettingsUITests.swift index dbd356f936..43dc0b0eca 100644 --- a/apple/TableProUITests/AppearanceSettingsUITests.swift +++ b/apple/TableProUITests/AppearanceSettingsUITests.swift @@ -4,6 +4,7 @@ final class AppearanceSettingsUITests: UITestCase { func testCustomThemeFromCreationToTrashAndBack() throws { let app = try launchOpeningURL("tablepro://settings/appearance") let settings = try appearancePane(in: app) + openManageThemes(in: settings) createTheme(basedOn: "Dracula", in: settings) let editor = window("theme-editor", in: app) @@ -25,6 +26,7 @@ final class AppearanceSettingsUITests: UITestCase { renameInRow("Dracula Copy", to: "Midnight", in: settings) + goBack(in: settings) let dark = settings.popUpButtons["appearance-dark-theme"] XCTAssertTrue(dark.waitToExist(timeout: 10)) choose("Midnight", in: dark) @@ -33,30 +35,42 @@ final class AppearanceSettingsUITests: UITestCase { "A custom dark theme should be offered in the Dark popup" ) + openManageThemes(in: settings) + XCTAssertTrue( + row("Dark, in use", in: settings).waitToExist(timeout: 5), + "The theme the Dark slot uses should say so in the list" + ) moveToTrash("Midnight", in: settings) + XCTAssertNil(themeDocument(named: "Midnight"), "The theme file should leave the Themes folder") + + goBack(in: settings) XCTAssertTrue( waitForPredicate(timeout: 5) { (dark.value as? String) == "Default Dark" }, "The slot that held the trashed theme should go back to its built-in" ) - XCTAssertNil(themeDocument(named: "Midnight"), "The theme file should leave the Themes folder") + // The list's model outlives the page, so Undo works from the root page after Back. app.typeShortcut(.undo) - XCTAssertTrue(row("Midnight", in: settings).waitToExist(timeout: 5), "Undo should bring the theme back") - XCTAssertTrue( - waitForPredicate(timeout: 5) { self.themeDocument(named: "Midnight") != nil }, - "Undo should put the file back in the Themes folder" - ) XCTAssertTrue( waitForPredicate(timeout: 5) { (dark.value as? String) == "Midnight" }, "Undo should give the Dark slot its theme back" ) + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.themeDocument(named: "Midnight") != nil }, + "Undo should put the file back in the Themes folder" + ) + + openManageThemes(in: settings) + XCTAssertTrue(row("Midnight", in: settings).waitToExist(timeout: 5), "Undo should bring the theme back to the list") } func testThemesListScrollsAndTakesArrowKeys() throws { let app = try launchOpeningURL("tablepro://settings/appearance") let settings = try appearancePane(in: app) + openManageThemes(in: settings) + let list = settings.outlines.containing(NSPredicate(format: "value == %@", "Default Light")).firstMatch - XCTAssertTrue(list.waitToExist(timeout: 10), "The Themes list should be on the Appearance pane") + XCTAssertTrue(waitUntilHittable(list, timeout: 10), "Manage Themes should list the themes") // The bar under the list marks where its visible rows end; an outline's own frame spans every row. let footer = element("appearance-theme-add", in: settings) XCTAssertTrue(footer.waitToExist(timeout: 10)) @@ -81,7 +95,25 @@ final class AppearanceSettingsUITests: UITestCase { ) } - // MARK: - Steps + private func openManageThemes(in settings: XCUIElement) { + selectSettingsPane("appearance", page: "themes", in: settings) + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Manage Themes" }, + "The link should push Manage Themes, the window is titled \(settings.title)" + ) + let list = element("appearance-themes-list", in: settings) + XCTAssertTrue(list.waitToExist(timeout: 10), "Manage Themes should show the themes list") + } + + private func goBack(in settings: XCUIElement) { + let back = settingsNavigationButton("Back", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 5) { back.exists && back.isEnabled }, "Back should be enabled on Manage Themes") + back.click() + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Appearance" }, + "Back should return to the Appearance pane, the window is titled \(settings.title)" + ) + } private func createTheme(basedOn source: String, in window: XCUIElement) { let add = element("appearance-theme-add", in: window) @@ -101,7 +133,7 @@ final class AppearanceSettingsUITests: UITestCase { item.click() } - /// The shared color panel cannot be driven reliably; ThemeEditorModelTests covers what a well hands back. + // The shared color panel cannot be driven reliably; ThemeEditorModelTests covers what a well hands back. private func resetAndUndoEditorBackground(in editor: XCUIElement, app: XCUIApplication, themeName: String) { let reset = element("theme-color-reset-editor.background", in: editor) XCTAssertTrue(reset.waitToExist(timeout: 10), "A Dracula copy sets the editor background") @@ -171,10 +203,8 @@ final class AppearanceSettingsUITests: UITestCase { XCTAssertTrue(waitForPredicate(timeout: 5) { !themeRow.exists }, "The trashed theme should leave the list") } - // MARK: - Helpers - private func appearancePane(in app: XCUIApplication) throws -> XCUIElement { - let settings = window("settings", in: app) + let settings = settingsWindow(in: app) XCTAssertTrue(settings.waitToExist(timeout: 10)) XCTAssertTrue( waitForPredicate(timeout: 5) { settings.title == "Appearance" }, @@ -183,8 +213,7 @@ final class AppearanceSettingsUITests: UITestCase { return settings } - /// A control clipped by its scroll view still reads as hittable, and a click on it lands on - /// whatever is drawn there, so the frames decide when it is in view. + // A control clipped by its scroll view still reads as hittable and a click lands on what is drawn there. private func reveal(_ control: XCUIElement, in scrollView: XCUIElement, scrollingAt point: CGVector) { let deadline = Date(timeIntervalSinceNow: 10) while control.frame.maxY > scrollView.frame.maxY || control.frame.minY < scrollView.frame.minY, Date() < deadline { From 661259ce84424227a70e492a0470ae72863b9f20 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:52 +0700 Subject: [PATCH 29/48] feat(settings): Editor pane with a SQL Formatting page --- .../Models/Settings/EditorSettings.swift | 83 ++-- .../Components/HighlightedSQLTextView.swift | 22 +- .../Views/Settings/EditorSettingsView.swift | 115 +++-- .../Entries/EditorSettingsEntry.swift | 37 +- .../Settings/Sections/FormatterSection.swift | 451 +++++++++++------- .../Settings/Sections/TypographySection.swift | 156 ++++-- .../Settings/EditorFontResolverTests.swift | 150 ++++++ .../Settings/FormatterPreviewTests.swift | 99 ++++ .../Support/UITestCase+EditorTabs.swift | 16 +- 9 files changed, 795 insertions(+), 334 deletions(-) create mode 100644 apple/TableProTests/Models/Settings/EditorFontResolverTests.swift create mode 100644 apple/TableProTests/Views/Settings/FormatterPreviewTests.swift diff --git a/apple/TablePro/Models/Settings/EditorSettings.swift b/apple/TablePro/Models/Settings/EditorSettings.swift index 61c096077e..243c81f3fa 100644 --- a/apple/TablePro/Models/Settings/EditorSettings.swift +++ b/apple/TablePro/Models/Settings/EditorSettings.swift @@ -1,9 +1,6 @@ -// -// EditorSettings.swift -// TablePro -// - import AppKit +import Combine +import CoreText import Foundation import TableProAutocomplete @@ -15,26 +12,28 @@ internal struct FontFamilyOption: Equatable, Identifiable, Sendable { internal enum EditorFontResolver { static let systemMonoId = "System Mono" - static let availableMonospacedFamilies: [FontFamilyOption] = { - var options: [FontFamilyOption] = [ - FontFamilyOption(id: systemMonoId, displayName: systemMonoId) - ] + // One CoreText query for monospaced faces; asking NSFontManager family by family took 83 to 863 ms. + static func availableMonospacedFamilies() -> [FontFamilyOption] { + familyOptions(from: monospacedFamilyNames()) + } - let familyNames = NSFontManager.shared.availableFontFamilies - .filter { $0 != systemMonoId } - .filter(isMonospacedFamily) - .sorted { lhs, rhs in - lhs.localizedCaseInsensitiveCompare(rhs) == .orderedAscending - } + static func familyOptions(from familyNames: [String]) -> [FontFamilyOption] { + let names = Set(familyNames) + .filter { !$0.hasPrefix(".") && $0 != systemMonoId } + .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending } + return [FontFamilyOption(id: systemMonoId, displayName: systemMonoId)] + + names.map { FontFamilyOption(id: $0, displayName: $0) } + } - var seen: Set = [systemMonoId] - for family in familyNames where !seen.contains(family) { - seen.insert(family) - options.append(FontFamilyOption(id: family, displayName: family)) + private static func monospacedFamilyNames() -> [String] { + let traits = [kCTFontSymbolicTrait: CTFontSymbolicTraits.traitMonoSpace.rawValue] as CFDictionary + let descriptor = CTFontDescriptorCreateWithAttributes([kCTFontTraitsAttribute: traits] as CFDictionary) + let collection = CTFontCollectionCreateWithFontDescriptors([descriptor] as CFArray, nil) + guard let matches = CTFontCollectionCreateMatchingFontDescriptors(collection) as? [CTFontDescriptor] else { + return [] } - - return options - }() + return matches.compactMap { CTFontDescriptorCopyAttribute($0, kCTFontFamilyNameAttribute) as? String } + } static func resolve(familyId: String, size: CGFloat) -> NSFont { guard familyId != systemMonoId else { @@ -49,16 +48,34 @@ internal enum EditorFontResolver { return NSFont.monospacedSystemFont(ofSize: size, weight: .regular) } +} + +// The font pickers' list, rebuilt when a font is installed or removed while the app runs. +@MainActor +internal final class MonospacedFontFamilies: ObservableObject { + internal static let shared = MonospacedFontFamilies() + + @Published internal private(set) var families: [FontFamilyOption] + private let load: () -> [FontFamilyOption] + private var fontSetChanges: AnyCancellable? - static func isAvailable(familyId: String) -> Bool { - guard familyId != systemMonoId else { return true } - return isMonospacedFamily(familyId) + internal init( + notificationCenter: NotificationCenter = .default, + load: @escaping () -> [FontFamilyOption] = { EditorFontResolver.availableMonospacedFamilies() } + ) { + self.load = load + families = load() + fontSetChanges = notificationCenter.publisher(for: NSFont.fontSetChangedNotification) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in + self?.reload() + } } - private static func isMonospacedFamily(_ familyId: String) -> Bool { - let descriptor = NSFontDescriptor(fontAttributes: [.family: familyId]) - guard let font = NSFont(descriptor: descriptor, size: 12) else { return false } - return font.fontDescriptor.symbolicTraits.contains(.monoSpace) + internal func reload() { + let latest = load() + guard latest != families else { return } + families = latest } } @@ -73,11 +90,10 @@ internal enum EditorKeyBindings: String, Codable, CaseIterable { case emacs } -/// Editor settings struct EditorSettings: Codable, Equatable { var showLineNumbers: Bool var highlightCurrentLine: Bool - var tabWidth: Int // 2, 4, or 8 spaces + var tabWidth: Int var wordWrap: Bool var keyBindings: EditorKeyBindings var keywordCase: SQLKeywordCase @@ -156,9 +172,7 @@ struct EditorSettings: Codable, Equatable { ) } - // Spelled out so `uppercaseKeywords` and `vimModeEnabled` stay on the wire after their properties became - // `keywordCase` and `keyBindings`. Editor settings sync as one JSON blob, so it carries both the key an older - // build reads and the key this one writes. + // Synced as one blob, so the legacy uppercaseKeywords and vimModeEnabled keys stay for older builds. private enum CodingKeys: String, CodingKey { case showLineNumbers case highlightCurrentLine @@ -212,7 +226,6 @@ struct EditorSettings: Codable, Equatable { try container.encode(jsonViewerPreferredMode, forKey: .jsonViewerPreferredMode) } - /// Clamped tab width (1-16) var clampedTabWidth: Int { min(max(tabWidth, 1), 16) } diff --git a/apple/TablePro/Views/Components/HighlightedSQLTextView.swift b/apple/TablePro/Views/Components/HighlightedSQLTextView.swift index 16611ae0f3..2d2978ce2c 100644 --- a/apple/TablePro/Views/Components/HighlightedSQLTextView.swift +++ b/apple/TablePro/Views/Components/HighlightedSQLTextView.swift @@ -1,8 +1,3 @@ -// -// HighlightedSQLTextView.swift -// TablePro -// - import AppKit import Combine import SwiftUI @@ -11,14 +6,12 @@ import TableProGrammars import TableProPluginKit import TableProTheme -/// A code view: `ThemeTextViewStyle` puts it on the editor's background, text, caret and selection, and its -/// syntax comes from the editor's own grammar and `EditorTheme`, so every token draws in the slot the SQL -/// editor gives it. +// A code view in the editor's theme slots and grammar, so every token draws as it does in the SQL editor. struct HighlightedSQLTextView: NSViewRepresentable { internal enum LineLayout: Equatable { case unwrapped case wrapped - /// Wraps, and is as tall as its text up to `maxLines`; it scrolls vertically past that. + // Wraps, and grows with its text up to maxLines; it scrolls past that. case fitted(maxLines: Int) } @@ -30,9 +23,9 @@ struct HighlightedSQLTextView: NSViewRepresentable { let sql: String var databaseType: DatabaseType = .mysql var highlighting: Highlighting = .engine - /// A SwiftUI `.accessibilityIdentifier` lands on the representable's wrapper, not on the text - /// view AppKit publishes, so the only way to name this element is to set it on the text view. + // A SwiftUI accessibilityIdentifier lands on the representable's wrapper, never on the text view AppKit publishes. var accessibilityIdentifier: String? + var accessibilityLabel = String(localized: "Query preview") var lineLayout: LineLayout = .unwrapped @ObservedObject private var themeEngine = ThemeEngine.shared @@ -45,7 +38,7 @@ struct HighlightedSQLTextView: NSViewRepresentable { } textView.setAccessibilityIdentifier(accessibilityIdentifier) - textView.setAccessibilityLabel(String(localized: "Query preview")) + textView.setAccessibilityLabel(accessibilityLabel) textView.isEditable = false textView.isSelectable = true textView.font = themeEngine.editorFonts.font @@ -113,6 +106,9 @@ struct HighlightedSQLTextView: NSViewRepresentable { if textChanged { textView.string = sql } + if textView.accessibilityLabel() != accessibilityLabel { + textView.setAccessibilityLabel(accessibilityLabel) + } // A short query would otherwise show the scroll view's own color below its last line. if scrollView.backgroundColor !== textView.backgroundColor { scrollView.backgroundColor = textView.backgroundColor @@ -171,8 +167,6 @@ struct HighlightedSQLTextView: NSViewRepresentable { } } - // MARK: - Syntax Highlighting - private var language: CodeLanguage { switch highlighting { case .json: diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index ceedf3e0f3..5e8c62f3fb 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -1,65 +1,102 @@ -// -// EditorSettingsView.swift -// TablePro -// - import SwiftUI import TableProAutocomplete struct EditorSettingsView: View { - @Binding var settings: EditorSettings - @Binding var typography: TypographySettings + static let tabWidths = [2, 4, 8] + + @ObservedObject var editor: SettingsSlice + @ObservedObject var typography: SettingsSlice var body: some View { Form { - TypographySection(domain: .editor, settings: $typography) - - Section("Display") { - Toggle("Show line numbers", isOn: $settings.showLineNumbers) - Toggle("Highlight current line", isOn: $settings.highlightCurrentLine) - Toggle("Highlight current statement", isOn: $settings.highlightCurrentStatement) - Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) - Toggle("Word wrap", isOn: $settings.wordWrap) + Section { + TypographyRows(domain: .editor, typography: $typography.value) + } header: { + Text("Font") } - Section("Gutter") { - Toggle("Code folding", isOn: $settings.codeFoldingEnabled) - Toggle("Run button beside each statement", isOn: $settings.showStatementRunControls) - .disabled(!settings.showLineNumbers) - .help(Text("The run button sits in the gutter, which needs line numbers.")) + Section { + Toggle("Highlight current line", isOn: $editor.value.highlightCurrentLine) + .accessibilityIdentifier("editor-highlight-current-line") + Toggle(isOn: $editor.value.highlightCurrentStatement) { + Text("Highlight current statement") + Text("A faint band behind the statement the cursor is in.") + } + .accessibilityIdentifier("editor-highlight-current-statement") + Toggle("Show invisible characters", isOn: $editor.value.showInvisibleCharacters) + .accessibilityIdentifier("editor-show-invisibles") + Toggle("Word wrap", isOn: $editor.value.wordWrap) + .accessibilityIdentifier("editor-word-wrap") + } header: { + Text("Display") } - Section("Editing") { - Picker("Tab width:", selection: $settings.tabWidth) { - Text("2 spaces").tag(2) - Text("4 spaces").tag(4) - Text("8 spaces").tag(8) - } - Picker("Keyword case:", selection: $settings.keywordCase) { - ForEach(SQLKeywordCase.allCases, id: \.self) { keywordCase in - Text(keywordCase.displayName).tag(keywordCase) - } + Section { + Toggle("Show line numbers", isOn: $editor.value.showLineNumbers) + .accessibilityIdentifier("editor-line-numbers") + Toggle(isOn: $editor.value.showStatementRunControls) { + Text("Run button beside each statement") + Text("Needs line numbers.") } - Toggle("Query parameters (:name syntax)", isOn: $settings.queryParametersEnabled) - Picker("Key bindings:", selection: $settings.keyBindings) { + .disabled(!editor.value.showLineNumbers) + .accessibilityIdentifier("editor-run-buttons") + Toggle("Code folding", isOn: $editor.value.codeFoldingEnabled) + .accessibilityIdentifier("editor-code-folding") + } header: { + Text("Gutter") + } + + Section { + Picker("Key bindings", selection: $editor.value.keyBindings) { Text("Standard").tag(EditorKeyBindings.standard) Text(verbatim: "Vim").tag(EditorKeyBindings.vim) Text(verbatim: "Emacs").tag(EditorKeyBindings.emacs) } + .pickerStyle(.menu) .accessibilityIdentifier("key-bindings-picker") + + Picker("Tab width", selection: Self.tabWidthBinding($editor.value)) { + SettingsChoiceItems(Self.tabWidths, including: editor.value.clampedTabWidth) { width in + Text("\(width) spaces") + } + } + .accessibilityIdentifier("editor-tab-width") + + Picker(selection: $editor.value.keywordCase) { + Text(SQLKeywordCase.matchTypedElseUpper.displayName).tag(SQLKeywordCase.matchTypedElseUpper) + Text(SQLKeywordCase.matchTypedElseLower.displayName).tag(SQLKeywordCase.matchTypedElseLower) + Divider() + Text(SQLKeywordCase.upper.displayName).tag(SQLKeywordCase.upper) + Text(SQLKeywordCase.lower.displayName).tag(SQLKeywordCase.lower) + } label: { + Text("Keyword case") + Text("The case completions use. UPPERCASE and lowercase also change keywords as you type.") + } + .accessibilityIdentifier("editor-keyword-case") + + Toggle(isOn: $editor.value.queryParametersEnabled) { + Text("Query parameters") + Text("Asks for a value for each :name placeholder before the query runs.") + } + .accessibilityIdentifier("editor-query-parameters") + } header: { + Text("Editing") } Section { - NavigationLink(value: SettingsSubpage.sqlFormatting) { - Label("SQL Formatting", systemImage: "text.alignleft") - } + SettingsDrillRow(route: SettingsRoute.page(.sqlFormatting), title: SettingsPage.sqlFormatting.title) } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-editor") } -} -#Preview { - EditorSettingsView(settings: .constant(.default), typography: .constant(.default)) - .frame(width: 450, height: 500) + // Shows the width the editor uses; a pick writes the stored field. + static func tabWidthBinding(_ editor: Binding) -> Binding { + Binding( + get: { editor.wrappedValue.clampedTabWidth }, + set: { editor.wrappedValue.tabWidth = $0 } + ) + } } diff --git a/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift index 229fe6b47e..0fab034a47 100644 --- a/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/EditorSettingsEntry.swift @@ -1,41 +1,24 @@ +import Combine import SwiftUI internal struct EditorSettingsEntry: View { internal let context: SettingsPaneContext - @ObservedObject private var editor: SettingsSlice - @ObservedObject private var typography: SettingsSlice - - internal init(context: SettingsPaneContext) { - self.context = context - self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) - self._typography = ObservedObject(wrappedValue: context.settings.typographySlice) - } internal var body: some View { - EditorSettingsView(settings: $editor.value, typography: $typography.value) + EditorSettingsView(editor: context.settings.editorSlice, typography: context.settings.typographySlice) } } internal struct EditorSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext - @ObservedObject private var formatter: SettingsSlice - @ObservedObject private var editor: SettingsSlice - - internal init(route: SettingsRoute, context: SettingsPaneContext) { - self.route = route - self.context = context - self._formatter = ObservedObject(wrappedValue: context.settings.formatterSlice) - self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) - } internal var body: some View { switch route { case .page(.sqlFormatting): - Form { FormatterSection(settings: $formatter.value, editor: editor.value) } - .formStyle(.grouped) + SQLFormattingPageHost(formatter: context.settings.formatterSlice, editor: context.settings.editorSlice) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } @@ -47,3 +30,15 @@ internal struct EditorStackPresentations: ViewModifier { content } } + +// Follows only the editor font, so a theme change elsewhere never re-renders the page. +private struct SQLFormattingPageHost: View { + @ObservedObject var formatter: SettingsSlice + @ObservedObject var editor: SettingsSlice + @State private var font = ThemeEngine.shared.editorFonts.font + + var body: some View { + SQLFormattingPage(settings: $formatter.value, editor: editor.value, font: font) + .onReceive(ThemeEngine.shared.$editorFonts.map(\.font).removeDuplicates()) { font = $0 } + } +} diff --git a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift index 24ff238f25..f72a9b7e45 100644 --- a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift +++ b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift @@ -1,136 +1,166 @@ -// -// FormatterSection.swift -// TablePro -// - import AppKit import os import SwiftUI import TableProAutocomplete import UniformTypeIdentifiers -struct FormatterSection: View { - private static let logger = Logger(subsystem: "com.TablePro", category: "FormatterSection") - private static let previewMaxLines = 18 - private static let previewSQL = """ - select u.id as user_id, u.name as user_name, count(o.id) as order_count \ - from users u left join orders o on u.id = o.user_id \ - where u.status = 'active' and cast(o.created_at as date) >= '2026-01-01' \ - group by u.id, u.name order by order_count desc; - """ - private static let indentWidths = [2, 4, 8] - private static let lineWidths = [0, 80, 100, 120] +struct SQLFormattingPage: View { + private static let logger = Logger(subsystem: "com.TablePro", category: "SQLFormattingPage") + static let indentWidths = [2, 4, 8] + static let lineWidths = [80, 100, 120] - @Binding var settings: SQLFormatterSettings - let editor: EditorSettings - @ObservedObject private var themeEngine = ThemeEngine.shared + enum IndentWidthChoice: Hashable { + case editor + case fixed(Int) - @State private var isImporting = false - @State private var exportDocument: SQLFormatterRulesDocument? - @State private var importError: String? - @State private var exportError: String? + init(_ settings: SQLFormatterSettings) { + self = settings.indentFollowsTabWidth ? .editor : .fixed(settings.rules.indentWidth) + } - private enum IndentWidthChoice: Hashable { - case tabWidth - case fixed(Int) + // One whole-value write, so the follow flag and the width never land separately. + func applied(to settings: SQLFormatterSettings) -> SQLFormatterSettings { + var updated = settings + switch self { + case .editor: + updated.indentFollowsTabWidth = true + case .fixed(let width): + updated.indentFollowsTabWidth = false + updated.rules.indentWidth = width + } + return updated + } } - private enum KeywordCaseChoice: Hashable { + enum KeywordCaseChoice: Hashable { case editor case fixed(SQLFormatterCase) + + init(_ settings: SQLFormatterSettings) { + self = settings.keywordCaseFollowsEditor ? .editor : .fixed(settings.rules.keywordCase) + } + + func applied(to settings: SQLFormatterSettings) -> SQLFormatterSettings { + var updated = settings + switch self { + case .editor: + updated.keywordCaseFollowsEditor = true + case .fixed(let formatterCase): + updated.keywordCaseFollowsEditor = false + updated.rules.keywordCase = formatterCase + } + return updated + } } + @Binding var settings: SQLFormatterSettings + let editor: EditorSettings + let font: NSFont + + @State private var isImporting = false + @State private var exportDocument: SQLFormatterRulesDocument? + @State private var importError: String? + @State private var exportError: String? + var body: some View { - Section { - Picker("Indent with:", selection: $settings.rules.indentStyle) { - Text("Spaces").tag(SQLFormatterIndentStyle.spaces) - Text("Tabs").tag(SQLFormatterIndentStyle.tabs) + Form { + Section { + FormatterPreview(options: settings.options(for: editor), font: font) + .equatable() } - Picker("Indent width:", selection: indentWidthChoice) { - Text(String(format: String(localized: "Tab width (%d)"), editor.clampedTabWidth)) - .tag(IndentWidthChoice.tabWidth) - ForEach(Self.options(Self.indentWidths, including: settings.rules.indentWidth), id: \.self) { width in - Text(String(format: String(localized: "%d spaces"), width)).tag(IndentWidthChoice.fixed(width)) + + Section { + Picker("Indent with", selection: $settings.rules.indentStyle) { + Text("Spaces").tag(SQLFormatterIndentStyle.spaces) + Text("Tabs").tag(SQLFormatterIndentStyle.tabs) } + .accessibilityIdentifier("formatter-indent-style") + indentWidthPicker + } header: { + Text("Indentation") } - Picker("Keyword case:", selection: keywordCaseChoice) { - Text(String(format: String(localized: "Same as editor (%@)"), caseName(editorKeywordCase))) - .tag(KeywordCaseChoice.editor) - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(KeywordCaseChoice.fixed(formatterCase)) + + Section { + keywordCasePicker + Picker("Functions", selection: $settings.rules.functionCase) { + caseItems } - } - Picker("Function case:", selection: $settings.rules.functionCase) { - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(formatterCase) + .accessibilityIdentifier("formatter-function-case") + Picker(selection: $settings.rules.dataTypeCase) { + caseItems + } label: { + Text("Data types") + Text("Engines that match function and type names by exact case, such as ClickHouse, keep the case you typed.") } + .accessibilityIdentifier("formatter-data-type-case") + } header: { + Text("Case") } - .help(Text("Engines that match function names by exact case, such as ClickHouse, keep the case you typed.")) - Picker("Data type case:", selection: $settings.rules.dataTypeCase) { - ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in - Text(caseName(formatterCase)).tag(formatterCase) + + Section { + lineWidthPicker + Picker(selection: $settings.rules.clauseItems) { + Text("Beside the keyword").tag(SQLFormatterClauseItems.sameLine) + Text("Below the keyword").tag(SQLFormatterClauseItems.newLine) + } label: { + Text("Clause items") + Text("Where a broken SELECT, SET, WITH, WHERE or HAVING list starts. A single item stays beside its keyword.") } - } - .help(Text("Engines that match type names by exact case, such as ClickHouse, keep the case you typed.")) - Picker("Commas:", selection: $settings.rules.commaPosition) { - Text("At the end of the line").tag(SQLFormatterCommaPosition.trailing) - Text("At the start of the line").tag(SQLFormatterCommaPosition.leading) - } - Picker("AND and OR:", selection: $settings.rules.logicalOperatorNewline) { - Text("At the start of the line").tag(SQLFormatterLogicalOperatorNewline.before) - Text("At the end of the line").tag(SQLFormatterLogicalOperatorNewline.after) - } - .help(Text("Where AND and OR go when a WHERE or HAVING condition breaks across lines.")) - Picker("Line width:", selection: $settings.rules.lineWidth) { - ForEach(Self.options(Self.lineWidths, including: settings.rules.lineWidth), id: \.self) { width in - Text(lineWidthName(width)).tag(width) + .accessibilityIdentifier("formatter-clause-items") + Picker("Commas", selection: $settings.rules.commaPosition) { + Text("At the end of the line").tag(SQLFormatterCommaPosition.trailing) + Text("At the start of the line").tag(SQLFormatterCommaPosition.leading) } + .accessibilityIdentifier("formatter-commas") + Picker(selection: $settings.rules.logicalOperatorNewline) { + Text("At the start of the line").tag(SQLFormatterLogicalOperatorNewline.before) + Text("At the end of the line").tag(SQLFormatterLogicalOperatorNewline.after) + } label: { + Text("AND and OR") + Text("Where they go when a WHERE or HAVING condition breaks.") + } + .accessibilityIdentifier("formatter-logical-operators") + Picker("Join condition", selection: $settings.rules.joinCondition) { + Text("On its own line").tag(SQLFormatterJoinCondition.newLine) + Text("On the JOIN line").tag(SQLFormatterJoinCondition.sameLine) + } + .accessibilityIdentifier("formatter-join-condition") + Toggle(isOn: $settings.rules.alignAliases) { + Text("Align column aliases") + Text("Lines up the AS of each SELECT item that sits on one line.") + } + .accessibilityIdentifier("formatter-align-aliases") + } header: { + Text("Line Breaks") } - .help(Text("A SELECT list, SET list or WHERE condition that fits in this width stays on one line.")) - Picker("Clause items:", selection: $settings.rules.clauseItems) { - Text("Beside the keyword").tag(SQLFormatterClauseItems.sameLine) - Text("Below the keyword").tag(SQLFormatterClauseItems.newLine) - } - .help(Text(""" - Where the items of a SELECT list, SET list, WITH list, or WHERE or HAVING condition start once it \ - breaks across lines. A single item stays beside its keyword. - """)) - Picker("Join condition:", selection: $settings.rules.joinCondition) { - Text("On its own line").tag(SQLFormatterJoinCondition.newLine) - Text("On the JOIN line").tag(SQLFormatterJoinCondition.sameLine) + + Section { + LabeledContent { + HStack(spacing: 8) { + importButton + exportButton + } + } label: { + Text("Rules file") + Text("A .sql-formatter.json in a linked SQL folder replaces these rules for files opened from that folder.") + } + } header: { + Text("Rules File") } - Toggle("Align column aliases", isOn: $settings.rules.alignAliases) - - preview - - LabeledContent("Rules file:") { - HStack { - Button("Import…") { isImporting = true } - .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in - importRules(result) - } - Button("Export…") { exportRules() } - .fileExporter( - isPresented: isExporting, - document: exportDocument, - contentType: .json, - defaultFilename: SQLFormatterRulesFile.exportFileName - ) { result in - if case .failure(let error) = result, (error as? CocoaError)?.code != .userCancelled { - reportExportFailure(error) - } - } - Button("Restore Defaults") { settings = .default } + + Section { + LabeledContent { + Button(String(localized: "Restore Defaults")) { settings = .default } .disabled(settings == .default) + .accessibilityIdentifier("formatter-restore-defaults") + } label: { + Text("Restore default rules") + Text("Returns every rule on this page to its default.") } } - } header: { - Text("Formatter") - } footer: { - Text("A .sql-formatter.json in a linked SQL folder replaces these rules for the files opened from that folder.") - .font(.caption) - .foregroundStyle(.secondary) } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.sqlFormatting.pageIdentifier) .alert( String(localized: "Couldn't Import Formatter Rules"), isPresented: isShowingImportError, @@ -138,7 +168,7 @@ struct FormatterSection: View { ) { _ in Button(String(localized: "OK")) {} } message: { message in - Text(message) + Text(verbatim: message) } .alert( String(localized: "Couldn't Export Formatter Rules"), @@ -147,88 +177,101 @@ struct FormatterSection: View { ) { _ in Button(String(localized: "OK")) {} } message: { message in - Text(message) + Text(verbatim: message) } } - // MARK: - Preview + private var indentWidthPicker: some View { + let widths = SettingsChoices.options(Self.indentWidths, including: settings.rules.indentWidth) + return Picker("Indent width", selection: indentWidthChoice) { + Text("Same as editor (\(editor.clampedTabWidth))").tag(IndentWidthChoice.editor) + Divider() + ForEach(widths.fixed, id: \.self) { width in + indentWidthTitle(width).tag(IndentWidthChoice.fixed(width)) + } + if let extra = widths.extra { + Divider() + indentWidthTitle(extra).tag(IndentWidthChoice.fixed(extra)) + } + } + .accessibilityIdentifier("formatter-indent-width") + } - private var previewText: String { - let formatted = try? SQLFormatterService().format( - Self.previewSQL, - dialect: .mysql, - options: settings.options(for: editor) - ) - return formatted?.formattedSQL ?? Self.previewSQL + // A tab counts as indent width columns when a line's width is measured. + private func indentWidthTitle(_ width: Int) -> Text { + settings.rules.indentStyle == .tabs ? Text("\(width) columns") : Text("\(width) spaces") } - // Unwrapped, since a wrapped preview would hide the line breaks the line width decides. - private var preview: some View { - let text = previewText - let lineCount = min(text.split(separator: "\n", omittingEmptySubsequences: false).count, Self.previewMaxLines) - let lineHeight = NSLayoutManager().defaultLineHeight(for: themeEngine.editorFonts.font) - return HighlightedSQLTextView( - sql: text, - databaseType: .mysql, - accessibilityIdentifier: "formatter-preview" - ) - .frame(height: CGFloat(lineCount) * lineHeight + Self.previewChromeHeight) - .clipShape(RoundedRectangle(cornerRadius: 6)) - .overlay( - RoundedRectangle(cornerRadius: 6) - .stroke(Color(nsColor: .separatorColor), lineWidth: 0.5) - ) + private var keywordCasePicker: some View { + Picker("Keywords", selection: keywordCaseChoice) { + Text("Same as editor (\(Self.caseName(editorKeywordCase)))").tag(KeywordCaseChoice.editor) + Divider() + ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in + Text(verbatim: Self.caseName(formatterCase)).tag(KeywordCaseChoice.fixed(formatterCase)) + } + } + .accessibilityIdentifier("formatter-keyword-case") } - // The text view's top and bottom inset, plus a legacy horizontal scroller when one takes room. - private static var previewChromeHeight: CGFloat { - let scroller = NSScroller.preferredScrollerStyle == .legacy - ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) - : 0 - return 24 + scroller + private var caseItems: some View { + ForEach(SQLFormatterCase.allCases, id: \.self) { formatterCase in + Text(verbatim: Self.caseName(formatterCase)).tag(formatterCase) + } } - // MARK: - Bindings + private var lineWidthPicker: some View { + let widths = Self.lineWidthOptions(including: settings.rules.lineWidth) + return Picker(selection: $settings.rules.lineWidth) { + Text("One item per line").tag(0) + Divider() + ForEach(widths.fixed, id: \.self) { width in + Text("\(width) characters").tag(width) + } + if let extra = widths.extra { + Divider() + Text("\(extra) characters").tag(extra) + } + } label: { + Text("Line width") + Text("A SELECT list, SET list or WHERE condition that fits stays on one line.") + } + .accessibilityIdentifier("formatter-line-width") + } - private var indentWidthChoice: Binding { - Binding( - get: { - settings.indentFollowsTabWidth - ? .tabWidth - : .fixed(settings.rules.indentWidth) - }, - set: { choice in - var formatter = settings - switch choice { - case .tabWidth: - formatter.indentFollowsTabWidth = true - case .fixed(let width): - formatter.indentFollowsTabWidth = false - formatter.rules.indentWidth = width + private var importButton: some View { + Button(String(localized: "Import…")) { isImporting = true } + .fileImporter(isPresented: $isImporting, allowedContentTypes: [.json]) { result in + importRules(result) + } + .accessibilityIdentifier("formatter-import") + } + + private var exportButton: some View { + Button(String(localized: "Export…")) { exportRules() } + .fileExporter( + isPresented: isExporting, + document: exportDocument, + contentType: .json, + defaultFilename: SQLFormatterRulesFile.exportFileName + ) { result in + if case .failure(let error) = result, (error as? CocoaError)?.code != .userCancelled { + reportExportFailure(error) } - settings = formatter } + .accessibilityIdentifier("formatter-export") + } + + private var indentWidthChoice: Binding { + Binding( + get: { IndentWidthChoice(settings) }, + set: { settings = $0.applied(to: settings) } ) } private var keywordCaseChoice: Binding { Binding( - get: { - settings.keywordCaseFollowsEditor - ? .editor - : .fixed(settings.rules.keywordCase) - }, - set: { choice in - var formatter = settings - switch choice { - case .editor: - formatter.keywordCaseFollowsEditor = true - case .fixed(let formatterCase): - formatter.keywordCaseFollowsEditor = false - formatter.rules.keywordCase = formatterCase - } - settings = formatter - } + get: { KeywordCaseChoice(settings) }, + set: { settings = $0.applied(to: settings) } ) } @@ -244,8 +287,6 @@ struct FormatterSection: View { Binding(get: { exportError != nil }, set: { if !$0 { exportError = nil } }) } - // MARK: - Import and export - private func importRules(_ result: Result) { guard case .success(let url) = result else { return } let isScoped = url.startAccessingSecurityScopedResource() @@ -272,13 +313,11 @@ struct FormatterSection: View { exportError = error.localizedDescription } - // MARK: - Labels - private var editorKeywordCase: SQLFormatterCase { editor.keywordCase.prefersUppercase ? .upper : .lower } - private func caseName(_ formatterCase: SQLFormatterCase) -> String { + static func caseName(_ formatterCase: SQLFormatterCase) -> String { switch formatterCase { case .upper: return String(localized: "UPPERCASE") case .lower: return String(localized: "lowercase") @@ -286,15 +325,67 @@ struct FormatterSection: View { } } - private func lineWidthName(_ width: Int) -> String { - width == 0 - ? String(localized: "One item per line") - : String(format: String(localized: "%d characters"), width) + // 0 is "One item per line", listed on its own above the widths. + static func lineWidthOptions(including current: Int) -> (fixed: [Int], extra: Int?) { + current == 0 ? (lineWidths, nil) : SettingsChoices.options(lineWidths, including: current) + } +} + +// Formats the sample only when its options or font change; other writes and theme ticks skip the body. +struct FormatterPreview: View, Equatable { + static let maxLines = 12 + static let sampleSQL = """ + select u.id as user_id, u.name as user_name, count(o.id) as order_count \ + from users u left join orders o on u.id = o.user_id \ + where u.status = 'active' and cast(o.created_at as date) >= '2026-01-01' \ + group by u.id, u.name order by order_count desc; + """ + + let options: SQLFormatterOptions + let font: NSFont + + static func == (lhs: FormatterPreview, rhs: FormatterPreview) -> Bool { + lhs.options == rhs.options && lhs.font == rhs.font + } + + // Unwrapped, since a wrapped preview would hide the line breaks the line width decides. + var body: some View { + let text = Self.formattedSample(options: options) + HighlightedSQLTextView( + sql: text, + databaseType: .mysql, + accessibilityIdentifier: "formatter-preview", + accessibilityLabel: String(localized: "Formatted preview"), + lineLayout: .unwrapped + ) + .frame(height: Self.height(lineCount: Self.lineCount(of: text), font: font)) + .clipShape(RoundedRectangle(cornerRadius: 6)) + .overlay( + RoundedRectangle(cornerRadius: 6) + .stroke(Color(nsColor: .separatorColor), lineWidth: 0.5) + ) + } + + static func formattedSample(options: SQLFormatterOptions) -> String { + let formatted = try? SQLFormatterService().format(sampleSQL, dialect: .mysql, options: options) + return formatted?.formattedSQL ?? sampleSQL + } + + static func lineCount(of text: String) -> Int { + text.split(separator: "\n", omittingEmptySubsequences: false).count } - // A value from an imported file that the picker does not offer still shows as selected. - private static func options(_ values: [Int], including current: Int) -> [Int] { - values.contains(current) ? values : (values + [current]).sorted() + static func height(lineCount: Int, font: NSFont) -> CGFloat { + let lineHeight = NSLayoutManager().defaultLineHeight(for: font) + return CGFloat(min(max(lineCount, 1), maxLines)) * lineHeight + chromeHeight + } + + // The text view's top and bottom inset, plus a legacy horizontal scroller when one takes room. + static var chromeHeight: CGFloat { + let scroller = NSScroller.preferredScrollerStyle == .legacy + ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) + : 0 + return 24 + scroller } } diff --git a/apple/TablePro/Views/Settings/Sections/TypographySection.swift b/apple/TablePro/Views/Settings/Sections/TypographySection.swift index e1daec9e3b..e3032fa4f0 100644 --- a/apple/TablePro/Views/Settings/Sections/TypographySection.swift +++ b/apple/TablePro/Views/Settings/Sections/TypographySection.swift @@ -1,55 +1,149 @@ import SwiftUI -/// Fonts are settings, not theme: importing Dracula must never change someone's font or size. -internal struct TypographySection: View { - internal enum Domain { +// Fonts are settings, not theme: importing a theme never changes someone's font or size. +internal struct TypographyRows: View { + internal enum Domain: Sendable { case editor case dataGrid - internal var caption: String { + internal var familyTitle: LocalizedStringKey { + switch self { + case .editor: "Family" + case .dataGrid: "Font" + } + } + + internal var sizeTitle: LocalizedStringKey { + switch self { + case .editor: "Size" + case .dataGrid: "Font size" + } + } + + internal var subtitle: String { switch self { case .editor: - return String(localized: "Applies to the SQL editor, the JSON viewer's Text mode, and the previews.") + String(localized: "The SQL editor, the JSON viewer's Text mode and SQL previews. Applies to this Mac.") case .dataGrid: - return String(localized: "Applies to grid cells, the inspector, cell popovers and the row diff.") + String(localized: "Grid cells, the inspector, cell popovers and the row diff. Applies to this Mac.") + } + } + + internal func missingFamilyNotice(_ family: String) -> String { + switch self { + case .editor: + String(format: String(localized: "%@ isn't installed. The editor uses System Mono."), family) + case .dataGrid: + String(format: String(localized: "%@ isn't installed. Grids use System Mono."), family) + } + } + + internal var familyIdentifier: String { + switch self { + case .editor: "editor-font-family" + case .dataGrid: "data-font-family" + } + } + + internal var sizeIdentifier: String { + switch self { + case .editor: "editor-font-size" + case .dataGrid: "data-font-size" + } + } + + internal func family(of typography: TypographySettings) -> String { + switch self { + case .editor: typography.editorFontFamily + case .dataGrid: typography.dataGridFontFamily + } + } + + internal func setFamily(_ family: String, in typography: inout TypographySettings) { + switch self { + case .editor: typography.editorFontFamily = family + case .dataGrid: typography.dataGridFontFamily = family + } + } + + // The size ThemeEngine draws, so an out-of-range stored size never leaves the pop-up blank. + internal func displayedSize(of typography: TypographySettings) -> Int { + switch self { + case .editor: typography.clampedEditorFontSize + case .dataGrid: typography.clampedDataGridFontSize + } + } + + internal func setSize(_ size: Int, in typography: inout TypographySettings) { + switch self { + case .editor: typography.editorFontSize = size + case .dataGrid: typography.dataGridFontSize = size } } } - internal let domain: Domain - @Binding internal var settings: TypographySettings + private let domain: Domain + @Binding private var typography: TypographySettings + @ObservedObject private var fonts = MonospacedFontFamilies.shared + + internal init(domain: Domain, typography: Binding) { + self.domain = domain + self._typography = typography + } internal var body: some View { - Section { - Picker(String(localized: "Family:"), selection: familyBinding) { - ForEach(EditorFontResolver.availableMonospacedFamilies) { family in - Text(family.displayName).tag(family.id) - } + let family = domain.family(of: typography) + let missing = Self.missingFamily(family, in: fonts.families) + + Picker(selection: Self.familyBinding(domain, of: $typography)) { + ForEach(fonts.families) { option in + Text(verbatim: option.displayName).tag(option.id) } + if let missing { + Divider() + Text(verbatim: Self.notInstalledTitle(missing)).tag(missing) + } + } label: { + Text(domain.familyTitle) + if let missing { + NoticeLabel(domain.missingFamilyNotice(missing), severity: .warning) + .font(.subheadline) + } else { + Text(domain.subtitle) + } + } + .accessibilityIdentifier(domain.familyIdentifier) - Picker(String(localized: "Size:"), selection: sizeBinding) { - ForEach(TypographySettings.sizeRange, id: \.self) { size in - Text(verbatim: "\(size) pt").tag(size) - } + Picker(selection: Self.sizeBinding(domain, of: $typography)) { + ForEach(TypographySettings.sizeRange, id: \.self) { size in + Text("\(size) pt").tag(size) } - } header: { - Text("Font") - } footer: { - Text(domain.caption) + } label: { + Text(domain.sizeTitle) } + .accessibilityIdentifier(domain.sizeIdentifier) } - private var familyBinding: Binding { - switch domain { - case .editor: return $settings.editorFontFamily - case .dataGrid: return $settings.dataGridFontFamily - } + // A saved family that is gone stays selectable, so the pop-up never draws blank and nothing is rewritten. + internal static func missingFamily(_ family: String, in families: [FontFamilyOption]) -> String? { + families.contains { $0.id == family } ? nil : family } - private var sizeBinding: Binding { - switch domain { - case .editor: return $settings.editorFontSize - case .dataGrid: return $settings.dataGridFontSize - } + internal static func notInstalledTitle(_ family: String) -> String { + String(format: String(localized: "%@ (Not Installed)"), family) + } + + internal static func familyBinding(_ domain: Domain, of typography: Binding) -> Binding { + Binding( + get: { domain.family(of: typography.wrappedValue) }, + set: { family in domain.setFamily(family, in: &typography.wrappedValue) } + ) + } + + internal static func sizeBinding(_ domain: Domain, of typography: Binding) -> Binding { + Binding( + get: { domain.displayedSize(of: typography.wrappedValue) }, + set: { size in domain.setSize(size, in: &typography.wrappedValue) } + ) } } diff --git a/apple/TableProTests/Models/Settings/EditorFontResolverTests.swift b/apple/TableProTests/Models/Settings/EditorFontResolverTests.swift new file mode 100644 index 0000000000..e9917a32f3 --- /dev/null +++ b/apple/TableProTests/Models/Settings/EditorFontResolverTests.swift @@ -0,0 +1,150 @@ +import AppKit +import Combine +import SwiftUI +@testable import TablePro +import TableProTestSupport +import Testing + +struct EditorFontResolverTests { + @Test("The family list puts System Mono first, then unique names sorted, with no hidden system families") + func familyOptionsOrder() { + let options = EditorFontResolver.familyOptions( + from: ["Menlo", ".AppleSystemUIFontMonospaced", "andale mono", "Menlo", "System Mono", "Courier New"] + ) + #expect(options.map { $0.id } == ["System Mono", "andale mono", "Courier New", "Menlo"]) + #expect(options.allSatisfy { $0.id == $0.displayName }) + } + + @Test("No family installed still offers System Mono") + func emptyFamilyList() { + #expect(EditorFontResolver.familyOptions(from: []).map { $0.id } == [EditorFontResolver.systemMonoId]) + } + + @Test("The installed monospaced families start with System Mono and are sorted and unique") + func installedFamilies() { + let ids = EditorFontResolver.availableMonospacedFamilies().map { $0.id } + #expect(ids.first == EditorFontResolver.systemMonoId) + let rest = Array(ids.dropFirst()) + #expect(Set(ids).count == ids.count) + #expect(!rest.contains { $0.hasPrefix(".") }) + #expect(zip(rest, rest.dropFirst()).allSatisfy { $0.localizedCaseInsensitiveCompare($1) != .orderedDescending }) + } + + @Test("A family that is not installed draws System Mono at the asked size") + func missingFamilyResolvesToSystemMono() { + let font = EditorFontResolver.resolve(familyId: "No Such Family 7d1c", size: 15) + #expect(font.pointSize == 15) + #expect(font.fontDescriptor.symbolicTraits.contains(.monoSpace)) + } +} + +@MainActor +struct MonospacedFontFamiliesTests { + private final class InstalledFonts { + var names: [String] = ["Menlo"] + } + + private final class ChangeCount { + var value = 0 + } + + @Test("Installing a font while the app runs rebuilds the list") + func rebuildsOnFontSetChange() async throws { + let center = NotificationCenter() + let installed = InstalledFonts() + let families = MonospacedFontFamilies(notificationCenter: center) { + EditorFontResolver.familyOptions(from: installed.names) + } + #expect(families.families.map { $0.id } == ["System Mono", "Menlo"]) + + installed.names = ["Menlo", "Fira Code"] + center.post(name: NSFont.fontSetChangedNotification, object: nil) + + try await waitUntil { families.families.map { $0.id } == ["System Mono", "Fira Code", "Menlo"] } + } + + @Test("A reload that finds the same families publishes nothing") + func unchangedReloadIsSilent() { + let installed = InstalledFonts() + let families = MonospacedFontFamilies(notificationCenter: NotificationCenter()) { + EditorFontResolver.familyOptions(from: installed.names) + } + let changes = ChangeCount() + let subscription = families.objectWillChange.sink { _ in changes.value += 1 } + families.reload() + #expect(changes.value == 0) + installed.names = ["Menlo", "PT Mono"] + families.reload() + #expect(changes.value == 1) + subscription.cancel() + } +} + +@MainActor +struct TypographyRowsTests { + private let families = EditorFontResolver.familyOptions(from: ["Menlo", "Monaco"]) + + @Test("An installed family adds no extra item") + func installedFamilyIsListed() { + #expect(TypographyRows.missingFamily("Menlo", in: families) == nil) + #expect(TypographyRows.missingFamily(EditorFontResolver.systemMonoId, in: families) == nil) + } + + @Test("A saved family that is gone stays selectable under its own name") + func missingFamilyIsKept() { + #expect(TypographyRows.missingFamily("Fira Code", in: families) == "Fira Code") + #expect(TypographyRows.notInstalledTitle("Fira Code").contains("Fira Code")) + } + + @Test("The size pop-up shows the drawn size and a pick writes the stored field") + func sizeBindingClamps() { + let slice = SettingsSlice(TypographySettings(editorFontSize: 40, dataGridFontSize: 5)) + let editor = TypographyRows.sizeBinding(.editor, of: sliceBinding(slice)) + let grid = TypographyRows.sizeBinding(.dataGrid, of: sliceBinding(slice)) + #expect(editor.wrappedValue == TypographySettings.sizeRange.upperBound) + #expect(grid.wrappedValue == TypographySettings.sizeRange.lowerBound) + + editor.wrappedValue = 16 + #expect(slice.value.editorFontSize == 16) + #expect(slice.value.dataGridFontSize == 5) + } + + @Test("Each domain reads and writes its own family") + func familyBindingPerDomain() { + let slice = SettingsSlice(TypographySettings(editorFontFamily: "Menlo", dataGridFontFamily: "Monaco")) + let editor = TypographyRows.familyBinding(.editor, of: sliceBinding(slice)) + let grid = TypographyRows.familyBinding(.dataGrid, of: sliceBinding(slice)) + #expect(editor.wrappedValue == "Menlo") + #expect(grid.wrappedValue == "Monaco") + + grid.wrappedValue = EditorFontResolver.systemMonoId + #expect(slice.value.dataGridFontFamily == EditorFontResolver.systemMonoId) + #expect(slice.value.editorFontFamily == "Menlo") + } +} + +@MainActor +struct EditorTabWidthChoiceTests { + @Test("A tab width off the list is offered after the list") + func offListTabWidth() { + let options = SettingsChoices.options(EditorSettingsView.tabWidths, including: EditorSettings(tabWidth: 3).clampedTabWidth) + #expect(options.fixed == [2, 4, 8]) + #expect(options.extra == 3) + } + + @Test("The tab width pop-up shows the width the editor uses and a pick writes the stored field") + func tabWidthBindingClamps() { + let slice = SettingsSlice(EditorSettings(tabWidth: 40)) + let binding = EditorSettingsView.tabWidthBinding(sliceBinding(slice)) + #expect(binding.wrappedValue == 16) + + binding.wrappedValue = 2 + #expect(slice.value.tabWidth == 2) + } +} + +// The binding a pane gets from $slice.value. +@MainActor +private func sliceBinding(_ slice: SettingsSlice) -> Binding { + ObservedObject(wrappedValue: slice).projectedValue.value +} diff --git a/apple/TableProTests/Views/Settings/FormatterPreviewTests.swift b/apple/TableProTests/Views/Settings/FormatterPreviewTests.swift new file mode 100644 index 0000000000..7ba780ae99 --- /dev/null +++ b/apple/TableProTests/Views/Settings/FormatterPreviewTests.swift @@ -0,0 +1,99 @@ +import AppKit +@testable import TablePro +import Testing + +@MainActor +struct FormatterPreviewTests { + private static let font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) + + private static func options(_ change: (inout SQLFormatterOptions) -> Void) -> SQLFormatterOptions { + var options = SQLFormatterOptions.default + change(&options) + return options + } + + @Test("The same options and font compare equal, so a re-render skips the format") + func equalInputsSkipTheBody() { + let first = FormatterPreview(options: .default, font: Self.font) + let second = FormatterPreview(options: .default, font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)) + #expect(first == second) + } + + @Test("A rule or font change formats again") + func changedInputsRender() { + let base = FormatterPreview(options: .default, font: Self.font) + let wider = FormatterPreview(options: Self.options { $0.lineWidth = 120 }, font: Self.font) + let larger = FormatterPreview(options: .default, font: NSFont.monospacedSystemFont(ofSize: 16, weight: .regular)) + #expect(base != wider) + #expect(base != larger) + } + + @Test("The sample follows the rules it is given") + func sampleFollowsTheRules() { + let upper = FormatterPreview.formattedSample(options: Self.options { $0.keywordCase = .upper }) + let lower = FormatterPreview.formattedSample(options: Self.options { $0.keywordCase = .lower }) + #expect(upper.hasPrefix("SELECT")) + #expect(lower.hasPrefix("select")) + + let onePerLine = FormatterPreview.formattedSample(options: Self.options { $0.lineWidth = 0 }) + let wide = FormatterPreview.formattedSample(options: Self.options { $0.lineWidth = 120 }) + #expect(FormatterPreview.lineCount(of: wide) < FormatterPreview.lineCount(of: onePerLine)) + } + + @Test("The preview grows with its lines up to twelve, plus the inset") + func heightStopsAtTwelveLines() { + let lineHeight = NSLayoutManager().defaultLineHeight(for: Self.font) + let chrome = FormatterPreview.chromeHeight + #expect(FormatterPreview.height(lineCount: 3, font: Self.font) == 3 * lineHeight + chrome) + #expect(FormatterPreview.height(lineCount: 30, font: Self.font) == 12 * lineHeight + chrome) + #expect(FormatterPreview.height(lineCount: 0, font: Self.font) == lineHeight + chrome) + } +} + +@MainActor +struct SQLFormattingChoiceTests { + @Test("A line width off the list is offered after the list; One item per line is never an extra") + func lineWidthOptions() { + #expect(SQLFormattingPage.lineWidthOptions(including: 60).extra == 60) + #expect(SQLFormattingPage.lineWidthOptions(including: 60).fixed == [80, 100, 120]) + #expect(SQLFormattingPage.lineWidthOptions(including: 0).extra == nil) + #expect(SQLFormattingPage.lineWidthOptions(including: 100).extra == nil) + } + + @Test("An imported indent width off the list stays selectable") + func indentWidthOptions() { + let options = SettingsChoices.options(SQLFormattingPage.indentWidths, including: 3) + #expect(options.fixed == [2, 4, 8]) + #expect(options.extra == 3) + } + + @Test("Picking a fixed indent width turns off following the editor and sets the width in one write") + func indentWidthChoiceWritesWholeValue() { + var following = SQLFormatterSettings.default + following.indentFollowsTabWidth = true + #expect(SQLFormattingPage.IndentWidthChoice(following) == .editor) + + let fixed = SQLFormattingPage.IndentWidthChoice.fixed(8).applied(to: following) + #expect(!fixed.indentFollowsTabWidth) + #expect(fixed.rules.indentWidth == 8) + #expect(SQLFormattingPage.IndentWidthChoice(fixed) == .fixed(8)) + + let back = SQLFormattingPage.IndentWidthChoice.editor.applied(to: fixed) + #expect(back.indentFollowsTabWidth) + #expect(back.rules.indentWidth == 8) + } + + @Test("Picking a fixed keyword case turns off following the editor and sets the case in one write") + func keywordCaseChoiceWritesWholeValue() { + let following = SQLFormatterSettings.default + #expect(SQLFormattingPage.KeywordCaseChoice(following) == .editor) + + let lower = SQLFormattingPage.KeywordCaseChoice.fixed(.lower).applied(to: following) + #expect(!lower.keywordCaseFollowsEditor) + #expect(lower.rules.keywordCase == .lower) + + let back = SQLFormattingPage.KeywordCaseChoice.editor.applied(to: lower) + #expect(back.keywordCaseFollowsEditor) + #expect(back.rules.keywordCase == .lower) + } +} diff --git a/apple/TableProUITests/Support/UITestCase+EditorTabs.swift b/apple/TableProUITests/Support/UITestCase+EditorTabs.swift index e63ccee6db..2a9393f334 100644 --- a/apple/TableProUITests/Support/UITestCase+EditorTabs.swift +++ b/apple/TableProUITests/Support/UITestCase+EditorTabs.swift @@ -1,8 +1,6 @@ import XCTest extension UITestCase { - // MARK: - Editor tabs - internal func editorTabs(titled title: String? = nil, in window: XCUIElement) -> XCUIElementQuery { let tabs = window.descendants(matching: .any).matching(identifier: "editor-tab") guard let title else { return tabs } @@ -30,8 +28,6 @@ extension UITestCase { ) } - // MARK: - Results - internal func resultSetChooser(in window: XCUIElement) -> XCUIElement { window.descendants(matching: .any).matching(identifier: "result-set-menu").firstMatch } @@ -52,16 +48,10 @@ extension UITestCase { grid.staticTexts.matching(NSPredicate(format: "value == %@", text)).firstMatch } - // MARK: - Key bindings - // Picks a key bindings mode in Settings > Editor and closes Settings. A new sandbox starts on Standard. internal func chooseKeyBindings(_ title: String, in app: XCUIApplication) { - app.typeShortcut(.settings) - let settings = window("settings", in: app) - XCTAssertTrue(settings.waitToExist(timeout: 10), "Cmd+, must open Settings") - let editorPane = settings.toolbars.buttons["Editor"] - XCTAssertTrue(editorPane.waitToExist(timeout: 10)) - editorPane.click() + let settings = openSettings(in: app) + selectSettingsPane("editor", in: settings) let keyBindings = settings.popUpButtons["key-bindings-picker"] XCTAssertTrue(scrollUntilHittable(keyBindings, in: settings, timeout: 30), "The Editor pane must offer key bindings") @@ -79,8 +69,6 @@ extension UITestCase { XCTAssertTrue(settings.waitForNonExistence(timeout: 10), "Settings must close") } - // MARK: - Editor text - internal func editorText(_ editor: XCUIElement) -> String { (editor.value as? String) ?? "" } From 44e9b133dc808370a966820fbba77396aa7a7236 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:52 +0700 Subject: [PATCH 30/48] feat(settings): Data pane with Query History and Data Rewind pages --- .../Models/Settings/AppSettings.swift | 97 ++---- .../Settings/DataResultsSettingsView.swift | 51 +--- .../Settings/Entries/DataSettingsEntry.swift | 36 +-- .../Settings/Sections/DataGridSection.swift | 281 +++++++++++------- .../Settings/Sections/DataRewindSection.swift | 123 +++++--- .../Settings/Sections/HistorySection.swift | 153 +++++++--- .../Settings/DataGridSettingsTests.swift | 255 ++++++++++++++++ 7 files changed, 670 insertions(+), 326 deletions(-) create mode 100644 apple/TableProTests/Models/Settings/DataGridSettingsTests.swift diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index eda5295543..d64571ceea 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -1,16 +1,6 @@ -// -// AppSettings.swift -// TablePro -// -// Application settings models - pure data structures -// - import Foundation import SwiftUI - -// MARK: - Appearance Settings - enum AppAppearanceMode: String, Codable, CaseIterable { case light case dark @@ -48,9 +38,6 @@ struct AppearanceSettings: Codable, Equatable { } } - -// MARK: - Data Grid Settings - enum DataGridRowHeight: Int, Codable, CaseIterable, Identifiable { case compact = 20 case normal = 24 @@ -216,44 +203,26 @@ struct DataGridSettings: Codable, Equatable { resultSetsKeptPerRun = container.decodeSetting(.resultSetsKeptPerRun, default: fallback.resultSetsKeptPerRun) } - // MARK: - Validated Properties - var validatedNullDisplay: String { - let sanitized = nullDisplay.sanitized - let maxLength = SettingsValidationRules.nullDisplayMaxLength - - if sanitized.isEmpty { - return "NULL" - } else if sanitized.count > maxLength { - return String(sanitized.prefix(maxLength)) - } - return sanitized + Self.normalizedNullDisplay(nullDisplay) } var validatedDefaultPageSize: Int { defaultPageSize.clamped(to: SettingsValidationRules.defaultPageSizeRange) } - var nullDisplayValidationError: String? { - let sanitized = nullDisplay.sanitized + // Blank is not an error: the field's prompt reads NULL, and a blank entry commits as NULL. + static func nullDisplayValidationError(for text: String) -> String? { let maxLength = SettingsValidationRules.nullDisplayMaxLength - - if sanitized.isEmpty { - return String(localized: "NULL display cannot be empty") - } else if sanitized.count > maxLength { - return String(format: String(localized: "NULL display must be %d characters or less"), maxLength) - } else if nullDisplay != sanitized { - return String(localized: "NULL display contains invalid characters (newlines/tabs)") - } - return nil + guard text.sanitized.count > maxLength else { return nil } + return String(format: String(localized: "Up to %lld characters"), maxLength) } - var defaultPageSizeValidationError: String? { - let range = SettingsValidationRules.defaultPageSizeRange - if defaultPageSize < range.lowerBound || defaultPageSize > range.upperBound { - return String(format: String(localized: "Page size must be between %@ and %@"), range.lowerBound.formatted(), range.upperBound.formatted()) - } - return nil + // Trimmed again after the cut, so a prefix that ends in a space never stores one. + static func normalizedNullDisplay(_ text: String) -> String { + let limited = String(text.sanitized.prefix(SettingsValidationRules.nullDisplayMaxLength)) + .trimmingCharacters(in: .whitespaces) + return limited.isEmpty ? "NULL" : limited } // Nil keeps every result. @@ -266,21 +235,25 @@ struct DataGridSettings: Codable, Equatable { return queryResultRowCap.clamped(to: SettingsValidationRules.queryResultRowCapRange) } - var queryResultRowCapValidationError: String? { - let range = SettingsValidationRules.queryResultRowCapRange - if queryResultRowCap != 0 && (queryResultRowCap < range.lowerBound || queryResultRowCap > range.upperBound) { - return String( - format: String(localized: "Query result row cap must be between %@ and %@"), - range.lowerBound.formatted(), - range.upperBound.formatted() - ) + var queryResultLimit: Int? { + guard truncateQueryResults else { return nil } + let cap = validatedQueryResultRowCap + return cap > 0 ? cap : nil + } + + // No limit keeps the stored cap, so turning the limit back on returns to it. + func withQueryResultLimit(_ limit: Int?) -> DataGridSettings { + var updated = self + if let limit { + updated.truncateQueryResults = true + updated.queryResultRowCap = limit + } else { + updated.truncateQueryResults = false } - return nil + return updated } } -// MARK: - Value Color Settings - struct ValueColorSettings: Codable, Equatable { var colorsValuesByType: Bool @@ -296,8 +269,6 @@ struct ValueColorSettings: Codable, Equatable { } } -// MARK: - History Settings - struct HistorySettings: Codable, Equatable { var maxEntries: Int // 0 = unlimited var maxDays: Int // 0 = unlimited @@ -328,8 +299,6 @@ struct HistorySettings: Codable, Equatable { keepRewindHistory = container.decodeSetting(.keepRewindHistory, default: fallback.keepRewindHistory) } - // MARK: - Validated Properties - var validatedMaxEntries: Int { max(0, maxEntries) } @@ -337,24 +306,8 @@ struct HistorySettings: Codable, Equatable { var validatedMaxDays: Int { max(0, maxDays) } - - var maxEntriesValidationError: String? { - if maxEntries < 0 { - return String(localized: "Maximum entries cannot be negative") - } - return nil - } - - var maxDaysValidationError: String? { - if maxDays < 0 { - return String(localized: "Maximum days cannot be negative") - } - return nil - } } -// MARK: - Tab Settings - struct TabSettings: Codable, Equatable { var enablePreviewTabs: Bool = true static let `default` = TabSettings() diff --git a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift index 0a71ad4606..33d2ddff4a 100644 --- a/apple/TablePro/Views/Settings/DataResultsSettingsView.swift +++ b/apple/TablePro/Views/Settings/DataResultsSettingsView.swift @@ -1,48 +1,29 @@ -// -// DataResultsSettingsView.swift -// TablePro -// - import SwiftUI struct DataResultsSettingsView: View { - @Binding var dataGrid: DataGridSettings - @Binding var valueColors: ValueColorSettings - @Binding var editor: EditorSettings - @Binding var typography: TypographySettings + @ObservedObject var dataGrid: SettingsSlice + let valueColors: SettingsSlice + let editor: SettingsSlice + let typography: SettingsSlice + let history: SettingsSlice var body: some View { Form { - TypographySection(domain: .dataGrid, settings: $typography) - - DataGridSection(settings: $dataGrid, valueColors: $valueColors) - - Section("JSON Viewer") { - Picker("Default view:", selection: $editor.jsonViewerPreferredMode) { - Text("Text").tag(JSONViewMode.text) - Text("Tree").tag(JSONViewMode.tree) - } - } + DataGridSection( + settings: $dataGrid.value, + typography: typography, + valueColors: valueColors, + editor: editor + ) Section { - NavigationLink(value: SettingsSubpage.queryHistory) { - Label("Query History", systemImage: "clock.arrow.circlepath") - } - NavigationLink(value: SettingsSubpage.dataRewind) { - Label("Data Rewind", systemImage: "arrow.uturn.backward") - } + // No value: Keep entries for also bounds query tab versions, so one word would mislead. + SettingsDrillRow(route: SettingsRoute.page(.queryHistory), title: SettingsPage.queryHistory.title) + DataRewindDrillRow(history: history) } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-data") } } - -#Preview { - DataResultsSettingsView( - dataGrid: .constant(.default), - valueColors: .constant(.default), - editor: .constant(.default), - typography: .constant(.default) - ) - .frame(width: 450, height: 500) -} diff --git a/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift index 4a7d190d4e..5b561f1c56 100644 --- a/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/DataSettingsEntry.swift @@ -2,25 +2,14 @@ import SwiftUI internal struct DataSettingsEntry: View { internal let context: SettingsPaneContext - @ObservedObject private var dataGrid: SettingsSlice - @ObservedObject private var valueColors: SettingsSlice - @ObservedObject private var editor: SettingsSlice - @ObservedObject private var typography: SettingsSlice - - internal init(context: SettingsPaneContext) { - self.context = context - self._dataGrid = ObservedObject(wrappedValue: context.settings.dataGridSlice) - self._valueColors = ObservedObject(wrappedValue: context.settings.valueColorsSlice) - self._editor = ObservedObject(wrappedValue: context.settings.editorSlice) - self._typography = ObservedObject(wrappedValue: context.settings.typographySlice) - } internal var body: some View { DataResultsSettingsView( - dataGrid: $dataGrid.value, - valueColors: $valueColors.value, - editor: $editor.value, - typography: $typography.value + dataGrid: context.settings.dataGridSlice, + valueColors: context.settings.valueColorsSlice, + editor: context.settings.editorSlice, + typography: context.settings.typographySlice, + history: context.settings.historySlice ) } } @@ -28,24 +17,15 @@ internal struct DataSettingsEntry: View { internal struct DataSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext - @ObservedObject private var history: SettingsSlice - - internal init(route: SettingsRoute, context: SettingsPaneContext) { - self.route = route - self.context = context - self._history = ObservedObject(wrappedValue: context.settings.historySlice) - } internal var body: some View { switch route { case .page(.queryHistory): - Form { HistorySection(settings: $history.value) } - .formStyle(.grouped) + QueryHistorySettingsPage(history: context.settings.historySlice, context: context) case .page(.dataRewind): - Form { DataRewindSection(settings: $history.value) } - .formStyle(.grouped) + DataRewindPage(history: context.settings.historySlice, context: context) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 3c42f96c46..94710016e5 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -1,162 +1,223 @@ -// -// DataGridSection.swift -// TablePro -// - import SwiftUI struct DataGridSection: View { - @Binding var settings: DataGridSettings - @Binding var valueColors: ValueColorSettings + static let pageSizes = [100, 500, 1_000, 5_000, 10_000] + static let exactCountThresholds = [1_000, 10_000, 100_000, 1_000_000, Int.max] + static let queryResultLimits = [100, 1_000, 5_000, 10_000, 50_000, 100_000, 500_000] + static let resultSetsKept = [0, 10, 20, 50, 100, 200, 500, 1_000] - // NULL display commits on Return/focus loss, not per keystroke: a live binding re-encodes the - // whole settings struct and reformats every open grid on each character. - @State private var nullDisplayDraft = "" - @FocusState private var nullDisplayFocused: Bool - - private func commitNullDisplay() { - if settings.nullDisplay != nullDisplayDraft { - settings.nullDisplay = nullDisplayDraft - } - } + @Binding var settings: DataGridSettings + let typography: SettingsSlice + let valueColors: SettingsSlice + let editor: SettingsSlice var body: some View { Section { - Picker("Row height:", selection: $settings.rowHeight) { + DataFontRows(typography: typography) + + Picker("Row height", selection: $settings.rowHeight) { ForEach(DataGridRowHeight.allCases) { height in Text(height.displayName).tag(height) } } + .accessibilityIdentifier("data-row-height-picker") + + Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) + .accessibilityIdentifier("data-alternate-rows-toggle") + + Toggle("Show row numbers", isOn: $settings.showRowNumbers) + .accessibilityIdentifier("data-row-numbers-toggle") + + Toggle(isOn: $settings.wrapText) { + Text("Wrap text in cells") + Text("Long values wrap onto up to 10 lines in new tabs. View > Wrap Text changes the open grid.") + } + .accessibilityIdentifier("data-wrap-text-toggle") + + Toggle(isOn: $settings.showInvisibleCharacters) { + Text("Show invisible characters") + Text("Marks zero-width, control and special space characters in cells and value fields.") + } + .accessibilityIdentifier("data-invisible-characters-toggle") + + Toggle("Show inspector when a row is selected", isOn: $settings.autoShowInspector) + .accessibilityIdentifier("data-auto-inspector-toggle") + } header: { + Text("Grid") + } - Picker("Date format:", selection: $settings.dateFormat) { + Section { + Picker("Date format", selection: $settings.dateFormat) { ForEach(DateFormatOption.allCases) { format in Text(format.displayName).tag(format) } } + .accessibilityIdentifier("data-date-format-picker") + + SettingsTextField( + "NULL display", + subtitle: "Up to \(SettingsValidationRules.nullDisplayMaxLength) characters", + text: $settings.nullDisplay, + prompt: Text(verbatim: "NULL"), + validate: DataGridSettings.nullDisplayValidationError(for:), + normalize: DataGridSettings.normalizedNullDisplay(_:) + ) + .accessibilityIdentifier("data-null-display-field") + + ColorValuesByTypeToggle(valueColors: valueColors) + + Toggle(isOn: $settings.enableSmartValueDetection) { + Text("Smart value detection") + Text("Shows UUIDs, Unix timestamps, JSON and serialized values in a readable form, judged from the first rows.") + } + .accessibilityIdentifier("data-smart-detection-toggle") - TextField("NULL display:", text: $nullDisplayDraft) - .focused($nullDisplayFocused) - .help("Max \(SettingsValidationRules.nullDisplayMaxLength) characters") - .onSubmit(commitNullDisplay) - .onChange(of: nullDisplayFocused) { focused in - if !focused { commitNullDisplay() } - } - .onChange(of: settings.nullDisplay) { value in - if !nullDisplayFocused { nullDisplayDraft = value } - } - .onAppear { nullDisplayDraft = settings.nullDisplay } + JSONViewModePicker(editor: editor) + } header: { + Text("Values") + } - Toggle("Show alternate row backgrounds", isOn: $settings.showAlternateRows) - Toggle("Show row numbers", isOn: $settings.showRowNumbers) - Toggle("Auto-show inspector on row select", isOn: $settings.autoShowInspector) - Toggle("Smart value detection", isOn: $settings.enableSmartValueDetection) - Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) - .help(String(localized: "Mark zero-width, control and special space characters in cells and value fields")) - Toggle("Wrap text in cells", isOn: $settings.wrapText) - .help(String(localized: "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid.")) - Toggle("Color values by type", isOn: $valueColors.colorsValuesByType) - .help(String(localized: "Draw strings, numbers, dates and other typed values in the colors of the theme's Values section")) - .accessibilityIdentifier("color-values-by-type-toggle") - - Picker("Default row sort:", selection: $settings.defaultSortBehavior) { + Section { + Picker(selection: $settings.defaultSortBehavior) { ForEach(DefaultSortBehavior.allCases) { behavior in Text(behavior.displayName).tag(behavior) } + } label: { + Text("Default sort") + Text("Applied when a table first opens.") } + .accessibilityIdentifier("data-default-sort-picker") - Picker("Sort direction:", selection: $settings.defaultSortDirection) { + Picker(selection: $settings.defaultSortDirection) { ForEach(SortDirection.allCases) { direction in Text(direction.displayName).tag(direction) } + } label: { + Text("Sort direction") + Text("Also the direction of the first click on a column header.") } + .accessibilityIdentifier("data-sort-direction-picker") } header: { - Text("Data Grid") - } footer: { - VStack(alignment: .leading, spacing: 4) { - if let error = settings.nullDisplayValidationError { - NoticeLabel(error, severity: .error) - } - Text("Default row sort is applied when a table first opens. Sort direction also sets which way the first click on a column header sorts.") - } + Text("Sorting") } Section { - Picker("Copy rows as:", selection: $settings.rowCopyFormat) { + Picker(selection: $settings.rowCopyFormat) { ForEach(RowCopyFormat.allCases) { format in Text(format.displayName).tag(format) } + } label: { + Text("Copy rows as") + Text("A single cell still copies its value. Edit > Copy Special offers every format.") } + .accessibilityIdentifier("data-copy-format-picker") } header: { Text("Copying") - } footer: { - Text("Copy uses this format for selected rows. A single cell still copies its value, and Edit > Copy Special offers every format.") - } - - Section("Pagination") { - Picker("Default page size:", selection: $settings.defaultPageSize) { - Text("100 rows").tag(100) - Text("500 rows").tag(500) - Text("1,000 rows").tag(1_000) - Text("5,000 rows").tag(5_000) - Text("10,000 rows").tag(10_000) - } - - Picker( - String(localized: "Count rows if estimate less than:"), - selection: $settings.countRowsIfEstimateLessThan - ) { - Text("1,000").tag(1_000) - Text("10,000").tag(10_000) - Text("100,000").tag(100_000) - Text("1,000,000").tag(1_000_000) - Text(String(localized: "Always count")).tag(Int.max) - } - .help(String(localized: "Tables with more estimated rows use approximate counts to avoid slow COUNT(*) queries")) } Section { - Toggle("Truncate query results", isOn: $settings.truncateQueryResults) - .help(String(localized: "Apply a row limit when running queries and cap results at the configured row count")) - - if settings.truncateQueryResults { - Picker("Row cap:", selection: $settings.queryResultRowCap) { - Text("100").tag(100) - Text("1,000").tag(1_000) - Text("5,000").tag(5_000) - Text("10,000").tag(10_000) - Text("50,000").tag(50_000) - Text("100,000").tag(100_000) - Text("500,000").tag(500_000) + Picker("Page size", selection: $settings.defaultPageSize) { + SettingsChoiceItems(Self.pageSizes, including: settings.defaultPageSize) { size in + Text(Self.rowsTitle(size)) } } - } header: { - Text("Query Result Row Cap") - } footer: { - VStack(alignment: .leading, spacing: 4) { - if let error = settings.queryResultRowCapValidationError { - NoticeLabel(error, severity: .error) + .accessibilityIdentifier("data-page-size-picker") + + Picker(selection: $settings.countRowsIfEstimateLessThan) { + SettingsChoiceItems(Self.exactCountThresholds, including: settings.countRowsIfEstimateLessThan) { threshold in + Text(Self.exactCountTitle(threshold)) } - if settings.truncateQueryResults, settings.queryResultRowCapValidationError == nil { - Text(""" - SELECT queries without their own LIMIT run with this cap applied. The query text in the \ - editor never changes. Capped results show a Fetch All button, and Execute Without Limit \ - skips the cap for one run. - """) + } label: { + Text("Exact row count") + Text("Larger tables show an estimated count, which avoids a slow COUNT(*).") + } + .accessibilityIdentifier("data-exact-count-picker") + + Picker(selection: Self.queryResultLimitBinding($settings)) { + Text("No limit").tag(Int?.none) + Divider() + SettingsChoiceItems( + Self.queryResultLimits.map { Optional($0) }, + including: settings.queryResultLimit ?? Self.queryResultLimits.first + ) { limit in + Text(Self.rowsTitle(limit ?? 0)) } + } label: { + Text("Query result limit") + Text( + """ + SELECT queries without their own LIMIT stop at this many rows. The editor text never changes. \ + Fetch All and Execute Without Limit skip it once. + """ + ) } - } + .accessibilityIdentifier("data-result-limit-picker") - Section { - Picker("Results kept per run:", selection: $settings.resultSetsKeptPerRun) { - Text("No limit").tag(0) - ForEach([10, 20, 50, 100, 200, 500, 1_000], id: \.self) { count in - Text(count.formatted()).tag(count) + Picker(selection: $settings.resultSetsKeptPerRun) { + SettingsChoiceItems(Self.resultSetsKept, including: settings.resultSetsKeptPerRun) { count in + Text(Self.resultSetsKeptTitle(count)) } + } label: { + Text("Results kept per run") + Text("A run that returns more keeps only the newest. Pinned results always stay.") } + .accessibilityIdentifier("data-results-kept-picker") } header: { - Text("Multiple Results") - } footer: { - Text("A run that returns more results with rows keeps only the newest. Pinned results always stay.") + Text("Pages and Limits") + } + } + + // Limit and switch change together in one write, so neither is seen without the other. + static func queryResultLimitBinding(_ settings: Binding) -> Binding { + Binding( + get: { settings.wrappedValue.queryResultLimit }, + set: { settings.wrappedValue = settings.wrappedValue.withQueryResultLimit($0) } + ) + } + + static func rowsTitle(_ count: Int) -> String { + String(localized: "\(count) rows") + } + + static func exactCountTitle(_ threshold: Int) -> String { + threshold == Int.max ? String(localized: "Always") : String(localized: "Under \(threshold) rows") + } + + static func resultSetsKeptTitle(_ count: Int) -> String { + count == 0 ? String(localized: "No limit") : SettingsFormat.count(count) + } +} + +// Each row below follows only its own category, so a write elsewhere never redraws the grid rows. +private struct DataFontRows: View { + @ObservedObject var typography: SettingsSlice + + var body: some View { + TypographyRows(domain: .dataGrid, typography: $typography.value) + } +} + +private struct ColorValuesByTypeToggle: View { + @ObservedObject var valueColors: SettingsSlice + + var body: some View { + // ThemeValueColorsNote names this label. + Toggle(isOn: $valueColors.value.colorsValuesByType) { + Text("Color values by type") + Text("Draws strings, numbers, dates and other typed values in the theme's Values colors.") + } + .accessibilityIdentifier("color-values-by-type-toggle") + } +} + +private struct JSONViewModePicker: View { + @ObservedObject var editor: SettingsSlice + + var body: some View { + Picker("Default JSON view", selection: $editor.value.jsonViewerPreferredMode) { + Text("Text").tag(JSONViewMode.text) + Text("Tree").tag(JSONViewMode.tree) } + .accessibilityIdentifier("data-json-view-picker") } } diff --git a/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift b/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift index 3368e62ea7..5fb6a99b34 100644 --- a/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataRewindSection.swift @@ -1,49 +1,104 @@ -// -// DataRewindSection.swift -// TablePro -// - import SwiftUI -struct DataRewindSection: View { +struct DataRewindPage: View { + @ObservedObject var history: SettingsSlice + let context: SettingsPaneContext @ObservedObject private var featureAccess = FeatureAccess.shared - @Binding var settings: HistorySettings + @State private var isClearing = false - private var isAvailable: Bool { - featureAccess.isAvailable(.dataRewind) + init(history: SettingsSlice, context: SettingsPaneContext) { + self.history = history + self.context = context } var body: some View { - Section("Data Rewind") { - Toggle("Keep saved changes for restoring", isOn: $settings.keepRewindHistory) - .disabled(!isAvailable) - - if isAvailable { - Text("Keeps what rows looked like before each save, on this Mac only, for 7 days. It is encrypted, and never synced.") - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } else { - LicenseGateRow(feature: .dataRewind) + let isAvailable = featureAccess.isAvailable(.dataRewind) + Form { + if !isAvailable { + Section { + LicenseGateRow(feature: .dataRewind) + } } - LabeledContent("Clear saved changes") { - Button("Clear Saved Changes…") { - Task { @MainActor in - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Clear Saved Changes?"), - message: String( - localized: "Saves already committed stay committed. You will not be able to restore their previous values." - ), - confirmButton: String(localized: "Clear"), - cancelButton: String(localized: "Cancel") - ) - guard confirmed else { return } - Task { _ = await QueryHistoryManager.shared.clearRewindSnapshots() } - } + Section { + Toggle(isOn: Self.keepBinding($history.value, isAvailable: isAvailable)) { + Text("Keep saved changes for restoring") + Text("Keeps what rows looked like before each save, for 7 days, on this Mac only. Encrypted and never synced.") } .disabled(!isAvailable) + .accessibilityIdentifier("rewind-keep-toggle") + } + + // Never license gated: saved changes from a lapsed license can still be cleared. + Section { + LabeledContent { + Button("Clear Saved Changes…", action: confirmClear) + .disabled(isClearing) + .accessibilityIdentifier("rewind-clear-button") + } label: { + Text("Clear saved changes") + Text("Committed saves stay committed. Their previous values can no longer be restored.") + } } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.dataRewind.pageIdentifier) + } + + static func isOn(_ settings: HistorySettings, isAvailable: Bool) -> Bool { + isAvailable && settings.keepRewindHistory + } + + // Reads off without a license but never writes that, so the choice returns with the license. + static func keepBinding(_ settings: Binding, isAvailable: Bool) -> Binding { + Binding( + get: { isOn(settings.wrappedValue, isAvailable: isAvailable) }, + set: { settings.wrappedValue.keepRewindHistory = $0 } + ) + } + + private func confirmClear() { + let context = context + Task { @MainActor in + let confirmed = await AlertHelper.confirmDestructive( + title: String(localized: "Clear Saved Changes?"), + message: String( + localized: "Saves already committed stay committed. You will not be able to restore their previous values." + ), + confirmButton: String(localized: "Clear"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + isClearing = true + let cleared = await SettingsClearing.run([ + { await QueryHistoryManager.shared.clearRewindSnapshots() }, + ]) + isClearing = false + if !cleared { + context.presentError( + title: String(localized: "Couldn't Clear Saved Changes"), + message: String(localized: "The saved changes couldn't be deleted. Try again.") + ) + } + } + } +} + +struct DataRewindDrillRow: View { + @ObservedObject var history: SettingsSlice + @ObservedObject private var featureAccess = FeatureAccess.shared + + init(history: SettingsSlice) { + self.history = history + } + + var body: some View { + let isOn = DataRewindPage.isOn(history.value, isAvailable: featureAccess.isAvailable(.dataRewind)) + SettingsDrillRow( + route: SettingsRoute.page(.dataRewind), + title: SettingsPage.dataRewind.title, + value: isOn ? String(localized: "On") : String(localized: "Off") + ) } } diff --git a/apple/TablePro/Views/Settings/Sections/HistorySection.swift b/apple/TablePro/Views/Settings/Sections/HistorySection.swift index 222f8a544f..2f37ec8c28 100644 --- a/apple/TablePro/Views/Settings/Sections/HistorySection.swift +++ b/apple/TablePro/Views/Settings/Sections/HistorySection.swift @@ -1,59 +1,118 @@ -// -// HistorySection.swift -// TablePro -// - import SwiftUI -struct HistorySection: View { - @Binding var settings: HistorySettings +struct QueryHistorySettingsPage: View { + static let maxEntries = [100, 500, 1_000, 5_000, 10_000, 0] + static let retentionDays = [7, 30, 90, 365, 0] + + @ObservedObject var history: SettingsSlice + let context: SettingsPaneContext + @State private var isClearing = false + + init(history: SettingsSlice, context: SettingsPaneContext) { + self.history = history + self.context = context + } var body: some View { - Section("Query History") { - Picker("Maximum entries:", selection: $settings.maxEntries) { - Text("100").tag(100) - Text("500").tag(500) - Text("1,000").tag(1_000) - Text("5,000").tag(5_000) - Text("10,000").tag(10_000) - Text("Unlimited").tag(0) - } + Form { + Section { + Toggle(isOn: $history.value.autoCleanup) { + Text("Remove old entries automatically") + Text( + """ + Removes entries past these limits at launch, every 100 queries and when a limit changes. \ + Removed entries can't be recovered. + """ + ) + } + .accessibilityIdentifier("history-auto-cleanup-toggle") - Picker("Keep entries for:", selection: $settings.maxDays) { - Text("7 days").tag(7) - Text("30 days").tag(30) - Text("90 days").tag(90) - Text("1 year").tag(365) - Text("Forever").tag(0) - } + Picker("Maximum entries", selection: $history.value.maxEntries) { + SettingsChoiceItems(Self.maxEntries, including: history.value.maxEntries) { count in + Text(Self.maxEntriesTitle(count)) + } + } + .disabled(!history.value.autoCleanup) + .accessibilityIdentifier("history-max-entries-picker") - Toggle("Auto cleanup", isOn: $settings.autoCleanup) - - LabeledContent("Clear all query history") { - Button("Clear History…") { - Task { @MainActor in - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Clear All History?"), - message: String( - localized: """ - This will permanently delete all query history entries, the saved changes kept \ - for restoring, and the earlier versions of your query tabs. This action cannot \ - be undone. - """ - ), - confirmButton: String(localized: "Clear"), - cancelButton: String(localized: "Cancel") - ) - if confirmed { - Task { - _ = await QueryHistoryManager.shared.clearEverything() - _ = await QueryHistoryManager.shared.clearRewindSnapshots() - _ = await QueryTabVersionStorage.shared.removeAll() - } - } + // Stays enabled while cleanup is off: it also bounds how long query tab versions are kept. + Picker(selection: $history.value.maxDays) { + SettingsChoiceItems(Self.retentionDays, including: history.value.maxDays) { days in + Text(Self.retentionTitle(days)) } + } label: { + Text("Keep entries for") + Text("Earlier versions of query tabs are kept this long too, up to 30 days.") + } + .accessibilityIdentifier("history-max-days-picker") + } + + Section { + LabeledContent { + Button("Clear History…", action: confirmClear) + .disabled(isClearing) + .accessibilityIdentifier("history-clear-button") + } label: { + Text("Clear query history") + Text("Also deletes saved changes kept for Data Rewind and earlier versions of query tabs.") } } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.queryHistory.pageIdentifier) + } + + static func maxEntriesTitle(_ count: Int) -> String { + count == 0 ? String(localized: "No limit") : SettingsFormat.count(count) + } + + static func retentionTitle(_ days: Int) -> String { + days == 0 ? String(localized: "Forever") : SettingsFormat.days(days) + } + + private func confirmClear() { + let context = context + Task { @MainActor in + let confirmed = await AlertHelper.confirmDestructive( + title: String(localized: "Clear All History?"), + message: String( + localized: """ + This will permanently delete all query history entries, the saved changes kept \ + for restoring, and the earlier versions of your query tabs. This action cannot \ + be undone. + """ + ), + confirmButton: String(localized: "Clear"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + isClearing = true + let cleared = await SettingsClearing.run([ + { await QueryHistoryManager.shared.clearEverything() }, + { await QueryHistoryManager.shared.clearRewindSnapshots() }, + { await QueryTabVersionStorage.shared.removeAll() }, + ]) + isClearing = false + if !cleared { + context.presentError( + title: String(localized: "Couldn't Clear Query History"), + message: String(localized: "Part of the history couldn't be deleted. Try again.") + ) + } + } + } +} + +enum SettingsClearing { + // Every step runs even after one fails, so a failed history delete still clears the rest. + @MainActor + static func run(_ steps: [@MainActor () async -> Bool]) async -> Bool { + var cleared = true + for step in steps { + let succeeded = await step() + cleared = cleared && succeeded + } + return cleared } } diff --git a/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift b/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift new file mode 100644 index 0000000000..c9290c403f --- /dev/null +++ b/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift @@ -0,0 +1,255 @@ +import Foundation +import SwiftUI +@testable import TablePro +import Testing + +struct QueryResultLimitTests { + @Test("No limit turns the limit off and keeps the stored cap") + func noLimitKeepsCap() { + let settings = DataGridSettings(queryResultRowCap: 5_000, truncateQueryResults: true) + let updated = settings.withQueryResultLimit(nil) + #expect(updated.truncateQueryResults == false) + #expect(updated.queryResultRowCap == 5_000) + #expect(updated.queryResultLimit == nil) + } + + @Test("Picking a limit turns it on and sets the cap together") + func pickSetsBoth() { + let settings = DataGridSettings(queryResultRowCap: 5_000, truncateQueryResults: false) + let updated = settings.withQueryResultLimit(50_000) + #expect(updated.truncateQueryResults) + #expect(updated.queryResultRowCap == 50_000) + #expect(updated.queryResultLimit == 50_000) + } + + @Test("A stored cap of 0 reads as No limit") + func zeroCapReadsNoLimit() { + #expect(DataGridSettings(queryResultRowCap: 0, truncateQueryResults: true).queryResultLimit == nil) + } + + @Test("A cap out of range reads as the cap queries run with") + func outOfRangeCapReadsClamped() { + #expect(DataGridSettings(queryResultRowCap: 50, truncateQueryResults: true).queryResultLimit == 100) + #expect(DataGridSettings(queryResultRowCap: 9_000_000, truncateQueryResults: true).queryResultLimit == 500_000) + } + + @Test("The pop-up writes the limit and the switch in one commit") + @MainActor + func bindingWritesOnce() { + let slice = SettingsSlice(DataGridSettings(queryResultRowCap: 5_000, truncateQueryResults: false)) + let commits = CommitLog() + slice.attach { _, new in commits.values.append(new) } + let binding = DataGridSection.queryResultLimitBinding(sliceBinding(slice)) + + #expect(binding.wrappedValue == nil) + binding.wrappedValue = 100_000 + + #expect(commits.values.count == 1) + #expect(commits.values.first?.truncateQueryResults == true) + #expect(commits.values.first?.queryResultRowCap == 100_000) + #expect(binding.wrappedValue == 100_000) + + binding.wrappedValue = nil + + #expect(commits.values.count == 2) + #expect(slice.value.truncateQueryResults == false) + #expect(slice.value.queryResultRowCap == 100_000) + } +} + +struct NullDisplayTests { + // Drives a draft the way SettingsTextField does: a write only on commit, then a read-back. + private struct FieldHarness { + var stored: String + var draft: SettingsTextDraft + var writes: [String] = [] + + init(stored: String) { + self.stored = stored + draft = SettingsTextDraft(stored) + } + + var error: String? { DataGridSettings.nullDisplayValidationError(for: draft.text) } + + mutating func type(_ text: String) { + draft.text = text + } + + mutating func commit() { + let resolved = draft.commit(to: stored) { candidate in + DataGridSettings.nullDisplayValidationError(for: candidate) == nil + ? .accept(DataGridSettings.normalizedNullDisplay(candidate)) + : .revert + } + if let resolved { + stored = resolved + writes.append(resolved) + } + draft.settle(to: stored) + } + + mutating func remoteChange(_ value: String) { + stored = value + draft.resync(to: value) + } + } + + @Test("A blank entry commits as NULL and the field reads it back") + func blankCommitsNull() { + var field = FieldHarness(stored: "(null)") + field.type(" ") + #expect(field.error == nil) + field.commit() + #expect(field.stored == "NULL") + #expect(field.draft.text == "NULL") + } + + @Test("A trailing space typed mid-word is not an error and is trimmed on commit") + func trailingSpaceIsNotAnError() { + var field = FieldHarness(stored: "NULL") + field.type("n/a ") + #expect(field.error == nil) + field.type(String(repeating: "x", count: 20) + " ") + #expect(field.error == nil) + field.type("n/a ") + field.commit() + #expect(field.stored == "n/a") + #expect(field.writes == ["n/a"]) + } + + @Test("More than 20 characters shows the error and a commit restores the saved value") + func overLimitReverts() { + var field = FieldHarness(stored: "NULL") + field.type(String(repeating: "x", count: 21)) + #expect(field.error != nil) + field.commit() + #expect(field.stored == "NULL") + #expect(field.writes.isEmpty) + #expect(field.draft.text == "NULL") + } + + @Test("An untouched field follows a remote change, an edited one keeps the edit") + func untouchedFollowsRemote() { + var field = FieldHarness(stored: "NULL") + field.remoteChange("") + #expect(field.draft.text == "") + + field.type("nil") + field.remoteChange("(none)") + #expect(field.draft.text == "nil") + field.commit() + #expect(field.stored == "nil") + } + + @Test("An unchanged commit writes nothing") + func unchangedCommitWritesNothing() { + var field = FieldHarness(stored: "NULL") + field.type("NULL ") + field.commit() + #expect(field.writes.isEmpty) + } + + @Test("The stored value is cleaned, cut to 20 characters, then trimmed again") + func sanitizeAfterPrefix() { + #expect(DataGridSettings.normalizedNullDisplay("abcdefghijklmnopqrs tuvwxyz") == "abcdefghijklmnopqrs") + #expect(DataGridSettings.normalizedNullDisplay(" a\tb\n") == "a b") + #expect(DataGridSettings.normalizedNullDisplay("\n\t ") == "NULL") + #expect(DataGridSettings(nullDisplay: String(repeating: "y", count: 30)).validatedNullDisplay.count == 20) + } +} + +@MainActor +struct DataPaneChoiceTests { + @Test("A page size off the list is offered after the list") + func pageSizeExtra() { + let options = SettingsChoices.options(DataGridSection.pageSizes, including: 250) + #expect(options.fixed == DataGridSection.pageSizes) + #expect(options.extra == 250) + #expect(SettingsChoices.options(DataGridSection.pageSizes, including: 1_000).extra == nil) + } + + @Test("Always is on the exact row count list, another threshold is offered after it") + func exactCountExtra() { + #expect(SettingsChoices.options(DataGridSection.exactCountThresholds, including: Int.max).extra == nil) + #expect(SettingsChoices.options(DataGridSection.exactCountThresholds, including: 50_000).extra == 50_000) + } + + @Test("No limit adds no extra result limit, an off-list cap does") + func resultLimitExtra() { + let limits = DataGridSection.queryResultLimits.map { Optional($0) } + let first = DataGridSection.queryResultLimits.first + let noLimit = DataGridSettings(truncateQueryResults: false).queryResultLimit + #expect(SettingsChoices.options(limits, including: noLimit ?? first).extra == nil) + let offList = DataGridSettings(queryResultRowCap: 2_500, truncateQueryResults: true).queryResultLimit + #expect(SettingsChoices.options(limits, including: offList ?? first).extra == .some(2_500)) + } + + @Test("History limits keep No limit and Forever on the list") + func historyChoices() { + #expect(SettingsChoices.options(QueryHistorySettingsPage.maxEntries, including: 0).extra == nil) + #expect(SettingsChoices.options(QueryHistorySettingsPage.maxEntries, including: 2_000).extra == 2_000) + #expect(SettingsChoices.options(QueryHistorySettingsPage.retentionDays, including: 0).extra == nil) + #expect(SettingsChoices.options(QueryHistorySettingsPage.retentionDays, including: 14).extra == 14) + } + + @Test("Row counts are grouped the way the locale groups them") + func rowTitlesGroupDigits() { + #expect(DataGridSection.rowsTitle(10_000).contains(SettingsFormat.count(10_000))) + #expect(DataGridSection.exactCountTitle(100_000).contains(SettingsFormat.count(100_000))) + #expect(DataGridSection.exactCountTitle(Int.max) == String(localized: "Always")) + } +} + +@MainActor +struct DataRewindSwitchTests { + @Test("Without a license the switch reads off and the saved choice stays") + func unlicensedReadsOff() { + let slice = SettingsSlice(HistorySettings(keepRewindHistory: true)) + let binding = DataRewindPage.keepBinding(sliceBinding(slice), isAvailable: false) + #expect(binding.wrappedValue == false) + #expect(slice.value.keepRewindHistory) + #expect(DataRewindPage.isOn(slice.value, isAvailable: false) == false) + } + + @Test("With a license the switch shows and writes the saved choice") + func licensedWrites() { + let slice = SettingsSlice(HistorySettings(keepRewindHistory: true)) + let binding = DataRewindPage.keepBinding(sliceBinding(slice), isAvailable: true) + #expect(binding.wrappedValue) + binding.wrappedValue = false + #expect(slice.value.keepRewindHistory == false) + #expect(DataRewindPage.isOn(slice.value, isAvailable: true) == false) + } +} + +@MainActor +struct SettingsClearingTests { + @Test("Every step runs in order even after one fails, and the failure is reported") + func runsEveryStep() async { + let log = CommitLog() + let cleared = await SettingsClearing.run([ + { log.values.append("history"); return true }, + { log.values.append("rewind"); return false }, + { log.values.append("versions"); return true }, + ]) + #expect(cleared == false) + #expect(log.values == ["history", "rewind", "versions"]) + } + + @Test("All steps succeeding reports success") + func allSucceed() async { + let cleared = await SettingsClearing.run([{ true }, { true }]) + #expect(cleared) + } +} + +@MainActor +private final class CommitLog { + var values: [Value] = [] +} + +// The binding a pane gets from $slice.value. +@MainActor +private func sliceBinding(_ slice: SettingsSlice) -> Binding { + ObservedObject(wrappedValue: slice).projectedValue.value +} From d17fa7f1e281f0881c357146b84ff837289bf467 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:53 +0700 Subject: [PATCH 31/48] feat(settings): Keyboard pane on the toolbar filter with a native shortcut recorder --- apple/TablePro/Models/UI/BoundKey.swift | 64 +-- .../Models/UI/KeyboardShortcutModels.swift | 277 ++++++------- .../Views/AIChat/ChatComposerTextView.swift | 60 ++- .../Entries/KeyboardSettingsEntry.swift | 10 +- .../Views/Settings/KeyboardSettingsView.swift | 363 +++++++++--------- .../Settings/ShortcutRecorderButton.swift | 153 ++++++++ .../Views/Settings/ShortcutRecorderView.swift | 322 ---------------- .../Settings/ShortcutRecordingSession.swift | 308 +++++++++++++++ .../Models/KeyboardShortcutTests.swift | 271 ++++++++++++- .../AIChat/ChatComposerReplaceTests.swift | 51 +++ .../ShortcutRecordingSessionTests.swift | 354 +++++++++++++++++ .../KeyboardSettingsUITests.swift | 49 +++ 12 files changed, 1534 insertions(+), 748 deletions(-) create mode 100644 apple/TablePro/Views/Settings/ShortcutRecorderButton.swift delete mode 100644 apple/TablePro/Views/Settings/ShortcutRecorderView.swift create mode 100644 apple/TablePro/Views/Settings/ShortcutRecordingSession.swift create mode 100644 apple/TableProTests/Views/AIChat/ChatComposerReplaceTests.swift create mode 100644 apple/TableProTests/Views/Settings/ShortcutRecordingSessionTests.swift create mode 100644 apple/TableProUITests/KeyboardSettingsUITests.swift diff --git a/apple/TablePro/Models/UI/BoundKey.swift b/apple/TablePro/Models/UI/BoundKey.swift index ba70973d23..5b02109b33 100644 --- a/apple/TablePro/Models/UI/BoundKey.swift +++ b/apple/TablePro/Models/UI/BoundKey.swift @@ -1,16 +1,7 @@ -// -// BoundKey.swift -// TablePro -// -// A keyboard shortcut stored as a hardware key code plus modifiers. Storing the -// physical key code (rather than the produced character) makes matching -// layout-independent and avoids the shifted-symbol ambiguity where "[" and "{" -// describe the same physical key. -// - import AppKit import SwiftUI +// Stored as the physical key code, so matching ignores the layout and "[" and "{" are one key. struct BoundKey: Codable, Equatable, Hashable { let keyCode: UInt16 let command: Bool @@ -26,10 +17,7 @@ struct BoundKey: Codable, Equatable, Hashable { self.control = control } - // MARK: - Recorder Capture - - /// Build from a recorded key event. Requires Command or Control, or one of the - /// bare keys allowed for grid actions (Escape, Delete, Forward Delete, Space). + // Requires Command or Control, or a bare key the grid can read (Escape, Delete, Forward Delete, Space, F-keys). init?(from event: NSEvent) { let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) let hasCommand = flags.contains(.command) @@ -44,15 +32,19 @@ struct BoundKey: Codable, Equatable, Hashable { self.control = hasControl } - // MARK: - Default Construction + // The raw chord with no gate; ShortcutAction.accepts(_:) decides whether it can be bound. + init(capturing event: NSEvent) { + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + self.init( + keyCode: event.keyCode, + command: flags.contains(.command), + shift: flags.contains(.shift), + option: flags.contains(.option), + control: flags.contains(.control) + ) + } - /// Build a binding from a base character, resolving it to a key code on the - /// active layout. Used to anchor default shortcuts to a semantic character. - /// A character with no key code on the active layout yields the cleared - /// sentinel, so the binding reads as unassigned rather than silently aliasing - /// some other physical key. Every default and reserved character is ASCII and - /// resolves through the US fallback, so the failure path is a programmer error - /// and trips an assertion in debug. + // A character with no key code on the active layout yields .cleared, so the binding reads as unassigned instead of aliasing another key. static func character( _ character: Character, command: Bool = false, @@ -67,7 +59,6 @@ struct BoundKey: Codable, Equatable, Hashable { return BoundKey(keyCode: keyCode, command: command, shift: shift, option: option, control: control) } - /// Build a binding from a named special key (layout-independent). static func special( _ key: KeyCode, command: Bool = false, @@ -78,9 +69,6 @@ struct BoundKey: Codable, Equatable, Hashable { BoundKey(keyCode: key.rawValue, command: command, shift: shift, option: option, control: control) } - // MARK: - Migration - - /// Convert a legacy character-string shortcut (pre-keyCode storage) to a BoundKey. init?(legacyKey: String, isSpecialKey: Bool, command: Bool, shift: Bool, option: Bool, control: Bool) { if legacyKey.isEmpty, !command, !shift, !option, !control { self = .cleared @@ -98,8 +86,6 @@ struct BoundKey: Codable, Equatable, Hashable { self.init(keyCode: keyCode, command: command, shift: shift, option: option, control: control) } - // MARK: - Matching - func matches(_ event: NSEvent) -> Bool { guard !isCleared else { return false } let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) @@ -114,15 +100,15 @@ struct BoundKey: Codable, Equatable, Hashable { command || shift || option || control } - /// Function keys (F1-F12) are valid as bare shortcuts: they reach the menu as - /// key-equivalents without a modifier and never collide with typing. + // F-keys reach the menu as bare key equivalents and never collide with typing. var isFunctionKey: Bool { KeyCode(rawValue: keyCode)?.functionKeyIndex != nil } - // MARK: - SwiftUI Integration + var isBareRecordable: Bool { + Self.isBareRecordable(keyCode) + } - /// The SwiftUI key equivalent, or nil when the key code has no representable key. var swiftUIKeyEquivalent: KeyEquivalent? { if let special = Self.specialKeyEquivalent(for: keyCode) { return special @@ -134,12 +120,7 @@ struct BoundKey: Codable, Equatable, Hashable { return KeyEquivalent(character) } - // MARK: - AppKit Integration - - /// The `NSMenuItem.keyEquivalent` string, or nil when the key code has no - /// representable key. Always the unshifted character, because AppKit infers - /// Shift from an uppercase key equivalent and the modifier belongs in - /// `modifierFlags` instead. + // Always the unshifted character: AppKit infers Shift from an uppercase equivalent, and Shift belongs in modifierFlags. var menuKeyEquivalent: String? { swiftUIKeyEquivalent.map { String($0.character) } } @@ -162,9 +143,6 @@ struct BoundKey: Codable, Equatable, Hashable { return flags } - // MARK: - Display - - /// Human-readable representation (e.g. "⌘S", "⇧⌘P", "⌥⌫"). var displayString: String { guard !isCleared else { return "" } var parts: [String] = [] @@ -189,16 +167,12 @@ struct BoundKey: Codable, Equatable, Hashable { return "?" } - // MARK: - Cleared Sentinel - static let cleared = BoundKey(keyCode: 0xFFFF) var isCleared: Bool { keyCode == 0xFFFF } - // MARK: - Special Key Tables - private static let bareRecordableKeyCodes: Set = [ KeyCode.escape.rawValue, KeyCode.delete.rawValue, diff --git a/apple/TablePro/Models/UI/KeyboardShortcutModels.swift b/apple/TablePro/Models/UI/KeyboardShortcutModels.swift index d0c8b2e698..df77fa4a3d 100644 --- a/apple/TablePro/Models/UI/KeyboardShortcutModels.swift +++ b/apple/TablePro/Models/UI/KeyboardShortcutModels.swift @@ -1,47 +1,24 @@ -// -// KeyboardShortcutModels.swift -// TablePro -// -// Data models for keyboard shortcut customization. The binding type itself -// lives in BoundKey.swift. -// - import AppKit import SwiftUI -// MARK: - Shortcut Context - -/// Where an action can fire. The same physical combo can mean different things -/// in different contexts because the focused responder resolves it (e.g. Cmd+[ -/// is pagination in the grid and indent in the editor). Two actions only -/// conflict when their contexts can be active at the same time. +// The focused responder resolves a combo (Cmd-[ pages the grid and outdents the editor), so two actions conflict only when their contexts can be active at once. enum ShortcutContext: String { case global case editor case dataGrid - /// Two contexts overlap when they can be the active responder at the same - /// time. Non-overlapping contexts (editor vs data grid) may share a combo: - /// the editor's local key monitor consumes the keystroke while it is focused, - /// so the grid's menu key-equivalent only fires when the grid has focus. The - /// conflict resolver guards uniqueness within an overlapping context; it does - /// not stop a user from binding a grid combo that also reaches a global menu - /// item, which focus alone cannot disambiguate. + // Editor and grid may share a combo: the editor's local key monitor takes it while the editor has focus. func overlaps(_ other: ShortcutContext) -> Bool { self == .global || other == .global || self == other } } -// MARK: - Shortcut Category - -/// Groups shortcuts in the settings list by the surface they act on. enum ShortcutCategory: String, Codable, CaseIterable, Identifiable { case editor case dataGrid case navigation case connections case debug - case app var id: String { rawValue } @@ -52,13 +29,10 @@ enum ShortcutCategory: String, Codable, CaseIterable, Identifiable { case .navigation: return String(localized: "Navigation") case .connections: return String(localized: "Connections") case .debug: return String(localized: "Debug") - case .app: return String(localized: "App") } } } -// MARK: - Shortcut Action - enum ShortcutAction: String, Codable, CaseIterable, Identifiable { // Connections case manageConnections @@ -253,9 +227,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { allCases.filter { $0.category == category && $0.isAvailable(enabledModules: enabledModules) } } - /// A command that dispatches to whichever surface holds focus must be `.global`, or the - /// conflict resolver treats its combo as free in the other context and AppKit blanks one of - /// the two menu items that end up claiming it. The three find commands all route that way. + // A command that dispatches to whichever surface has focus must be .global, or AppKit blanks one of the two menu items that end up sharing its combo. var context: ShortcutContext { switch self { case .find, .findAndReplace, .findNext, .findPrevious, .useSelectionForFind: @@ -271,9 +243,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { .copyRowsExplicit, .copyWithHeaders, .copyAsJson, .toggleFilters, .jumpToColumn, .copyCellValue, .copyAsCsv, .copyAsCsvWithHeaders, .copyAsMarkdown, .copyAsInClause, .copyAsInsert, .copyAsUpdate, - /// Named rather than left to the `default:` below. It reverses a row the grid is - /// showing, so it belongs in the grid's context the way Add Row and Delete do, and - /// inheriting `.global` would let the recorder call a grid combo free for it. + // Named so it never falls to default: and .global, which would let the recorder call a grid combo free for it. .restorePreviousValues: return .dataGrid default: @@ -285,9 +255,7 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { self == .switchToRecentTab || self == .switchToLeastRecentTab } - /// The focused grid reads this action's key from `keyDown`, whatever its modifiers, so its menu - /// item never carries a key equivalent. Its default, Option-Return, breaks a line in a text - /// field, and AppKit hands an equivalent to the menu before the field sees the key. + // The grid reads this key in keyDown, so its menu item has no equivalent: Option-Return breaks a line in a text field, and AppKit hands an equivalent to the menu first. var isReadByFocusedGrid: Bool { self == .openValueEditor } @@ -297,13 +265,26 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { isReadByFocusedGrid || other.isReadByFocusedGrid || context.overlaps(other.context) } + // The focused grid reads a bare key only for this action; nothing dispatches one for Delete or Clear Selection. var allowsBareKey: Bool { - switch self { - case .previewFKReference, .clearSelection, .delete: + self == .previewFKReference + } + + func accepts(_ key: BoundKey) -> Bool { + if key.command || key.control || key.isFunctionKey { + return true + } + if key == KeyboardSettings.defaultShortcuts[self] { return true - default: - return false } + guard key.isBareRecordable else { return false } + return key.hasModifier || allowsBareKey + } + + var modifierRefusal: String { + self == .previewFKReference + ? String(localized: "Use ⌘ or ⌃, Space, or a function key.") + : String(localized: "Add ⌘ or ⌃ to this shortcut.") } var displayName: String { @@ -438,12 +419,44 @@ enum ShortcutAction: String, Codable, CaseIterable, Identifiable { } } -// MARK: - Built-in Editor Shortcuts +struct ShortcutSection: Identifiable, Equatable { + let category: ShortcutCategory + let actions: [ShortcutAction] + + var id: ShortcutCategory { category } +} + +extension ShortcutAction { + private static let modifierGlyphs: Set = ["⌃", "⌥", "⇧", "⌘"] + + // Every whitespace-separated term has to match; a term holding a modifier glyph can match the bound key too. + static func settingsSections( + matching query: String, + in settings: KeyboardSettings, + enabledModules: Set + ) -> [ShortcutSection] { + let terms = query.split(whereSeparator: \.isWhitespace).map(String.init) + return ShortcutCategory.allCases.compactMap { category in + let actions = settingsRows(in: category, enabledModules: enabledModules) + .filter { $0.matches(terms, in: settings) } + return actions.isEmpty ? nil : ShortcutSection(category: category, actions: actions) + } + } + + private func matches(_ terms: [String], in settings: KeyboardSettings) -> Bool { + terms.allSatisfy { term in + if displayName.localizedStandardContains(term) || category.displayName.localizedStandardContains(term) { + return true + } + guard term.contains(where: { Self.modifierGlyphs.contains($0) }), + let key = settings.boundKey(for: self) else { return false } + return key.displayString.localizedStandardContains(term) + } + } +} extension ShortcutAction { - /// Shortcuts owned by the embedded SQL editor. They are not customizable, but - /// the recorder surfaces them so a user does not silently shadow one with an - /// editor-context binding. + // Owned by the embedded editor and not rebindable; listed so an editor-context binding never shadows one. static let editorBuiltIns: [(key: BoundKey, name: String)] = [ (.character("/", command: true), String(localized: "Toggle Comment")), (.character("[", command: true), String(localized: "Outdent")), @@ -457,16 +470,16 @@ extension ShortcutAction { (.special(.downArrow, shift: true, option: true), String(localized: "Extend Selection to Next Statement")) ] - /// AppKit's own text-editing key bindings, taken from `StandardKeyBinding.dict`. - /// The editor's local key monitor claims `editorBuiltIns` before the menu bar - /// sees them, but these resolve at the very end of dispatch, inside the focused - /// responder's `interpretKeyEvents`. An enabled menu key equivalent is matched - /// long before that, so a data-grid action bound to one of these has to stand - /// down while a text input holds focus. + // StandardKeyBinding.dict and the text input keys: they resolve last, in interpretKeyEvents, so an enabled menu equivalent always beats them. static let standardTextEditingBindings: [(key: BoundKey, name: String)] = [ (.special(.delete, command: true), String(localized: "Delete to Beginning of Line")), (.special(.delete, option: true), String(localized: "Delete Word Backward")), (.special(.forwardDelete, option: true), String(localized: "Delete Word Forward")), + (.special(.delete, shift: true), String(localized: "Delete Backward")), + (.special(.forwardDelete, shift: true), String(localized: "Delete Forward")), + (.special(.space, shift: true), String(localized: "Insert Space")), + (.special(.space, option: true), String(localized: "Insert Non-Breaking Space")), + (.special(.escape, option: true), String(localized: "Complete Word")), (.special(.leftArrow, command: true), String(localized: "Move to Beginning of Line")), (.special(.rightArrow, command: true), String(localized: "Move to End of Line")), (.special(.upArrow, command: true), String(localized: "Move to Beginning of Document")), @@ -475,10 +488,7 @@ extension ShortcutAction { (.special(.rightArrow, option: true), String(localized: "Move Word Right")) ] - /// Every key equivalent a menu builder hardcodes, and so every combo no `ShortcutAction` - /// can be bound to. These fire regardless of focus, and AppKit blanks the loser when two - /// menu items claim one combo, so a binding the recorder let through would silently kill - /// the hardcoded command instead. An entry added to a menu builder belongs here too. + // Hardcoded by a menu builder: AppKit blanks the loser when two items share a combo, so no action may take one. A new menu-builder key goes here too. static let reservedAppShortcuts: [(key: BoundKey, name: String)] = { var shortcuts: [(key: BoundKey, name: String)] = [ (.character("=", command: true), String(localized: "Zoom In")), @@ -503,9 +513,6 @@ extension ShortcutAction { return shortcuts }() - /// The name of a reserved command this combo would shadow: an app-level menu - /// shortcut (always), or a built-in editor or system text command when the - /// action can fire while the editor is focused. static func reservedConflict(for key: BoundKey, context: ShortcutContext) -> String? { if let appName = reservedAppShortcuts.first(where: { $0.key == key })?.name { return appName @@ -517,24 +524,15 @@ extension ShortcutAction { return standardTextEditingBindings.first(where: { $0.key == key })?.name } - /// Whether this action's binding duplicates one of AppKit's standard - /// text-editing bindings, which the focused responder owns. Only data-grid - /// actions yield: an editor or global action is meant to fire while text is - /// focused, so it keeps its key equivalent and the recorder warns instead. + // Only grid actions stand down while text has focus; an editor or global action keeps its key and the recorder refuses the combo instead. func shadowsStandardTextEditingBinding(_ key: BoundKey?) -> Bool { guard context == .dataGrid, let key, !key.isCleared else { return false } return Self.standardTextEditingBindings.contains { $0.key == key } } } -// MARK: - Keyboard Settings - -/// User's keyboard shortcut customization settings. -/// Only stores overrides; an empty dictionary means all defaults. +// Only overrides are stored, keyed by action rawValue; a renamed action's stale entry never matches. struct KeyboardSettings: Codable, Equatable { - /// User-customized shortcuts (action rawValue -> BoundKey). - /// Only contains overrides; missing entries use defaults. A renamed action's - /// stale key becomes a harmless no-op (never matched by any action). var shortcuts: [String: BoundKey] static let `default` = KeyboardSettings(shortcuts: [:]) @@ -545,13 +543,9 @@ struct KeyboardSettings: Codable, Equatable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) - // BoundKey requires `keyCode` and LegacyKeyCombo requires `key`, and - // neither field exists in the other shape, so the two never decode each - // other's payload. Modern data is tried first; a legacy file fails that - // decode and falls through to migration. Only then are unreadable - // entries dropped one by one, or a legacy file would lose every entry. + // The two shapes never decode each other (keyCode vs key); entries drop one by one only after both fail, or a legacy file would lose them all. if let modern = try? container.decodeIfPresent([String: BoundKey].self, forKey: .shortcuts) { - shortcuts = modern ?? [:] + shortcuts = modern } else if let legacy = try? container.decode([String: LegacyKeyCombo].self, forKey: .shortcuts) { shortcuts = legacy.compactMapValues { $0.migrated() } } else { @@ -559,14 +553,7 @@ struct KeyboardSettings: Codable, Equatable { } } - /// Get the effective shortcut for an action (user override or default). - /// Returns nil if the user explicitly cleared the shortcut, or if a chord the user assigned - /// by hand has already claimed this action's default. - /// - /// The yield is resolved here rather than written into `shortcuts`, which means only what the - /// user chose. Storing it would make the stand-down permanent: rebinding the conflicting chord - /// would leave the default cleared forever, Settings would show the action as customized, and - /// its Reset arrow would appear to work until the next launch re-applied the clear. + // A default an override claims yields here, never in `shortcuts`, so rebinding the claimant re-arms it and the action never reads as customized. func shortcut(for action: ShortcutAction) -> BoundKey? { if let override = shortcuts[action.rawValue] { return override @@ -576,8 +563,7 @@ struct KeyboardSettings: Codable, Equatable { return fallback } - /// The action whose user-assigned chord stands this default down, if any. Only overrides - /// claim: two defaults cannot collide, because `DefaultShortcutHygieneTests` forbids it. + // Only overrides claim: DefaultShortcutHygieneTests keeps two defaults from colliding. private func findOverrideClaimant(of key: BoundKey, excluding action: ShortcutAction) -> ShortcutAction? { guard !key.isCleared else { return nil } for (rawValue, override) in shortcuts { @@ -593,12 +579,24 @@ struct KeyboardSettings: Codable, Equatable { return nil } + func boundKey(for action: ShortcutAction) -> BoundKey? { + guard let key = shortcut(for: action), !key.isCleared else { return nil } + return key + } + func isCustomized(_ action: ShortcutAction) -> Bool { shortcuts[action.rawValue] != nil } - /// Find a conflicting action for the given combo within an overlapping - /// context, excluding the specified action. + var customizedCount: Int { + shortcuts.keys.filter { ShortcutAction(rawValue: $0) != nil }.count + } + + func defaultClaimant(for action: ShortcutAction) -> ShortcutAction? { + guard !isCustomized(action), let fallback = Self.defaultShortcuts[action] else { return nil } + return findOverrideClaimant(of: fallback, excluding: action) + } + func findConflict(for key: BoundKey, excluding action: ShortcutAction) -> ShortcutAction? { findConflict(for: key, excluding: action, enabledModules: AppModule.storedEnabledModules()) } @@ -608,32 +606,77 @@ struct KeyboardSettings: Codable, Equatable { excluding action: ShortcutAction, enabledModules: Set ) -> ShortcutAction? { - guard !key.isCleared else { return nil } - for other in ShortcutAction.allCases where other != action && other.isAvailable(enabledModules: enabledModules) { - guard action.contends(with: other), - let otherKey = shortcut(for: other), !otherKey.isCleared, - otherKey == key else { continue } - return other + conflicts(for: key, excluding: action, enabledModules: enabledModules).first + } + + func conflicts( + for key: BoundKey, + excluding action: ShortcutAction, + enabledModules: Set + ) -> [ShortcutAction] { + guard !key.isCleared else { return [] } + return ShortcutAction.allCases.filter { other in + other != action + && other.isAvailable(enabledModules: enabledModules) + && action.contends(with: other) + && boundKey(for: other) == key } - return nil } mutating func setShortcut(_ key: BoundKey, for action: ShortcutAction) { shortcuts[action.rawValue] = key } - /// Clear a shortcut so the action has no binding. mutating func clearShortcut(for action: ShortcutAction) { shortcuts[action.rawValue] = BoundKey.cleared } - /// Reset a specific action to its default shortcut. mutating func resetToDefault(for action: ShortcutAction) { shortcuts.removeValue(forKey: action.rawValue) } - /// Drop overrides that can never dispatch (bare keys on menu-driven actions), - /// reverting them to their default. Cleared and unknown overrides are kept. + // Picking the default again stores nothing, so the action stops reading as customized. + func assigning(_ key: BoundKey, to action: ShortcutAction) -> KeyboardSettings { + var next = self + if key == Self.defaultShortcuts[action], findOverrideClaimant(of: key, excluding: action) == nil { + next.resetToDefault(for: action) + } else { + next.setShortcut(key, for: action) + } + return next + } + + // An action with no default needs no cleared marker to have no key. + func clearing(_ action: ShortcutAction) -> KeyboardSettings { + var next = self + if Self.defaultShortcuts[action] == nil { + next.resetToDefault(for: action) + } else { + next.clearShortcut(for: action) + } + return next + } + + func resetting(_ action: ShortcutAction) -> KeyboardSettings { + var next = self + next.resetToDefault(for: action) + return next + } + + // A holder still on its default needs no write: the new override claims that default. + func reassigning( + _ key: BoundKey, + to action: ShortcutAction, + enabledModules: Set + ) -> KeyboardSettings { + var next = self + for holder in conflicts(for: key, excluding: action, enabledModules: enabledModules) where isCustomized(holder) { + next = next.clearing(holder) + } + return next.assigning(key, to: action) + } + + // Drops overrides that can never dispatch (a bare key on a menu action); cleared and unknown entries stay. func sanitized() -> KeyboardSettings { var cleaned = shortcuts for (rawValue, key) in shortcuts { @@ -645,10 +688,7 @@ struct KeyboardSettings: Codable, Equatable { return KeyboardSettings(shortcuts: cleaned) } - /// Build a SwiftUI KeyboardShortcut for the given action's menu item. - /// Returns nil when the shortcut is cleared, has no representable key, or is a - /// bare (modifier-less) key. Bare keys dispatch through the responder chain in - /// the focused view, not through a global menu key-equivalent. + // A bare key reaches the focused responder, never a menu key equivalent. func keyboardShortcut(for action: ShortcutAction) -> KeyboardShortcut? { guard !action.isReadByFocusedGrid, let key = shortcut(for: action), !key.isCleared, key.hasModifier || key.isFunctionKey, @@ -658,10 +698,6 @@ struct KeyboardSettings: Codable, Equatable { return KeyboardShortcut(equivalent, modifiers: key.eventModifiers) } - /// The AppKit key equivalent for the given action's menu item, resolved through - /// user overrides. Returns nil under the same conditions as `keyboardShortcut(for:)`: - /// a cleared binding, an unrepresentable key, or a bare key, which reaches the - /// focused responder directly rather than through a global menu key-equivalent. func menuKeyEquivalent(for action: ShortcutAction) -> (characters: String, modifiers: NSEvent.ModifierFlags)? { guard !action.isReadByFocusedGrid, let key = shortcut(for: action), !key.isCleared, key.hasModifier || key.isFunctionKey, @@ -671,19 +707,12 @@ struct KeyboardSettings: Codable, Equatable { return (characters, key.modifierFlags) } - /// A tooltip/help string that appends the action's resolved shortcut, e.g. - /// "Switch Connection (⌃⌘C)". Returns just the label when the shortcut is - /// cleared or unset. Reflects user overrides because it resolves through - /// `shortcut(for:)`. func shortcutHint(_ label: String, for action: ShortcutAction) -> String { guard let key = shortcut(for: action), !key.isCleared else { return label } return "\(label) (\(key.displayString))" } - // MARK: - Default Shortcuts - - // An action absent here shows as unassigned until the user binds it. Commit and Roll Back Transaction ship - // unbound: they are infrequent, and a stray Roll Back discards work. + // Commit and Roll Back Transaction ship unbound: they are infrequent, and a stray Roll Back discards work. static let defaultShortcuts: [ShortcutAction: BoundKey] = [ // Connections .newConnection: .character("n", command: true), @@ -750,12 +779,7 @@ struct KeyboardSettings: Codable, Equatable { .jumpToColumn: .character("j", command: true, shift: true), // Navigation - /// Not the Safari chord. Command+[ and Command+] are Previous/Next Page and are claimed - /// again by the editor's own indent and outdent, Option+Command+[ and ] are the result - /// tabs, Shift+Command+[ and ] are the editor tabs, Control+Command+Left and Right are - /// Previous/Next Statement, and Option+Command+Left is Toggle Fold. Two menu items cannot - /// share a key equivalent: AppKit blanks the loser's. This completes the bracket family - /// the app already reads as "step through something". + // Not Safari's chord: Cmd-[ ] page and indent, Opt-Cmd-[ ] step results, Shift-Cmd-[ ] step tabs, and two menu items cannot share one. .navigateBack: .character("[", command: true, control: true), .navigateForward: .character("]", command: true, control: true), .newTab: .character("t", command: true), @@ -765,8 +789,7 @@ struct KeyboardSettings: Codable, Equatable { .toggleTableBrowser: .character("0", command: true), .toggleInspector: .character("i", command: true, option: true), .toggleAssistant: .character("a", command: true, option: true), - /// Not Shift-Command-A, which Apple's own table assigns to Deselect All and which - /// `clearSelection` is waiting for. This keeps the "a is the assistant" family together. + // Not Shift-Cmd-A, Apple's Deselect All, which clearSelection waits for. .toggleAgentMode: .character("a", command: true, shift: true, option: true), .toggleFilters: .character("f", command: true, shift: true), .toggleHistory: .character("y", command: true), @@ -783,10 +806,7 @@ struct KeyboardSettings: Codable, Equatable { .focusAssistant: .character("a", command: true, option: true, control: true), .showPreviousTab: .character("[", command: true, shift: true), .showNextTab: .character("]", command: true, shift: true), - /// The one Control chord among the defaults. Control-Tab is not a system hotkey, it is the - /// chord AppKit itself gives tab switching in every app with window tabs, and it is what - /// DataGrip, VS Code and Zed switch recent tabs with. Show Previous and Next Window Tab - /// have no default, since this is the chord AppKit would otherwise give them. + // Control-Tab is AppKit's own tab-switching chord, not a system hotkey; window tabs get no default so they never take it. .switchToRecentTab: .special(.tab, control: true), .switchToLeastRecentTab: .special(.tab, shift: true, control: true), .toggleWorkspaceRail: .character("0", command: true, option: true), @@ -801,10 +821,7 @@ struct KeyboardSettings: Codable, Equatable { ] } -// MARK: - Legacy Migration - -/// The pre-keyCode stored shape of a shortcut. Used only to migrate persisted -/// settings to BoundKey. +// The pre-keyCode stored shape, read only to migrate. private struct LegacyKeyCombo: Codable { let key: String var command = false diff --git a/apple/TablePro/Views/AIChat/ChatComposerTextView.swift b/apple/TablePro/Views/AIChat/ChatComposerTextView.swift index 9be8004b76..03c02c0025 100644 --- a/apple/TablePro/Views/AIChat/ChatComposerTextView.swift +++ b/apple/TablePro/Views/AIChat/ChatComposerTextView.swift @@ -1,8 +1,3 @@ -// -// ChatComposerTextView.swift -// TablePro -// - import AppKit import SwiftUI import UniformTypeIdentifiers @@ -75,18 +70,9 @@ struct ChatComposerTextView: NSViewRepresentable { scrollView.noteFocusRingMaskChanged() } - // Replacing the string outright while an input method has marked text cancels the - // composition. Routing through shouldChangeText/didChangeText also keeps the undo - // stack and the delegate notifications intact. + // Replacing the string under marked text cancels the input method's composition. if textView.string != text, !textView.hasMarkedText() { - let selected = textView.selectedRange() - let full = NSRange(location: 0, length: (textView.string as NSString).length) - if textView.shouldChangeText(in: full, replacementString: text) { - textView.textStorage?.replaceCharacters(in: full, with: text) - textView.didChangeText() - } - let clampedLocation = min(selected.location, (text as NSString).length) - textView.setSelectedRange(NSRange(location: clampedLocation, length: 0)) + textView.replaceAll(with: text) } textView.placeholder = placeholder @@ -198,11 +184,7 @@ struct ChatComposerTextView: NSViewRepresentable { } final class ChatComposerNSTextView: NSTextView { - /// The placeholder is painted in `draw(_:)`, which the accessibility tree never sees, so the - /// only thing that names this field to VoiceOver is the value set here. Keeping the two - /// together means no assignment path can leave the field nameless: guarding the call at one - /// caller is what left it unset since #2097, because `makeNSView` had already stored the same - /// string and the caller's comparison was never true again. + // draw(_:) paints the placeholder where VoiceOver never looks, so this setter is the only thing that names the field. var placeholder: String = "" { didSet { guard oldValue != placeholder else { return } @@ -282,10 +264,7 @@ final class ChatComposerNSTextView: NSTextView { return resigned } - /// Measured on macOS 27: unparenting the pane moves the window's first responder away without - /// ever sending `resignFirstResponder` here, so focus has to be re-read from the window rather - /// than waited for. Switching the trailing pane away and back otherwise left the composer - /// believing it still held focus, and the highlight painted over a field that did not. + // Measured on macOS 27: unparenting the pane moves first responder away without resignFirstResponder. override func viewDidMoveToWindow() { super.viewDidMoveToWindow() onFocusChange?(window?.firstResponder === self) @@ -316,6 +295,21 @@ final class ChatComposerNSTextView: NSTextView { onSizeChange?() } + // Through shouldChangeText and didChangeText, so undo and the delegate see the edit. + func replaceAll(with text: String) { + let selected = selectedRange() + let oldLength = (string as NSString).length + let full = NSRange(location: 0, length: oldLength) + if shouldChangeText(in: full, replacementString: text) { + textStorage?.replaceCharacters(in: full, with: text) + didChangeText() + } + let newLength = (string as NSString).length + // A caret at the old end, an empty composer included, follows the text, so typing after a slash pick lands after "/name ". + let caret = selected.location >= oldLength ? newLength : min(selected.location, newLength) + setSelectedRange(NSRange(location: caret, length: 0)) + } + override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) guard string.isEmpty, !placeholder.isEmpty else { return } @@ -359,10 +353,7 @@ final class ChatComposerNSTextView: NSTextView { } if let urls = pasteboard.readObjects(forClasses: [NSURL.self]) as? [URL], let fileURL = urls.first(where: { (try? $0.resourceValues(forKeys: [.contentTypeKey]))?.contentType?.conforms(to: .image) ?? false }) { - /// Identifying the file and reading it are separate answers. Folding the read into the - /// same `if let` made an unreadable image (an iCloud file still in the cloud, a network - /// volume that went away) fall through to `super.paste`, which pastes its path as text - /// into the prompt. The user asked for the picture and silently got a file URL. + // A separate read, so an unreadable image reports a failure instead of falling through to pasting its path. do { let data = try Data(contentsOf: fileURL) let uti = (try? fileURL.resourceValues(forKeys: [.contentTypeKey]))?.contentType?.identifier @@ -412,13 +403,7 @@ final class ChatComposerScrollView: NSScrollView { return scrollView } - /// The composer's rounded surface is drawn by SwiftUI, so AppKit has to be told the shape to - /// wrap; left to itself it rings the square bounds. This is the shape `ShortcutRecorderNSView` - /// uses for the same job, and the radius is the one the SwiftUI background reads. - /// - /// The document view carries the focus, but the ring belongs on the scroll view: measured on - /// macOS 27, `focusRingType` on the text view never produces a `drawFocusRingMask` call, while - /// on the scroll view it does, `.noBorder` included. + // SwiftUI draws the rounded surface, so AppKit needs its shape; on macOS 27 only the scroll view, not the text view, gets drawFocusRingMask. override func drawFocusRingMask() { NSBezierPath( roundedRect: bounds, @@ -429,8 +414,7 @@ final class ChatComposerScrollView: NSScrollView { override var focusRingMaskBounds: NSRect { bounds } - /// The mask is derived from `bounds`, and the composer grows from one line to five as the user - /// types, so the cached ring has to be invalidated with the size that produced it. + // The composer grows as the user types, and the cached ring keeps the size that produced it. override func setFrameSize(_ newSize: NSSize) { let changed = newSize != frame.size super.setFrameSize(newSize) diff --git a/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift index c076b89608..2b1d16eaa2 100644 --- a/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/KeyboardSettingsEntry.swift @@ -2,24 +2,26 @@ import SwiftUI internal struct KeyboardSettingsEntry: View { internal let context: SettingsPaneContext - @ObservedObject private var keyboard: SettingsSlice internal init(context: SettingsPaneContext) { self.context = context - self._keyboard = ObservedObject(wrappedValue: context.settings.keyboardSlice) } + // Never nil: SettingsPaneContext.filtersItsList(.keyboard) is true. internal var body: some View { - KeyboardSettingsView(settings: $keyboard.value) + if let filter = context.filter { + KeyboardSettingsView(keyboard: context.settings.keyboardSlice, filter: filter) + } } } +// Keyboard has no pages, and the navigation model never pushes another pane's route here. internal struct KeyboardSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } diff --git a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift index f2e4288fce..099bc9dd36 100644 --- a/apple/TablePro/Views/Settings/KeyboardSettingsView.swift +++ b/apple/TablePro/Views/Settings/KeyboardSettingsView.swift @@ -1,232 +1,215 @@ -// -// KeyboardSettingsView.swift -// TablePro -// -// Settings view for customizing keyboard shortcuts. -// - import AppKit import SwiftUI -/// Settings view for keyboard shortcut customization +// A List, not a grouped Form: a Form builds all 126 rows on first show, a List only the visible ones. struct KeyboardSettingsView: View { - @Binding var settings: KeyboardSettings - + @ObservedObject private var keyboard: SettingsSlice + @ObservedObject private var filter: SettingsPaneFilter @ObservedObject private var modules = AppModuleSettings.shared - @State private var searchText = "" - @State private var conflictAlert: ConflictAlertState? - @State private var systemReservedAlert: ShortcutAction? - @State private var reservedAlert: ReservedAlertState? - @State private var needsModifierAlert: ShortcutAction? - @State private var confirmsReset = false - - private var content: some View { - VStack(spacing: 0) { - NativeSearchField( - text: $searchText, - placeholder: String(localized: "Search shortcuts…"), - accessibilityIdentifier: "shortcut-search" - ) - .padding(.horizontal, 20) - .padding(.top, 16) - .padding(.bottom, 8) - - Form { - ForEach(ShortcutCategory.allCases) { category in - let actions = filteredActions(for: category) - if !actions.isEmpty { - Section(category.displayName) { - ForEach(actions) { action in - shortcutRow(for: action) - } - } - } - } + @StateObject private var session: ShortcutRecordingSession + @State private var selection: ShortcutAction? + @State private var confirmsRestore = false + + init(keyboard: SettingsSlice, filter: SettingsPaneFilter) { + _keyboard = ObservedObject(wrappedValue: keyboard) + _filter = ObservedObject(wrappedValue: filter) + _session = StateObject(wrappedValue: ShortcutRecordingSession(keyboard: keyboard)) + } - Section { - HStack { - Spacer() - Button(String(localized: "Reset to Defaults")) { - confirmsReset = true + var body: some View { + let settings = keyboard.value + let sections = ShortcutAction.settingsSections( + matching: filter.query, + in: settings, + enabledModules: modules.enabledModules + ) + SettingsFullPageList { + List(selection: $selection) { + ForEach(sections) { section in + Section(section.category.displayName) { + ForEach(section.actions, id: \.self) { action in + row(for: action, in: settings) } - .disabled(settings.shortcuts.isEmpty) } } } - .formStyle(.grouped) - } - } - - var body: some View { - content - .alert(String(localized: "Reset All Shortcuts?"), isPresented: $confirmsReset) { - Button(String(localized: "Reset"), role: .destructive) { - settings = .default - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - Text(String(localized: "Every custom shortcut goes back to its default.")) - } - .alert( - String(localized: "Shortcut Conflict"), - isPresented: Binding( - get: { conflictAlert != nil }, - set: { if !$0 { conflictAlert = nil } } - ) - ) { - Button(String(localized: "Cancel"), role: .cancel) { - conflictAlert = nil - } - Button(String(localized: "Reassign")) { - if let state = conflictAlert { - if settings.isCustomized(state.conflictingAction) { - settings.clearShortcut(for: state.conflictingAction) - } - settings.setShortcut(state.combo, for: state.action) + .contextMenu(forSelectionType: ShortcutAction.self) { actions in + if let action = actions.first { + rowMenu(for: action, in: settings) + } + } primaryAction: { actions in + if let action = actions.first { + session.begin(action) } - conflictAlert = nil } - } message: { - if let state = conflictAlert { - Text( - String( - format: String(localized: "%@ is already used by \"%@\" in %@. Reassigning removes it from that action."), - state.combo.displayString, - state.conflictingAction.displayName, - state.conflictingAction.category.displayName - ) - ) + } emptyState: { + if sections.isEmpty { + UnavailableStateView.search(text: filter.query) } - } - .alert( - String(localized: "System Reserved Shortcut"), - isPresented: Binding( - get: { systemReservedAlert != nil }, - set: { if !$0 { systemReservedAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - systemReservedAlert = nil + } bar: { + SettingsListBar { + Text(Self.summary(customized: settings.customizedCount)) + .foregroundStyle(.secondary) + } trailing: { + Button(String(localized: "Restore Defaults…")) { + confirmsRestore = true + } + .disabled(settings.shortcuts.isEmpty) + .accessibilityIdentifier("shortcut-restore-defaults") } - } message: { - Text(String(localized: "This shortcut is reserved by macOS and cannot be assigned.")) } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-keyboard") .alert( - String(localized: "Reserved Shortcut"), + session.reassignment?.title ?? "", isPresented: Binding( - get: { reservedAlert != nil }, - set: { if !$0 { reservedAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - reservedAlert = nil - } - } message: { - if let state = reservedAlert { - Text( - String( - format: String(localized: "This shortcut is reserved for \"%@\" and cannot be assigned."), - state.name - ) - ) + get: { session.reassignment != nil }, + set: { if !$0 { session.dismissReassignment() } } + ), + presenting: session.reassignment + ) { request in + Button(String(localized: "Reassign")) { + session.confirm(request) } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { request in + Text(request.message) } - .alert( - String(localized: "Modifier Key Required"), - isPresented: Binding( - get: { needsModifierAlert != nil }, - set: { if !$0 { needsModifierAlert = nil } } - ) - ) { - Button(String(localized: "OK"), role: .cancel) { - needsModifierAlert = nil + .alert(String(localized: "Restore Default Shortcuts?"), isPresented: $confirmsRestore) { + Button(String(localized: "Restore Defaults"), role: .destructive) { + keyboard.value = .default } + Button(String(localized: "Cancel"), role: .cancel) {} } message: { - Text(String(localized: "This action needs ⌘ or ⌃. Option and Shift can join them, but cannot hold a shortcut on their own.")) + Text(String(localized: "Every shortcut you changed goes back to its default.")) } - .onAppear { - SystemHotkeyChecker.shared.reload() + .onDisappear { + session.reset() } } - // MARK: - Shortcut Row + private func row(for action: ShortcutAction, in settings: KeyboardSettings) -> some View { + let isArmed = session.recording == action + return ShortcutRow( + action: action, + key: settings.boundKey(for: action), + isCustomized: settings.isCustomized(action), + claimant: settings.defaultClaimant(for: action), + refusal: session.feedback?.action == action ? session.feedback?.message : nil, + isArmed: isArmed, + heldModifiers: isArmed ? session.heldModifiers : [], + keyboard: keyboard, + session: session + ) + } @ViewBuilder - private func shortcutRow(for action: ShortcutAction) -> some View { - HStack(spacing: 8) { - Text(action.displayName) - .frame(maxWidth: .infinity, alignment: .leading) + private func rowMenu(for action: ShortcutAction, in settings: KeyboardSettings) -> some View { + Button(String(localized: "Record Shortcut")) { + session.begin(action) + } + Button(String(localized: "Remove Shortcut")) { + keyboard.value = keyboard.value.clearing(action) + } + .disabled(settings.boundKey(for: action) == nil) + Button(String(localized: "Reset to Default")) { + keyboard.value = keyboard.value.resetting(action) + } + .disabled(!settings.isCustomized(action)) + } + + static func summary(customized count: Int) -> String { + count == 0 + ? String(localized: "No custom shortcuts") + : String(format: String(localized: "%lld customized"), count) + } +} + +// Plain values only, so arming or a refusal re-renders just the rows it touches. +private struct ShortcutRow: View { + let action: ShortcutAction + let key: BoundKey? + let isCustomized: Bool + let claimant: ShortcutAction? + let refusal: String? + let isArmed: Bool + let heldModifiers: NSEvent.ModifierFlags + let keyboard: SettingsSlice + let session: ShortcutRecordingSession - if settings.isCustomized(action) { - Button { - settings.resetToDefault(for: action) - } label: { - Image(systemName: "arrow.uturn.backward") + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(action.displayName) + note + } + Spacer(minLength: 12) + if isCustomized { + resetButton + } + ShortcutRecorderField( + action: action, + key: key, + isArmed: isArmed, + heldModifiers: heldModifiers, + session: session + ) + .fixedSize() + } + .accessibilityElement(children: .contain) + .accessibilityActions { + Button(String(localized: "Record Shortcut")) { + session.begin(action) + } + if key != nil { + Button(String(localized: "Remove Shortcut")) { + keyboard.value = keyboard.value.clearing(action) } - .buttonStyle(.borderless) - .controlSize(.small) - .help(String(localized: "Reset to default")) - .accessibilityLabel(String(localized: "Reset to default")) } - - ShortcutRecorderView( - combo: Binding( - get: { settings.shortcut(for: action) }, - set: { _ in } - ), - onRecord: { newCombo in - handleRecord(newCombo, for: action) - }, - onClear: { - settings.clearShortcut(for: action) - }, - onUnusableModifiers: { - needsModifierAlert = action + if isCustomized { + Button(String(localized: "Reset to Default")) { + keyboard.value = keyboard.value.resetting(action) } - ) - .frame(width: 160, height: 24) + } } } - // MARK: - Helpers - - private func filteredActions(for category: ShortcutCategory) -> [ShortcutAction] { - let categoryActions = ShortcutAction.settingsRows(in: category, enabledModules: modules.enabledModules) - if searchText.isEmpty { - return categoryActions + @ViewBuilder private var note: some View { + if let refusal { + // One Text, not a NoticeLabel: a Label moves the row separator to its title, past the glyph. + (Text(Image(systemName: NoticeSeverity.warning.symbolName)).foregroundColor(NoticeSeverity.warning.tint) + + Text(verbatim: " " + refusal)) + .font(.subheadline) + .foregroundStyle(.secondary) + } else if let claimant, let fallback = KeyboardSettings.defaultShortcuts[action] { + Text(String( + format: String(localized: "Default %@ is used by “%@”."), + fallback.displayString, + claimant.displayName + )) + .font(.subheadline) + .foregroundStyle(.secondary) } - let query = searchText.lowercased() - return categoryActions.filter { $0.displayName.lowercased().contains(query) } } - private func handleRecord(_ key: BoundKey, for action: ShortcutAction) { - if !key.hasModifier, !action.allowsBareKey, !key.isFunctionKey { - needsModifierAlert = action - return + private var resetButton: some View { + Button { + keyboard.value = keyboard.value.resetting(action) + } label: { + Image(systemName: "arrow.uturn.backward") + .frame(minWidth: 20, minHeight: 20) + .contentShape(Rectangle()) } + .buttonStyle(.borderless) + .help(resetHelp) + .accessibilityLabel(String(format: String(localized: "Reset %@ to default"), action.displayName)) + .accessibilityIdentifier("shortcut-reset-\(action.rawValue)") + } - switch ShortcutConflictResolver.resolve(key, for: action, in: settings) { - case .none: - settings.setShortcut(key, for: action) - case .systemReserved: - systemReservedAlert = action - case .reserved(let name): - reservedAlert = ReservedAlertState(action: action, name: name) - case .otherAction(let other): - conflictAlert = ConflictAlertState(action: action, conflictingAction: other, combo: key) + private var resetHelp: String { + guard let fallback = KeyboardSettings.defaultShortcuts[action] else { + return String(localized: "Reset to None") } + return String(format: String(localized: "Reset to %@"), fallback.displayString) } } - -// MARK: - Alert State - -private struct ConflictAlertState { - let action: ShortcutAction - let conflictingAction: ShortcutAction - let combo: BoundKey -} - -private struct ReservedAlertState { - let action: ShortcutAction - let name: String -} diff --git a/apple/TablePro/Views/Settings/ShortcutRecorderButton.swift b/apple/TablePro/Views/Settings/ShortcutRecorderButton.swift new file mode 100644 index 0000000000..ff99266f89 --- /dev/null +++ b/apple/TablePro/Views/Settings/ShortcutRecorderButton.swift @@ -0,0 +1,153 @@ +import AppKit +import SwiftUI + +struct ShortcutRecorderLook: Equatable { + let title: String + let isPlaceholder: Bool + let isArmed: Bool + let accessibilityValue: String + + init(key: BoundKey?, isArmed: Bool, heldModifiers: NSEvent.ModifierFlags) { + self.isArmed = isArmed + if isArmed { + let held = Self.glyphs(for: heldModifiers) + title = held.isEmpty ? String(localized: "Type Shortcut") : held + isPlaceholder = false + accessibilityValue = String(localized: "Recording") + } else if let key, !key.isCleared { + title = key.displayString + isPlaceholder = false + accessibilityValue = key.displayString + } else { + title = String(localized: "None") + isPlaceholder = true + accessibilityValue = title + } + } + + static func glyphs(for flags: NSEvent.ModifierFlags) -> String { + var glyphs = "" + if flags.contains(.control) { glyphs += "⌃" } + if flags.contains(.option) { glyphs += "⌥" } + if flags.contains(.shift) { glyphs += "⇧" } + if flags.contains(.command) { glyphs += "⌘" } + return glyphs + } +} + +// AppKit so one control carries the key title, the armed look and its accessibility value; SwiftUI bordered buttons ignore foregroundStyle. +final class ShortcutRecorderButton: NSButton { + private static let minimumWidth: CGFloat = 112 + + private(set) var shortcutAction: ShortcutAction? + private weak var session: ShortcutRecordingSession? + private var look: ShortcutRecorderLook? + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + // Momentary push in every state, so the role stays AXButton; a toggle type reads as a checkbox. + setButtonType(.momentaryPushIn) + bezelStyle = .push + font = .systemFont(ofSize: NSFont.systemFontSize) + setContentHuggingPriority(.required, for: .horizontal) + target = self + action = #selector(press(_:)) + let help = String(localized: "Press to record a new shortcut. Delete removes it, Escape cancels.") + toolTip = help + setAccessibilityHelp(help) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override var intrinsicContentSize: NSSize { + var size = super.intrinsicContentSize + size.width = max(size.width, Self.minimumWidth) + return size + } + + // Return goes to the window's default button unless the focused recorder claims it. + override func keyDown(with event: NSEvent) { + if event.keyCode == KeyCode.return.rawValue || event.keyCode == KeyCode.enter.rawValue { + performClick(nil) + } else { + super.keyDown(with: event) + } + } + + func configure(action: ShortcutAction, session: ShortcutRecordingSession) { + self.session = session + guard shortcutAction != action else { return } + shortcutAction = action + setAccessibilityLabel(action.displayName) + setAccessibilityIdentifier("shortcut-recorder-\(action.rawValue)") + } + + func apply(_ wanted: ShortcutRecorderLook) { + let current = look + guard wanted != current else { return } + look = wanted + if wanted.title != current?.title || wanted.isPlaceholder != current?.isPlaceholder { + if wanted.isPlaceholder { + attributedTitle = Self.placeholderTitle(wanted.title) + } else { + title = wanted.title + } + invalidateIntrinsicContentSize() + } + if wanted.isArmed != current?.isArmed { + bezelColor = wanted.isArmed ? .controlAccentColor : nil + } + if wanted.accessibilityValue != current?.accessibilityValue { + setAccessibilityValue(wanted.accessibilityValue) + if current != nil { + NSAccessibility.post(element: self, notification: .valueChanged) + } + } + } + + func cancelOwnRecording() { + guard let shortcutAction, let session, session.recording == shortcutAction else { return } + session.cancel() + } + + @objc private func press(_ sender: Any?) { + guard let shortcutAction else { return } + session?.toggle(shortcutAction, anchor: self) + } + + private static func placeholderTitle(_ title: String) -> NSAttributedString { + let paragraph = NSMutableParagraphStyle() + paragraph.alignment = .center + return NSAttributedString(string: title, attributes: [ + .foregroundColor: NSColor.secondaryLabelColor, + .font: NSFont.systemFont(ofSize: NSFont.systemFontSize), + .paragraphStyle: paragraph, + ]) + } +} + +struct ShortcutRecorderField: NSViewRepresentable { + let action: ShortcutAction + let key: BoundKey? + let isArmed: Bool + let heldModifiers: NSEvent.ModifierFlags + let session: ShortcutRecordingSession + + func makeNSView(context: Context) -> ShortcutRecorderButton { + let button = ShortcutRecorderButton(frame: .zero) + updateNSView(button, context: context) + return button + } + + func updateNSView(_ button: ShortcutRecorderButton, context: Context) { + button.configure(action: action, session: session) + button.apply(ShortcutRecorderLook(key: key, isArmed: isArmed, heldModifiers: heldModifiers)) + } + + static func dismantleNSView(_ button: ShortcutRecorderButton, coordinator: Void) { + button.cancelOwnRecording() + } +} diff --git a/apple/TablePro/Views/Settings/ShortcutRecorderView.swift b/apple/TablePro/Views/Settings/ShortcutRecorderView.swift deleted file mode 100644 index 1d0826f062..0000000000 --- a/apple/TablePro/Views/Settings/ShortcutRecorderView.swift +++ /dev/null @@ -1,322 +0,0 @@ -// -// ShortcutRecorderView.swift -// TablePro -// -// Press-to-record keyboard shortcut capture component. -// - -import AppKit -import os -import SwiftUI - -// MARK: - ShortcutRecorderNSView - -/// AppKit NSView that captures keyboard shortcuts via press-to-record interaction -final class ShortcutRecorderNSView: NSView { - /// Callback when a valid shortcut is recorded - var onRecord: ((BoundKey) -> Void)? - - /// Callback when the shortcut is cleared (Delete key while recording) - var onClear: (() -> Void)? - - /// Callback when the captured combo carries no modifier the menu can use, so the - /// caller can say why instead of leaving the recorder to beep with no explanation. - var onUnusableModifiers: (() -> Void)? - - /// The currently displayed key combo - var currentCombo: BoundKey? { - didSet { - needsDisplay = true - NSAccessibility.post(element: self, notification: .valueChanged) - } - } - - /// Whether the view is currently in recording mode - private var isRecording = false { - didSet { - guard isRecording != oldValue else { return } - if isRecording { startRecordingMonitor() } else { stopRecordingMonitor() } - needsDisplay = true - NSAccessibility.post(element: self, notification: .valueChanged) - } - } - - /// A menu key equivalent is consumed in `sendEvent` before the responder chain runs, so - /// `keyDown` never sees Command W and the menu command fires instead of being recorded. A - /// local monitor runs earlier than menu dispatch, which is the only place the key is still - /// interceptable. - private let recordingMonitor = OSAllocatedUnfairLock(uncheckedState: nil) - - /// Currently held modifier flags during recording (for live display) - private var activeModifiers: NSEvent.ModifierFlags = [] - - // MARK: - Initialization - - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - wantsLayer = true - layer?.cornerRadius = 6 - focusRingType = .exterior - setAccessibilityRole(.button) - } - - override func drawFocusRingMask() { - NSBezierPath(roundedRect: bounds, xRadius: 6, yRadius: 6).fill() - } - - override var focusRingMaskBounds: NSRect { bounds } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - // MARK: - First Responder - - override var acceptsFirstResponder: Bool { true } - - /// Focus alone does not start recording. Full Keyboard Access moves focus with Tab, and - /// arming on focus swallowed that Tab and trapped the user in this field. Recording - /// starts on a deliberate click, Space, Return, or an accessibility press. - override func becomeFirstResponder() -> Bool { - let result = super.becomeFirstResponder() - if result { - activeModifiers = [] - } - return result - } - - override func resignFirstResponder() -> Bool { - let result = super.resignFirstResponder() - if result { - isRecording = false - activeModifiers = [] - } - return result - } - - // MARK: - Mouse Handling - - override func mouseDown(with event: NSEvent) { - window?.makeFirstResponder(self) - isRecording = true - } - - // MARK: - Keyboard Handling - - override func keyDown(with event: NSEvent) { - guard !isRecording else { return } - let isActivation = event.keyCode == KeyCode.space.rawValue - || event.keyCode == KeyCode.return.rawValue - guard isActivation else { - super.keyDown(with: event) - return - } - activeModifiers = [] - isRecording = true - } - - private func startRecordingMonitor() { - guard recordingMonitor.withLockUnchecked({ $0 }) == nil else { return } - let monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged]) { [weak self] event in - guard let self else { return event } - return self.handleRecordingEvent(event) - } - recordingMonitor.withLockUnchecked { $0 = monitor } - } - - private func stopRecordingMonitor() { - guard let monitor = recordingMonitor.withLockUnchecked({ $0 }) else { return } - NSEvent.removeMonitor(monitor) - recordingMonitor.withLockUnchecked { $0 = nil } - } - - /// A local monitor is app-wide, so anything arriving while this view's window is not key - /// belongs to another window and has to pass through untouched. - func handleRecordingEvent(_ event: NSEvent) -> NSEvent? { - guard isRecording, window?.isKeyWindow == true else { return event } - guard event.type != .flagsChanged else { - activeModifiers = event.modifierFlags.intersection(.deviceIndependentFlagsMask) - needsDisplay = true - return nil - } - - let isBareKey = !event.modifierFlags.contains(.command) && !event.modifierFlags.contains(.control) - - if event.keyCode == KeyCode.escape.rawValue, isBareKey { - endRecording() - return nil - } - if event.keyCode == KeyCode.delete.rawValue, isBareKey { - onClear?() - endRecording() - return nil - } - guard let combo = BoundKey(from: event) else { - endRecording() - onUnusableModifiers?() - return nil - } - onRecord?(combo) - endRecording() - return nil - } - - private func endRecording() { - isRecording = false - activeModifiers = [] - window?.makeFirstResponder(nil) - } - - override func viewDidMoveToWindow() { - super.viewDidMoveToWindow() - guard window == nil else { return } - isRecording = false - } - - deinit { - guard let monitor = recordingMonitor.withLockUnchecked({ $0 }) else { return } - NSEvent.removeMonitor(monitor) - } - - // MARK: - Drawing - - override func draw(_ dirtyRect: NSRect) { - let bounds = self.bounds - let isArmed = isRecording && window?.isKeyWindow == true && NSApp.isActive - - if isArmed { - NSColor.controlAccentColor.withAlphaComponent(0.1).setFill() - } else { - NSColor.controlBackgroundColor.setFill() - } - let bgPath = NSBezierPath(roundedRect: bounds, xRadius: 6, yRadius: 6) - bgPath.fill() - - if isArmed { - NSColor.controlAccentColor.setStroke() - } else { - NSColor.separatorColor.setStroke() - } - let borderPath = NSBezierPath( - roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), - xRadius: 6, - yRadius: 6 - ) - borderPath.lineWidth = isArmed ? 2.0 : 1.0 - borderPath.stroke() - - let text = displayText - let textColor: NSColor = isRecording ? .secondaryLabelColor : .labelColor - let font = NSFont.systemFont(ofSize: 12, weight: .medium) - let attributes: [NSAttributedString.Key: Any] = [ - .font: font, - .foregroundColor: textColor - ] - let attrString = NSAttributedString(string: text, attributes: attributes) - let textSize = attrString.size() - let textRect = NSRect( - x: (bounds.width - textSize.width) / 2, - y: (bounds.height - textSize.height) / 2, - width: textSize.width, - height: textSize.height - ) - attrString.draw(in: textRect) - } - - /// The text to display in the view - private var displayText: String { - if isRecording { - let modifierString = modifierDisplayString - if modifierString.isEmpty { - return String(localized: "Type shortcut…") - } - return modifierString - } - - if let combo = currentCombo, !combo.isCleared { - return combo.displayString - } - return String(localized: "None") - } - - /// Build modifier display string from currently held modifiers - private var modifierDisplayString: String { - var parts: [String] = [] - if activeModifiers.contains(.control) { parts.append("⌃") } - if activeModifiers.contains(.option) { parts.append("⌥") } - if activeModifiers.contains(.shift) { parts.append("⇧") } - if activeModifiers.contains(.command) { parts.append("⌘") } - return parts.joined() - } - - // MARK: - Accessibility - - override func isAccessibilityElement() -> Bool { true } - - override func accessibilityRole() -> NSAccessibility.Role? { .button } - - override func accessibilityLabel() -> String? { - String(localized: "Shortcut recorder") - } - - override func accessibilityValue() -> Any? { - if isRecording { - return String(localized: "Recording shortcut") - } - if let combo = currentCombo, !combo.isCleared { - return combo.displayString - } - return String(localized: "None") - } - - override func accessibilityPerformPress() -> Bool { - window?.makeFirstResponder(self) - isRecording = true - return true - } - - // MARK: - Intrinsic Size - - override var intrinsicContentSize: NSSize { - NSSize(width: 160, height: 24) - } -} - -// MARK: - ShortcutRecorderView (SwiftUI Wrapper) - -/// SwiftUI wrapper for the AppKit shortcut recorder -struct ShortcutRecorderView: NSViewRepresentable { - @Binding var combo: BoundKey? - - /// Called when a new combo is recorded (before setting binding) - var onRecord: ((BoundKey) -> Void)? - - /// Called when the shortcut is cleared - var onClear: (() -> Void)? - - /// Called when the pressed combo carries no modifier a menu key equivalent can use. - var onUnusableModifiers: (() -> Void)? - - func makeNSView(context: Context) -> ShortcutRecorderNSView { - let view = ShortcutRecorderNSView() - view.currentCombo = combo - view.onRecord = { newCombo in - onRecord?(newCombo) - } - view.onClear = { - onClear?() - } - view.onUnusableModifiers = { - onUnusableModifiers?() - } - return view - } - - func updateNSView(_ nsView: ShortcutRecorderNSView, context: Context) { - nsView.currentCombo = combo - nsView.onRecord = { [onRecord] newCombo in onRecord?(newCombo) } - nsView.onClear = { [onClear] in onClear?() } - nsView.onUnusableModifiers = { [onUnusableModifiers] in onUnusableModifiers?() } - } -} diff --git a/apple/TablePro/Views/Settings/ShortcutRecordingSession.swift b/apple/TablePro/Views/Settings/ShortcutRecordingSession.swift new file mode 100644 index 0000000000..fe373e0c8d --- /dev/null +++ b/apple/TablePro/Views/Settings/ShortcutRecordingSession.swift @@ -0,0 +1,308 @@ +import AppKit +import Combine +import os + +enum ShortcutRecordingStep: Equatable { + case pass + case cancelAndPass + case holdModifiers(NSEvent.ModifierFlags) + case swallow + case cancel + case remove + case refuse(String) + case capture(BoundKey) +} + +struct ShortcutRecordingFeedback: Equatable { + let action: ShortcutAction + let message: String +} + +struct ShortcutReassignment: Equatable { + let action: ShortcutAction + let key: BoundKey + let holders: [ShortcutAction] + + var title: String { + String(format: String(localized: "Reassign %@ to “%@”?"), key.displayString, action.displayName) + } + + var message: String { + if holders.count == 1, let holder = holders.first { + return String( + format: String(localized: "It is used by “%@” in %@, which will have no shortcut."), + holder.displayName, + holder.category.displayName + ) + } + let names = holders.map { String(format: String(localized: "“%@”"), $0.displayName) } + return String( + format: String(localized: "It is used by %@. They will have no shortcut."), + ListFormatter.localizedString(byJoining: names) + ) + } +} + +@MainActor +final class ShortcutRecordingSession: ObservableObject { + private struct Tokens { + var monitor: Any? + var resignObserver: (any NSObjectProtocol)? + } + + @Published private(set) var recording: ShortcutAction? + @Published private(set) var heldModifiers: NSEvent.ModifierFlags = [] + @Published private(set) var feedback: ShortcutRecordingFeedback? + @Published private(set) var reassignment: ShortcutReassignment? + + private let keyboard: SettingsSlice + private let signalRefusal: @MainActor (String) -> Void + private weak var window: NSWindow? + private weak var anchor: NSView? + // A lock, so the nonisolated deinit can still remove the monitor. + private let tokens = OSAllocatedUnfairLock(uncheckedState: Tokens()) + + init( + keyboard: SettingsSlice, + signalRefusal: @escaping @MainActor (String) -> Void = { ShortcutRecordingSession.beepAndAnnounce($0) } + ) { + self.keyboard = keyboard + self.signalRefusal = signalRefusal + } + + deinit { + let current = tokens.withLockUnchecked { $0 } + if let monitor = current.monitor { + NSEvent.removeMonitor(monitor) + } + if let observer = current.resignObserver { + NotificationCenter.default.removeObserver(observer) + } + } + + // A local monitor, because AppKit hands a menu key equivalent such as Cmd-W to the menu before any keyDown. + func begin(_ action: ShortcutAction, anchor: NSView? = nil) { + cancel() + SystemHotkeyChecker.shared.reload() + let window = anchor?.window ?? NSApp.keyWindow + self.window = window + self.anchor = anchor ?? window?.firstResponder as? NSView + if feedback?.action != action { + feedback = nil + } + recording = action + install(observing: window) + } + + func toggle(_ action: ShortcutAction, anchor: NSView? = nil) { + if recording == action { + cancel() + } else { + begin(action, anchor: anchor) + } + } + + // Never moves focus: the control that started recording keeps it. + func cancel() { + let current = tokens.withLockUnchecked { tokens -> Tokens in + let old = tokens + tokens = Tokens() + return old + } + if let monitor = current.monitor { + NSEvent.removeMonitor(monitor) + } + if let observer = current.resignObserver { + NotificationCenter.default.removeObserver(observer) + } + window = nil + anchor = nil + if recording != nil { + recording = nil + } + if !heldModifiers.isEmpty { + heldModifiers = [] + } + } + + func reset() { + cancel() + feedback = nil + } + + func confirm(_ request: ShortcutReassignment) { + reassignment = nil + keyboard.value = keyboard.value.reassigning( + request.key, + to: request.action, + enabledModules: AppModule.storedEnabledModules() + ) + } + + func dismissReassignment() { + reassignment = nil + } + + @discardableResult + func perform(_ step: ShortcutRecordingStep, for action: ShortcutAction) -> Bool { + switch step { + case .pass: + return false + case .cancelAndPass: + cancel() + return false + case .holdModifiers(let flags): + if heldModifiers != flags { + heldModifiers = flags + } + return true + case .swallow: + return true + case .cancel: + cancel() + return true + case .remove: + finish(action) + keyboard.value = keyboard.value.clearing(action) + return true + case .refuse(let message): + refuse(message, for: action) + return true + case .capture(let key): + capture(key, for: action) + return true + } + } + + nonisolated static func classify( + _ event: NSEvent, + recording action: ShortcutAction, + isInRecordingWindow: Bool, + hitsRecordingButton: Bool + ) -> ShortcutRecordingStep { + guard isInRecordingWindow else { return .pass } + switch event.type { + case .leftMouseDown, .rightMouseDown, .otherMouseDown: + // The button's own action toggles recording off. + return hitsRecordingButton ? .pass : .cancelAndPass + case .flagsChanged: + return .holdModifiers(event.modifierFlags.intersection(chordModifiers)) + case .keyDown: + break + default: + return .pass + } + if event.isARepeat { + return .swallow + } + let modifiers = event.modifierFlags.intersection(chordModifiers) + switch event.keyCode { + case KeyCode.tab.rawValue where modifiers.isDisjoint(with: [.command, .control, .option]): + return .cancelAndPass + case KeyCode.escape.rawValue where modifiers.isEmpty: + return .cancel + case KeyCode.delete.rawValue where modifiers.isEmpty: + return .remove + default: + let key = BoundKey(capturing: event) + return action.accepts(key) ? .capture(key) : .refuse(action.modifierRefusal) + } + } + + nonisolated private static let chordModifiers: NSEvent.ModifierFlags = [.command, .option, .shift, .control] + + static func beepAndAnnounce(_ message: String) { + NSSound.beep() + NSAccessibility.post( + element: NSApp as Any, + notification: .announcementRequested, + userInfo: [ + .announcement: message, + .priority: NSAccessibilityPriorityLevel.high.rawValue, + ] + ) + } + + private func install(observing window: NSWindow?) { + let monitor = NSEvent.addLocalMonitorForEvents( + matching: [.keyDown, .flagsChanged, .leftMouseDown, .rightMouseDown, .otherMouseDown] + ) { [weak self] nsEvent in + nonisolated(unsafe) let event = nsEvent + let consumed = MainActor.assumeIsolated { self?.handle(event) ?? false } + return consumed ? nil : nsEvent + } + let observer = window.map { window in + NotificationCenter.default.addObserver( + forName: NSWindow.didResignKeyNotification, + object: window, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.cancel() } + } + } + tokens.withLockUnchecked { $0 = Tokens(monitor: monitor, resignObserver: observer) } + } + + private func handle(_ event: NSEvent) -> Bool { + guard let action = recording else { return false } + // The pane's host is hidden, not removed, when another pane shows. + if let anchor, anchor.window == nil || anchor.isHiddenOrHasHiddenAncestor { + cancel() + return false + } + let isInWindow = window.map { event.window === $0 && $0.isKeyWindow } ?? false + let isMouseDown = [.leftMouseDown, .rightMouseDown, .otherMouseDown].contains(event.type) + let step = Self.classify( + event, + recording: action, + isInRecordingWindow: isInWindow, + hitsRecordingButton: isMouseDown && Self.recorderAction(at: event) == action + ) + return perform(step, for: action) + } + + private static func recorderAction(at event: NSEvent) -> ShortcutAction? { + guard let contentView = event.window?.contentView else { return nil } + let point = contentView.superview?.convert(event.locationInWindow, from: nil) ?? event.locationInWindow + var view = contentView.hitTest(point) + while let current = view { + if let button = current as? ShortcutRecorderButton { + return button.shortcutAction + } + view = current.superview + } + return nil + } + + private func capture(_ key: BoundKey, for action: ShortcutAction) { + let settings = keyboard.value + switch ShortcutConflictResolver.resolve(key, for: action, in: settings) { + case .systemReserved: + refuse(String(format: String(localized: "%@ is used by macOS."), key.displayString), for: action) + case .reserved(let name): + refuse(String(format: String(localized: "%@ is used by “%@”."), key.displayString, name), for: action) + case .otherAction: + finish(action) + reassignment = ShortcutReassignment( + action: action, + key: key, + holders: settings.conflicts(for: key, excluding: action, enabledModules: AppModule.storedEnabledModules()) + ) + case .none: + finish(action) + keyboard.value = settings.assigning(key, to: action) + } + } + + private func refuse(_ message: String, for action: ShortcutAction) { + feedback = ShortcutRecordingFeedback(action: action, message: message) + signalRefusal(message) + } + + private func finish(_ action: ShortcutAction) { + cancel() + if feedback?.action == action { + feedback = nil + } + } +} diff --git a/apple/TableProTests/Models/KeyboardShortcutTests.swift b/apple/TableProTests/Models/KeyboardShortcutTests.swift index 477c32dbd4..20896182c9 100644 --- a/apple/TableProTests/Models/KeyboardShortcutTests.swift +++ b/apple/TableProTests/Models/KeyboardShortcutTests.swift @@ -1,12 +1,3 @@ -// -// KeyboardShortcutTests.swift -// TableProTests -// -// Pins the keyboard shortcut model: keyCode-based defaults, context-scoped -// conflict detection, the built-in editor shortcut registry, bare-key handling, -// and migration from the legacy character-string storage. -// - import AppKit import Foundation @testable import TablePro @@ -27,9 +18,7 @@ struct EditorBuiltInNameTests { } struct DefaultShortcutHygieneTests { - /// Control-Tab is not a system hotkey the way Control-1 is (that one switches Spaces, which is - /// why this rule exists). It is the chord AppKit itself gives tab switching in every app with - /// window tabs, so the recent-tab commands are the one exception, and only on Tab. + // Control-1 switches Spaces, which is why the rule exists; Control-Tab is AppKit's own tab switching. private static let controlTabDefaults: Set = [.switchToRecentTab, .switchToLeastRecentTab] @Test("No default uses Control without Command, apart from Control-Tab tab switching") @@ -112,6 +101,20 @@ struct ReservedShortcutTests { #expect(ShortcutAction.reservedConflict(for: key, context: .global) != nil) } + @Test("Shift and Option text keys are reserved while text can have focus", arguments: [ + BoundKey.special(.delete, shift: true), + .special(.forwardDelete, shift: true), + .special(.space, shift: true), + .special(.space, option: true), + .special(.escape, option: true), + ]) + func textInputKeysAreReserved(key: BoundKey) { + #expect(ShortcutAction.reservedConflict(for: key, context: .editor) != nil) + #expect(ShortcutAction.reservedConflict(for: key, context: .global) != nil) + #expect(ShortcutAction.reservedConflict(for: key, context: .dataGrid) == nil) + #expect(ShortcutAction.addRow.shadowsStandardTextEditingBinding(key)) + } + @Test("Cmd+Delete does not conflict in data-grid context because focus resolves it") func commandDeleteDoesNotConflictInGrid() { let key = BoundKey.special(.delete, command: true) @@ -175,11 +178,13 @@ struct StandardTextEditingBindingTests { } struct BareKeyValidationTests { - @Test("Grid actions allow bare keys") - func gridActionsAllowBareKeys() { + // Changed on purpose: nothing dispatches a bare key for Delete or Clear Selection. + @Test("Only Preview FK Reference allows a bare key") + func onlyPreviewFKReferenceAllowsBareKeys() { #expect(ShortcutAction.previewFKReference.allowsBareKey) - #expect(ShortcutAction.clearSelection.allowsBareKey) - #expect(ShortcutAction.delete.allowsBareKey) + #expect(!ShortcutAction.clearSelection.allowsBareKey) + #expect(!ShortcutAction.delete.allowsBareKey) + #expect(ShortcutAction.allCases.filter { $0.allowsBareKey } == [.previewFKReference]) } @Test("Menu actions reject bare keys") @@ -188,9 +193,7 @@ struct BareKeyValidationTests { #expect(!ShortcutAction.executeQuery.allowsBareKey) } - /// The recorder tells the user a shortcut needs Command or Control, so the capture rule has - /// to be exactly that. Option and Shift only ever qualify a combo, they never carry one, and - /// a letter key held with either alone is a text-input keystroke rather than a shortcut. + // A letter with Option or Shift alone is typing, not a shortcut. @Test("Option and Shift cannot hold a shortcut without Command or Control") func optionAndShiftAloneAreNotRecordable() { func capture(_ flags: NSEvent.ModifierFlags) -> BoundKey? { @@ -299,6 +302,12 @@ struct KeyboardSettingsSanitizeTests { #expect(sanitized.shortcut(for: .toggleInspector) == KeyboardSettings.defaultShortcuts[.toggleInspector]) } + @Test("A bare-key override on Delete is dropped on load, since nothing dispatches it") + func dropsBareDeleteOverride() { + let settings = KeyboardSettings(shortcuts: [ShortcutAction.delete.rawValue: .special(.forwardDelete)]) + #expect(!settings.sanitized().isCustomized(.delete)) + } + @Test("Bare-key override on a grid action survives") func keepsBareKeyGridOverride() { let space = BoundKey.special(.space) @@ -459,3 +468,227 @@ struct ShortcutHintTests { #expect(hint == "Manage Connections") } } + +struct ShortcutAcceptanceTests { + @Test("Command or Control makes any key bindable") + func commandOrControlIsAccepted() { + #expect(ShortcutAction.refresh.accepts(.character("e", command: true))) + #expect(ShortcutAction.refresh.accepts(.character("e", control: true))) + } + + @Test("A bare function key is accepted") + func functionKeyIsAccepted() { + #expect(ShortcutAction.refresh.accepts(BoundKey(keyCode: KeyCode.f5.rawValue))) + } + + @Test("Option or Shift alone on a letter is refused") + func optionLetterIsRefused() { + #expect(!ShortcutAction.refresh.accepts(.character("e", option: true))) + #expect(!ShortcutAction.refresh.accepts(.character("e", shift: true))) + #expect(!ShortcutAction.refresh.accepts(.special(.return))) + } + + @Test("A modified Delete, Escape or Space is accepted for a menu action") + func modifiedBareRecordableKeyIsAccepted() { + #expect(ShortcutAction.addRow.accepts(.special(.delete, option: true))) + #expect(ShortcutAction.addRow.accepts(.special(.space, shift: true))) + #expect(ShortcutAction.addRow.accepts(.special(.escape, option: true))) + } + + @Test("A bare Space is accepted only for Preview FK Reference") + func bareSpaceOnlyForPreview() { + #expect(ShortcutAction.previewFKReference.accepts(.special(.space))) + #expect(!ShortcutAction.delete.accepts(.special(.space))) + #expect(!ShortcutAction.clearSelection.accepts(.special(.forwardDelete))) + } + + @Test("An action's own default is always accepted") + func ownDefaultIsAccepted() { + for (action, key) in KeyboardSettings.defaultShortcuts { + #expect(action.accepts(key), "\(action.rawValue) refuses its own default \(key.displayString)") + } + } + + @Test("Preview FK Reference explains that Space and function keys also work") + func previewRefusalNamesItsExtraKeys() { + #expect(ShortcutAction.previewFKReference.modifierRefusal == String(localized: "Use ⌘ or ⌃, Space, or a function key.")) + #expect(ShortcutAction.refresh.modifierRefusal == String(localized: "Add ⌘ or ⌃ to this shortcut.")) + } + + @Test("Capturing keeps the raw chord that BoundKey(from:) would refuse") + func capturingKeepsRawChord() throws { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [.option, .function], + timestamp: 0, + windowNumber: 0, + context: nil, + characters: "e", + charactersIgnoringModifiers: "e", + isARepeat: false, + keyCode: KeyCode.e.rawValue + )) + #expect(BoundKey(from: event) == nil) + #expect(BoundKey(capturing: event) == BoundKey(keyCode: KeyCode.e.rawValue, option: true)) + } +} + +struct KeyboardSettingsEditingTests { + private let modules: Set = [] + + @Test("boundKey maps a cleared shortcut to nil") + func boundKeyHidesCleared() { + var settings = KeyboardSettings.default + #expect(settings.boundKey(for: .refresh) == .character("r", command: true)) + settings.clearShortcut(for: .refresh) + #expect(settings.shortcut(for: .refresh) == .cleared) + #expect(settings.boundKey(for: .refresh) == nil) + } + + @Test("Assigning a new key stores an override") + func assigningStoresOverride() { + let settings = KeyboardSettings.default.assigning(.character("j", command: true), to: .refresh) + #expect(settings.shortcuts[ShortcutAction.refresh.rawValue] == .character("j", command: true)) + } + + @Test("Assigning the default again stores nothing") + func assigningDefaultDropsOverride() { + let custom = KeyboardSettings.default.assigning(.character("j", command: true), to: .refresh) + let back = custom.assigning(.character("r", command: true), to: .refresh) + #expect(!back.isCustomized(.refresh)) + #expect(back == .default) + } + + @Test("Assigning the default keeps the override while another override claims it") + func assigningClaimedDefaultKeepsOverride() { + let claimed = KeyboardSettings(shortcuts: [ShortcutAction.executeQuery.rawValue: .character("r", command: true)]) + let settings = claimed.assigning(.character("r", command: true), to: .refresh) + #expect(settings.isCustomized(.refresh)) + } + + @Test("Clearing an action with a default stores the cleared marker") + func clearingWithDefault() { + let settings = KeyboardSettings.default.clearing(.refresh) + #expect(settings.shortcuts[ShortcutAction.refresh.rawValue] == .cleared) + #expect(settings.boundKey(for: .refresh) == nil) + } + + @Test("Clearing an action with no default removes its override") + func clearingWithoutDefault() { + let custom = KeyboardSettings.default.assigning(.character("j", command: true), to: .manageConnections) + let settings = custom.clearing(.manageConnections) + #expect(!settings.isCustomized(.manageConnections)) + #expect(settings.boundKey(for: .manageConnections) == nil) + } + + @Test("Resetting removes the override") + func resettingRestoresDefault() { + let settings = KeyboardSettings.default.clearing(.refresh).resetting(.refresh) + #expect(settings == .default) + } + + @Test("The count leaves out entries for actions that no longer exist") + func customizedCountSkipsUnknownEntries() { + let settings = KeyboardSettings(shortcuts: [ + ShortcutAction.refresh.rawValue: .character("j", command: true), + "future.unknown.action": .character("x", command: true), + ]) + #expect(settings.customizedCount == 1) + #expect(KeyboardSettings.default.customizedCount == 0) + } + + @Test("Conflicts list every contending holder of the key") + func conflictsListEveryHolder() { + let key = BoundKey.character("j", command: true, option: true, control: true) + let settings = KeyboardSettings(shortcuts: [ + ShortcutAction.formatQuery.rawValue: key, + ShortcutAction.addRow.rawValue: key, + ]) + #expect(settings.conflicts(for: key, excluding: .newTab, enabledModules: modules) == [.formatQuery, .addRow]) + #expect(settings.conflicts(for: key, excluding: .formatQuery, enabledModules: modules) == []) + } + + @Test("Reassigning clears every customized holder in one value") + func reassigningClearsCustomizedHolders() { + let key = BoundKey.character("j", command: true, option: true, control: true) + let settings = KeyboardSettings(shortcuts: [ + ShortcutAction.formatQuery.rawValue: key, + ShortcutAction.addRow.rawValue: key, + ]) + let next = settings.reassigning(key, to: .newTab, enabledModules: modules) + #expect(next.boundKey(for: .newTab) == key) + #expect(next.boundKey(for: .formatQuery) == nil) + #expect(next.boundKey(for: .addRow) == nil) + #expect(next.conflicts(for: key, excluding: .newTab, enabledModules: modules).isEmpty) + } + + @Test("Reassigning leaves a holder on its default uncustomized, standing down") + func reassigningStandsDownDefaultHolder() { + let next = KeyboardSettings.default.reassigning(.character("r", command: true), to: .executeQuery, enabledModules: modules) + #expect(next.boundKey(for: .executeQuery) == .character("r", command: true)) + #expect(!next.isCustomized(.refresh)) + #expect(next.boundKey(for: .refresh) == nil) + #expect(next.defaultClaimant(for: .refresh) == .executeQuery) + } + + @Test("A default nobody claimed has no claimant") + func unclaimedDefaultHasNoClaimant() { + #expect(KeyboardSettings.default.defaultClaimant(for: .refresh) == nil) + #expect(KeyboardSettings.default.defaultClaimant(for: .manageConnections) == nil) + } +} + +struct KeyboardShortcutFilterTests { + private let modules: Set = [] + + private func actions(_ query: String, in settings: KeyboardSettings = .default) -> [ShortcutAction] { + ShortcutAction.settingsSections(matching: query, in: settings, enabledModules: modules).flatMap { $0.actions } + } + + @Test("An empty query lists every available action under its category") + func emptyQueryListsEverything() { + let sections = ShortcutAction.settingsSections(matching: " ", in: .default, enabledModules: modules) + let categories = sections.map { $0.category } + let rows = sections.flatMap { $0.actions } + #expect(categories == [.editor, .dataGrid, .navigation, .connections]) + #expect(rows.count == ShortcutAction.allCases.filter { $0.module == nil }.count) + } + + @Test("Debug rows appear only while the Routine Debugger is on") + func debugRowsFollowTheModule() { + let on = ShortcutAction.settingsSections(matching: "", in: .default, enabledModules: [.routineDebugger]) + #expect(on.contains { $0.category == .debug }) + } + + @Test("Matching ignores case and diacritics") + func matchingIsLocalizedStandard() { + #expect(actions("refresh") == [.refresh]) + #expect(actions("RÉFRESH") == [.refresh]) + } + + @Test("Every term has to match, against the name or the category") + func everyTermMustMatch() { + #expect(actions("copy csv") == [.copyAsCsv, .copyAsCsvWithHeaders]) + #expect(actions("data grid refresh") == [.refresh]) + #expect(actions("refresh zzz").isEmpty) + } + + @Test("A term with a modifier glyph also matches the bound key") + func glyphTermMatchesKey() { + #expect(actions("⌘R").contains(.refresh)) + let custom = KeyboardSettings.default.assigning(.character("k", command: true, option: true, control: true), to: .manageConnections) + #expect(actions("⌃⌥⌘K", in: custom) == [.manageConnections]) + } + + @Test("A cleared key never matches a glyph term") + func clearedKeyDoesNotMatch() { + let cleared = KeyboardSettings.default.clearing(.refresh) + #expect(!actions("⌘R", in: cleared).contains(.refresh)) + } + + @Test("No match leaves no sections") + func noMatchLeavesNoSections() { + #expect(ShortcutAction.settingsSections(matching: "zzzz", in: .default, enabledModules: modules).isEmpty) + } +} diff --git a/apple/TableProTests/Views/AIChat/ChatComposerReplaceTests.swift b/apple/TableProTests/Views/AIChat/ChatComposerReplaceTests.swift new file mode 100644 index 0000000000..7fbe8a479c --- /dev/null +++ b/apple/TableProTests/Views/AIChat/ChatComposerReplaceTests.swift @@ -0,0 +1,51 @@ +import AppKit +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct ChatComposerReplaceTests { + private func composer(_ text: String, caret: Int) -> ChatComposerNSTextView { + let textView = ChatComposerNSTextView.make() + textView.string = text + textView.setSelectedRange(NSRange(location: caret, length: 0)) + return textView + } + + @Test("A slash pick into an empty composer leaves the caret after the command") + func emptyComposerCaretFollowsText() { + let textView = composer("", caret: 0) + textView.replaceAll(with: "/explain ") + #expect(textView.string == "/explain ") + #expect(textView.selectedRange() == NSRange(location: 9, length: 0)) + } + + @Test("A caret at the end of the old text moves to the end of the new text") + func caretAtEndFollowsText() { + let textView = composer("select 1", caret: 8) + textView.replaceAll(with: "/optimize select 1") + #expect(textView.selectedRange() == NSRange(location: 18, length: 0)) + } + + @Test("A caret inside the text stays where it was") + func caretInsideStays() { + let textView = composer("select 1", caret: 3) + textView.replaceAll(with: "select 1 from t") + #expect(textView.selectedRange() == NSRange(location: 3, length: 0)) + } + + @Test("A caret past the new end is clamped to it") + func caretPastNewEndIsClamped() { + let textView = composer("select 1 from t", caret: 12) + textView.replaceAll(with: "select") + #expect(textView.selectedRange() == NSRange(location: 6, length: 0)) + } + + @Test("Clearing the composer leaves the caret at the start") + func clearingLeavesCaretAtStart() { + let textView = composer("select 1", caret: 8) + textView.replaceAll(with: "") + #expect(textView.string.isEmpty) + #expect(textView.selectedRange() == NSRange(location: 0, length: 0)) + } +} diff --git a/apple/TableProTests/Views/Settings/ShortcutRecordingSessionTests.swift b/apple/TableProTests/Views/Settings/ShortcutRecordingSessionTests.swift new file mode 100644 index 0000000000..c20f2031ea --- /dev/null +++ b/apple/TableProTests/Views/Settings/ShortcutRecordingSessionTests.swift @@ -0,0 +1,354 @@ +import AppKit +import Foundation +@testable import TablePro +import Testing + +struct ShortcutRecordingClassifyTests { + // kVK_Command, the key code a Command flagsChanged event carries. + private static let commandKeyCode: UInt16 = 55 + + private func step( + _ keyCode: KeyCode, + _ flags: NSEvent.ModifierFlags = [], + for action: ShortcutAction = .refresh, + isRepeat: Bool = false, + inWindow: Bool = true + ) throws -> ShortcutRecordingStep { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: flags, + timestamp: 0, + windowNumber: 0, + context: nil, + characters: "", + charactersIgnoringModifiers: "", + isARepeat: isRepeat, + keyCode: keyCode.rawValue + )) + return classify(event, for: action, inWindow: inWindow) + } + + private func click( + _ type: NSEvent.EventType = .leftMouseDown, + inWindow: Bool = true, + hitsButton: Bool = false + ) throws -> ShortcutRecordingStep { + let event = try #require(NSEvent.mouseEvent( + with: type, + location: .zero, + modifierFlags: [], + timestamp: 0, + windowNumber: 0, + context: nil, + eventNumber: 0, + clickCount: 1, + pressure: 1 + )) + return classify(event, inWindow: inWindow, hitsButton: hitsButton) + } + + private func classify( + _ event: NSEvent, + for action: ShortcutAction = .refresh, + inWindow: Bool = true, + hitsButton: Bool = false + ) -> ShortcutRecordingStep { + ShortcutRecordingSession.classify( + event, + recording: action, + isInRecordingWindow: inWindow, + hitsRecordingButton: hitsButton + ) + } + + @Test("An event for another window, or a window that is not key, passes untouched") + func otherWindowPasses() throws { + #expect(try step(.w, .command, inWindow: false) == .pass) + #expect(try click(inWindow: false) == .pass) + } + + @Test("A click on the recording button passes, so its own action stops recording") + func clickOnOwnButtonPasses() throws { + #expect(try click(hitsButton: true) == .pass) + } + + @Test("Any other click cancels and still reaches its target", arguments: [ + NSEvent.EventType.leftMouseDown, .rightMouseDown, .otherMouseDown, + ]) + func otherClickCancels(type: NSEvent.EventType) throws { + #expect(try click(type) == .cancelAndPass) + } + + @Test("Held modifiers are shown and swallowed, without Caps Lock or Fn") + func modifiersAreHeld() throws { + let event = try #require(NSEvent.keyEvent( + with: .flagsChanged, + location: .zero, + modifierFlags: [.command, .shift, .capsLock, .function], + timestamp: 0, + windowNumber: 0, + context: nil, + characters: "", + charactersIgnoringModifiers: "", + isARepeat: false, + keyCode: Self.commandKeyCode + )) + #expect(classify(event) == .holdModifiers([.command, .shift])) + } + + @Test("Key repeat is swallowed") + func repeatIsSwallowed() throws { + #expect(try step(.j, .command, isRepeat: true) == .swallow) + } + + @Test("Tab and Shift-Tab cancel and move focus on") + func tabLeaves() throws { + #expect(try step(.tab) == .cancelAndPass) + #expect(try step(.tab, .shift) == .cancelAndPass) + } + + @Test("Control-Tab is recorded") + func controlTabIsRecorded() throws { + #expect(try step(.tab, .control) == .capture(.special(.tab, control: true))) + } + + @Test("Escape cancels on every row, Option-Escape is a chord") + func escapeCancels() throws { + #expect(try step(.escape) == .cancel) + #expect(try step(.escape, for: .previewFKReference) == .cancel) + #expect(try step(.escape, .option, for: .addRow) == .capture(.special(.escape, option: true))) + } + + @Test("Delete removes the shortcut, a modified Delete is a chord") + func deleteRemoves() throws { + #expect(try step(.delete) == .remove) + #expect(try step(.delete, .shift, for: .addRow) == .capture(.special(.delete, shift: true))) + } + + @Test("A bare Forward Delete is refused unless the action allows a bare key") + func bareForwardDelete() throws { + #expect(try step(.forwardDelete, for: .delete) == .refuse(ShortcutAction.delete.modifierRefusal)) + #expect(try step(.forwardDelete, for: .previewFKReference) == .capture(.special(.forwardDelete))) + } + + @Test("Command-W is captured instead of closing the window") + func commandWIsCaptured() throws { + #expect(try step(.w, .command) == .capture(.character("w", command: true))) + } + + @Test("Option or Shift alone on a letter is refused with the reason") + func optionLetterIsRefused() throws { + #expect(try step(.e, .option) == .refuse(String(localized: "Add ⌘ or ⌃ to this shortcut."))) + #expect( + try step(.e, .option, for: .previewFKReference) + == .refuse(String(localized: "Use ⌘ or ⌃, Space, or a function key.")) + ) + #expect(try step(.return) == .refuse(ShortcutAction.refresh.modifierRefusal)) + } + + @Test("A bare Space records only for Preview FK Reference") + func bareSpace() throws { + #expect(try step(.space, for: .previewFKReference) == .capture(.special(.space))) + #expect(try step(.space) == .refuse(ShortcutAction.refresh.modifierRefusal)) + } +} + +@MainActor +struct ShortcutRecordingSessionTests { + @MainActor + private final class Signals { + var messages: [String] = [] + } + + private let free = BoundKey.character("j", command: true, option: true, control: true) + + private func makeSession( + _ settings: KeyboardSettings = .default + ) -> (session: ShortcutRecordingSession, slice: SettingsSlice, signals: Signals) { + let slice = SettingsSlice(settings) + let signals = Signals() + let session = ShortcutRecordingSession(keyboard: slice) { signals.messages.append($0) } + return (session, slice, signals) + } + + @Test("Toggling the recording row twice starts and stops recording") + func toggleStartsAndStops() { + let (session, _, _) = makeSession() + session.toggle(.refresh) + #expect(session.recording == .refresh) + session.toggle(.newTab) + #expect(session.recording == .newTab) + session.toggle(.newTab) + #expect(session.recording == nil) + } + + @Test("Cancel drops the held modifiers") + func cancelClearsModifiers() { + let (session, _, _) = makeSession() + session.begin(.refresh) + #expect(session.perform(.holdModifiers([.command, .option]), for: .refresh)) + #expect(session.heldModifiers == [.command, .option]) + session.cancel() + #expect(session.heldModifiers.isEmpty) + #expect(session.recording == nil) + } + + @Test("A free chord is assigned and recording ends") + func freeChordIsAssigned() { + let (session, slice, signals) = makeSession() + session.begin(.refresh) + #expect(session.perform(.capture(free), for: .refresh)) + #expect(slice.value.boundKey(for: .refresh) == free) + #expect(session.recording == nil) + #expect(signals.messages.isEmpty) + } + + @Test("Recording the default again stores nothing") + func defaultChordStoresNothing() { + let (session, slice, _) = makeSession() + session.begin(.refresh) + session.perform(.capture(.character("r", command: true)), for: .refresh) + #expect(slice.value == .default) + } + + @Test("A reserved chord is refused inline and recording stays armed") + func reservedChordIsRefused() { + let (session, slice, signals) = makeSession() + session.begin(.refresh) + session.perform(.capture(.character("q", command: true)), for: .refresh) + let message = String(format: String(localized: "%@ is used by “%@”."), "⌘Q", String(localized: "Quit TablePro")) + #expect(session.recording == .refresh) + #expect(session.feedback == ShortcutRecordingFeedback(action: .refresh, message: message)) + #expect(signals.messages == [message]) + #expect(slice.value == .default) + session.cancel() + } + + @Test("A modifier refusal keeps recording armed") + func refusalKeepsRecording() { + let (session, _, signals) = makeSession() + session.begin(.refresh) + #expect(session.perform(.refuse("Nope"), for: .refresh)) + #expect(session.recording == .refresh) + #expect(signals.messages == ["Nope"]) + session.cancel() + } + + @Test("A refusal stays under its row until another row records") + func feedbackClearsOnOtherRow() { + let (session, _, _) = makeSession() + session.begin(.refresh) + session.perform(.refuse("Nope"), for: .refresh) + session.cancel() + #expect(session.feedback?.action == .refresh) + session.begin(.refresh) + #expect(session.feedback?.action == .refresh) + session.begin(.newTab) + #expect(session.feedback == nil) + session.cancel() + } + + @Test("A chord held by another action asks to reassign, and confirming moves it in one write") + func conflictAsksToReassign() throws { + let (session, slice, _) = makeSession() + session.begin(.executeQuery) + session.perform(.capture(.character("r", command: true)), for: .executeQuery) + #expect(session.recording == nil) + let request = try #require(session.reassignment) + #expect(request.holders == [.refresh]) + #expect(request.title == String( + format: String(localized: "Reassign %@ to “%@”?"), + "⌘R", + ShortcutAction.executeQuery.displayName + )) + #expect(request.message == String( + format: String(localized: "It is used by “%@” in %@, which will have no shortcut."), + ShortcutAction.refresh.displayName, + ShortcutCategory.dataGrid.displayName + )) + #expect(slice.value == .default) + + session.confirm(request) + #expect(session.reassignment == nil) + #expect(slice.value.boundKey(for: .executeQuery) == .character("r", command: true)) + #expect(slice.value.boundKey(for: .refresh) == nil) + } + + @Test("Several holders are named together") + func severalHoldersAreListed() { + let request = ShortcutReassignment(action: .newTab, key: free, holders: [.formatQuery, .addRow]) + let names = ListFormatter.localizedString(byJoining: [ + String(format: String(localized: "“%@”"), ShortcutAction.formatQuery.displayName), + String(format: String(localized: "“%@”"), ShortcutAction.addRow.displayName), + ]) + #expect(request.message == String(format: String(localized: "It is used by %@. They will have no shortcut."), names)) + } + + @Test("Cancelling the reassignment writes nothing") + func dismissWritesNothing() { + let (session, slice, _) = makeSession() + session.begin(.executeQuery) + session.perform(.capture(.character("r", command: true)), for: .executeQuery) + session.dismissReassignment() + #expect(session.reassignment == nil) + #expect(slice.value == .default) + } + + @Test("Delete removes the shortcut and ends recording") + func removeClearsShortcut() { + let (session, slice, _) = makeSession() + session.begin(.refresh) + #expect(session.perform(.remove, for: .refresh)) + #expect(slice.value.boundKey(for: .refresh) == nil) + #expect(session.recording == nil) + } + + @Test("Passing events are not consumed") + func passIsNotConsumed() { + let (session, _, _) = makeSession() + session.begin(.refresh) + #expect(!session.perform(.pass, for: .refresh)) + #expect(session.recording == .refresh) + #expect(!session.perform(.cancelAndPass, for: .refresh)) + #expect(session.recording == nil) + } +} + +struct ShortcutRecorderLookTests { + @Test("Idle with a key shows the key") + func idleWithKey() { + let look = ShortcutRecorderLook(key: .character("s", command: true), isArmed: false, heldModifiers: []) + #expect(look.title == "⌘S") + #expect(!look.isPlaceholder) + #expect(look.accessibilityValue == "⌘S") + } + + @Test("Idle with no key or a cleared key shows None as a placeholder") + func idleWithoutKey() { + for key in [nil, BoundKey.cleared] { + let look = ShortcutRecorderLook(key: key, isArmed: false, heldModifiers: []) + #expect(look.title == String(localized: "None")) + #expect(look.isPlaceholder) + } + } + + @Test("Armed shows the prompt, then the held modifiers in menu order") + func armedShowsModifiers() { + let idle = ShortcutRecorderLook(key: .character("s", command: true), isArmed: true, heldModifiers: []) + #expect(idle.title == String(localized: "Type Shortcut")) + #expect(idle.accessibilityValue == String(localized: "Recording")) + #expect(!idle.isPlaceholder) + let held = ShortcutRecorderLook(key: nil, isArmed: true, heldModifiers: [.command, .shift, .option, .control]) + #expect(held.title == "⌃⌥⇧⌘") + } +} + +@MainActor +struct KeyboardSettingsSummaryTests { + @Test("The list bar counts customized shortcuts") + func summaryCountsCustomizations() { + #expect(KeyboardSettingsView.summary(customized: 0) == String(localized: "No custom shortcuts")) + #expect(KeyboardSettingsView.summary(customized: 3) == String(format: String(localized: "%lld customized"), 3)) + } +} diff --git a/apple/TableProUITests/KeyboardSettingsUITests.swift b/apple/TableProUITests/KeyboardSettingsUITests.swift new file mode 100644 index 0000000000..4c91362c90 --- /dev/null +++ b/apple/TableProUITests/KeyboardSettingsUITests.swift @@ -0,0 +1,49 @@ +import XCTest + +final class KeyboardSettingsUITests: UITestCase { + // One launch: filter from the toolbar, cancel, record, then restore every default. + func testFilterRecordAndRestoreDefaults() throws { + let app = try launchApp() + let settings = openSettings(in: app) + selectSettingsPane("keyboard", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Keyboard" }, "Picking Keyboard must title the window") + + app.typeShortcut(.find) + let search = settings.searchFields.matching(identifier: "shortcut-search").firstMatch + XCTAssertTrue( + waitForPredicate(timeout: 5) { self.holdsKeyboardFocus(search) }, + "Cmd-F on Keyboard must focus the toolbar filter" + ) + search.typeText("Refresh") + + let refresh = settings.buttons.matching(identifier: "shortcut-recorder-refresh").firstMatch + let executeQuery = settings.buttons.matching(identifier: "shortcut-recorder-executeQuery").firstMatch + XCTAssertTrue(waitUntilHittable(refresh, timeout: 5), "The filter must keep the Refresh row") + XCTAssertTrue(waitForPredicate(timeout: 5) { !executeQuery.exists }, "The filter must drop rows that do not match") + XCTAssertEqual(refresh.title, "⌘R") + + refresh.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { refresh.title == "Type Shortcut" }, "A click must arm the recorder") + attachScreenshot(of: settings, named: "settings-keyboard-armed") + app.typeKey(.escape, modifierFlags: []) + XCTAssertTrue(waitForPredicate(timeout: 5) { refresh.title == "⌘R" }, "Escape must cancel and keep the key") + + refresh.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { refresh.title == "Type Shortcut" }) + app.typeKey("j", modifierFlags: [.command, .option, .control]) + XCTAssertTrue( + waitForPredicate(timeout: 5) { refresh.title == "⌃⌥⌘J" }, + "A free chord must be recorded, the recorder shows \(refresh.title)" + ) + XCTAssertTrue(settings.buttons["shortcut-reset-refresh"].exists, "A customized row offers its reset button") + + let restore = settings.buttons["shortcut-restore-defaults"] + XCTAssertTrue(waitForPredicate(timeout: 5) { restore.isEnabled }, "A customized shortcut enables Restore Defaults") + restore.click() + let confirmation = settings.sheets.firstMatch + XCTAssertTrue(confirmation.waitToExist(timeout: 5), "Restore Defaults must ask first") + confirmation.buttons["Restore Defaults"].click() + XCTAssertTrue(waitForPredicate(timeout: 5) { refresh.title == "⌘R" }, "Restoring must bring the default back") + XCTAssertTrue(waitForPredicate(timeout: 5) { !restore.isEnabled }, "Nothing is left to restore") + } +} From 6ad7083d7ff01641833621481c802e9bca8cb962 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:53 +0700 Subject: [PATCH 32/48] feat(settings): Notifications pane --- .../NotificationPermissionMonitor.swift | 12 +-- .../Settings/NotificationSettings.swift | 14 +-- .../Entries/NotificationsSettingsEntry.swift | 5 +- .../Settings/NotificationsSettingsView.swift | 85 +++++++++++-------- .../Settings/NotificationSettingsTests.swift | 41 +++++++++ .../NotificationPermissionMonitorTests.swift | 12 +++ 6 files changed, 115 insertions(+), 54 deletions(-) create mode 100644 apple/TableProTests/Models/Settings/NotificationSettingsTests.swift diff --git a/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift index 87721602aa..d4c18a7244 100644 --- a/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift +++ b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift @@ -1,18 +1,11 @@ -// -// NotificationPermissionMonitor.swift -// TablePro -// - import AppKit import Combine import UserNotifications -// The permission changes in System Settings while TablePro is in the background, so the pane reads -// it again each time the app comes back. It never asks for permission: NotificationAuthorization -// is the one requester. +// Reads only, again on each activation since System Settings can change it meanwhile; NotificationAuthorization is the one requester. @MainActor internal final class NotificationPermissionMonitor: ObservableObject { - @Published internal private(set) var status: UNAuthorizationStatus = .notDetermined + @Published internal private(set) var status: UNAuthorizationStatus private let authorization: NotificationAuthorization private var activation: AnyCancellable? @@ -23,6 +16,7 @@ internal final class NotificationPermissionMonitor: ObservableObject { center: NotificationCenter = .default ) { self.authorization = authorization + status = authorization.status activation = center.publisher(for: NSApplication.didBecomeActiveNotification) .sink { [weak self] _ in Task { @MainActor in await self?.refresh() } diff --git a/apple/TablePro/Models/Settings/NotificationSettings.swift b/apple/TablePro/Models/Settings/NotificationSettings.swift index f0664d81fc..8e377c24b0 100644 --- a/apple/TablePro/Models/Settings/NotificationSettings.swift +++ b/apple/TablePro/Models/Settings/NotificationSettings.swift @@ -1,15 +1,11 @@ -// -// NotificationSettings.swift -// TablePro -// - import Foundation -/// Whether a finished operation is worth a notification, and how long is long enough to count. +// The threshold also decides the tab's unseen mark, with the switch on or off. struct NotificationSettings: Codable, Equatable { static let minimumThresholdSeconds = 5 static let maximumThresholdSeconds = 600 static let defaultThresholdSeconds = 20 + static let thresholdChoices = [5, 10, 20, 30, 60, 120, 300, 600] var isEnabled: Bool var thresholdSeconds: Int @@ -20,6 +16,12 @@ struct NotificationSettings: Codable, Equatable { min(max(thresholdSeconds, Self.minimumThresholdSeconds), Self.maximumThresholdSeconds) } + var thresholdOptions: [Int] { + let current = validatedThresholdSeconds + guard !Self.thresholdChoices.contains(current) else { return Self.thresholdChoices } + return (Self.thresholdChoices + [current]).sorted() + } + init( isEnabled: Bool = true, thresholdSeconds: Int = NotificationSettings.defaultThresholdSeconds diff --git a/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift index 0c12c2a3ae..e32848c91a 100644 --- a/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/NotificationsSettingsEntry.swift @@ -10,16 +10,17 @@ internal struct NotificationsSettingsEntry: View { } internal var body: some View { - NotificationsSettingsView(settings: $notifications.value) + NotificationsSettingsView(settings: $notifications.value, visit: context.visit) } } +// Notifications has no pages, and the navigation model never pushes another pane's route here. internal struct NotificationsSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } diff --git a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift index 5914fda4d7..ce5b64ff8c 100644 --- a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift +++ b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift @@ -1,64 +1,75 @@ -// -// NotificationsSettingsView.swift -// TablePro -// - import AppKit import SwiftUI import UserNotifications struct NotificationsSettingsView: View { @Binding var settings: NotificationSettings + @ObservedObject var visit: SettingsPaneVisit @StateObject private var permission = NotificationPermissionMonitor() var body: some View { Form { - Section { - Toggle("Notify when long-running work finishes", isOn: $settings.isEnabled) - .accessibilityIdentifier("notifications-enabled-toggle") - - Picker("Only after", selection: $settings.thresholdSeconds) { - ForEach(Self.thresholdChoices, id: \.self) { seconds in - Text(Self.thresholdLabel(seconds)).tag(seconds) - } + if settings.isEnabled, permission.status == .denied { + Section { + permissionRow } - .disabled(!settings.isEnabled) - } header: { - Text("Notifications") - } footer: { - Text("TablePro only notifies when the result is not already on screen.") - .font(.caption) - .foregroundStyle(.secondary) } - if permission.status == .denied { - Section { - HStack(spacing: 8) { - NoticeLabel(String(localized: "Notifications are turned off for TablePro in System Settings.")) - Spacer() - Button("Open System Settings", action: Self.openSystemSettings) + Section { + Toggle(isOn: $settings.isEnabled) { + Text("Show notifications") + Text( + "When long-running work finishes out of sight, an agent needs your answer or its reply fails, or an extension can't load or update." + ) + } + .accessibilityIdentifier("notifications-enabled-toggle") + + Picker(selection: threshold) { + ForEach(settings.thresholdOptions, id: \.self) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)).tag(seconds) } + } label: { + Text("Treat work as long-running after") + Text( + "When work this long finishes out of sight, its tab is marked and, with notifications on, a notification shows." + ) } + .pickerStyle(.menu) + .accessibilityIdentifier("notifications-threshold-picker") } } .formStyle(.grouped) - .task { + .task(id: visit.count) { await permission.refresh() } } - private static let thresholdChoices = [5, 10, 20, 30, 60, 120, 300, 600] - - private static func thresholdLabel(_ seconds: Int) -> String { - guard seconds >= 60 else { - return String(format: String(localized: "%lld seconds"), seconds) - } - let minutes = seconds / 60 - if minutes == 1 { - return String(localized: "1 minute") + private var permissionRow: some View { + LabeledContent { + Button("Open System Settings", action: Self.openSystemSettings) + .accessibilityIdentifier("notifications-open-system-settings") + } label: { + Label { + Text("Notifications are off in System Settings") + Text("TablePro can't show any notification until you allow it there.") + } icon: { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .accessibilityHidden(true) + } } - return String(format: String(localized: "%lld minutes"), minutes) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("notifications-permission-row") + } + + // A stored value outside the allowed range shows the value that applies instead of a blank pop-up. + private var threshold: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.validatedThresholdSeconds }, + set: { settings.wrappedValue.thresholdSeconds = $0 } + ) } private static func openSystemSettings() { diff --git a/apple/TableProTests/Models/Settings/NotificationSettingsTests.swift b/apple/TableProTests/Models/Settings/NotificationSettingsTests.swift new file mode 100644 index 0000000000..bf74de43c5 --- /dev/null +++ b/apple/TableProTests/Models/Settings/NotificationSettingsTests.swift @@ -0,0 +1,41 @@ +import Foundation +@testable import TablePro +import Testing + +struct NotificationSettingsTests { + @Test("A threshold on the list offers exactly the fixed choices") + func onListValueKeepsTheChoices() { + for seconds in NotificationSettings.thresholdChoices { + let settings = NotificationSettings(thresholdSeconds: seconds) + #expect(settings.thresholdOptions == NotificationSettings.thresholdChoices) + } + } + + @Test("A threshold off the list is offered in order among the choices", arguments: [ + (45, [5, 10, 20, 30, 45, 60, 120, 300, 600]), + (90, [5, 10, 20, 30, 60, 90, 120, 300, 600]), + ]) + func offListValueIsInserted(seconds: Int, expected: [Int]) { + let settings = NotificationSettings(thresholdSeconds: seconds) + #expect(settings.thresholdOptions == expected) + } + + @Test("A threshold outside the allowed range offers the value that applies") + func outOfRangeValueOffersTheClamp() { + #expect(NotificationSettings(thresholdSeconds: 1).thresholdOptions == NotificationSettings.thresholdChoices) + #expect(NotificationSettings(thresholdSeconds: 900).thresholdOptions == NotificationSettings.thresholdChoices) + #expect(NotificationSettings(thresholdSeconds: 7).thresholdOptions == [5, 7, 10, 20, 30, 60, 120, 300, 600]) + } + + @Test("The default threshold is one of the choices") + func defaultIsOnTheList() { + #expect(NotificationSettings.thresholdChoices.contains(NotificationSettings.default.thresholdSeconds)) + } + + @Test("A stored record with the legacy kind list still decodes its fields") + func ignoresLegacyKindIds() throws { + let json = #"{"isEnabled":false,"thresholdSeconds":90,"disabledKindIds":["export"]}"# + let settings = try JSONDecoder().decode(NotificationSettings.self, from: Data(json.utf8)) + #expect(settings == NotificationSettings(isEnabled: false, thresholdSeconds: 90)) + } +} diff --git a/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift b/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift index 3b6f9d5813..fc30730bb7 100644 --- a/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift +++ b/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift @@ -43,6 +43,18 @@ struct NotificationPermissionMonitorTests { try await waitUntil { monitor.status == .denied } } + @Test("A monitor built after a denied read shows the denied state before its own read") + func startsFromTheLastKnownStatus() async { + let presenter = StubPermissionPresenter() + presenter.status = .denied + let authorization = NotificationAuthorization(presenter: presenter) + await authorization.refresh() + + let monitor = NotificationPermissionMonitor(authorization: authorization, center: NotificationCenter()) + + #expect(monitor.status == .denied) + } + @Test("Reading the permission never asks for it") func neverRequests() async { let presenter = StubPermissionPresenter() From 7a561cf15ba9fce65954e264d90153c41a87eef4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:53 +0700 Subject: [PATCH 33/48] feat(settings): iCloud Sync pane --- .../Models/Settings/SyncSettings.swift | 18 +- .../Settings/Entries/SyncSettingsEntry.swift | 11 +- .../Views/Settings/Sections/SyncSection.swift | 119 ------- .../Views/Settings/SyncSettingsView.swift | 293 +++++++++++++++--- .../Models/Settings/SyncSettingsTests.swift | 133 ++++++++ 5 files changed, 394 insertions(+), 180 deletions(-) delete mode 100644 apple/TablePro/Views/Settings/Sections/SyncSection.swift create mode 100644 apple/TableProTests/Models/Settings/SyncSettingsTests.swift diff --git a/apple/TablePro/Models/Settings/SyncSettings.swift b/apple/TablePro/Models/Settings/SyncSettings.swift index 55954bf595..d536309fc8 100644 --- a/apple/TablePro/Models/Settings/SyncSettings.swift +++ b/apple/TablePro/Models/Settings/SyncSettings.swift @@ -1,14 +1,6 @@ -// -// SyncSettings.swift -// TablePro -// -// User-configurable sync preferences -// - import Foundation import TableProSyncTransport -/// User preferences for iCloud sync behavior struct SyncSettings: Codable, Equatable { var enabled: Bool var syncConnections: Bool @@ -82,6 +74,16 @@ struct SyncSettings: Codable, Equatable { var syncsPasswords: Bool { enabled && syncConnections && syncPasswords } + + // Passwords ride on connection records, so turning Connections off turns them off in the same write. + func settingConnections(_ on: Bool) -> SyncSettings { + var copy = self + copy.syncConnections = on + if !on { + copy.syncPasswords = false + } + return copy + } } internal extension SyncSettings { diff --git a/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift index 4625f19016..b486807b93 100644 --- a/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/SyncSettingsEntry.swift @@ -2,18 +2,25 @@ import SwiftUI internal struct SyncSettingsEntry: View { internal let context: SettingsPaneContext + @ObservedObject private var sync: SettingsSlice + + internal init(context: SettingsPaneContext) { + self.context = context + self._sync = ObservedObject(wrappedValue: context.settings.syncSlice) + } internal var body: some View { - SyncSettingsView() + SyncSettingsView(settings: $sync.value) } } +// iCloud Sync has no pages since What Syncs moved inline, so nothing reaches this. internal struct SyncSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } diff --git a/apple/TablePro/Views/Settings/Sections/SyncSection.swift b/apple/TablePro/Views/Settings/Sections/SyncSection.swift deleted file mode 100644 index c325cac6e2..0000000000 --- a/apple/TablePro/Views/Settings/Sections/SyncSection.swift +++ /dev/null @@ -1,119 +0,0 @@ -// -// SyncSection.swift -// TablePro -// - -import SwiftUI -import TableProSyncTransport - -struct SyncSection: View { - @ObservedObject private var featureAccess = FeatureAccess.shared - @ObservedObject private var settingsManager = AppSettingsManager.shared - @ObservedObject private var syncCoordinator = SyncCoordinator.shared - - private var isProAvailable: Bool { - featureAccess.isAvailable(.iCloudSync) - } - - var body: some View { - Section { - Toggle("Sync this Mac with iCloud", isOn: $settingsManager.sync.enabled) - .help("Syncs connections, table favorites, settings, and SSH profiles across your Macs via iCloud.") - .disabled(!isProAvailable) - - if !isProAvailable { - LicenseGateRow(feature: .iCloudSync) - } - } header: { - Text("iCloud Sync") - } - - if settingsManager.sync.enabled && isProAvailable { - statusSection - Section { - NavigationLink(value: SettingsSubpage.whatSyncs) { - Label("What Syncs", systemImage: "checklist") - } - } - } - } - - // MARK: - Status - - // A blocker is explained by the notice at the top of the pane, so the Status row only names it. - private var statusSection: some View { - let presentation = SyncStatusPresentation(status: syncCoordinator.syncStatus) - return Section("Sync Status") { - LabeledContent(String(localized: "Status")) { - HStack(spacing: 4) { - if syncCoordinator.syncStatus.isSyncing { - ProgressView() - .controlSize(.small) - } else { - Image(systemName: presentation.symbolName) - .foregroundStyle(presentation.isWarning ? Color.orange : Color.secondary) - .accessibilityHidden(true) - } - Text(presentation.title) - } - } - - if let lastSync = syncCoordinator.lastSyncDate { - LabeledContent(String(localized: "Last Synced")) { - Text(lastSync, style: .relative) - } - } - - if presentation.offersSyncNow { - Button(String(localized: "Sync Now")) { - Task { await syncCoordinator.syncNow() } - } - .disabled(syncCoordinator.syncStatus.isSyncing) - } - - if let detail = presentation.statusDetail { - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - } -} - -// The sync-category toggles, shown on the What Syncs drill-in. -struct SyncCategoriesSection: View { - @ObservedObject var settingsManager: AppSettingsManager - - var body: some View { - Section("Sync Categories") { - Toggle("Connections", isOn: $settingsManager.sync.syncConnections) - .onChange(of: settingsManager.sync.syncConnections) { newValue in - if !newValue, settingsManager.sync.syncPasswords { - settingsManager.sync.syncPasswords = false - } - } - - if settingsManager.sync.syncConnections { - Toggle("Passwords", isOn: $settingsManager.sync.syncPasswords) - .help("Syncs passwords via iCloud Keychain (end-to-end encrypted).") - .padding(.leading, 20) - - Text("Only affects new saves. Re-save a password to update its sync.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - .padding(.leading, 20) - } - - Toggle("Groups & Tags", isOn: $settingsManager.sync.syncGroupsAndTags) - Toggle("SSH Profiles", isOn: $settingsManager.sync.syncSSHProfiles) - Toggle("Credential Profiles", isOn: $settingsManager.sync.syncCredentialProfiles) - Toggle("Settings", isOn: $settingsManager.sync.syncSettings) - Toggle("Table Favorites", isOn: $settingsManager.sync.syncTableFavorites) - Toggle("Table Folders", isOn: $settingsManager.sync.syncTableFolders) - Toggle("Database Favorites", isOn: $settingsManager.sync.syncDatabaseFavorites) - Toggle("Saved Queries", isOn: $settingsManager.sync.syncSQLFavorites) - } - } -} diff --git a/apple/TablePro/Views/Settings/SyncSettingsView.swift b/apple/TablePro/Views/Settings/SyncSettingsView.swift index c71657a438..453c1cb2d5 100644 --- a/apple/TablePro/Views/Settings/SyncSettingsView.swift +++ b/apple/TablePro/Views/Settings/SyncSettingsView.swift @@ -1,66 +1,121 @@ -// -// SyncSettingsView.swift -// TablePro -// - import AppKit import os import SwiftUI import TableProSyncTransport +struct SyncPaneLayout: Equatable { + let notice: SyncNotice? + let isToggleDisabled: Bool + let showsLicenseGate: Bool + let showsStatus: Bool + let showsLastSynced: Bool + let offersSyncNow: Bool + let showsCategories: Bool + + init(enabled: Bool, isLicensed: Bool, presentation: SyncStatusPresentation) { + let showsLive = enabled && isLicensed + notice = presentation.notice + // A lapsed license can still turn sync off. + isToggleDisabled = !isLicensed && !enabled + showsLicenseGate = !isLicensed + showsStatus = showsLive && presentation.notice == nil + showsLastSynced = showsLive + offersSyncNow = presentation.offersSyncNow + // The categories apply before the first upload, so they show while sync is off too. + showsCategories = isLicensed + } +} + // Its own pane: sync runs on the Apple Account, a different identity from the email on a license. struct SyncSettingsView: View { - @ObservedObject private var syncCoordinator = SyncCoordinator.shared + @Binding var settings: SyncSettings + + @ObservedObject private var coordinator = SyncCoordinator.shared + @ObservedObject private var featureAccess = FeatureAccess.shared + + private static let logger = Logger(subsystem: "com.TablePro", category: "SyncSettingsView") + + private var isSyncing: Bool { + coordinator.syncStatus.isSyncing + } var body: some View { + let presentation = SyncStatusPresentation(status: coordinator.syncStatus) + let layout = SyncPaneLayout( + enabled: settings.enabled, + isLicensed: featureAccess.isAvailable(.iCloudSync), + presentation: presentation + ) + Form { - if let notice = SyncStatusPresentation(status: syncCoordinator.syncStatus).notice { - SyncNoticeSection(notice: notice) + if let notice = layout.notice { + Section { + noticeRow(notice) + } } - SyncSection() - } - .formStyle(.grouped) - } -} + Section { + Toggle(isOn: $settings.enabled) { + Text("Sync this Mac with iCloud") + Text( + "Keep your connections and the items you choose the same on devices signed in to your Apple Account." + ) + } + .disabled(layout.isToggleDisabled) + .accessibilityIdentifier("settings-sync-toggle") -private struct SyncNoticeSection: View { - let notice: SyncNotice + if layout.showsLicenseGate { + LicenseGateRow(feature: .iCloudSync) + } - @ObservedObject private var syncCoordinator = SyncCoordinator.shared - @ObservedObject private var updates = UpdateCenter.shared + if layout.showsStatus { + statusRow(presentation) + } - private static let logger = Logger(subsystem: "com.TablePro", category: "SyncSettingsView") + if layout.showsLastSynced { + lastSyncedRow(offersSyncNow: layout.offersSyncNow) + } + } - var body: some View { - Section { - HStack(alignment: .top, spacing: 10) { - Image(systemName: notice.symbolName) - .foregroundStyle(.orange) - .accessibilityHidden(true) + if layout.showsCategories { + categoriesSection + } + } + .formStyle(.grouped) + } - VStack(alignment: .leading, spacing: 4) { + private func noticeRow(_ notice: SyncNotice) -> some View { + VStack(alignment: .leading, spacing: 10) { + Label { + VStack(alignment: .leading, spacing: 2) { Text(notice.title) - .font(.headline) + .fontWeight(.semibold) + .accessibilityAddTraits(.isHeader) Text(notice.message) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) + } + } icon: { + Image(systemName: notice.symbolName) + .font(.title2) + .foregroundStyle(.orange) + .accessibilityHidden(true) + } - if !notice.actions.isEmpty { - HStack(spacing: 8) { - ForEach(notice.actions, id: \.self) { action in - control(for: action) - } - } - .padding(.top, 2) + if !notice.actions.isEmpty { + HStack(spacing: 8) { + Spacer(minLength: 0) + ForEach(notice.actions) { action in + control(for: action) } } - - Spacer() } - .padding(.vertical, 4) } + .padding(.vertical, 4) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-sync-notice") } @ViewBuilder @@ -68,9 +123,9 @@ private struct SyncNoticeSection: View { switch action { case .tryAgain: Button(action.title) { - Task { await syncCoordinator.syncNow() } + Task { await coordinator.syncNow() } } - .disabled(syncCoordinator.syncStatus.isSyncing) + .disabled(isSyncing) case .manageStorage: Button(action.title) { Self.openSystemSettings("x-apple.systempreferences:com.apple.systempreferences.AppleIDSettings*AppleIDSettings?iCloud") @@ -80,36 +135,172 @@ private struct SyncNoticeSection: View { Self.openSystemSettings("x-apple.systempreferences:com.apple.systempreferences.AppleIDSettings") } case .checkForUpdates: - Button(updates.status.appUpdateTitle) { - updates.performAppUpdateAction() - } - .disabled(!updates.isAppUpdateActionEnabled) + SyncUpdateActionButton() case .uploadAgain: Button(action.title) { - Task { await SyncCoordinator.shared.uploadAgain() } + Task { await coordinator.uploadAgain() } } case .turnOffSync: - // Through the setting, which also turns password sync off and stops the coordinator. + // The setting's commit also turns password sync off and stops the coordinator. Button(action.title) { - AppSettingsManager.shared.sync.enabled = false + settings.enabled = false } } } + private func statusRow(_ presentation: SyncStatusPresentation) -> some View { + LabeledContent { + // First baseline keeps the value on the label's baseline while the spinner shows. + HStack(alignment: .firstTextBaseline, spacing: 4) { + if isSyncing { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } else { + Image(systemName: presentation.symbolName) + .foregroundStyle(presentation.isWarning ? Color.orange : Color.secondary) + .accessibilityHidden(true) + } + + Text(presentation.title) + .accessibilityIdentifier("settings-sync-status") + } + } label: { + Text("Status") + if let detail = presentation.statusDetail { + Text(detail) + } + } + } + + private func lastSyncedRow(offersSyncNow: Bool) -> some View { + LabeledContent { + HStack(alignment: .firstTextBaseline, spacing: 10) { + SyncLastSyncedText(date: coordinator.lastSyncDate) + + if offersSyncNow { + Button("Sync Now") { + Task { await coordinator.syncNow() } + } + .disabled(isSyncing) + .accessibilityIdentifier("settings-sync-now") + } + } + } label: { + Text("Last synced") + } + } + + private var categoriesSection: some View { + Section("What Syncs") { + Toggle(isOn: syncConnections) { + Text("Connections") + Text("Connections set to Local only are left out.") + } + .accessibilityIdentifier("settings-sync-category-connections") + + Toggle(isOn: $settings.syncPasswords) { + Text("Passwords") + Text( + "Stored in iCloud Keychain, end-to-end encrypted. Applies to each password the next time you save it." + ) + } + .disabled(!settings.syncConnections) + .accessibilityIdentifier("settings-sync-category-passwords") + + Toggle("Groups & Tags", isOn: $settings.syncGroupsAndTags) + .accessibilityIdentifier("settings-sync-category-groups-and-tags") + + Toggle("SSH Profiles", isOn: $settings.syncSSHProfiles) + .accessibilityIdentifier("settings-sync-category-ssh-profiles") + + Toggle("Credential Profiles", isOn: $settings.syncCredentialProfiles) + .accessibilityIdentifier("settings-sync-category-credential-profiles") + + Toggle("Saved Queries", isOn: $settings.syncSQLFavorites) + .accessibilityIdentifier("settings-sync-category-saved-queries") + + Toggle("Table Favorites", isOn: $settings.syncTableFavorites) + .accessibilityIdentifier("settings-sync-category-table-favorites") + + Toggle("Table Folders", isOn: $settings.syncTableFolders) + .accessibilityIdentifier("settings-sync-category-table-folders") + + Toggle("Database Favorites", isOn: $settings.syncDatabaseFavorites) + .accessibilityIdentifier("settings-sync-category-database-favorites") + + // Generic on purpose: the list of settings that stay on this Mac keeps growing. + Toggle(isOn: $settings.syncSettings) { + Text("Settings") + Text( + "Preferences and custom themes. Some settings, such as fonts and the appearance mode, stay on this Mac." + ) + } + .accessibilityIdentifier("settings-sync-category-settings") + } + } + + private var syncConnections: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.syncConnections }, + set: { settings.wrappedValue = settings.wrappedValue.settingConnections($0) } + ) + } + // Notes and Freeform open these Apple Account panes, but the addresses are not documented. private static func openSystemSettings(_ address: String) { if let url = URL(string: address), NSWorkspace.shared.open(url) { return } logger.notice("System Settings did not open the Apple Account pane; opening System Settings instead") - NSWorkspace.shared.openApplication( - at: URL(fileURLWithPath: "/System/Applications/System Settings.app"), - configuration: NSWorkspace.OpenConfiguration() - ) + guard let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.systempreferences") else { + logger.error("System Settings is not installed") + return + } + NSWorkspace.shared.openApplication(at: app, configuration: NSWorkspace.OpenConfiguration()) + } +} + +// Only this button observes UpdateCenter, so an update check redraws it and not the pane. +private struct SyncUpdateActionButton: View { + @ObservedObject private var updates = UpdateCenter.shared + + var body: some View { + Button(updates.status.appUpdateTitle) { + updates.performAppUpdateAction() + } + .disabled(!updates.isAppUpdateActionEnabled) + } +} + +// Reads like Time Machine's latest backup ("Today at 14:50") and moves to "Yesterday" without a reopen. +private struct SyncLastSyncedText: View { + let date: Date? + + private static let formatter: DateFormatter = { + let formatter = DateFormatter() + formatter.locale = .autoupdatingCurrent + formatter.dateStyle = .medium + formatter.timeStyle = .short + formatter.doesRelativeDateFormatting = true + return formatter + }() + + var body: some View { + if let date { + TimelineView(.everyMinute) { context in + Text(verbatim: Self.formatter.string(from: min(date, context.date))) + .accessibilityIdentifier("settings-sync-last-synced") + } + } else { + Text("Never") + .accessibilityIdentifier("settings-sync-last-synced") + } } } #Preview { - SyncSettingsView() - .frame(width: 640, height: 500) + SyncSettingsView(settings: .constant(.default)) + .frame(width: 520, height: 500) } diff --git a/apple/TableProTests/Models/Settings/SyncSettingsTests.swift b/apple/TableProTests/Models/Settings/SyncSettingsTests.swift new file mode 100644 index 0000000000..2925239f14 --- /dev/null +++ b/apple/TableProTests/Models/Settings/SyncSettingsTests.swift @@ -0,0 +1,133 @@ +import Foundation +@testable import TablePro +import TableProSyncTransport +import Testing + +struct SyncSettingsTests { + private static let everythingOn = SyncSettings( + enabled: true, + syncConnections: true, + syncGroupsAndTags: true, + syncSettings: true, + syncPasswords: true, + syncSSHProfiles: true, + syncCredentialProfiles: true, + syncTableFavorites: true, + syncDatabaseFavorites: true, + syncSQLFavorites: true, + syncTableFolders: true + ) + + @Test("Turning Connections off turns Passwords off and leaves every other category") + func connectionsOffClearsPasswords() { + let result = Self.everythingOn.settingConnections(false) + + var expected = Self.everythingOn + expected.syncConnections = false + expected.syncPasswords = false + #expect(result == expected) + #expect(!result.syncsPasswords) + } + + @Test("Turning Connections on keeps Passwords as it was", arguments: [true, false]) + func connectionsOnKeepsPasswords(passwords: Bool) { + var settings = Self.everythingOn + settings.syncConnections = false + settings.syncPasswords = passwords + settings.syncTableFolders = false + + let result = settings.settingConnections(true) + + var expected = settings + expected.syncConnections = true + #expect(result == expected) + } + + @Test("Turning Connections off when it is already off changes nothing") + func connectionsOffTwiceIsStable() { + let once = SyncSettings.default.settingConnections(false) + #expect(once.settingConnections(false) == once) + } +} + +struct SyncPaneLayoutTests { + private static func layout( + enabled: Bool, + isLicensed: Bool, + status: SyncStatus = .idle + ) -> SyncPaneLayout { + SyncPaneLayout(enabled: enabled, isLicensed: isLicensed, presentation: SyncStatusPresentation(status: status)) + } + + @Test("Unlicensed and off: the switch is disabled and only the license gate shows") + func unlicensedOff() { + let layout = Self.layout(enabled: false, isLicensed: false, status: .disabled(.licenseRequired)) + #expect(layout.isToggleDisabled) + #expect(layout.showsLicenseGate) + #expect(!layout.showsStatus) + #expect(!layout.showsLastSynced) + #expect(!layout.showsCategories) + #expect(layout.notice == nil) + } + + @Test("A lapsed license leaves the switch enabled so sync can be turned off") + func lapsedLicenseCanTurnOff() { + let layout = Self.layout(enabled: true, isLicensed: false, status: .disabled(.licenseExpired)) + #expect(!layout.isToggleDisabled) + #expect(layout.showsLicenseGate) + #expect(!layout.showsStatus) + #expect(!layout.showsLastSynced) + #expect(!layout.showsCategories) + } + + @Test("Licensed and off: the categories show so they can be chosen before the first upload") + func licensedOffShowsCategories() { + let layout = Self.layout(enabled: false, isLicensed: true, status: .disabled(.userDisabled)) + #expect(!layout.isToggleDisabled) + #expect(!layout.showsLicenseGate) + #expect(!layout.showsStatus) + #expect(!layout.showsLastSynced) + #expect(layout.showsCategories) + } + + @Test("Licensed, on and idle: status, last synced with Sync Now, and the categories") + func licensedOnIdle() { + let layout = Self.layout(enabled: true, isLicensed: true, status: .idle) + #expect(layout.notice == nil) + #expect(layout.showsStatus) + #expect(layout.showsLastSynced) + #expect(layout.offersSyncNow) + #expect(layout.showsCategories) + } + + @Test( + "A failure that a retry can clear keeps the Status row and Sync Now", + arguments: [SyncError.offline, .busy, .recordsRejected(count: 2), .pullNotSaved, .unexpected] + ) + func nonBlockerError(error: SyncError) { + let layout = Self.layout(enabled: true, isLicensed: true, status: .error(error)) + #expect(layout.notice == nil) + #expect(layout.showsStatus) + #expect(layout.offersSyncNow) + } + + @Test( + "A blocker shows the notice instead of the Status row and drops Sync Now", + arguments: [SyncBlocker.storageFull, .signedOut, .accountNotReady, .dataDeletedFromICloud, .appUpdateRequired] + ) + func blockerShowsNotice(blocker: SyncBlocker) { + let layout = Self.layout(enabled: true, isLicensed: true, status: .error(.blocked(blocker))) + #expect(layout.notice != nil) + #expect(!layout.showsStatus) + #expect(layout.showsLastSynced) + #expect(!layout.offersSyncNow) + #expect(layout.showsCategories) + } + + @Test("While syncing the Status row stays") + func syncingKeepsStatus() { + let layout = Self.layout(enabled: true, isLicensed: true, status: .syncing) + #expect(layout.showsStatus) + #expect(layout.offersSyncNow) + } +} From 1e99f279d8d5d67eb1b5bb4397279b1d645aafb6 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:24:54 +0700 Subject: [PATCH 34/48] feat(settings): Account pane with Features, Devices, Teams and License pages --- .../TeamLibrary/TeamLibrarySync.swift | 16 +- .../TablePro/Models/Settings/ProFeature.swift | 9 +- .../Views/Account/DeviceLimitSheet.swift | 138 +-- .../Views/Account/LicenseKeySheet.swift | 33 +- .../Account/AccountFeaturesSection.swift | 69 +- .../Account/AccountSettingsContent.swift | 36 +- .../Account/AccountSettingsModel.swift | 170 ++- .../Account/AccountSettingsView.swift | 1017 +++++++++-------- .../Account/LicensePresentation.swift | 14 +- .../Entries/AccountSettingsEntry.swift | 112 +- .../AccountSettingsContentTests.swift | 78 +- .../Settings/AccountSettingsModelTests.swift | 201 +++- .../AccountSettingsUITests.swift | 41 + 13 files changed, 1240 insertions(+), 694 deletions(-) create mode 100644 apple/TableProUITests/AccountSettingsUITests.swift diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift index ef259ef854..f9f06ec53b 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibrarySync.swift @@ -1,8 +1,3 @@ -// -// TeamLibrarySync.swift -// TablePro -// - import Combine import Foundation import os @@ -91,6 +86,11 @@ internal final class TeamLibrarySync: ObservableObject { !writableTeams.isEmpty } + // What a sign-out drops with the rest of the library: edits not pushed yet and conflicts not resolved. + var hasUnsentChanges: Bool { + teams.values.contains { !$0.pending.isEmpty || !$0.conflicts.isEmpty } + } + func start() { guard scheduleTask == nil else { return } loadIfNeeded() @@ -209,8 +209,6 @@ internal final class TeamLibrarySync: ObservableObject { publishContent() } - // MARK: - Sync - private func performSync() async -> TeamLibrarySyncOutcome { guard account.session.isSignedIn else { return .skipped } guard account.access.isAvailable(.teamLibrary) else { @@ -501,8 +499,6 @@ internal final class TeamLibrarySync: ObservableObject { commit(state) } - // MARK: - Publish - // `owns` tells this Mac's own items from someone else's that a publish only moves. private func publish( to teamID: String, @@ -572,8 +568,6 @@ internal final class TeamLibrarySync: ObservableObject { return .success(conflicted > 0 ? .conflicts(conflicted) : .published(edits.count)) } - // MARK: - Helpers - private func serially(_ work: @escaping @MainActor () async -> Value) -> Task { let previous = tail let task = Task { @MainActor in diff --git a/apple/TablePro/Models/Settings/ProFeature.swift b/apple/TablePro/Models/Settings/ProFeature.swift index 741fb45c3c..097a22179a 100644 --- a/apple/TablePro/Models/Settings/ProFeature.swift +++ b/apple/TablePro/Models/Settings/ProFeature.swift @@ -1,8 +1,3 @@ -// -// ProFeature.swift -// TablePro -// - import Foundation // Raw values are the feature codes the entitlement carries (product.md, Feature codes). @@ -58,9 +53,9 @@ internal enum ProFeature: String, CaseIterable { case .linkedFolders: return "folder.badge.gearshape" case .teamCatalog: - return "person.2.fill" + return "person.2" case .teamLibrary: - return "books.vertical.fill" + return "books.vertical" case .compareSync: return "arrow.left.arrow.right.square" case .dataRewind: diff --git a/apple/TablePro/Views/Account/DeviceLimitSheet.swift b/apple/TablePro/Views/Account/DeviceLimitSheet.swift index 759af1efac..9c475b2cf1 100644 --- a/apple/TablePro/Views/Account/DeviceLimitSheet.swift +++ b/apple/TablePro/Views/Account/DeviceLimitSheet.swift @@ -1,8 +1,3 @@ -// -// DeviceLimitSheet.swift -// TablePro -// - import SwiftUI internal struct DeviceLimitSheet: View { @@ -16,66 +11,53 @@ internal struct DeviceLimitSheet: View { } var body: some View { - VStack(alignment: .leading, spacing: 16) { - HStack(alignment: .top, spacing: 12) { - Image(systemName: "laptopcomputer.and.iphone") - .font(.largeTitle) - .foregroundStyle(.secondary) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 4) { - Text("Your plan is in use on 3 other devices") - .font(.headline) - - Text("Remove one to use your plan on this Mac. Until then, TablePro works on the Free plan here.") - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - - VStack(spacing: 0) { - ForEach(model.rows) { row in - if row.id != model.rows.first?.id { - Divider() + VStack(spacing: 0) { + header + + Divider() + + Form { + Section { + ForEach(model.rows) { row in + DeviceLimitRow( + row: row, + isRemoving: model.removing == row.id, + isDisabled: model.removing != nil + ) { + pendingRemoval = row + } } - DeviceLimitRow( - row: row, - isRemoving: model.removing == row.id, - isDisabled: model.removing != nil - ) { - pendingRemoval = row + + if let failure = model.failure { + NoticeLabel(failure) + .font(.subheadline) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("device-limit-error") } } } - .background(.background, in: RoundedRectangle(cornerRadius: 8)) - .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Color(nsColor: .separatorColor))) + .formStyle(.grouped) + // A grouped Form answers any proposal with the whole height, so it alone is capped. + .frame(height: 260) - if let failure = model.failure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .font(.callout) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("device-limit-error") - } + Divider() - HStack { + DialogFooter { Button(String(localized: "Manage Devices…")) { openURL(model.services.configuration.portalDevices) } - - Spacer() - + } actions: { Button(String(localized: "Not Now")) { dismiss() } .keyboardShortcut(.cancelAction) .accessibilityIdentifier("device-limit-not-now") } + .padding(16) } - .padding(20) .frame(width: 480) .onChange(of: model.isResolved) { isResolved in if isResolved { dismiss() } } - .confirmationDialog( + .alert( pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), presenting: pendingRemoval @@ -83,12 +65,34 @@ internal struct DeviceLimitSheet: View { Button(String(localized: "Remove"), role: .destructive) { Task { await model.remove(row) } } + Button(String(localized: "Cancel"), role: .cancel) {} } message: { _ in Text("TablePro on that device signs out the next time it checks your account, and this Mac takes its place.") } .accessibilityElement(children: .contain) .accessibilityIdentifier("device-limit-sheet") } + + private var header: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: "desktopcomputer") + .font(.largeTitle) + .foregroundStyle(.secondary) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 4) { + Text("Your plan is in use on 3 other devices") + .font(.headline) + + Text("Remove one to use your plan on this Mac. Until then, TablePro works on the Free plan here.") + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + Spacer(minLength: 0) + } + .padding(20) + } } private struct DeviceLimitRow: View { @@ -98,38 +102,32 @@ private struct DeviceLimitRow: View { let onRemove: () -> Void var body: some View { - HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 2) { - Text(row.name) - .lineLimit(1) - .truncationMode(.middle) - - Text(AccountDeviceText.detail(system: row.system, lastSeenAt: row.lastSeenAt)) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - } - - Spacer(minLength: 12) - + SettingsRecordRow( + title: row.name, + subtitle: AccountDeviceText.detail(system: row.system, lastSeenAt: row.lastSeenAt) + ) { if let offlineUntil = row.offlineUntil { Text(AccountDeviceText.offlineFile(until: offlineUntil)) - .font(.callout) .foregroundStyle(.secondary) - .multilineTextAlignment(.trailing) + .lineLimit(1) + .layoutPriority(1) } else if isRemoving { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Removing")) } else { - Button(String(localized: "Remove"), action: onRemove) + Button(String(localized: "Remove…"), action: onRemove) .disabled(isDisabled) + .fixedSize() .accessibilityLabel(Text(String(format: String(localized: "Remove %@"), row.name))) } } - .padding(.horizontal, 12) - .padding(.vertical, 8) - .accessibilityElement(children: .contain) + .contextMenu { + if row.offlineUntil == nil { + Button(String(localized: "Remove…"), action: onRemove) + .disabled(isDisabled) + } + } } } @@ -143,6 +141,12 @@ internal enum AccountDeviceText { return String(format: String(localized: "%@ · %@"), system, lastSeen) } + // This Mac is the one showing the list, so it is seen now whatever the server last recorded. + static func detail(system: String, lastSeenAt: Date, isThisMac: Bool) -> String { + guard isThisMac else { return detail(system: system, lastSeenAt: lastSeenAt) } + return String(format: String(localized: "%@ · %@"), String(localized: "This Mac"), detail(system: system, lastSeenAt: Date())) + } + static func offlineFile(until date: Date) -> String { String(format: String(localized: "Offline file until %@"), date.formatted(date: .abbreviated, time: .omitted)) } diff --git a/apple/TablePro/Views/Account/LicenseKeySheet.swift b/apple/TablePro/Views/Account/LicenseKeySheet.swift index b68ae5e34d..82f1dfbb55 100644 --- a/apple/TablePro/Views/Account/LicenseKeySheet.swift +++ b/apple/TablePro/Views/Account/LicenseKeySheet.swift @@ -1,8 +1,3 @@ -// -// LicenseKeySheet.swift -// TablePro -// - import SwiftUI // Use License Key…: a key an older build saved here is offered filled in, and deleted once it is exchanged. @@ -15,6 +10,7 @@ internal struct LicenseKeySheet: View { @Environment(\.dismiss) private var dismiss @State private var key: String @State private var failure: String? + @State private var exchange: Task? @FocusState private var isFieldFocused: Bool init(storedKey: String?, signedInEmail: String?, isWorking: Bool, onUse: @escaping (String) async -> String?) { @@ -57,29 +53,26 @@ internal struct LicenseKeySheet: View { if storedKey != nil, trimmedKey == storedKey { Text("An older version of TablePro saved this key on this Mac. It is deleted once it is used.") - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } if let failure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .font(.callout) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) + NoticeLabel(failure) + .font(.subheadline) + .accessibilityElement(children: .combine) .accessibilityIdentifier("license-key-error") } - HStack { - Spacer() - + DialogFooter { if isWorking { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Checking the license key")) } - Button(String(localized: "Cancel")) { dismiss() } + Button(String(localized: "Cancel"), action: cancel) .keyboardShortcut(.cancelAction) Button(String(localized: "Use Key"), action: use) @@ -91,14 +84,22 @@ internal struct LicenseKeySheet: View { .padding(20) .frame(width: 440) .onAppear { isFieldFocused = true } + .onDisappear { exchange?.cancel() } } private func use() { guard !trimmedKey.isEmpty, !isWorking else { return } failure = nil let key = trimmedKey - Task { - failure = await onUse(key) + exchange = Task { + let result = await onUse(key) + guard !Task.isCancelled else { return } + failure = result } } + + private func cancel() { + exchange?.cancel() + dismiss() + } } diff --git a/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift b/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift index 1f77c0c5bc..3f73a68183 100644 --- a/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift +++ b/apple/TablePro/Views/Settings/Account/AccountFeaturesSection.swift @@ -1,32 +1,48 @@ -// -// AccountFeaturesSection.swift -// TablePro -// - import SwiftUI -struct AccountFeaturesSection: View { +internal struct AccountFeaturesPage: View { @ObservedObject var access: FeatureAccess - let offersPurchase: Bool + + private var offersPurchase: Bool { + !access.state.isSignedIn && access.state.entitlement == nil && access.state.legacy == nil + } var body: some View { - Section { - ForEach(ProFeature.allCases, id: \.self) { feature in - AccountFeatureRow(feature: feature, isIncluded: access.isAvailable(feature)) + Form { + Section { + ForEach(ProFeature.allCases, id: \.self) { feature in + AccountFeatureRow(feature: feature, isIncluded: access.isAvailable(feature)) + } } - } header: { - Text("Features") - } footer: { - HStack(spacing: 16) { + + Section { if offersPurchase { - Link("Buy a License", destination: SupportLinks.pricing(.licenseSettings)) - .countsUpgradeClicks(from: .licenseSettings) + LabeledContent { + Link(String(localized: "View Plans…"), destination: SupportLinks.pricing(.licenseSettings)) + .buttonStyle(.bordered) + .fixedSize() + .countsUpgradeClicks(from: .licenseSettings) + .accessibilityIdentifier("account-view-plans") + } label: { + Text("Paid plans") + Text("Compare what each plan includes.") + } } - Link("Learn More About Licensing", destination: SupportLinks.licensingGuide) + LabeledContent { + Link(String(localized: "Learn More…"), destination: SupportLinks.licensingGuide) + .buttonStyle(.bordered) + .fixedSize() + .accessibilityIdentifier("account-licensing-guide") + } label: { + Text("Plans and devices") + Text("How plans, devices and offline files work.") + } } - .font(.callout) } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountFeatures.pageIdentifier) } } @@ -45,12 +61,12 @@ private struct AccountFeatureRow: View { Text(feature.displayName) Text(feature.featureDescription) - .font(.callout) + .font(.subheadline) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } - Spacer() + Spacer(minLength: 12) if isIncluded { Label { @@ -60,13 +76,18 @@ private struct AccountFeatureRow: View { Image(systemName: "checkmark.circle.fill") .foregroundStyle(.green) } + .fixedSize() } else { - Image(systemName: "lock.fill") - .foregroundStyle(.secondary) - .accessibilityLabel(Text(feature.paidPlanRequirement)) + Label { + Text("Not included") + } icon: { + Image(systemName: "lock.fill") + } + .foregroundStyle(.secondary) + .fixedSize() + .accessibilityLabel(Text(feature.paidPlanRequirement)) } } - .padding(.vertical, 2) .accessibilityElement(children: .combine) } } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift index b0d4029775..f94d98fa95 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift @@ -1,8 +1,3 @@ -// -// AccountSettingsContent.swift -// TablePro -// - import Foundation // What Settings > Account shows for one account state (clients.md, Settings > Account). @@ -81,6 +76,14 @@ internal struct AccountSettingsContent: Equatable { let isExpired: Bool } + enum VerificationState: Equatable { + case verified(at: Date, until: Date) + case offlineFile(until: Date) + case expired(on: Date) + case offlineFileExpired(on: Date) + case notVerified + } + static let expiryWarning: TimeInterval = 3 * 24 * 60 * 60 let identity: Identity @@ -89,6 +92,7 @@ internal struct AccountSettingsContent: Equatable { let plans: [PlanRow] let isFree: Bool let showsDevices: Bool + let showsTeams: Bool let devices: [DeviceRow]? let teams: [TeamRow]? let verification: Verification? @@ -119,6 +123,7 @@ internal struct AccountSettingsContent: Equatable { plans: plans, isFree: showsPlan && !isDeviceLimit && entitlement != nil && plans.isEmpty, showsDevices: state.isSignedIn, + showsTeams: state.isSignedIn, devices: state.isSignedIn ? devices.map { deviceRows($0, machineID: machineID, now: now) } : nil, teams: state.isSignedIn ? profile.map { teamRows($0, configuration: configuration) } : nil, verification: entitlement.map { @@ -134,6 +139,21 @@ internal struct AccountSettingsContent: Equatable { ) } + var verificationState: VerificationState? { + guard let verification else { return canRefresh ? .notVerified : nil } + switch (verification.isOfflineFile, verification.isExpired) { + case (false, false): return .verified(at: verification.verifiedAt, until: verification.validUntil) + case (true, false): return .offlineFile(until: verification.validUntil) + case (false, true): return .expired(on: verification.validUntil) + case (true, true): return .offlineFileExpired(on: verification.validUntil) + } + } + + // A notice with Try Again already runs the check the verification row's Refresh would. + var offersRetry: Bool { + notices.contains { LicensePresentation.action(for: $0) == .retryValidation } + } + // Without GET /v2/me, so a team plan's payment notice offers no billing link here. static func notices(state: AccountState, configuration: AccountConfiguration, now: Date) -> [Notice] { let isDeviceLimit = state.refresh.isDeviceLimit @@ -268,6 +288,12 @@ internal struct AccountSettingsContent: Equatable { // The pane, the gates and Welcome read a state in the same words. extension AccountSettingsContent.Notice { + // A canceling plan is the person's own choice, so it informs rather than warns. + var isInformational: Bool { + if case .canceling = self { return true } + return false + } + var title: String { switch self { case .deviceLimit: diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift index 5cbc081119..a43d572399 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsModel.swift @@ -1,10 +1,6 @@ -// -// AccountSettingsModel.swift -// TablePro -// - import Combine import Foundation +import TableProHTTP internal struct AccountRemote: Equatable { var value: Value? @@ -19,6 +15,26 @@ internal struct AccountActionFailure: Equatable, Identifiable { var id: String { title + message } } +internal struct AccountSignOutConfirmation: Equatable { + let discardsTeamChanges: Bool + let removesOfflineFile: Bool + + var discardsSomething: Bool { + discardsTeamChanges || removesOfflineFile + } + + var message: String { + var sentences = [String(localized: "Paid features stop on this Mac until you sign in again.")] + if discardsTeamChanges { + sentences.append(String(localized: "Team library changes that were not sent yet are discarded.")) + } + if removesOfflineFile { + sentences.append(String(localized: "The imported offline file is removed.")) + } + return sentences.joined(separator: " ") + } +} + @MainActor internal final class AccountSettingsModel: ObservableObject { enum Activity: Equatable { @@ -30,6 +46,20 @@ internal final class AccountSettingsModel: ObservableObject { case usingKey } + struct Loader { + var profile: @MainActor () async throws(AccountError) -> AccountProfile + var devices: @MainActor () async throws(AccountError) -> [AccountDevice] + + static func live(_ services: AccountServices) -> Loader { + Loader( + profile: { () async throws(AccountError) -> AccountProfile in try await services.fetchProfile() }, + devices: { () async throws(AccountError) -> [AccountDevice] in try await services.fetchDevices() } + ) + } + } + + static let freshness: TimeInterval = 60 + @Published private(set) var profile = AccountRemote() @Published private(set) var devices = AccountRemote<[AccountDevice]>() @Published private(set) var activity: Activity? @@ -40,15 +70,34 @@ internal final class AccountSettingsModel: ObservableObject { // Read once when the sheet opens, not on every render: it comes from the Keychain. @Published private(set) var licenseKeyPrefill: String? @Published var presentsOfflineImporter = false + @Published var pendingRemoval: AccountSettingsContent.DeviceRow? + // Taken when Sign Out… is clicked, so the dialog names what this Mac held at that moment. + @Published private(set) var signOutConfirmation: AccountSignOutConfirmation? let services: AccountServices + private let loader: Loader private let now: () -> Date + private let openURL: @MainActor (URL) -> Void + private let hasUnsentTeamChanges: @MainActor () -> Bool private var stateObserver: AnyCancellable? private var loadedSignedIn: Bool? + // Bumped when the loaded data is dropped, so a load still out for the old account lands nowhere. + private var generation = 0 + private var lastLoad: Date? + private var returnsFromPortal = false - init(services: AccountServices, now: @escaping () -> Date = { Date() }) { + init( + services: AccountServices, + loader: Loader? = nil, + now: @escaping () -> Date = { Date() }, + openURL: @escaping @MainActor (URL) -> Void = { _ = WebPageOpener.open($0, scope: .httpsOrLoopbackHTTP) }, + hasUnsentTeamChanges: @escaping @MainActor () -> Bool = { TeamLibrarySync.shared.hasUnsentChanges } + ) { self.services = services + self.loader = loader ?? .live(services) self.now = now + self.openURL = openURL + self.hasUnsentTeamChanges = hasUnsentTeamChanges stateObserver = services.access.$state .dropFirst() .sink { [weak self] state in @@ -80,6 +129,29 @@ internal final class AccountSettingsModel: ObservableObject { activity != nil } + var confirmsSignOut: Bool { + signOutConfirmation != nil + } + + // Every show of the pane and every return to the window: a portal visit may have changed the account. + func refreshOnVisit() async { + guard returnsFromPortal else { + await reloadIfStale() + return + } + returnsFromPortal = false + await services.checkNow() + await reload() + } + + func reloadIfStale() async { + if services.access.state.isSignedIn == loadedSignedIn, let lastLoad, + now().timeIntervalSince(lastLoad) < Self.freshness { + return + } + await reload() + } + // Keeps what it loaded before when a load fails; a sign-in or sign-out drops it first. func reload() async { let isSignedIn = services.access.state.isSignedIn @@ -88,32 +160,55 @@ internal final class AccountSettingsModel: ObservableObject { loadedSignedIn = isSignedIn } guard isSignedIn else { return } - async let profileLoad: Void = loadProfile() - async let devicesLoad: Void = loadDevices() - _ = await (profileLoad, devicesLoad) + let started = generation + async let profileLoad = loadProfile() + async let devicesLoad = loadDevices() + let (profileLoaded, devicesLoaded) = await (profileLoad, devicesLoad) + guard started == generation, profileLoaded, devicesLoaded else { return } + lastLoad = now() } - func loadProfile() async { - if profile.value == nil { - profile.isLoading = true - } + @discardableResult + func loadProfile() async -> Bool { + let started = generation + profile.isLoading = true do throws(AccountError) { - profile = AccountRemote(value: try await services.fetchProfile()) + let value = try await loader.profile() + guard started == generation else { return false } + profile = AccountRemote(value: value) + return true + } catch .canceled { + if started == generation { + profile.isLoading = false + } + return false } catch { + guard started == generation else { return false } profile.isLoading = false profile.failure = error.friendlyDescription ?? String(localized: "Could not load your teams.") + return false } } - func loadDevices() async { - if devices.value == nil { - devices.isLoading = true - } + @discardableResult + func loadDevices() async -> Bool { + let started = generation + devices.isLoading = true do throws(AccountError) { - devices = AccountRemote(value: try await services.fetchDevices()) + let value = try await loader.devices() + guard started == generation else { return false } + devices = AccountRemote(value: value) + return true + } catch .canceled { + if started == generation { + devices.isLoading = false + } + return false } catch { + guard started == generation else { return false } devices.isLoading = false devices.failure = error.friendlyDescription ?? String(localized: "Could not load your devices.") + return false } } @@ -130,7 +225,19 @@ internal final class AccountSettingsModel: ObservableObject { presentDeviceLimitIfReached() } + func requestSignOut() { + signOutConfirmation = AccountSignOutConfirmation( + discardsTeamChanges: hasUnsentTeamChanges(), + removesOfflineFile: services.access.state.entitlement?.isOffline == true + ) + } + + func cancelSignOut() { + signOutConfirmation = nil + } + func signOut() async { + signOutConfirmation = nil activity = .signingOut defer { activity = nil } await services.signOut() @@ -143,7 +250,14 @@ internal final class AccountSettingsModel: ObservableObject { await reload() } + // The next return to the window checks the account again: billing, devices and teams change in the portal. + func openPortal(_ url: URL) { + returnsFromPortal = true + openURL(url) + } + func removeDevice(_ device: AccountSettingsContent.DeviceRow) async { + pendingRemoval = nil activity = .removing(device.id) defer { activity = nil } do throws(AccountError) { @@ -171,20 +285,30 @@ internal final class AccountSettingsModel: ObservableObject { } } - // Nil when the key signed this Mac in; the message to show beside the key otherwise. + func offlineFilePickerFailed(_ error: any Error) { + actionFailure = AccountActionFailure( + title: String(localized: "Could not import the offline file"), + message: error.localizedDescription + ) + } + + // Nil when the key signed this Mac in or the exchange was canceled; the message to show beside the key otherwise. func useLicenseKey(_ key: String) async -> String? { activity = .usingKey defer { activity = nil } do throws(AccountError) { _ = try await services.useLicenseKey(key) + } catch .canceled { + return nil } catch { return error.licenseKeyDescription ?? String(localized: "Could not use this license key.") } presentsLicenseKey = false presentDeviceLimitIfReached() - // The key may belong to another account than the one signed in before. + // The key may belong to another account than the one signed in before. The sheet closing cancels its own + // task, so the reload runs outside it. forgetLoaded() - await reload() + Task { await reload() } return nil } @@ -200,6 +324,8 @@ internal final class AccountSettingsModel: ObservableObject { } private func forgetLoaded() { + generation += 1 + lastLoad = nil profile = AccountRemote() devices = AccountRemote() } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift index ac37ac9a77..f59961f1c7 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift @@ -1,459 +1,331 @@ -// -// AccountSettingsView.swift -// TablePro -// - import SwiftUI -import UniformTypeIdentifiers -// Settings > Account (clients.md): Account, Plan, Features, Devices, Teams, Offline. +// Settings > Account (clients.md): identity, Plan, then the Features, Devices, Teams and Offline File pages. internal struct AccountSettingsView: View { - @StateObject private var model: AccountSettingsModel - @Environment(\.openURL) private var openURL - @State private var pendingRemoval: AccountSettingsContent.DeviceRow? - - init(model: @autoclosure @escaping () -> AccountSettingsModel) { - _model = StateObject(wrappedValue: model()) - } - - private enum Subpage: Hashable { - case features, devices, teams, offline - } - - private var showsTeams: Bool { - let content = model.content - let failure = model.access.state.isSignedIn ? model.profile.failure : nil - return content.teams?.isEmpty == false || failure != nil || (content.teams == nil && model.profile.isLoading) - } + @ObservedObject var model: AccountSettingsModel + let showDevices: () -> Void var body: some View { let content = model.content Form { - AccountIdentitySection(model: model, identity: content.identity) + AccountIdentitySection(model: model, identity: content.identity, canRefresh: content.canRefresh) if content.showsPlan { - planSection(content) + AccountPlanSection(model: model, content: content, showDevices: showDevices) } Section { - NavigationLink(value: Subpage.features) { - Label("Features", systemImage: "star") - } - if content.showsDevices { - NavigationLink(value: Subpage.devices) { - Label("Devices", systemImage: "laptopcomputer") - } - } - if showsTeams { - NavigationLink(value: Subpage.teams) { - Label("Teams", systemImage: "person.2") - } - } - NavigationLink(value: Subpage.offline) { - Label("Offline", systemImage: "wifi.slash") - } - } - } - .formStyle(.grouped) - .navigationDestination(for: Subpage.self) { subpage in - destination(for: subpage) - } - .task { await model.reload() } - .sheet(isPresented: $model.presentsDeviceLimit) { - DeviceLimitSheet(model: DeviceLimitModel(services: model.services)) - } - .sheet(isPresented: $model.presentsLicenseKey) { - LicenseKeySheet( - storedKey: model.licenseKeyPrefill, - signedInEmail: model.access.state.isSignedIn ? model.profile.value?.email ?? model.access.state.entitlement?.email : nil, - isWorking: model.activity == .usingKey - ) { key in - await model.useLicenseKey(key) - } - } - .fileImporter( - isPresented: $model.presentsOfflineImporter, - allowedContentTypes: [UTType(filenameExtension: "jwt") ?? .data], - allowsMultipleSelection: false - ) { result in - if case .success(let urls) = result, let url = urls.first { - Task { await model.importOfflineFile(at: url) } - } - } - .alert( - model.actionFailure?.title ?? "", - isPresented: Binding(get: { model.actionFailure != nil }, set: { if !$0 { model.actionFailure = nil } }), - presenting: model.actionFailure - ) { _ in - Button(String(localized: "OK")) {} - } message: { failure in - Text(failure.message) - } - .confirmationDialog( - pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", - isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), - presenting: pendingRemoval - ) { row in - Button(String(localized: "Remove"), role: .destructive) { - Task { await model.removeDevice(row) } - } - } message: { _ in - Text("TablePro on that device signs out the next time it checks your account. Its paid features keep working until its last check expires.") - } - } - - @ViewBuilder - private func destination(for subpage: Subpage) -> some View { - let content = model.content - switch subpage { - case .features: - Form { - AccountFeaturesSection(access: model.access, offersPurchase: content.identity == .signedOut) - } - .formStyle(.grouped) - .settingsDrillIn(title: String(localized: "Features")) - case .devices: - Form { devicesSection(content.devices) } - .formStyle(.grouped) - .settingsDrillIn(title: String(localized: "Devices")) - case .teams: - Form { teamsSection(content.teams) } - .formStyle(.grouped) - .settingsDrillIn(title: String(localized: "Teams")) - case .offline: - Form { AccountOfflineSection(model: model, content: content) } - .formStyle(.grouped) - .settingsDrillIn(title: String(localized: "Offline")) - } - } - - // MARK: - Plan - - private func planSection(_ content: AccountSettingsContent) -> some View { - Section { - ForEach(content.notices) { notice in - AccountNoticeRow(notice: notice, model: model) - } - - ForEach(content.plans) { plan in - AccountPlanRow(plan: plan) - } - - if content.notices.isEmpty, content.plans.isEmpty, !content.isFree { - AccountLoadingRow(label: String(localized: "Checking your plan")) - } - - if content.isFree { - HStack { - VStack(alignment: .leading, spacing: 2) { - Text("You're on Free") - Text("Paid plans add the features below.") - .font(.callout) - .foregroundStyle(.secondary) - } - - Spacer() - - Button(String(localized: "Upgrade…")) { - Telemetry.shared.upgradeClicked(from: .licenseSettings) - openURL(model.services.configuration.portalBilling) - } - .accessibilityIdentifier("account-upgrade") - } - } - } header: { - Text("Plan") - } - } - - // MARK: - Devices - - private func devicesSection(_ devices: [AccountSettingsContent.DeviceRow]?) -> some View { - Section { - if let devices { - ForEach(devices) { device in - AccountDeviceRow( - device: device, - isRemoving: model.activity == .removing(device.id), - isDisabled: model.isBusy - ) { - pendingRemoval = device - } - } - } else if model.devices.isLoading { - AccountLoadingRow(label: String(localized: "Loading devices")) - } - - if let failure = model.devices.failure { - AccountLoadFailureRow(message: failure) { - Task { await model.loadDevices() } - } - } - } header: { - Text("Devices") - } footer: { - Text("A plan works on up to 3 devices at a time. Removing one signs TablePro out there.") - .font(.callout) - .foregroundStyle(.secondary) - } - } - - // MARK: - Teams + SettingsDrillRow(route: SettingsRoute.page(.accountFeatures), title: SettingsPage.accountFeatures.title) - @ViewBuilder - private func teamsSection(_ teams: [AccountSettingsContent.TeamRow]?) -> some View { - let failure = model.access.state.isSignedIn ? model.profile.failure : nil - if teams?.isEmpty == false || failure != nil || (teams == nil && model.profile.isLoading) { - Section { - ForEach(teams ?? []) { team in - AccountTeamRow(team: team) + if content.showsDevices { + SettingsDrillRow( + route: SettingsRoute.page(.accountDevices), + title: SettingsPage.accountDevices.title, + value: content.devices.map { $0.count.formatted(.number) } + ) } - if teams == nil, model.profile.isLoading { - AccountLoadingRow(label: String(localized: "Loading teams")) + if content.showsTeams { + SettingsDrillRow( + route: SettingsRoute.page(.accountTeams), + title: SettingsPage.accountTeams.title, + value: content.teams.map { $0.isEmpty ? String(localized: "None") : $0.count.formatted(.number) } + ) } - if let failure { - AccountLoadFailureRow(message: failure) { - Task { await model.loadProfile() } - } - } - } header: { - Text("Teams") + SettingsDrillRow(route: SettingsRoute.page(.accountOffline), title: SettingsPage.accountOffline.title) } } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-account") } } -// MARK: - Account - private struct AccountIdentitySection: View { @ObservedObject var model: AccountSettingsModel let identity: AccountSettingsContent.Identity - @Environment(\.openURL) private var openURL + let canRefresh: Bool var body: some View { Section { switch identity { - case .account(let name, let email, let isSignedIn): - signedIn(name: name, email: email, isSignedIn: isSignedIn) + case .account(let name, let email, true): + signedIn(name: name, email: email) + case .account(let name, let email, false): + offlineFile(name: name, email: email) case .licenseKey(let isValid): licenseKey(isValid: isValid) case .signedOut: signedOut } - } header: { - Text("Account") } } @ViewBuilder - private func signedIn(name: String?, email: String?, isSignedIn: Bool) -> some View { - HStack(spacing: 12) { - Image(systemName: "person.crop.circle.fill") - .font(.system(size: 36)) - .foregroundStyle(.secondary) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 2) { - Text(name ?? email ?? String(localized: "Signed in")) - .font(.headline) - .lineLimit(1) - .truncationMode(.tail) - - if name != nil, let email { - Text(email) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - - if !isSignedIn { - Text("From an offline file") - .font(.callout) - .foregroundStyle(.secondary) - } - } - .textSelection(.enabled) - - Spacer() - + private func signedIn(name: String?, email: String?) -> some View { + AccountIdentityRow( + systemImage: "person.crop.circle.fill", + tint: .secondary, + title: name ?? email ?? String(localized: "Signed in"), + subtitles: name == nil ? [] : [email].compactMap { $0 }, + fullText: email + ) { if model.activity == .signingOut { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Signing out")) } - } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) - - HStack { - if isSignedIn { - Button(String(localized: "Manage Account…")) { - openURL(model.services.configuration.accountURL) - } - .accessibilityIdentifier("account-manage") - Spacer() + Button(String(localized: "Sign Out…")) { + model.requestSignOut() + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-sign-out") + } - Button(String(localized: "Sign Out")) { - Task { await model.signOut() } - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-sign-out") - } else { - signInButton - Spacer() + LabeledContent { + Button(String(localized: "Manage Account…")) { + model.openPortal(model.services.configuration.accountURL) } + .fixedSize() + .accessibilityIdentifier("account-manage") + } label: { + Text("Profile, sign-in methods and billing") } } - // The key exchange signs this Mac in, so a sign-in here would leave the key unexchanged. - private func licenseKey(isValid: Bool) -> some View { - HStack(spacing: 12) { - Image(systemName: isValid ? "checkmark.seal.fill" : "seal") - .font(.largeTitle) - .foregroundStyle(isValid ? Color.green : Color.secondary) - .accessibilityHidden(true) + // A Mac that only holds an offline file has no session, so it can still sign in. + @ViewBuilder + private func offlineFile(name: String?, email: String?) -> some View { + AccountIdentityRow( + systemImage: "person.crop.circle.fill", + tint: .secondary, + title: name ?? email ?? String(localized: "Signed in"), + subtitles: (name == nil ? [] : [email].compactMap { $0 }) + [String(localized: "From an offline file")], + fullText: email + ) { + signInControl + } - VStack(alignment: .leading, spacing: 2) { - Text("License key") - .font(.headline) + signInFailure + } - Text(isValid + // The key exchange signs this Mac in, so a sign-in here would leave the key unexchanged. + private func licenseKey(isValid: Bool) -> some View { + AccountIdentityRow( + systemImage: isValid ? "checkmark.seal.fill" : "seal", + tint: isValid ? .green : .secondary, + title: String(localized: "License key"), + subtitles: [ + isValid ? String(localized: "TablePro signs you in with your license key the next time it reaches the server.") - : String(localized: "Connect to the internet to verify your license.")) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + : String(localized: "Connect to the internet to verify your license."), + ], + wrapsSubtitles: true + ) { + if canRefresh { + AccountRefreshControl(model: model) } } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) } @ViewBuilder private var signedOut: some View { - VStack(alignment: .leading, spacing: 4) { + LabeledContent { + signInControl + } label: { Text("Sign in to TablePro") - .font(.headline) - Text("Your account unlocks the features your plan includes on this Mac. Everything else works without an account.") - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) } - .padding(.vertical, 2) - if let failure = model.signInFailure { - Label(failure, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("account-sign-in-error") - } + signInFailure - HStack(spacing: 10) { - signInButton - .buttonStyle(.borderedProminent) + SettingsHelpRow(SignInCopy.codeHint) + } + private var signInControl: some View { + HStack(spacing: 8) { if model.activity == .signingIn { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Signing in")) } - Spacer() + Button(String(localized: "Sign In")) { + Task { + await model.signIn(using: WebAuthenticationSessionAuthenticator()) + } + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-sign-in-button") } + } - Text(SignInCopy.codeHint) - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + @ViewBuilder + private var signInFailure: some View { + if let failure = model.signInFailure { + AccountFailureLine(message: failure, identifier: "account-sign-in-error") + } } +} + +private struct AccountIdentityRow: View { + let systemImage: String + let tint: Color + let title: String + let subtitles: [String] + var fullText: String? + var wrapsSubtitles = false + @ViewBuilder let trailing: Trailing - private var signInButton: some View { - Button(String(localized: "Sign In")) { - Task { - await model.signIn(using: WebAuthenticationSessionAuthenticator()) + var body: some View { + HStack(spacing: 10) { + Image(systemName: systemImage) + .resizable() + .scaledToFit() + .frame(width: 32, height: 32) + .foregroundStyle(tint) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 1) { + Text(title) + .lineLimit(1) + .truncationMode(.tail) + + ForEach(subtitles, id: \.self) { subtitle in + if wrapsSubtitles { + Text(subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else { + Text(subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } } + .textSelection(.enabled) + .help(fullText ?? "") + + Spacer(minLength: 12) + + trailing } - .disabled(model.isBusy) - .accessibilityIdentifier("account-sign-in-button") + .accessibilityElement(children: .contain) } } -// MARK: - Offline - -private struct AccountOfflineSection: View { +private struct AccountPlanSection: View { @ObservedObject var model: AccountSettingsModel let content: AccountSettingsContent + let showDevices: () -> Void var body: some View { Section { - if let verification = content.verification { - HStack { - Text(Self.verificationText(verification)) - .fixedSize(horizontal: false, vertical: true) + ForEach(content.notices) { notice in + AccountNoticeRow(notice: notice, model: model, showDevices: showDevices) + } - Spacer() + ForEach(content.plans) { plan in + AccountPlanRow(plan: plan, model: model) + } - refreshButton + if content.isFree { + LabeledContent { + Button(String(localized: "Upgrade…")) { + Telemetry.shared.upgradeClicked(from: .licenseSettings) + model.openPortal(model.services.configuration.portalBilling) + } + .fixedSize() + .accessibilityIdentifier("account-upgrade") + } label: { + Text("You're on Free") + Text("A paid plan adds the features listed under Features.") } + } - // The last check still holds, so no notice above names a Refresh that just failed. - if LicensePresentation.checkFailureMessage(model.access.state.refresh) != nil { - LicenseCheckFailureLine() - } - } else if content.canRefresh { - HStack { - Text("Not verified yet") - .foregroundStyle(.secondary) - Spacer() - refreshButton - } + if content.notices.isEmpty, content.plans.isEmpty, !content.isFree { + AccountLoadingRow(label: String(localized: "Checking your plan")) } - LabeledContent(String(localized: "Machine ID")) { - HStack(spacing: 8) { - Text(verbatim: content.machineID) - .font(.callout.monospaced()) - .lineLimit(1) - .truncationMode(.middle) - .textSelection(.enabled) - .accessibilityIdentifier("account-machine-id") + if let state = content.verificationState { + AccountVerificationRow( + state: state, + model: model, + showsRefresh: content.canRefresh && !content.offersRetry + ) + } - Button(String(localized: "Copy")) { - ClipboardService.shared.writeText(content.machineID) - } - .accessibilityLabel(Text("Copy Machine ID")) - } + // The last check still holds, so no notice above names a Refresh that just failed. + if content.verification != nil, + let failure = LicensePresentation.checkFailureMessage(model.access.state.refresh) { + AccountFailureLine(message: failure) } + } header: { + Text("Plan") + } + } +} - HStack { - Button(String(localized: "Import Offline File…")) { - model.presentsOfflineImporter = true - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-import-offline-file") +private struct AccountNoticeRow: View { + let notice: AccountSettingsContent.Notice + @ObservedObject var model: AccountSettingsModel + let showDevices: () -> Void - Button(String(localized: "Use License Key…")) { - model.presentLicenseKey() - } - .disabled(model.isBusy) - .accessibilityIdentifier("account-use-license-key") + private var severity: NoticeSeverity { + notice.isInformational ? .info : .warning + } - Spacer() + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: severity.symbolName) + .foregroundStyle(severity.tint) + .frame(width: 16) + .accessibilityHidden(true) + + VStack(alignment: .leading, spacing: 3) { + Text(notice.title) + + Text(notice.message) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } - } header: { - Text("Offline") - } footer: { - Text("For a Mac that never reaches the internet, create an offline file for this machine ID in your account, then import it here.") - .font(.callout) - .foregroundStyle(.secondary) + + Spacer(minLength: 12) + + action } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("account-notice-\(notice.id)") } @ViewBuilder - private var refreshButton: some View { - if content.canRefresh { + private var action: some View { + switch notice { + case .deviceLimit: + Button(String(localized: "Show Devices"), action: showDevices) + .fixedSize() + .accessibilityIdentifier("account-choose-device") + case .paymentProblem(let plan): + if let billing = plan.billing { + Button(String(localized: "Update Payment Method…")) { model.openPortal(billing) } + .fixedSize() + } + case .canceling: + // The plan's own row has Billing…, where the cancellation is resumed. + EmptyView() + case .expiringSoon(_, true), .expired(_, true): + Button(String(localized: "Import Offline File…")) { model.presentsOfflineImporter = true } + .disabled(model.isBusy) + .fixedSize() + case .expiringSoon, .expired, .verificationFailed: HStack(spacing: 8) { if model.activity == .checking { ProgressView() @@ -461,62 +333,36 @@ private struct AccountOfflineSection: View { .accessibilityLabel(Text("Refreshing")) } - Button(String(localized: "Refresh")) { + Button(String(localized: "Try Again")) { Task { await model.checkNow() } } .disabled(model.isBusy) - .accessibilityIdentifier("account-refresh") + .fixedSize() } } } - - static func verificationText(_ verification: AccountSettingsContent.Verification) -> String { - let until = verification.validUntil.formatted(date: .abbreviated, time: .omitted) - if verification.isExpired { - return verification.isOfflineFile - ? String(format: String(localized: "Offline file expired on %@"), until) - : String(format: String(localized: "Expired on %@"), until) - } - if verification.isOfflineFile { - return String(format: String(localized: "Offline file, valid until %@"), until) - } - return String( - format: String(localized: "Verified %@, valid until %@"), - verification.verifiedAt.formatted(.relative(presentation: .named)), - until - ) - } } -// MARK: - Rows - private struct AccountPlanRow: View { let plan: AccountSettingsContent.PlanRow - @Environment(\.openURL) private var openURL + @ObservedObject var model: AccountSettingsModel var body: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(plan.title) - - Text(plan.owner) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.tail) - } - - Spacer(minLength: 12) - + SettingsRecordRow(title: plan.title, subtitle: plan.owner) { if let status = plan.status { AccountPlanStatusLabel(status: status) } if let billing = plan.billing { - Button(String(localized: "Billing…")) { openURL(billing) } + Button(String(localized: "Billing…")) { model.openPortal(billing) } + .fixedSize() } } - .accessibilityElement(children: .contain) + .modifier(AccountRowMenu(title: String(localized: "Billing…"), isAvailable: plan.billing != nil) { + if let billing = plan.billing { + model.openPortal(billing) + } + }) } } @@ -524,171 +370,281 @@ private struct AccountPlanStatusLabel: View { let status: AccountSettingsContent.PlanStatus var body: some View { - switch status { - case .paymentProblem: - Label(String(localized: "Payment problem"), systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - case .active: - Text("Active") - .foregroundStyle(.secondary) - case .lifetime: - Text("Lifetime") - .foregroundStyle(.secondary) - case .renewsOn(let date): - Text(String(format: String(localized: "Renews on %@"), date.formatted(date: .abbreviated, time: .omitted))) - .foregroundStyle(.secondary) - case .endsOn(let date), .canceling(endsAt: .some(let date)): - Text(String(format: String(localized: "Ends on %@"), date.formatted(date: .abbreviated, time: .omitted))) - .foregroundStyle(.secondary) - case .canceling(endsAt: .none): - Text("Canceling") - .foregroundStyle(.secondary) + Group { + switch status { + case .paymentProblem: + Label { + Text("Payment problem") + } icon: { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + } + case .active: + Text("Active") + case .lifetime: + Text("Lifetime") + case .renewsOn(let date): + Text(String(format: String(localized: "Renews on %@"), date.formatted(date: .abbreviated, time: .omitted))) + case .endsOn(let date), .canceling(endsAt: .some(let date)): + Text(String(format: String(localized: "Ends on %@"), date.formatted(date: .abbreviated, time: .omitted))) + case .canceling(endsAt: .none): + Text("Canceling") + } } + .foregroundStyle(.secondary) + .lineLimit(1) + .layoutPriority(1) } } -private struct AccountNoticeRow: View { - let notice: AccountSettingsContent.Notice +private struct AccountVerificationRow: View { + let state: AccountSettingsContent.VerificationState @ObservedObject var model: AccountSettingsModel - @Environment(\.openURL) private var openURL + let showsRefresh: Bool var body: some View { - HStack(alignment: .top, spacing: 10) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 4) { - Text(notice.title) - .font(.headline) - - Text(notice.message) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - - action - .padding(.top, 2) + SettingsRecordRow(title: title, subtitle: subtitle) { + if showsRefresh { + AccountRefreshControl(model: model) } + } + } - Spacer(minLength: 0) + private var title: String { + switch state { + case .verified(let at, _): + String(format: String(localized: "Verified %@"), at.formatted(.relative(presentation: .named))) + case .offlineFile, .offlineFileExpired: + String(localized: "Offline file") + case .expired: + String(localized: "Expired") + case .notVerified: + String(localized: "Not verified yet") } - .padding(.vertical, 2) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("account-notice-\(notice.id)") } - @ViewBuilder - private var action: some View { - switch notice { - case .deviceLimit: - Button(String(localized: "Choose a Device…")) { model.presentsDeviceLimit = true } - .accessibilityIdentifier("account-choose-device") - case .paymentProblem(let plan): - if let billing = plan.billing { - Button(String(localized: "Update Payment Method…")) { openURL(billing) } + private var subtitle: String? { + switch state { + case .verified(_, let until), .offlineFile(let until): + String(format: String(localized: "Valid until %@"), until.formatted(date: .abbreviated, time: .omitted)) + case .expired(let on), .offlineFileExpired(let on): + String(format: String(localized: "Expired on %@"), on.formatted(date: .abbreviated, time: .omitted)) + case .notVerified: + nil + } + } +} + +private struct AccountRefreshControl: View { + @ObservedObject var model: AccountSettingsModel + + var body: some View { + HStack(spacing: 8) { + if model.activity == .checking { + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Refreshing")) } - case .canceling: - // The plan's own row has Billing…, where the cancellation is resumed. - EmptyView() - case .expiringSoon(_, true), .expired(_, true): - Button(String(localized: "Import Offline File…")) { model.presentsOfflineImporter = true } - case .expiringSoon, .expired, .verificationFailed: - Button(String(localized: "Try Again")) { + + Button(String(localized: "Refresh")) { Task { await model.checkNow() } } .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-refresh") } } } -private struct AccountDeviceRow: View { - let device: AccountSettingsContent.DeviceRow - let isRemoving: Bool - let isDisabled: Bool - let onRemove: () -> Void +internal struct AccountDevicesPage: View { + @ObservedObject var model: AccountSettingsModel var body: some View { - HStack(spacing: 10) { - Image(systemName: device.system.hasPrefix("macOS") ? "laptopcomputer" : "desktopcomputer") - .foregroundStyle(.secondary) - .frame(width: 20) - .accessibilityHidden(true) + let devices = model.content.devices + Form { + Section { + if let devices { + if devices.isEmpty, model.devices.failure == nil { + Text("No devices are signed in.") + .foregroundStyle(.secondary) + } - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 6) { - Text(device.name) - .lineLimit(1) - .truncationMode(.middle) + ForEach(devices) { device in + AccountDeviceRow( + device: device, + isRemoving: model.activity == .removing(device.id), + isDisabled: model.isBusy + ) { + model.pendingRemoval = device + } + } + } else if model.devices.isLoading { + AccountLoadingRow(label: String(localized: "Loading devices")) + } - if device.isThisMac { - Text("This Mac") - .font(.caption) - .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(Capsule().fill(Color(nsColor: .quaternaryLabelColor))) + if let failure = model.devices.failure { + AccountLoadFailureRow(message: failure, isRetrying: model.devices.isLoading) { + Task { await model.loadDevices() } } } - Text(AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt)) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) + SettingsHelpRow("A plan works on up to 3 devices at a time. Removing one signs TablePro out there.") } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountDevices.pageIdentifier) + } +} - Spacer(minLength: 12) +private struct AccountDeviceRow: View { + let device: AccountSettingsContent.DeviceRow + let isRemoving: Bool + let isDisabled: Bool + let onRemove: () -> Void + var body: some View { + SettingsRecordRow( + title: device.name, + subtitle: AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt, isThisMac: device.isThisMac) + ) { if let offlineUntil = device.offlineUntil { Text(AccountDeviceText.offlineFile(until: offlineUntil)) - .font(.callout) .foregroundStyle(.secondary) + .lineLimit(1) + .layoutPriority(1) } else if isRemoving { ProgressView() .controlSize(.small) .accessibilityLabel(Text("Removing")) } else if device.canRemove { - Button(String(localized: "Remove"), action: onRemove) + Button(String(localized: "Remove…"), action: onRemove) .disabled(isDisabled) + .fixedSize() .accessibilityLabel(Text(String(format: String(localized: "Remove %@"), device.name))) } } + .modifier(AccountRowMenu( + title: String(localized: "Remove…"), + isAvailable: device.canRemove && !isRemoving, + isDisabled: isDisabled, + action: onRemove + )) + } +} + +internal struct AccountTeamsPage: View { + @ObservedObject var model: AccountSettingsModel + + var body: some View { + let teams = model.content.teams + Form { + Section { + if let teams { + if teams.isEmpty, model.profile.failure == nil { + Text("You are not on a team.") + .foregroundStyle(.secondary) + } + + ForEach(teams) { team in + AccountTeamRow(team: team, model: model) + } + } else if model.profile.isLoading { + AccountLoadingRow(label: String(localized: "Loading teams")) + } + + if let failure = model.profile.failure { + AccountLoadFailureRow(message: failure, isRetrying: model.profile.isLoading) { + Task { await model.loadProfile() } + } + } + } + } + .formStyle(.grouped) .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountTeams.pageIdentifier) } } private struct AccountTeamRow: View { let team: AccountSettingsContent.TeamRow - @Environment(\.openURL) private var openURL + @ObservedObject var model: AccountSettingsModel + + private var subtitle: String { + let seat = team.hasSeat ? String(localized: "Seat assigned") : String(localized: "No seat") + guard let role = team.role else { return seat } + return String(format: String(localized: "%@ · %@"), role, seat) + } var body: some View { - HStack(spacing: 12) { - VStack(alignment: .leading, spacing: 2) { - Text(team.name) - .lineLimit(1) - .truncationMode(.tail) - .help(team.name) + SettingsRecordRow(title: team.name, subtitle: subtitle) { + Button(String(localized: "Manage…")) { model.openPortal(team.manage) } + .fixedSize() + .accessibilityLabel(Text(String(format: String(localized: "Manage %@"), team.name))) + } + .modifier(AccountRowMenu(title: String(localized: "Manage…")) { + model.openPortal(team.manage) + }) + } +} - if let role = team.role { - Text(role) - .font(.callout) - .foregroundStyle(.secondary) - } - } +internal struct AccountOfflinePage: View { + @ObservedObject var model: AccountSettingsModel - Spacer(minLength: 12) + var body: some View { + let machineID = model.services.machineID + Form { + Section { + LabeledContent(String(localized: "Machine ID")) { + HStack(spacing: 8) { + Text(verbatim: machineID) + .font(.body.monospaced()) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .frame(maxWidth: 240, alignment: .trailing) + .help(machineID) + .accessibilityIdentifier("account-machine-id") + + Button(String(localized: "Copy")) { + ClipboardService.shared.writeText(machineID) + } + .fixedSize() + .accessibilityLabel(Text("Copy Machine ID")) + } + } - if team.hasSeat { - Label(String(localized: "Seat"), systemImage: "checkmark.circle.fill") - .foregroundStyle(.secondary) - } else { - Text("No seat") - .foregroundStyle(.secondary) + LabeledContent { + Button(String(localized: "Import Offline File…")) { + model.presentsOfflineImporter = true + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-import-offline-file") + } label: { + Text("Offline file") + Text("For a Mac that never reaches the internet, create an offline file for this machine ID in your account, then import it here.") + } } - Button(String(localized: "Manage…")) { openURL(team.manage) } - .accessibilityLabel(Text(String(format: String(localized: "Manage %@"), team.name))) + Section { + LabeledContent { + Button(String(localized: "Use License Key…")) { + model.presentLicenseKey() + } + .disabled(model.isBusy) + .fixedSize() + .accessibilityIdentifier("account-use-license-key") + } label: { + Text("License key") + Text("Sign this Mac in with a key from an older version of TablePro.") + } + } } + .formStyle(.grouped) .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.accountOffline.pageIdentifier) } } @@ -699,6 +655,7 @@ private struct AccountLoadingRow: View { HStack(spacing: 8) { ProgressView() .controlSize(.small) + .accessibilityHidden(true) Text(label) .foregroundStyle(.secondary) } @@ -708,17 +665,65 @@ private struct AccountLoadingRow: View { private struct AccountLoadFailureRow: View { let message: String + let isRetrying: Bool let onRetry: () -> Void var body: some View { - HStack(spacing: 8) { - Label(message, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.secondary) + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .frame(width: 16) + .accessibilityHidden(true) + + Text(message) .fixedSize(horizontal: false, vertical: true) - Spacer() + Spacer(minLength: 12) - Button(String(localized: "Try Again"), action: onRetry) + if isRetrying { + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Loading")) + } else { + Button(String(localized: "Try Again"), action: onRetry) + .fixedSize() + } + } + .accessibilityElement(children: .contain) + } +} + +private struct AccountFailureLine: View { + let message: String + var identifier: String? + + var body: some View { + NoticeLabel(message) + .font(.subheadline) + .accessibilityElement(children: .combine) + .accessibilityIdentifier(identifier ?? "") + } +} + +// A row's one action also sits in its context menu and its accessibility actions. +private struct AccountRowMenu: ViewModifier { + let title: String + var isAvailable = true + var isDisabled = false + let action: () -> Void + + func body(content: Content) -> some View { + if isAvailable { + content + .contextMenu { + Button(title, action: action) + .disabled(isDisabled) + } + .accessibilityAction(named: Text(title)) { + if !isDisabled { action() } + } + } else { + content } } } diff --git a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift index c67dd3969b..02698f0bae 100644 --- a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift +++ b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift @@ -1,8 +1,3 @@ -// -// LicensePresentation.swift -// TablePro -// - import Foundation internal enum LicenseNoticeAction: Equatable { @@ -86,7 +81,7 @@ internal enum LicensePresentation { // plan stays in the pane: the person chose it, and the pane shows the date it ends. static func welcomeLine(state: AccountState, configuration: AccountConfiguration, now: Date) -> LicenseNotice? { let notices = AccountSettingsContent.notices(state: state, configuration: configuration, now: now) - if let first = notices.first(where: { !$0.isCanceling }) { + if let first = notices.first(where: { !$0.isInformational }) { return notice(first) } guard !state.isSignedIn, state.legacy == nil else { return nil } @@ -120,10 +115,3 @@ internal enum LicensePresentation { return error.friendlyDescription } } - -private extension AccountSettingsContent.Notice { - var isCanceling: Bool { - if case .canceling = self { return true } - return false - } -} diff --git a/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift index 5d98a879fc..42102627d1 100644 --- a/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/AccountSettingsEntry.swift @@ -1,41 +1,127 @@ import SwiftUI +import UniformTypeIdentifiers internal struct AccountSettingsEntry: View { internal let context: SettingsPaneContext internal var body: some View { - AccountSettingsView(model: context.models.account) + AccountSettingsView(model: context.models.account) { [context] in + context.navigation.push(.page(.accountDevices), in: .account) + } } } internal struct AccountSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext - @ObservedObject private var account: AccountSettingsModel - - internal init(route: SettingsRoute, context: SettingsPaneContext) { - self.route = route - self.context = context - self._account = ObservedObject(wrappedValue: context.models.account) - } internal var body: some View { switch route { case .page(.accountFeatures): - Form { - AccountFeaturesSection(access: account.access, offersPurchase: account.content.identity == .signedOut) - } - .formStyle(.grouped) + AccountFeaturesPage(access: context.models.account.access) + case .page(.accountDevices): + AccountDevicesPage(model: context.models.account) + case .page(.accountTeams): + AccountTeamsPage(model: context.models.account) + case .page(.accountOffline): + AccountOfflinePage(model: context.models.account) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } +// The root and every page share the model's sheets, dialogs and file panel, so they hang off the pane's stack. internal struct AccountStackPresentations: ViewModifier { internal let context: SettingsPaneContext internal func body(content: Content) -> some View { + content.modifier(AccountPresentations(model: context.models.account, visit: context.visit, context: context)) + } +} + +private struct AccountPresentations: ViewModifier { + private static let offlineFileTypes = [UTType(filenameExtension: "jwt") ?? .data] + private static let signedInPages: [SettingsRoute] = [.page(.accountDevices), .page(.accountTeams)] + + @ObservedObject var model: AccountSettingsModel + @ObservedObject var visit: SettingsPaneVisit + let context: SettingsPaneContext + + func body(content: Content) -> some View { content + .task(id: visit.count) { + await model.refreshOnVisit() + } + .onChange(of: model.access.state.isSignedIn) { isSignedIn in + guard !isSignedIn else { return } + for route in Self.signedInPages where context.path.routes.contains(route) { + context.navigation.removeRoute(route) + } + } + .sheet(isPresented: $model.presentsDeviceLimit) { + DeviceLimitSheet(model: DeviceLimitModel(services: model.services)) + } + .sheet(isPresented: $model.presentsLicenseKey) { + LicenseKeySheet( + storedKey: model.licenseKeyPrefill, + signedInEmail: signedInEmail, + isWorking: model.activity == .usingKey + ) { key in + await model.useLicenseKey(key) + } + } + .fileImporter( + isPresented: $model.presentsOfflineImporter, + allowedContentTypes: Self.offlineFileTypes, + allowsMultipleSelection: false + ) { result in + switch result { + case .success(let urls): + if let url = urls.first { + Task { await model.importOfflineFile(at: url) } + } + case .failure(let error): + model.offlineFilePickerFailed(error) + } + } + .alert( + model.actionFailure?.title ?? "", + isPresented: Binding(get: { model.actionFailure != nil }, set: { if !$0 { model.actionFailure = nil } }), + presenting: model.actionFailure + ) { _ in + Button(String(localized: "OK")) {} + } message: { failure in + Text(failure.message) + } + .alert( + model.pendingRemoval.map { String(format: String(localized: "Remove “%@”?"), $0.name) } ?? "", + isPresented: Binding(get: { model.pendingRemoval != nil }, set: { if !$0 { model.pendingRemoval = nil } }), + presenting: model.pendingRemoval + ) { device in + Button(String(localized: "Remove"), role: .destructive) { + Task { await model.removeDevice(device) } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { _ in + Text("TablePro on that device signs out the next time it checks your account. Its paid features keep working until its last check expires.") + } + .alert( + String(localized: "Sign out of TablePro on this Mac?"), + isPresented: Binding(get: { model.confirmsSignOut }, set: { if !$0 { model.cancelSignOut() } }), + presenting: model.signOutConfirmation + ) { confirmation in + Button(String(localized: "Sign Out"), role: confirmation.discardsSomething ? .destructive : nil) { + Task { await model.signOut() } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(confirmation.message) + } + } + + private var signedInEmail: String? { + guard model.access.state.isSignedIn else { return nil } + return model.profile.value?.email ?? model.access.state.entitlement?.email } } diff --git a/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift b/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift index 833651c65f..831cef074f 100644 --- a/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift +++ b/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift @@ -1,8 +1,3 @@ -// -// AccountSettingsContentTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -356,4 +351,77 @@ struct AccountSettingsContentTests { #expect(AccountCodes.systemName(platform: "linux", osVersion: "") == "Linux") #expect(AccountCodes.systemName(platform: "windows", osVersion: "11") == "11") } + + @Test("The verification row reads the last check, an offline file or an expiry, and waits for a first check") + func verificationStates() { + let issuedAt = Self.now.addingTimeInterval(-2 * 60 * 60) + let validUntil = Self.now.addingTimeInterval(14 * Self.day) + let expiredAt = Self.now.addingTimeInterval(-Self.day) + let lapsed = Self.entitlement(issuedAt: Self.now.addingTimeInterval(-15 * Self.day), expiresAt: expiredAt) + + let verified = Self.make(AccountState(isSignedIn: true, entitlement: Self.entitlement(), refresh: .succeeded(Self.now))) + #expect(verified.verificationState == .verified(at: issuedAt, until: validUntil)) + + let offline = Self.make(AccountState(entitlement: Self.entitlement(isOffline: true))) + #expect(offline.verificationState == .offlineFile(until: validUntil)) + + let expired = Self.make(AccountState(isSignedIn: true, entitlement: lapsed, refresh: .failed(.network("offline")))) + #expect(expired.verificationState == .expired(on: expiredAt)) + + let offlineExpired = Self.make(AccountState(entitlement: Self.entitlement( + issuedAt: Self.now.addingTimeInterval(-15 * Self.day), expiresAt: expiredAt, isOffline: true + ))) + #expect(offlineExpired.verificationState == .offlineFileExpired(on: expiredAt)) + + #expect(Self.make(AccountState(isSignedIn: true)).verificationState == .notVerified) + #expect(Self.make(AccountState()).verificationState == nil) + } + + @Test("A notice that already offers Try Again hides the verification row's Refresh") + func retryNoticeReplacesRefresh() { + let failed = Self.make(AccountState(isSignedIn: true, refresh: .failed(.network("offline")))) + #expect(failed.offersRetry) + + let expiringOffline = Self.make(AccountState(entitlement: Self.entitlement( + expiresAt: Self.now.addingTimeInterval(Self.day), isOffline: true + ))) + #expect(!expiringOffline.offersRetry) + + let healthy = Self.make(AccountState(isSignedIn: true, entitlement: Self.entitlement(), refresh: .succeeded(Self.now))) + #expect(!healthy.offersRetry) + } + + @Test("Devices and Teams are shown while signed in, even before they load; an offline file shows neither") + func signedInPages() { + let signedIn = Self.make(AccountState(isSignedIn: true, entitlement: Self.entitlement(), refresh: .succeeded(Self.now))) + #expect(signedIn.showsDevices) + #expect(signedIn.showsTeams) + #expect(signedIn.teams == nil) + + let offline = Self.make(AccountState(entitlement: Self.entitlement(isOffline: true))) + #expect(!offline.showsDevices) + #expect(!offline.showsTeams) + } + + @Test("Only a canceling plan informs; every other notice warns") + func noticeSeverity() throws { + let canceling = Self.make(AccountState( + isSignedIn: true, + entitlement: Self.entitlement([Self.license(source: "subscription", status: "canceling", endsAt: Self.now)]), + refresh: .succeeded(Self.now) + )) + #expect(try #require(canceling.notices.first).isInformational) + #expect(!AccountSettingsContent.Notice.deviceLimit.isInformational) + #expect(!AccountSettingsContent.Notice.verificationFailed(message: nil).isInformational) + } + + @Test("This Mac's row says so and reads as seen now; another device keeps its last check") + func deviceDetail() { + let lastSeen = Date().addingTimeInterval(-3 * Self.day) + let thisMac = AccountDeviceText.detail(system: "macOS 27.0", lastSeenAt: lastSeen, isThisMac: true) + #expect(thisMac == AccountDeviceText.detail(system: "This Mac · macOS 27.0", lastSeenAt: Date())) + + let other = AccountDeviceText.detail(system: "macOS 15.1", lastSeenAt: lastSeen, isThisMac: false) + #expect(other == AccountDeviceText.detail(system: "macOS 15.1", lastSeenAt: lastSeen)) + } } diff --git a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift index 2b5e97a02b..b06d652dbd 100644 --- a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift +++ b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift @@ -1,8 +1,3 @@ -// -// AccountSettingsModelTests.swift -// TableProTests -// - import Foundation @testable import TablePro import TableProTestSupport @@ -185,8 +180,204 @@ struct AccountSettingsModelTests { #expect(model.content.plans.first?.status == .lifetime) } + @Test("A visit within a minute of the last load reuses it, and a later one loads again") + func reloadIfStaleSkipsAFreshLoad() async throws { + let fixture = try AccountFixture() + try await fixture.signIn() + let clock = TestNow() + let loads = CountingLoads() + let model = AccountSettingsModel(services: fixture.services, loader: loads.loader, now: { clock.date }) + + await model.reloadIfStale() + #expect(loads.profile == 1) + #expect(loads.devices == 1) + + clock.date += AccountSettingsModel.freshness - 1 + await model.reloadIfStale() + #expect(loads.profile == 1) + + clock.date += 2 + await model.reloadIfStale() + #expect(loads.profile == 2) + #expect(loads.devices == 2) + } + + @Test("A load canceled before it answers records no failure, stops loading, and the next visit loads again") + func canceledLoadRecordsNothing() async throws { + let fixture = try AccountFixture() + try await fixture.signIn() + let gate = AsyncGate() + let loads = CountingLoads() + loads.profileGate = gate + loads.profileFailure = .canceled + let model = AccountSettingsModel(services: fixture.services, loader: loads.loader) + + let load = Task { await model.reload() } + await gate.arrived(1) + #expect(model.profile.isLoading) + await gate.open() + await load.value + + #expect(!model.profile.isLoading) + #expect(model.profile.failure == nil) + #expect(model.profile.value == nil) + + loads.profileFailure = nil + await model.reloadIfStale() + #expect(loads.profile == 2) + #expect(model.profile.value != nil) + } + + @Test("A result that answers after the account signed out lands nowhere") + func lateResultFromAnOldAccountIsDropped() async throws { + let fixture = try AccountFixture() + try await fixture.signIn() + let gate = AsyncGate() + let loads = CountingLoads() + loads.profileGate = gate + let model = AccountSettingsModel(services: fixture.services, loader: loads.loader) + + let load = Task { await model.reload() } + await gate.arrived(1) + await model.signOut() + try await waitUntil { !model.profile.isLoading } + await gate.open() + await load.value + + #expect(model.profile.value == nil) + #expect(model.devices.value == nil) + #expect(model.content.identity == .signedOut) + } + + @Test("Sign Out… asks first and names the team edits a sign-out discards; Cancel keeps the session") + func signOutConfirmationNamesUnsentTeamChanges() async throws { + let fixture = try await TeamLibraryFixture() + await fixture.sync.sync() + await fixture.library { $0.pushFaults = [503] } + let result = try await fixture.sync.publishSavedQueries( + favorites: [TeamLibraryFixture.favorite(name: "Orders")], + folders: [], + to: TeamLibraryFixture.team + ) + #expect(result == .queued(.server)) + let sync = fixture.sync + let model = AccountSettingsModel(services: fixture.account.services, hasUnsentTeamChanges: { sync.hasUnsentChanges }) + + model.requestSignOut() + + #expect(model.confirmsSignOut) + #expect(model.signOutConfirmation == AccountSignOutConfirmation(discardsTeamChanges: true, removesOfflineFile: false)) + #expect(model.signOutConfirmation?.discardsSomething == true) + model.cancelSignOut() + #expect(!model.confirmsSignOut) + #expect(fixture.account.services.session.isSignedIn) + + #expect(await fixture.sync.sync() == .synced) + #expect(!fixture.sync.hasUnsentChanges) + model.requestSignOut() + #expect(model.signOutConfirmation?.discardsSomething == false) + } + + @Test("Signing out with an imported offline file says the file goes, and it does") + func signOutRemovesTheOfflineFile() async throws { + let fixture = try AccountFixture() + try await fixture.signIn() + let directory = fixture.entitlementFile.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let file = directory.appendingPathComponent("tablepro-offline-abababababab.jwt") + try Data(await fixture.server.signedEntitlement(offline: true).utf8).write(to: file) + let model = AccountSettingsModel(services: fixture.services, hasUnsentTeamChanges: { false }) + await model.importOfflineFile(at: file) + + model.requestSignOut() + #expect(model.signOutConfirmation == AccountSignOutConfirmation(discardsTeamChanges: false, removesOfflineFile: true)) + await model.signOut() + + #expect(!model.confirmsSignOut) + #expect(!FileManager.default.fileExists(atPath: fixture.entitlementFile.path)) + #expect(model.content.identity == .signedOut) + } + + @Test("Confirming a device removal clears the pending removal the dialog showed") + func pendingRemovalLivesOnTheModel() async throws { + let fixture = try AccountFixture() + await fixture.server.set { + $0.devices.append(FakeAccountServer.device(id: "dev_old", name: "Old Mac", machineID: String(repeating: "1", count: 64))) + } + try await fixture.signIn() + let model = AccountSettingsModel(services: fixture.services) + await model.reload() + let row = try #require(model.content.devices?.first { $0.id == "dev_old" }) + + model.pendingRemoval = row + await model.removeDevice(row) + + #expect(model.pendingRemoval == nil) + #expect(model.devices.value?.contains { $0.id == "dev_old" } == false) + } + + @Test("Back from a portal page the account is checked again, even right after a load") + func returnFromThePortalChecksTheAccount() async throws { + let fixture = try AccountFixture() + try await fixture.signIn() + let opened = OpenedURLs() + let loads = CountingLoads() + let model = AccountSettingsModel(services: fixture.services, loader: loads.loader, openURL: { opened.urls.append($0) }) + let entitlementPath = "/devices/\(FakeAccountServer.deviceID)/entitlement" + await model.refreshOnVisit() + let checks = await fixture.server.requests(to: entitlementPath).count + + model.openPortal(fixture.services.configuration.portalBilling) + #expect(opened.urls == [fixture.services.configuration.portalBilling]) + await model.refreshOnVisit() + + #expect(await fixture.server.requests(to: entitlementPath).count == checks + 1) + #expect(loads.profile == 2) + + await model.refreshOnVisit() + #expect(await fixture.server.requests(to: entitlementPath).count == checks + 1) + #expect(loads.profile == 2) + } + private static func refreshToken(in keychain: InMemoryKeychain) -> String? { guard case .found(let token) = keychain.readStringResult(forKey: AccountSession.refreshTokenKey) else { return nil } return token } } + +@MainActor +private final class TestNow { + var date = Date() +} + +@MainActor +private final class OpenedURLs { + var urls: [URL] = [] +} + +@MainActor +private final class CountingLoads { + var profile = 0 + var devices = 0 + var profileGate: AsyncGate? + var profileFailure: AccountError? + + var loader: AccountSettingsModel.Loader { + AccountSettingsModel.Loader( + profile: { () async throws(AccountError) -> AccountProfile in + self.profile += 1 + if let gate = self.profileGate { + await gate.wait() + } + if let failure = self.profileFailure { + throw failure + } + return AccountProfile(email: "ada@m16.example", name: "Ada", memberships: []) + }, + devices: { () async throws(AccountError) -> [AccountDevice] in + self.devices += 1 + return [] + } + ) + } +} diff --git a/apple/TableProUITests/AccountSettingsUITests.swift b/apple/TableProUITests/AccountSettingsUITests.swift new file mode 100644 index 0000000000..4f626b1247 --- /dev/null +++ b/apple/TableProUITests/AccountSettingsUITests.swift @@ -0,0 +1,41 @@ +import XCTest + +final class AccountSettingsUITests: UITestCase { + func testUseLicenseKeyCancelsAndBackReturnsToAccount() throws { + let app = try launchOpeningURL("tablepro://settings/license") + + let settings = settingsWindow(in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "A settings link must open the settings window") + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Account" }, + "The license link must open the Account pane, the window is titled \(settings.title)" + ) + + let offline = settings.descendants(matching: .any).matching(identifier: "settings-drill-offline").firstMatch + XCTAssertTrue(scrollUntilHittable(offline, in: settings, timeout: 10), "Account must link to Offline File and License Key") + offline.click() + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Offline File and License Key" }, + "The row must push its page, the window is titled \(settings.title)" + ) + + let useKey = settings.buttons["account-use-license-key"] + XCTAssertTrue(waitUntilHittable(useKey, timeout: 5), "The page must offer Use License Key…") + useKey.click() + + let sheet = settings.children(matching: .sheet).firstMatch + XCTAssertTrue(sheet.waitToExist(timeout: 5), "Use License Key… must open its sheet") + XCTAssertTrue(sheet.textFields["license-key-field"].waitToExist(timeout: 5), "The sheet must ask for the key") + sheet.buttons["Cancel"].click() + XCTAssertTrue(waitForPredicate(timeout: 5) { !sheet.exists }, "Cancel must close the sheet") + + let back = settingsNavigationButton("Back", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 5) { back.exists && back.isEnabled }, "The page must leave Back to Account") + back.click() + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == "Account" }, + "Back must return to Account, the window is titled \(settings.title)" + ) + XCTAssertFalse(settings.children(matching: .sheet).firstMatch.exists, "No sheet may come back with the pane") + } +} From 2b8846f725867d533a741a92a18acd1adc2c50ad Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:45:53 +0700 Subject: [PATCH 35/48] feat(settings): Connections pane with Linked Folders and Trusted Links pages --- .../ExternalConnectionTrustStore.swift | 15 +- .../Settings/ConnectionHealthCheck.swift | 31 +- .../Models/Settings/GeneralSettings.swift | 20 +- .../WelcomeViewModel+TeamCatalog.swift | 11 +- .../Settings/ConnectionsSettingsView.swift | 116 +++++-- .../Entries/ConnectionsSettingsEntry.swift | 24 +- .../Views/Settings/LinkedFoldersSection.swift | 297 +++++++++++------- .../Sections/ConnectionsSettingsSection.swift | 64 ---- .../TrustedExternalConnectionsSection.swift | 144 ++++++--- .../Database/ConnectionHealthCheckTests.swift | 18 +- .../ExternalConnectionTrustStoreTests.swift | 32 ++ .../Settings/SettingsFieldDecodingTests.swift | 47 ++- .../WelcomeViewModelTeamCatalogTests.swift | 11 +- .../ConnectionsSettingsModelsTests.swift | 187 +++++++++++ 14 files changed, 696 insertions(+), 321 deletions(-) delete mode 100644 apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift create mode 100644 apple/TableProTests/Views/Settings/ConnectionsSettingsModelsTests.swift diff --git a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift index f5d6e5cc99..74f7c23ddf 100644 --- a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift +++ b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift @@ -1,8 +1,4 @@ -// -// ExternalConnectionTrustStore.swift -// TablePro -// - +import Combine import Foundation import os @@ -29,11 +25,17 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki ) private let defaults: UserDefaults + private let changeSubject = PassthroughSubject() internal init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { self.defaults = defaults } + // Sent after the write, so a subscriber that reads entries() sees the change. + internal var changes: AnyPublisher { + changeSubject.eraseToAnyPublisher() + } + internal func isTrusted(_ key: ExternalConnectionTrustKey) -> Bool { guard key.isLoopbackHost else { return false } return entries().contains { $0.key == key } @@ -48,14 +50,17 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki updated.append(TrustedExternalConnection(key: key, trustedAt: Date())) save(updated) Self.logger.info("Trusted external connection \(key.displayDescription, privacy: .private(mask: .hash))") + changeSubject.send(()) } internal func revoke(_ key: ExternalConnectionTrustKey) { save(entries().filter { $0.key != key }) + changeSubject.send(()) } internal func revokeAll() { defaults.removeValue(for: Self.storageKey) + changeSubject.send(()) } internal func entries() -> [TrustedExternalConnection] { diff --git a/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift b/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift index a25c2cc721..6c4d204f34 100644 --- a/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift +++ b/apple/TablePro/Models/Settings/ConnectionHealthCheck.swift @@ -1,20 +1,6 @@ -// -// ConnectionHealthCheck.swift -// TablePro -// - import Foundation -/// How often TablePro asks an open connection whether it still works. -/// -/// The check is a real query on almost every engine, so a connection nobody is using still costs -/// the server about 2,880 of them a day. That is invisible on a database you own and expensive on -/// one you rent: a serverless compute suspends only after some minutes with no queries, so a -/// steady heartbeat holds it awake and billing around the clock (#2700). -/// -/// `onDemand` is the answer for those, and it is not the same as having no answer. TablePro checks -/// the connection the first time it is used after a quiet spell instead, which costs one round -/// trip the user's own action paid for, rather than a stream of them nobody asked for. +// Every check is a real query, so a steady heartbeat keeps a serverless database awake and billing (#2700). internal enum ConnectionHealthCheck: Int, Codable, CaseIterable, Identifiable, Sendable { case onDemand = 0 case every30Seconds = 30 @@ -25,28 +11,21 @@ internal enum ConnectionHealthCheck: Int, Codable, CaseIterable, Identifiable, S internal var title: String { switch self { - case .onDemand: return String(localized: "Only when I use the connection") + case .onDemand: return String(localized: "Only when used") case .every30Seconds: return String(localized: "Every 30 seconds") case .every5Minutes: return String(localized: "Every 5 minutes") case .every15Minutes: return String(localized: "Every 15 minutes") } } - /// How long to wait between checks, or nil when nothing is scheduled at all. Nil is why - /// `onDemand` starts no monitor rather than starting one with a very long interval: a task - /// that never has anything to do is still a task that wakes up. + // Nil starts no monitor at all, rather than one with a long interval that still wakes up. internal var interval: Duration? { guard rawValue > 0 else { return nil } return .seconds(rawValue) } - /// How recently the connection must have answered for TablePro to take its word for it. - /// - /// One value for every setting rather than one per case, because it answers a question the - /// poll rate has no part in: how long a socket that worked stays worth believing. At the - /// default it never fires, since a check every 30 seconds keeps the answer far fresher than - /// this; on the long intervals and on `onDemand` it is what makes the first action after a - /// quiet spell verify before it runs. + // How long an answer stays believable whatever the poll rate; on long intervals and on demand it makes + // the first action after a quiet spell verify before it runs. internal static let freshness: Duration = .seconds(300) internal static func isFresh(_ lastVerifiedAt: Date, now: Date = Date()) -> Bool { diff --git a/apple/TablePro/Models/Settings/GeneralSettings.swift b/apple/TablePro/Models/Settings/GeneralSettings.swift index 4babe30e3f..97de3be62a 100644 --- a/apple/TablePro/Models/Settings/GeneralSettings.swift +++ b/apple/TablePro/Models/Settings/GeneralSettings.swift @@ -1,8 +1,3 @@ -// -// GeneralSettings.swift -// TablePro -// - import Foundation enum StartupBehavior: String, Codable, CaseIterable, Identifiable { @@ -118,6 +113,7 @@ struct GeneralSettings: Codable, Equatable { startupBehavior = container.decodeSetting(.startupBehavior, default: fallback.startupBehavior) language = container.decodeSetting(.language, default: fallback.language) queryTimeoutSeconds = container.decodeSetting(.queryTimeoutSeconds, default: fallback.queryTimeoutSeconds) + .clamped(to: DatabaseConnection.queryTimeoutSecondsRange) shareAnalytics = container.decodeSetting(.shareAnalytics, default: fallback.shareAnalytics) showRecentTables = container.decodeSetting(.showRecentTables, default: fallback.showRecentTables) showObjectComments = container.decodeSetting(.showObjectComments, default: fallback.showObjectComments) @@ -129,3 +125,17 @@ struct GeneralSettings: Codable, Equatable { connectionHealthCheck = container.decodeSetting(.connectionHealthCheck, default: fallback.connectionHealthCheck) } } + +extension GeneralSettings { + static let standardQueryTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] + + // A stored value off the standard list gets its own item, so the pop-up never draws blank. + static func queryTimeoutChoices(including current: Int) -> [Int] { + guard current > 0, !standardQueryTimeouts.contains(current) else { return standardQueryTimeouts } + return (standardQueryTimeouts + [current]).sorted() + } + + static func queryTimeoutTitle(_ seconds: Int, locale: Locale = .autoupdatingCurrent) -> String { + SettingsFormat.duration(seconds: seconds, locale: locale) + } +} diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift b/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift index 01ee7fe723..7e74aad27c 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+TeamCatalog.swift @@ -1,10 +1,3 @@ -// -// WelcomeViewModel+TeamCatalog.swift -// TablePro -// -// Publishing connections to the shared team catalog. -// - import AppKit extension WelcomeViewModel { @@ -47,8 +40,8 @@ extension WelcomeViewModel { format: String( localized: "Choose a shared folder for your team's connection catalog. Teammates add this folder under Settings > %1$@ > %2$@ to see published connections." ), - SettingsPane.general.title, - LinkedFoldersSection.title + SettingsPane.connections.title, + SettingsPage.linkedFolders.title ) } diff --git a/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift index 60bf8e810c..6cf0e8eb78 100644 --- a/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift +++ b/apple/TablePro/Views/Settings/ConnectionsSettingsView.swift @@ -1,42 +1,112 @@ -// -// ConnectionsSettingsView.swift -// TablePro -// - import SwiftUI +import TableProConnectionLibrary struct ConnectionsSettingsView: View { @Binding var settings: GeneralSettings + private let listPreferences: ConnectionListPreferences + private let recentConnections: RecentConnectionsStore - private static let standardTimeouts = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] - - private var queryTimeoutOptions: [Int] { - let current = settings.queryTimeoutSeconds - if current > 0, !Self.standardTimeouts.contains(current) { - return (Self.standardTimeouts + [current]).sorted() - } - return Self.standardTimeouts + init( + settings: Binding, + listPreferences: ConnectionListPreferences = .shared, + recentConnections: RecentConnectionsStore = .shared + ) { + _settings = settings + self.listPreferences = listPreferences + self.recentConnections = recentConnections } var body: some View { Form { - ConnectionsSettingsSection(healthCheck: $settings.connectionHealthCheck) + Section { + Picker(selection: $settings.connectionHealthCheck) { + ForEach(ConnectionHealthCheck.allCases.filter { $0.interval != nil }) { option in + Text(option.title).tag(option) + } + Divider() + Text(ConnectionHealthCheck.onDemand.title).tag(ConnectionHealthCheck.onDemand) + } label: { + Text("Check open connections") + Text( + """ + A small query on each open connection catches a drop early. For a database that sleeps \ + when idle or bills per query, pick Only when used: it checks when you next use the connection. + """ + ) + } + .accessibilityIdentifier("connection-health-check-picker") - Section("Query Execution") { - Picker("Query timeout:", selection: $settings.queryTimeoutSeconds) { - Text("No limit").tag(0) - ForEach(queryTimeoutOptions, id: \.self) { seconds in - Text("\(seconds) seconds").tag(seconds) + Picker(selection: $settings.queryTimeoutSeconds) { + ForEach(GeneralSettings.queryTimeoutChoices(including: settings.queryTimeoutSeconds), id: \.self) { seconds in + Text(verbatim: GeneralSettings.queryTimeoutTitle(seconds)).tag(seconds) } + Divider() + Text("No limit").tag(0) + } label: { + Text("Query timeout") + Text( + "Stops longer queries on drivers that support it. A connection's own timeout overrides this. Applies to connections opened after a change." + ) } - .help(String(localized: "Maximum time to wait for a query to complete. Set to 0 for no limit. Applied to new connections.")) + .accessibilityIdentifier("query-timeout-picker") } + + RecentConnectionsSection(listPreferences: listPreferences, recentConnections: recentConnections) + + ConnectionsPagesSection() } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-connections") } } -#Preview { - ConnectionsSettingsView(settings: .constant(.default)) - .frame(width: 520, height: 400) +private struct RecentConnectionsSection: View { + @ObservedObject var listPreferences: ConnectionListPreferences + @ObservedObject var recentConnections: RecentConnectionsStore + + var body: some View { + Section { + Toggle(isOn: Binding(get: { listPreferences.showsRecent }, set: { listPreferences.setShowsRecent($0) })) { + Text("Show recent connections") + Text("Adds a Recent section to the welcome window and the connection switcher.") + } + .accessibilityIdentifier("show-recent-connections-toggle") + + // Stays enabled while Recent is hidden: the history also drives the Last Connected sort. + LabeledContent { + Button(String(localized: "Clear Recent")) { + recentConnections.clear() + } + .disabled(recentConnections.ledger.isEmpty) + .accessibilityLabel(Text("Clear Recent Connections")) + .accessibilityIdentifier("clear-recent-connections-button") + } label: { + Text("Connection history") + Text("When you last opened each connection, used by Recent and the Last Connected sort. Stays on this Mac.") + } + } header: { + Text("Recent Connections") + } + } +} + +private struct ConnectionsPagesSection: View { + @EnvironmentObject private var linkedFolders: LinkedFoldersModel + @EnvironmentObject private var trustedLinks: TrustedLinksModel + + var body: some View { + Section { + SettingsDrillRow( + route: SettingsRoute.page(.linkedFolders), + title: SettingsPage.linkedFolders.title, + value: SettingsFormat.count(linkedFolders.folders.count) + ) + SettingsDrillRow( + route: SettingsRoute.page(.trustedLinks), + title: SettingsPage.trustedLinks.title, + value: SettingsFormat.count(trustedLinks.entries.count) + ) + } + } } diff --git a/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift index 6053b1a588..4b84bfa786 100644 --- a/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/ConnectionsSettingsEntry.swift @@ -21,21 +21,35 @@ internal struct ConnectionsSettingsPageEntry: View { internal var body: some View { switch route { case .page(.linkedFolders): - Form { LinkedFoldersSection() } - .formStyle(.grouped) + LinkedFoldersPage() case .page(.trustedLinks): - Form { TrustedExternalConnectionsSection() } - .formStyle(.grouped) + TrustedLinksPage() default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + // The model never pushes a route of another pane onto this stack. + EmptyView() } } } +// The root's counts and both pages read one pair of models, alive as long as the pane host. internal struct ConnectionsStackPresentations: ViewModifier { internal let context: SettingsPaneContext + @ObservedObject private var visit: SettingsPaneVisit + @StateObject private var linkedFolders = LinkedFoldersModel() + @StateObject private var trustedLinks = TrustedLinksModel() + + internal init(context: SettingsPaneContext) { + self.context = context + self._visit = ObservedObject(wrappedValue: context.visit) + } internal func body(content: Content) -> some View { content + .environmentObject(linkedFolders) + .environmentObject(trustedLinks) + .task(id: visit.count) { + linkedFolders.reload() + trustedLinks.refresh() + } } } diff --git a/apple/TablePro/Views/Settings/LinkedFoldersSection.swift b/apple/TablePro/Views/Settings/LinkedFoldersSection.swift index 571b702a52..4ce5300a13 100644 --- a/apple/TablePro/Views/Settings/LinkedFoldersSection.swift +++ b/apple/TablePro/Views/Settings/LinkedFoldersSection.swift @@ -1,173 +1,228 @@ -// -// LinkedFoldersSection.swift -// TablePro -// -// Settings section for managing linked folders. -// Linked folders are watched for .tablepro connection files. -// - import AppKit +import Combine import SwiftUI import TableProImport +import UniformTypeIdentifiers + +@MainActor +internal final class LinkedFoldersModel: ObservableObject { + @Published internal private(set) var folders: [LinkedFolder] + + private let storage: LinkedFolderStorage + private let reloadWatcher: @MainActor () -> Void + private var updates: AnyCancellable? + + internal init( + storage: LinkedFolderStorage = .shared, + updates: AnyPublisher = AppEvents.shared.linkedFoldersDidUpdate.eraseToAnyPublisher(), + reloadWatcher: @escaping @MainActor () -> Void = { LinkedFolderWatcher.shared.reload() } + ) { + self.storage = storage + self.reloadWatcher = reloadWatcher + folders = storage.loadFolders() + // A folder added or removed anywhere else would otherwise leave the list as it was at load. + self.updates = updates.sink { [weak self] _ in + self?.reload() + } + } -struct LinkedFoldersSection: View { - static var title: String { String(localized: "Linked Folders") } + internal func reload() { + apply(storage.loadFolders()) + } + + internal func add(_ url: URL) { + let path = PathPortability.contractHome(url.path) + let current = storage.loadFolders() + guard !current.contains(where: { $0.path == path }) else { + apply(current) + return + } + storage.addFolder(LinkedFolder(path: path)) + apply(storage.loadFolders()) + reloadWatcher() + } + + internal func remove(_ folder: LinkedFolder) { + storage.removeFolder(folder) + apply(storage.loadFolders()) + reloadWatcher() + } + + internal func setEnabled(_ isEnabled: Bool, for folder: LinkedFolder) { + var current = storage.loadFolders() + guard let index = current.firstIndex(where: { $0.id == folder.id }), + current[index].isEnabled != isEnabled else { return } + current[index].isEnabled = isEnabled + storage.saveFolders(current) + apply(current) + reloadWatcher() + } + + private func apply(_ loaded: [LinkedFolder]) { + guard loaded != folders else { return } + folders = loaded + } +} +internal struct LinkedFoldersPage: View { + @EnvironmentObject private var model: LinkedFoldersModel @ObservedObject private var featureAccess = FeatureAccess.shared @ObservedObject private var watcher = LinkedFolderWatcher.shared - @State private var folders: [LinkedFolder] = LinkedFolderStorage.shared.loadFolders() + @State private var isAddingFolder = false private var isLicensed: Bool { featureAccess.isAvailable(.linkedFolders) } - var body: some View { - Section { - if !isLicensed { - LicenseGateRow(feature: .linkedFolders) - } + internal var body: some View { + Form { + Section { + if !isLicensed { + LicenseGateRow(feature: .linkedFolders) + } - if folders.isEmpty { - Text("No linked folders. Add a folder to watch for shared connection files.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - ForEach(folders) { folder in - folderRow(folder) + if model.folders.isEmpty { + Text("No linked folders") + .foregroundStyle(.secondary) + } else { + ForEach(model.folders) { folder in + LinkedFolderRow( + folder: folder, + status: folder.isEnabled ? watcher.folderStatuses[folder.id] : nil, + canTurnOn: isLicensed, + model: model + ) + } } - } - Button { - addFolder() - } label: { - Label("Add Folder…", systemImage: "plus") + SettingsHelpRow( + "TablePro reads .tablepro files saved without a passphrase from these folders. Their connections appear read only in the sidebar." + ) + } footer: { + SettingsSectionActions { + Button(String(localized: "Add Folder…")) { + isAddingFolder = true + } + .disabled(!isLicensed) + .accessibilityIdentifier("linked-folders-add-button") + } } - .disabled(!isLicensed) - } header: { - Text(Self.title) - } footer: { - Text("Watched folders are scanned for .tablepro files without a passphrase. Connections appear read only in the sidebar.") - .font(.caption) - .foregroundStyle(.secondary) } - /// The list is seeded once at init, so without this a folder added or removed anywhere else - /// leaves this pane showing the set as it stood when the window was first built. - .onReceive(AppEvents.shared.linkedFoldersDidUpdate) { _ in - folders = LinkedFolderStorage.shared.loadFolders() + .formStyle(.grouped) + .fileImporter(isPresented: $isAddingFolder, allowedContentTypes: [.folder]) { result in + if case .success(let url) = result { + model.add(url) + } } + .modifier(LinkedFolderDialogMessage()) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.linkedFolders.pageIdentifier) } +} - // MARK: - Folder Row +private struct LinkedFolderRow: View { + let folder: LinkedFolder + let status: LinkedFolderStatus? + let canTurnOn: Bool + let model: LinkedFoldersModel - private func folderRow(_ folder: LinkedFolder) -> some View { - HStack(spacing: 8) { - Toggle(isOn: Binding( - get: { folder.isEnabled }, - set: { newValue in - guard let index = folders.firstIndex(where: { $0.id == folder.id }) else { return } - folders[index].isEnabled = newValue - LinkedFolderStorage.shared.saveFolders(folders) - LinkedFolderWatcher.shared.reload() + var body: some View { + LabeledContent { + HStack(spacing: 8) { + Toggle(isOn: Binding(get: { folder.isEnabled }, set: { model.setEnabled($0, for: folder) })) { + Text(verbatim: folder.name) + } + .toggleStyle(.switch) + .labelsHidden() + // A folder already on can always be turned off, licensed or not. + .disabled(!canTurnOn && !folder.isEnabled) + .accessibilityLabel(String(format: String(localized: "Watch %@"), folder.name)) + + Menu { + actions + } label: { + Image(systemName: "ellipsis.circle") } - )) { - EmptyView() + .menuStyle(.button) + .buttonStyle(.borderless) + .menuIndicator(.hidden) + .fixedSize() + .help(String(localized: "Actions")) + .accessibilityLabel(String(format: String(localized: "Actions for %@"), folder.name)) } - .toggleStyle(.switch) - .controlSize(.mini) - .labelsHidden() - .accessibilityLabel(folder.name) - + } label: { VStack(alignment: .leading, spacing: 1) { - Text(folder.name) - .font(.body) + Text(verbatim: folder.name) .lineLimit(1) - - Text(folder.path) - .font(.caption) + Text(verbatim: folder.path) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.middle) - - if folder.isEnabled, let status = watcher.folderStatuses[folder.id] { - statusLines(status) + .help(folder.path) + if let status { + LinkedFolderStatusLines(status: status) + .font(.subheadline) } } .accessibilityElement(children: .combine) - - Spacer() - - Button(role: .destructive) { - removeFolder(folder) - } label: { - Image(systemName: "trash") - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) + .accessibilityActions { + Button(String(localized: "Show in Finder"), action: showInFinder) + Button(String(localized: "Remove"), action: remove) } - .buttonStyle(.plain) - .help(String(localized: "Remove Folder")) - .accessibilityLabel(String(localized: "Remove folder")) } + .contextMenu { + actions + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("linked-folder-row-\(folder.id.uuidString)") } - @ViewBuilder - private func statusLines(_ status: LinkedFolderStatus) -> some View { + @ViewBuilder private var actions: some View { + Button(String(localized: "Show in Finder"), action: showInFinder) + Divider() + Button(String(localized: "Remove"), role: .destructive, action: remove) + } + + private func remove() { + model.remove(folder) + } + + private func showInFinder() { + NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: folder.expandedPath)]) + } +} + +private struct LinkedFolderStatusLines: View { + let status: LinkedFolderStatus + + var body: some View { switch status.contents { case .missing: - warning(String(localized: "Folder not found")) + NoticeLabel(String(localized: "Folder not found")) case .unreadable: - warning(String(localized: "Can't read this folder")) + NoticeLabel(String(localized: "Can't read this folder")) case .connections(let count, let unreadableFiles): - Text(LinkedFolderStatusCopy.connections(count)) - .font(.caption) + Text(verbatim: LinkedFolderStatusCopy.connections(count)) .foregroundStyle(.secondary) if unreadableFiles > 0 { - warning(LinkedFolderStatusCopy.unreadableFiles(unreadableFiles)) + NoticeLabel(LinkedFolderStatusCopy.unreadableFiles(unreadableFiles)) } if !status.isWatched { - warning(String(localized: "Not watching this folder for changes")) + NoticeLabel(String(localized: "Not watching this folder for changes")) } } } +} - private func warning(_ message: String) -> some View { - Label { - Text(message) - .foregroundStyle(.secondary) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - } - .font(.caption) - } - - // MARK: - Actions - - private func addFolder() { - let panel = NSOpenPanel() - panel.canChooseFiles = false - panel.canChooseDirectories = true - panel.allowsMultipleSelection = false - panel.message = String(localized: "Choose a folder to watch for .tablepro connection files") - - guard let window = NSApp.keyWindow else { return } - panel.beginSheetModal(for: window) { response in - guard response == .OK, let url = panel.url else { return } - let path = PathPortability.contractHome(url.path) - - guard !self.folders.contains(where: { $0.path == path }) else { return } - - let folder = LinkedFolder(path: path) - LinkedFolderStorage.shared.addFolder(folder) - self.folders = LinkedFolderStorage.shared.loadFolders() - LinkedFolderWatcher.shared.reload() +private struct LinkedFolderDialogMessage: ViewModifier { + func body(content: Content) -> some View { + if #available(macOS 14.0, *) { + content.fileDialogMessage(Text("Choose a folder to watch for .tablepro connection files")) + } else { + content } } - - private func removeFolder(_ folder: LinkedFolder) { - LinkedFolderStorage.shared.removeFolder(folder) - folders = LinkedFolderStorage.shared.loadFolders() - LinkedFolderWatcher.shared.reload() - } } // Explicit singular and plural keys: see OperationCompletionCopy for why not inflection. diff --git a/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift b/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift deleted file mode 100644 index dd01138ce1..0000000000 --- a/apple/TablePro/Views/Settings/Sections/ConnectionsSettingsSection.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// ConnectionsSettingsSection.swift -// TablePro -// - -import SwiftUI -import TableProConnectionLibrary - -internal struct ConnectionsSettingsSection: View { - @Binding private var healthCheck: ConnectionHealthCheck - @ObservedObject private var listPreferences: ConnectionListPreferences - @ObservedObject private var recentConnections: RecentConnectionsStore - - internal init( - healthCheck: Binding, - listPreferences: ConnectionListPreferences = .shared, - recentConnections: RecentConnectionsStore = .shared - ) { - _healthCheck = healthCheck - self.listPreferences = listPreferences - self.recentConnections = recentConnections - } - - private var showsRecent: Binding { - Binding( - get: { listPreferences.showsRecent }, - set: { listPreferences.setShowsRecent($0) } - ) - } - - internal var body: some View { - Section("Connections") { - Toggle("Show recent connections", isOn: showsRecent) - .accessibilityIdentifier("show-recent-connections-toggle") - .help(String(localized: """ - Adds a Recent section with the connections you opened lately to the welcome window \ - and the connection switcher. - """)) - - LabeledContent("Recent connection history") { - Button("Clear Recent") { - recentConnections.clear() - } - .disabled(recentConnections.ledger.isEmpty) - .accessibilityIdentifier("clear-recent-connections-button") - .help(String(localized: "Forgets which connections you opened and when. Sorting by Last Connected starts over.")) - } - - Picker("Check connections:", selection: $healthCheck) { - ForEach(ConnectionHealthCheck.allCases) { option in - Text(option.title).tag(option) - } - } - .accessibilityIdentifier("connection-health-check-picker") - .help(String(localized: """ - TablePro runs a small query on each open connection so it can notice a dropped \ - one and reconnect before you hit it. Only when I use the connection stops that \ - background traffic, which is what a database that sleeps when idle, or bills \ - per query, needs; TablePro then checks the connection the first time you use \ - it after a pause. - """)) - } - } -} diff --git a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift index e0a1dc3802..806bb88c6c 100644 --- a/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift +++ b/apple/TablePro/Views/Settings/Sections/TrustedExternalConnectionsSection.swift @@ -1,58 +1,126 @@ -// -// TrustedExternalConnectionsSection.swift -// TablePro -// - +import Combine import SwiftUI -struct TrustedExternalConnectionsSection: View { - private let store: ExternalConnectionTrustStore +internal struct TrustedLinkEntry: Identifiable, Equatable, Sendable { + internal let key: ExternalConnectionTrustKey + internal let title: String + // Two saved connections can share type, host, database and user, so the name tells their entries apart. + internal let savedConnectionName: String? + + internal var id: ExternalConnectionTrustKey { key } +} + +@MainActor +internal final class TrustedLinksModel: ObservableObject { + @Published internal private(set) var entries: [TrustedLinkEntry] = [] - @State private var entries: [TrustedExternalConnection] = [] + private let store: ExternalConnectionTrustStore + private let savedConnectionNames: @MainActor () -> [UUID: String] + private var changes: AnyCancellable? - init(store: ExternalConnectionTrustStore = .shared) { + internal init( + store: ExternalConnectionTrustStore = .shared, + savedConnectionNames: @escaping @MainActor () -> [UUID: String] = TrustedLinksModel.savedConnectionNames + ) { self.store = store + self.savedConnectionNames = savedConnectionNames + refresh() + changes = store.changes.sink { [weak self] _ in + self?.refresh() + } } - var body: some View { - Section { - if entries.isEmpty { - Text("No links are trusted yet.") - .foregroundStyle(.secondary) - } else { - ForEach(entries) { entry in - LabeledContent { - Button("Forget") { - store.revoke(entry.key) - refresh() - } - } label: { - Text(entry.key.displayDescription) - if let name = savedConnectionName(of: entry) { - Text(String(format: String(localized: "Saved connection “%@”"), name)) + internal func refresh() { + let trusted = store.entries().sorted { $0.trustedAt > $1.trustedAt } + let names = trusted.contains { $0.key.savedConnectionId != nil } ? savedConnectionNames() : [:] + let updated = trusted.map { entry in + TrustedLinkEntry( + key: entry.key, + title: entry.key.displayDescription, + savedConnectionName: entry.key.savedConnectionId.flatMap { names[$0] } + ) + } + guard updated != entries else { return } + entries = updated + } + + internal func forget(_ key: ExternalConnectionTrustKey) { + store.revoke(key) + } + + internal func forgetAll() { + store.revokeAll() + } + + static func savedConnectionNames() -> [UUID: String] { + Dictionary( + ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, + uniquingKeysWith: { first, _ in first } + ) + } +} + +internal struct TrustedLinksPage: View { + @EnvironmentObject private var model: TrustedLinksModel + @State private var isConfirmingForgetAll = false + + internal var body: some View { + Form { + Section { + if model.entries.isEmpty { + Text("No trusted links") + .foregroundStyle(.secondary) + } else { + ForEach(model.entries) { entry in + TrustedLinkRow(entry: entry) { + model.forget(entry.key) } } } - Button(String(localized: "Forget All"), role: .destructive) { - store.revokeAll() - refresh() + SettingsHelpRow( + "A link you chose Always Allow for connects without asking again. Only connections on this Mac can be trusted." + ) + } footer: { + SettingsSectionActions { + Button(String(localized: "Forget All…")) { + isConfirmingForgetAll = true + } + .disabled(model.entries.isEmpty) + .accessibilityIdentifier("trusted-links-forget-all-button") } } - } header: { - Text("Trusted Links") - } footer: { - Text("Links you chose to always allow. TablePro connects without asking. Only connections on this machine can be trusted.") } - .onAppear(perform: refresh) + .formStyle(.grouped) + .alert(String(localized: "Forget All Trusted Links?"), isPresented: $isConfirmingForgetAll) { + Button(String(localized: "Forget All"), role: .destructive) { + model.forgetAll() + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("Each link asks again before it connects. This applies only to this Mac.") + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.trustedLinks.pageIdentifier) } +} - // Two saved connections can share type, host, database and user, so the name tells their entries apart. - private func savedConnectionName(of entry: TrustedExternalConnection) -> String? { - entry.key.savedConnectionId.flatMap { ConnectionStorage.shared.loadConnection(id: $0)?.name } +private struct TrustedLinkRow: View { + let entry: TrustedLinkEntry + let onForget: () -> Void + + var body: some View { + SettingsRecordRow(title: entry.title, subtitle: subtitle) { + Button(String(localized: "Forget"), action: onForget) + .accessibilityLabel(String(format: String(localized: "Forget %@"), entry.title)) + } + .help(entry.title) + .contextMenu { + Button(String(localized: "Forget"), action: onForget) + } } - private func refresh() { - entries = store.entries().sorted { $0.trustedAt > $1.trustedAt } + private var subtitle: String? { + entry.savedConnectionName.map { String(format: String(localized: "Saved connection “%@”"), $0) } } } diff --git a/apple/TableProTests/Core/Database/ConnectionHealthCheckTests.swift b/apple/TableProTests/Core/Database/ConnectionHealthCheckTests.swift index 41b78ea78e..c3d2052fe7 100644 --- a/apple/TableProTests/Core/Database/ConnectionHealthCheckTests.swift +++ b/apple/TableProTests/Core/Database/ConnectionHealthCheckTests.swift @@ -1,12 +1,3 @@ -// -// ConnectionHealthCheckTests.swift -// TableProTests -// -// The setting behind #2700: how often TablePro talks to a database nobody is using, and the -// freshness rule that lets it stop talking without the app losing track of whether a connection -// still works. -// - import Foundation @testable import TablePro import Testing @@ -43,9 +34,7 @@ struct ConnectionHealthCheckTests { #expect(decoded.connectionHealthCheck == .every30Seconds) } - /// Settings sync between devices, so a newer TablePro can write an interval this build has no - /// case for. Decoding that as the enum throws, which would take the whole of General down with - /// it and reset every other setting the user had. + // A newer Mac can sync an interval this build has no case for; throwing would reset all of General. @Test("an interval from a newer version falls back instead of failing the whole decode") func unknownIntervalFallsBack() throws { let json = Data(#"{"startupBehavior":"reopenLast","connectionHealthCheck":600,"queryTimeoutSeconds":90}"#.utf8) @@ -75,4 +64,9 @@ struct ConnectionHealthCheckTests { #expect(Set(cases.map(\.id)).count == cases.count) #expect(cases.allSatisfy { !$0.title.isEmpty }) } + + @Test("stored values keep their raw values, so synced settings still decode") + func rawValuesAreStable() { + #expect(ConnectionHealthCheck.allCases.map(\.rawValue) == [0, 30, 300, 900]) + } } diff --git a/apple/TableProTests/Core/Storage/ExternalConnectionTrustStoreTests.swift b/apple/TableProTests/Core/Storage/ExternalConnectionTrustStoreTests.swift index dd70d0aec3..143c9e7b45 100644 --- a/apple/TableProTests/Core/Storage/ExternalConnectionTrustStoreTests.swift +++ b/apple/TableProTests/Core/Storage/ExternalConnectionTrustStoreTests.swift @@ -1,3 +1,4 @@ +import Combine import Foundation @testable import TablePro import Testing @@ -120,6 +121,37 @@ struct ExternalConnectionTrustStoreTests { #expect(store.entries().isEmpty) } + @Test("Trust, revoke and revoke all notify after the write lands") + func changesFollowEachWrite() throws { + let store = try makeStore() + var seenCounts: [Int] = [] + let subscription = store.changes.sink { _ in + seenCounts.append(store.entries().count) + } + + store.trust(loopbackKey(scopeName: "ddev-shop")) + store.trust(loopbackKey(scopeName: "ddev-blog")) + store.revoke(loopbackKey(scopeName: "ddev-shop")) + store.revokeAll() + + #expect(seenCounts == [1, 2, 1, 0]) + subscription.cancel() + } + + @Test("A refused remote trust sends no change") + func refusedTrustIsSilent() throws { + let store = try makeStore() + var changes = 0 + let subscription = store.changes.sink { _ in changes += 1 } + + store.trust(ExternalConnectionTrustKey( + databaseType: "MySQL", host: "db.evil.example.com", database: "db", username: "db", scopeName: "" + )) + + #expect(changes == 0) + subscription.cancel() + } + @Test("Trusting the same key twice keeps one entry") func trustIsIdempotent() throws { let store = try makeStore() diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index d8ebaadf97..41ff855003 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -1,8 +1,3 @@ -// -// SettingsFieldDecodingTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -31,6 +26,20 @@ struct SettingsFieldDecodingTests { #expect(settings.queryTimeoutSeconds == 120) } + @Test("A query timeout out of range is clamped on load, so the pop-up always has its item") + func queryTimeoutIsClamped() throws { + let range = DatabaseConnection.queryTimeoutSecondsRange + + let negative = try decode(GeneralSettings.self, #"{"queryTimeoutSeconds":-5}"#) + #expect(negative.queryTimeoutSeconds == range.lowerBound) + + let tooLong = try decode(GeneralSettings.self, #"{"queryTimeoutSeconds":\#(range.upperBound + 1)}"#) + #expect(tooLong.queryTimeoutSeconds == range.upperBound) + + let inRange = try decode(GeneralSettings.self, #"{"queryTimeoutSeconds":3600}"#) + #expect(inRange.queryTimeoutSeconds == 3_600) + } + @Test("A bad Editor value falls back alone") func editorKeepsOtherFields() throws { let settings = try decode( @@ -265,3 +274,31 @@ struct AISettingsProviderDecodingTests { #expect(loaded.activeProviderID == keptID) } } + +struct GeneralSettingsQueryTimeoutTests { + @Test("The standard list is offered as is when the stored value is on it or is no limit") + func standardChoices() { + let standard = [10, 20, 30, 40, 50, 60, 90, 120, 180, 300, 600] + #expect(GeneralSettings.standardQueryTimeouts == standard) + #expect(GeneralSettings.queryTimeoutChoices(including: 60) == standard) + #expect(GeneralSettings.queryTimeoutChoices(including: 0) == standard) + } + + @Test("A custom stored value is merged into the list in order") + func customValueIsMerged() { + let choices = GeneralSettings.queryTimeoutChoices(including: 45) + #expect(choices == [10, 20, 30, 40, 45, 50, 60, 90, 120, 180, 300, 600]) + + let long = GeneralSettings.queryTimeoutChoices(including: 3_600) + #expect(long.last == 3_600) + #expect(long.filter { $0 == 3_600 }.count == 1) + } + + @Test( + "Titles are whole-word durations", + arguments: [(1, "1 second"), (300, "5 minutes"), (90, "1 minute, 30 seconds"), (3_600, "1 hour")] + ) + func titles(seconds: Int, expected: String) { + #expect(GeneralSettings.queryTimeoutTitle(seconds, locale: Locale(identifier: "en_US")) == expected) + } +} diff --git a/apple/TableProTests/ViewModels/WelcomeViewModelTeamCatalogTests.swift b/apple/TableProTests/ViewModels/WelcomeViewModelTeamCatalogTests.swift index c08b2eac70..7a34037498 100644 --- a/apple/TableProTests/ViewModels/WelcomeViewModelTeamCatalogTests.swift +++ b/apple/TableProTests/ViewModels/WelcomeViewModelTeamCatalogTests.swift @@ -1,18 +1,13 @@ -// -// WelcomeViewModelTeamCatalogTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @MainActor struct WelcomeViewModelTeamCatalogTests { - @Test("The catalog folder panel names the Settings pane Linked Folders lives in") - func folderPanelNamesTheGeneralPane() { + @Test("The catalog folder panel names the Settings pane and page Linked Folders lives in") + func folderPanelNamesTheConnectionsPage() { let message = WelcomeViewModel.teamCatalogFolderPanelMessage - let path = "Settings > \(SettingsPane.general.title) > \(LinkedFoldersSection.title)" + let path = "Settings > \(SettingsPane.connections.title) > \(SettingsPage.linkedFolders.title)" #expect(message.contains(path)) } diff --git a/apple/TableProTests/Views/Settings/ConnectionsSettingsModelsTests.swift b/apple/TableProTests/Views/Settings/ConnectionsSettingsModelsTests.swift new file mode 100644 index 0000000000..f260391d62 --- /dev/null +++ b/apple/TableProTests/Views/Settings/ConnectionsSettingsModelsTests.swift @@ -0,0 +1,187 @@ +import Combine +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct LinkedFoldersModelTests { + private let pool = EphemeralDefaultsPool() + private let updates = PassthroughSubject() + + private final class WatcherReloads { + var count = 0 + } + + private func makeModel( + _ storage: LinkedFolderStorage, + reloads: WatcherReloads = WatcherReloads() + ) -> LinkedFoldersModel { + LinkedFoldersModel( + storage: storage, + updates: updates.eraseToAnyPublisher(), + reloadWatcher: { reloads.count += 1 } + ) + } + + @Test("Folders load when the model is made") + func loadsInInit() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + let folder = LinkedFolder(path: "/tmp/team") + storage.addFolder(folder) + + #expect(makeModel(storage).folders == [folder]) + } + + @Test("Adding a folder in the home folder stores it with a tilde and reloads the watcher") + func addContractsHome() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + let reloads = WatcherReloads() + let model = makeModel(storage, reloads: reloads) + + model.add(URL(fileURLWithPath: NSHomeDirectory() + "/Shared/team", isDirectory: true)) + + #expect(model.folders.map { $0.path } == ["~/Shared/team"]) + #expect(storage.loadFolders().map { $0.path } == ["~/Shared/team"]) + #expect(reloads.count == 1) + } + + @Test("Adding a folder that is already linked changes nothing") + func addSkipsDuplicate() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + storage.addFolder(LinkedFolder(path: "/tmp/team")) + let reloads = WatcherReloads() + let model = makeModel(storage, reloads: reloads) + + model.add(URL(fileURLWithPath: "/tmp/team", isDirectory: true)) + + #expect(model.folders.count == 1) + #expect(storage.loadFolders().count == 1) + #expect(reloads.count == 0) + } + + @Test("Turning a folder off persists and reloads the watcher") + func setEnabledPersists() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + let folder = LinkedFolder(path: "/tmp/team") + storage.addFolder(folder) + let reloads = WatcherReloads() + let model = makeModel(storage, reloads: reloads) + + model.setEnabled(false, for: folder) + model.setEnabled(false, for: folder) + + #expect(model.folders.first?.isEnabled == false) + #expect(storage.loadFolders().first?.isEnabled == false) + #expect(reloads.count == 1, "A second write of the same value is a no-op") + } + + @Test("Removing a folder persists and reloads the watcher") + func removePersists() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + let folder = LinkedFolder(path: "/tmp/team") + storage.addFolder(folder) + let reloads = WatcherReloads() + let model = makeModel(storage, reloads: reloads) + + model.remove(folder) + + #expect(model.folders.isEmpty) + #expect(storage.loadFolders().isEmpty) + #expect(reloads.count == 1) + } + + @Test("A change made elsewhere shows up when the watcher reports an update") + func reloadsOnUpdate() throws { + let storage = LinkedFolderStorage(defaults: try pool.make().defaults) + let model = makeModel(storage) + storage.addFolder(LinkedFolder(path: "/tmp/elsewhere")) + + #expect(model.folders.isEmpty) + updates.send(()) + + #expect(model.folders.map { $0.path } == ["/tmp/elsewhere"]) + } +} + +@MainActor +struct TrustedLinksModelTests { + private let pool = EphemeralDefaultsPool() + + private func key(_ scope: String, savedConnectionId: UUID? = nil) -> ExternalConnectionTrustKey { + ExternalConnectionTrustKey( + databaseType: "MySQL", + host: "127.0.0.1", + database: "db", + username: "db", + scopeName: scope, + savedConnectionId: savedConnectionId + ) + } + + private func seededDefaults(_ entries: [TrustedExternalConnection]) throws -> UserDefaults { + let defaults = try pool.make().defaults + defaults.set(try JSONEncoder().encode(entries), forKey: "com.TablePro.externalConnectionTrust.entries") + return defaults + } + + @Test("Entries list newest first with the saved connection's name") + func entriesSortedWithNames() throws { + let savedId = UUID() + let defaults = try seededDefaults([ + TrustedExternalConnection(key: key("older"), trustedAt: Date(timeIntervalSince1970: 100)), + TrustedExternalConnection(key: key("newer", savedConnectionId: savedId), trustedAt: Date(timeIntervalSince1970: 200)), + ]) + var lookups = 0 + let model = TrustedLinksModel(store: ExternalConnectionTrustStore(defaults: defaults)) { + lookups += 1 + return [savedId: "Shop"] + } + + #expect(model.entries.map { $0.key.scopeName } == ["newer", "older"]) + #expect(model.entries.map { $0.savedConnectionName } == ["Shop", nil]) + #expect(lookups == 1, "Names resolve once per refresh") + } + + @Test("Names are not looked up when no entry came from a saved connection") + func noLookupWithoutSavedConnections() throws { + let defaults = try seededDefaults([ + TrustedExternalConnection(key: key("ddev-shop"), trustedAt: Date(timeIntervalSince1970: 100)), + ]) + var lookups = 0 + _ = TrustedLinksModel(store: ExternalConnectionTrustStore(defaults: defaults)) { + lookups += 1 + return [:] + } + + #expect(lookups == 0) + } + + @Test("Forget and Forget All only narrow trust, and the list follows the store") + func forgetNarrowsTrust() throws { + let store = ExternalConnectionTrustStore(defaults: try pool.make().defaults) + store.trust(key("ddev-shop")) + store.trust(key("ddev-blog")) + let model = TrustedLinksModel(store: store) { [:] } + + model.forget(key("ddev-shop")) + + #expect(model.entries.map { $0.key.scopeName } == ["ddev-blog"]) + #expect(store.isTrusted(key("ddev-shop")) == false) + #expect(store.isTrusted(key("ddev-blog"))) + + model.forgetAll() + + #expect(model.entries.isEmpty) + #expect(store.entries().isEmpty) + } + + @Test("A link trusted from a prompt shows up without a refresh") + func followsOutsideTrust() throws { + let store = ExternalConnectionTrustStore(defaults: try pool.make().defaults) + let model = TrustedLinksModel(store: store) { [:] } + + store.trust(key("ddev-shop")) + + #expect(model.entries.map { $0.key.scopeName } == ["ddev-shop"]) + } +} From b19d61db81c125260a5b320deed354e110ad4afa Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:45:54 +0700 Subject: [PATCH 36/48] feat(settings): Profiles pane on shared SSH and credential drafts --- .../TableProSSHConfig/Models/SSHTypes.swift | 62 +- .../Storage/CredentialProfileStorage.swift | 159 ++-- .../Core/Storage/SSHProfileStorage.swift | 174 ++-- .../Models/Connection/CredentialProfile.swift | 79 +- .../Models/Connection/SSHServerDraft.swift | 190 +++++ .../Connection/SSHTunnelFormState.swift | 106 ++- .../Connection/SSHProfileEditorView.swift | 672 +++++----------- .../Views/Connection/SSHServerFields.swift | 306 +++++++ .../Views/Connection/SecretReveal.swift | 37 +- .../Panes/Transports/SSHServerSections.swift | 269 +------ .../Entries/ProfilesSettingsEntry.swift | 13 +- .../Profiles/ConnectionCountCopy.swift | 131 +++ .../CredentialProfileEditorSheet.swift | 748 ++++++++++-------- .../Profiles/ProfilesSettingsModel.swift | 224 ++++++ .../Profiles/ProfilesSettingsView.swift | 312 +++----- .../Storage/ProfileStorageSafetyTests.swift | 312 ++++++++ .../SSHSecretRevealProvenanceTests.swift | 43 + .../ClearedSecretSaveTests.swift | 42 +- 18 files changed, 2308 insertions(+), 1571 deletions(-) create mode 100644 apple/TablePro/Models/Connection/SSHServerDraft.swift create mode 100644 apple/TablePro/Views/Connection/SSHServerFields.swift create mode 100644 apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift create mode 100644 apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift create mode 100644 apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift create mode 100644 apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift diff --git a/apple/Packages/TableProMacCore/Sources/TableProSSHConfig/Models/SSHTypes.swift b/apple/Packages/TableProMacCore/Sources/TableProSSHConfig/Models/SSHTypes.swift index e742094fee..6c04c7f537 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProSSHConfig/Models/SSHTypes.swift +++ b/apple/Packages/TableProMacCore/Sources/TableProSSHConfig/Models/SSHTypes.swift @@ -1,8 +1,3 @@ -// -// SSHTypes.swift -// TablePro -// - import Foundation import TableProSSHTransport @@ -41,11 +36,7 @@ public enum SSHAuthMethod: String, CaseIterable, Identifiable, Codable, Sendable } public extension SSHAuthMethod { - /// iPhone and iPad wrote the case name ("sshAgent", "privateKey") into `sshConfigJson` and into - /// `.tablepro` files before the two sides agreed on these raw values, and a strict decode read - /// every one of them as Password: an agent or key tunnel that silently stopped authenticating, - /// and that the next push from this Mac then wrote back as Password for good. Both spellings - /// decode, so a connection synced from an already-shipped iOS build is read as it was meant. + // Shipped iOS builds wrote the case name ("sshAgent"), which a strict decode read back as Password. init(carrying raw: String) { switch raw { case Self.password.rawValue, "password": self = .password @@ -83,9 +74,7 @@ public enum SSHAgentSocketOption: String, CaseIterable, Identifiable, Sendable { } } - /// Says which agent the choice actually reaches. `SSH_AUTH_SOCK` is the ssh-agent macOS - /// starts for the login session, so it never finds 1Password however the shell is set up, - /// and the connect used to fail with a passphrase prompt for an unrelated key (#2583). + // SSH_AUTH_SOCK is the login session's ssh-agent, which never reaches 1Password however the shell is set up (#2583). public var explanation: String { switch self { case .systemDefault: @@ -130,9 +119,14 @@ public enum SSHJumpAuthMethod: String, CaseIterable, Identifiable, Codable, Send public var id: String { rawValue } - /// Same rule as `SSHAuthMethod` above: a hop an iOS build wrote names its case, not its raw - /// value, and a strict decode threw `dataCorrupted` inside `jumpHosts`, which took the whole - /// SSH configuration and with it the connection. + public var displayName: String { + switch self { + case .privateKey: return String(localized: "Private Key") + case .sshAgent: return String(localized: "SSH Agent") + } + } + + // A hop an iOS build wrote names its case; a strict decode threw inside jumpHosts and lost the connection. public init(carrying raw: String) { switch raw { case Self.privateKey.rawValue, "privateKey", "publicKey": self = .privateKey @@ -170,8 +164,7 @@ public struct SSHJumpHost: Codable, Hashable, Identifiable, Sendable { } public var isValid: Bool { - // Username and port may be empty: the runtime resolver fills them - // from ~/.ssh/config (User, Port directives) when the alias matches. + // Username and port may be empty: ~/.ssh/config fills them when the host is an alias. !host.isEmpty && (authMethod == .sshAgent || !privateKeyPath.isEmpty) } @@ -185,9 +178,7 @@ extension SSHJumpHost { case id, host, port, username, authMethod, privateKeyPath } - /// Same rule as `SSHConfiguration` below: every property has a default, so every key decodes as - /// optional. A required decode threw `keyNotFound` on a hop an older iOS build wrote without - /// `authMethod`, and that failure took the whole connection out of the sync pull. + // Every key decodes as optional: a hop an older iOS build wrote without authMethod threw keyNotFound. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() @@ -199,13 +190,10 @@ extension SSHJumpHost { } } -/// How a file-backed connection reaches a database file that lives on an SSH server. public enum RemoteFileAccess: String, Codable, Hashable, Sendable { - /// Fetch a snapshot over SFTP and open the copy on this Mac, read-only. The original is never - /// written. This is what a connection saved before the live mode existed decodes to. + // A read-only SFTP snapshot; what a connection saved before the live mode existed decodes to. case readOnlyCopy - /// Run statements on the server against the live database through the SQLite agent, so reads - /// and writes act on the file the server's own programs are using. + // Statements run on the server against the live file, through the SQLite agent. case onServer } @@ -223,19 +211,10 @@ public struct SSHConfiguration: Codable, Hashable, Sendable { public var totpDigits: Int = 6 public var totpPeriod: Int = 30 - /// The database file on the SSH server, for a connection whose driver opens a file rather than - /// reaching a port. Empty means this configuration forwards TCP, which is what every - /// server-backed connection does. - /// - /// A leading `~` and a relative path are both left as the user typed them and resolved against - /// the account's home at connect time. SFTP performs no expansion of its own and rejects a - /// literal `~/x` outright, so resolving early would only move the failure somewhere less - /// explainable. + // Empty forwards TCP. `~` and relative paths stay as typed and resolve at connect time: SFTP expands neither. public var remoteFilePath: String = "" - /// Whether the named file is opened as a read-only copy on this Mac or as a live session on the - /// server. Defaults to the copy, so a configuration written before the live mode existed keeps - /// its old behaviour, and an older app that cannot decode this key falls back the same way. + // Defaults to the copy, so a configuration from before the live mode, or an older app, keeps the old behaviour. public var remoteFileAccess: RemoteFileAccess = .readOnlyCopy public init( @@ -272,8 +251,7 @@ public struct SSHConfiguration: Codable, Hashable, Sendable { public var forwardsRemoteFile: Bool { enabled && !remoteFilePath.isEmpty } - /// Username may be empty: the runtime resolver supplies `User` from - /// `~/.ssh/config` when the host is an alias. + // Username may be empty: ~/.ssh/config supplies User when the host is an alias. public var isValid: Bool { guard enabled else { return true } guard !host.isEmpty else { return false } @@ -289,11 +267,7 @@ extension SSHConfiguration { case remoteFileAccess } - /// Every property here declares a default, so every key decodes as optional. A required decode - /// on a field that has a default cannot round-trip a payload written before that field existed: - /// it throws `keyNotFound` and takes the whole connection with it, because a connection that - /// fails to decode is a connection the user no longer has. `agentSocketPath` was the one still - /// required, which is why a stored SSH config from before it existed could not be read back. + // Every key decodes as optional: a payload written before a field existed must not lose the connection. public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) enabled = try container.decodeIfPresent(Bool.self, forKey: .enabled) ?? false diff --git a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift index 829cac0e6e..adad2a60d6 100644 --- a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift +++ b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift @@ -1,8 +1,3 @@ -// -// CredentialProfileStorage.swift -// TablePro -// - import Foundation import os import TableProImport @@ -12,20 +7,49 @@ extension Notification.Name { static let credentialProfilesDidChange = Notification.Name("CredentialProfilesDidChange") } -/// The named credential profiles, in a file beside `connections.json` and stamped the same way. -/// -/// Not `UserDefaults`, which is where SSH profiles live. A credential profile can declare a -/// `PasswordSource.command(shell:)`, and the trust tag is the only thing standing between an -/// attacker-writable file and a command this Mac never agreed to run. `ConnectionStorage` has that -/// tag; the defaults domain has nothing of the kind. +enum ProfileSecretRead: Equatable, Sendable { + case found(String) + case absent + case unreadable + + init(_ result: KeychainStringResult) { + switch result { + case .found(let value): + self = value.isEmpty ? .absent : .found(value) + case .notFound: + self = .absent + case .locked, .userCancelled, .authFailed, .error: + self = .unreadable + } + } + + var value: String? { + guard case .found(let value) = self else { return nil } + return value + } +} + +enum ProfileSecretChange: Equatable, Sendable { + case write(String) + case keep + case delete + + // An empty field over a secret that could not be read means "not shown", never "cleared". + static func decide(applies: Bool, value: String, read: ProfileSecretRead) -> ProfileSecretChange { + if applies, !value.isEmpty { + return read == .found(value) ? .keep : .write(value) + } + return read == .unreadable ? .keep : .delete + } +} + +// A file and not UserDefaults: a profile can name a shell command, and only the file's trust tag stops one this Mac never agreed to run. @MainActor final class CredentialProfileStorage { static let shared = CredentialProfileStorage() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "CredentialProfileStorage") - /// The prefix is load-bearing. `TableProMobile`'s `KeychainSecureStore.cleanOrphanedCredentials` - /// sweeps `com.TablePro.password.` and deletes any item whose trailing UUID is not a saved - /// connection, and a profile id is never a connection id. + // TableProMobile sweeps `com.TablePro.password.` items whose UUID is not a connection, so profile secrets must not share that prefix. static let secretKeyPrefix = "com.TablePro.credprofile." private static let secretPrefix = secretKeyPrefix @@ -34,13 +58,9 @@ final class CredentialProfileStorage { private let syncTracker: SyncChangeTracker private let connectionStorageProvider: () -> ConnectionStorage - /// True when the file exists and would not decode. Saving then would write an empty list over - /// whatever it holds, so every mutation refuses until a load succeeds. + // Every mutation refuses while this is true, or a save would write an empty list over the file. private(set) var lastLoadFailed = false - /// Whether the profiles file is the one TablePro last wrote. `resolvePassword` reads it before - /// running a profile's password source, exactly as it reads `ConnectionStorage.storeIsTrusted` - /// before running a connection's. var storeIsTrusted: Bool { file.isTrusted } init( @@ -68,8 +88,6 @@ final class CredentialProfileStorage { return directory.appendingPathComponent("credentialProfiles.json") } - // MARK: - Profile CRUD - func loadProfiles() -> [CredentialProfile] { guard let profiles = file.load() else { lastLoadFailed = true @@ -108,8 +126,6 @@ final class CredentialProfileStorage { return false } guard file.save(profiles) else { return false } - /// The Settings window is kept alive between openings, so a profile created from a - /// connection window has to reach a Profiles pane that is already on screen. NotificationCenter.default.post(name: .credentialProfilesDidChange, object: nil) return true } @@ -118,15 +134,18 @@ final class CredentialProfileStorage { func addProfile(_ profile: CredentialProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // A record this build cannot read still owns its id, so a second record under it would replace it on save. + guard !profiles.contains(where: { $0.id == profile.id }), !file.unreadableIds.contains(profile.id) else { + Self.logger.error("Refusing to add credential profile \(profile.id.uuidString, privacy: .public): the id is taken") + return false + } var placed = profile placed.sortOrder = (profiles.map { $0.sortOrder }.max() ?? -1) + 1 profiles.append(placed) return saveProfiles(profiles) } - /// Returns only the profiles this call created. A name already here is skipped, so a file can - /// never select one of this Mac's credentials by naming it. Nil when the store is unreadable - /// or the save failed. + // A name already here is skipped, so a file can never select one of this Mac's credentials by naming it. func addImportedProfiles(_ imported: [PlannedCredentialProfile]) -> [BundleRef: UUID]? { guard !imported.isEmpty else { return [:] } var profiles = loadProfiles() @@ -163,9 +182,7 @@ final class CredentialProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - /// Best effort, and deliberately not part of the result. The profile is saved and the - /// connect path resolves the username from it either way; this is what keeps the copy on - /// each connection, which every other reader of `username` uses, in step. + // Best effort: the connect path resolves the username from the profile either way. if !writeUsernameThrough(profile) { Self.logger.error( "Saved credential profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it" @@ -174,30 +191,24 @@ final class CredentialProfileStorage { return true } - /// Deleting hands each linked connection the profile's username and its stored password, as - /// that connection's own inline credentials, so nothing stops connecting. Returns false without - /// deleting anything when that hand-over cannot be completed. + // Linked connections take the profile's credentials as their own first; nothing is deleted if that hand-over fails. @discardableResult func deleteProfile(_ profile: CredentialProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // The stored record, not the caller's copy, which can predate a sync or another window's edit. + var current = profiles.first { $0.id == profile.id } ?? profile + current.secureFieldIds = Array(Set(current.secureFieldIds).union(profile.secureFieldIds)).sorted() profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(from: profile) else { return false } + guard unlinkConnections(from: current) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.credentialProfile, id: profile.id.uuidString) - deleteSecrets(for: profile) + deleteSecrets(for: current) return true } - // MARK: - Linked Connections - - /// Copies the profile's username onto every connection that links to it. - /// - /// `connection.username` stays populated for a linked connection on purpose. It is read raw by - /// the AWS IAM signer, the `~/.pgpass` lookup, `NativeDumpRegistry`'s `-U` flags, - /// `ExternalConnectionTrustKey` and the connection record pushed to iCloud, and blanking it - /// would have pushed an empty username over the good value on a second Mac. + // connection.username stays filled for a linked connection: the IAM signer, ~/.pgpass, dump flags and sync read it raw. @discardableResult func writeUsernameThrough(_ profile: CredentialProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -214,6 +225,13 @@ final class CredentialProfileStorage { @discardableResult func unlinkConnections(from profile: CredentialProfile) -> Bool { let storage = connectionStorageProvider() + // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. + guard !storage.isLibraryUnreadable else { + Self.logger.error( + "Refusing to unlink from credential profile \(profile.id.uuidString, privacy: .public): the connections could not be read" + ) + return false + } let linked = storage.loadConnections().filter { $0.credentialMode == .profile(id: profile.id) } guard !linked.isEmpty else { return true } @@ -234,16 +252,10 @@ final class CredentialProfileStorage { let converted = storage.mutateConnections(ids: Set(linked.map { $0.id })) { connection in connection.credentialMode = .inline connection.username = profile.username - /// Every inline password field is written, not only the one this profile used. A - /// connection that carried a prompt flag or a pgpass flag from before it was linked - /// would otherwise keep it and override the password just copied in. + // Every inline password flag is written, or a stale prompt or pgpass flag overrides the password just copied in. connection.promptForPassword = profile.passwordMode == .prompt connection.usePgpass = profile.passwordMode == .pgpass - /// A password source can name a shell command, and `connections.json` re-stamps itself - /// as trusted whenever the user saves it. Carrying one out of a profiles file that - /// something else wrote would move a command from a store that refuses to run it into - /// one that will, with a profile delete standing in for the user's consent. So it is - /// carried only from a file TablePro itself last wrote; otherwise the connection asks. + // connections.json re-stamps itself on a user save, so a source from an untrusted profiles file would become runnable. if case .source(let source) = profile.passwordMode, carriesSource { connection.passwordSource = source } else { @@ -261,8 +273,7 @@ final class CredentialProfileStorage { return converted } - // MARK: - Secrets - + @discardableResult func savePassword(_ password: String, for profileId: UUID) -> Bool { keychain.writeString(password, forKey: Self.passwordKey(profileId)) } @@ -272,6 +283,10 @@ final class CredentialProfileStorage { .value(label: "Credential profile password (profileId=\(profileId.uuidString))", logger: Self.logger) } + func readPassword(for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.passwordKey(profileId))) + } + func deletePassword(for profileId: UUID) { keychain.delete(forKey: Self.passwordKey(profileId)) } @@ -289,12 +304,15 @@ final class CredentialProfileStorage { ) } + func readSecureField(fieldId: String, for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.fieldKey(fieldId, profileId))) + } + func deleteSecureField(fieldId: String, for profileId: UUID) { keychain.delete(forKey: Self.fieldKey(fieldId, profileId)) } - /// Every keychain item this type writes, removed together. A key written here and missing from - /// this list is a secret that outlives its owner with nothing left that can name it. + // Every Keychain item this type writes. A key missing here outlives its profile with nothing left to name it. func deleteSecrets(for profile: CredentialProfile) { deletePassword(for: profile.id) for fieldId in profile.secureFieldIds { @@ -339,35 +357,24 @@ final class CredentialProfileStorage { } } - private enum SecretRead { - case readable(String?) - case unreadable - } - - /// Nil when anything the profile owns exists but could not be read. A profile with no stored - /// secret reads as an empty set, which is correct for prompt, pgpass and source modes. + // Nil when anything the profile owns exists but could not be read; prompt, pgpass and source modes own no password. private func readSecrets(for profile: CredentialProfile) -> ProfileSecrets? { var password: String? if profile.passwordMode.usesStoredSecret { - guard case .readable(let value) = readSecret(Self.passwordKey(profile.id)) else { return nil } - password = value + switch readPassword(for: profile.id) { + case .found(let value): password = value + case .absent: break + case .unreadable: return nil + } } var fields: [String: String] = [:] for fieldId in profile.secureFieldIds { - guard case .readable(let value) = readSecret(Self.fieldKey(fieldId, profile.id)) else { return nil } - if let value { fields[fieldId] = value } + switch readSecureField(fieldId: fieldId, for: profile.id) { + case .found(let value): fields[fieldId] = value + case .absent: break + case .unreadable: return nil + } } return ProfileSecrets(password: password, fields: fields) } - - private func readSecret(_ key: String) -> SecretRead { - switch keychain.readStringResult(forKey: key) { - case .found(let value): - return .readable(value.isEmpty ? nil : value) - case .notFound: - return .readable(nil) - case .locked, .userCancelled, .authFailed, .error: - return .unreadable - } - } } diff --git a/apple/TablePro/Core/Storage/SSHProfileStorage.swift b/apple/TablePro/Core/Storage/SSHProfileStorage.swift index 455d73840f..4c77829cba 100644 --- a/apple/TablePro/Core/Storage/SSHProfileStorage.swift +++ b/apple/TablePro/Core/Storage/SSHProfileStorage.swift @@ -1,8 +1,3 @@ -// -// SSHProfileStorage.swift -// TablePro -// - import Foundation import os import TableProSyncTransport @@ -25,9 +20,7 @@ final class SSHProfileStorage { private let syncTracker: SyncChangeTracker private(set) var lastLoadFailed = false - /// The keychain arrives through `AppStorageEnvironment` rather than as `KeychainHelper.shared`, - /// so a sandboxed run keeps its profile secrets inside the sandbox instead of writing them to - /// the real login keychain, exactly as `ConnectionStorage` already does. + // The Keychain comes from AppStorageEnvironment, so a sandboxed run keeps profile secrets inside the sandbox. init( userDefaults: UserDefaults = AppStorageEnvironment.shared.defaults, keychain: any KeychainStoring = AppStorageEnvironment.shared.keychain, @@ -40,8 +33,6 @@ final class SSHProfileStorage { self.connectionStorageProvider = connectionStorage } - // MARK: - Profile CRUD - func loadProfiles() -> [SSHProfile] { guard let data = defaults.data(forKey: profilesKey) else { lastLoadFailed = false @@ -59,8 +50,7 @@ final class SSHProfileStorage { } } - /// Returns `false` when nothing reached disk, so a caller that also writes keychain items or - /// tombstones can abort instead of stranding them against a profile that was never persisted. + // False when nothing reached disk, so a caller that also writes Keychain items or tombstones can stop. @discardableResult func saveProfiles(_ profiles: [SSHProfile]) -> Bool { let previous = loadProfiles() @@ -90,6 +80,10 @@ final class SSHProfileStorage { func addProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + guard !profiles.contains(where: { $0.id == profile.id }) else { + Self.logger.error("Refusing to add SSH profile \(profile.id.uuidString, privacy: .public): the id is taken") + return false + } profiles.append(profile) return saveProfiles(profiles) } @@ -101,9 +95,7 @@ final class SSHProfileStorage { guard let index = profiles.firstIndex(where: { $0.id == profile.id }) else { return false } profiles[index] = profile guard saveProfiles(profiles) else { return false } - /// Best effort, and deliberately not part of the result. The profile is the source of - /// truth and it is saved; a connection whose snapshot could not be rewritten is still - /// resolved against the profile by `refreshingLinkedProfile` at connect time. + // Best effort: a connection whose snapshot was not rewritten is resolved against the profile at connect time. if !refreshLinkedConnections(with: profile) { Self.logger.error("Saved SSH profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it") } @@ -114,8 +106,10 @@ final class SSHProfileStorage { func deleteProfile(_ profile: SSHProfile) -> Bool { var profiles = loadProfiles() guard !lastLoadFailed else { return false } + // The stored record, not the caller's copy: unlinking writes its configuration into every linked connection. + let current = profiles.first { $0.id == profile.id } ?? profile profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(fromProfile: profile) else { return false } + guard unlinkConnections(fromProfile: current) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.sshProfile, id: profile.id.uuidString) @@ -127,14 +121,7 @@ final class SSHProfileStorage { loadProfiles().first { $0.id == id } } - // MARK: - Linked Connections - - /// Writes an edited profile's configuration into every connection that links to it. - /// - /// A linked connection stores `.profile(id:snapshot:)`, and that snapshot is what - /// `resolvedSSHConfig` hands to the tunnel, the URL formatter, the display strings and the - /// stage labels. Only the secrets were ever resolved live, so changing a profile's host left - /// every already-linked connection tunnelling to the old one while sending the new password. + // A linked connection tunnels through its stored snapshot, so an edited profile has to be written into each one. @discardableResult func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool = true) -> Bool { let storage = connectionStorageProvider() @@ -148,11 +135,7 @@ final class SSHProfileStorage { } } - /// The connection as it would be if the fan-out above had already run for it. - /// - /// The fan-out covers an edit made here. This covers the window before one has run: a profile - /// edited on another Mac and synced down, or a connection whose store could not be written. - /// Connecting is the moment the answer has to be right, so it asks the profile directly. + // Covers a profile edited on another Mac, or a fan-out that could not be written, at the moment it matters. func refreshingLinkedProfile(_ connection: DatabaseConnection) -> DatabaseConnection { guard case .profile(let profileId, _) = connection.sshTunnelMode, let profile = profile(for: profileId) @@ -160,19 +143,15 @@ final class SSHProfileStorage { return profile.applied(to: connection) } - /// Turns every connection pointing at a profile that is going away into an inline tunnel - /// carrying the same configuration, so a delete never leaves a connection addressing a profile - /// id that no longer resolves. - /// - /// The configuration comes from the profile as it stands now, never from the connection's - /// stored snapshot: a snapshot the fan-out never reached is stale, and converting that one - /// while handing over the profile's current password would send new credentials to the old - /// server. Returns false without changing anything when the secrets cannot be moved, because a - /// connection converted without them cannot authenticate and there is nothing left to recover - /// them from once the profile is deleted. + // The tunnel comes from the profile as it stands, never a stale snapshot, or new credentials reach the old server. @discardableResult func unlinkConnections(fromProfile profile: SSHProfile) -> Bool { let storage = connectionStorageProvider() + // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. + guard !storage.isLibraryUnreadable else { + Self.logger.error("Refusing to unlink from SSH profile \(profile.id.uuidString, privacy: .public): the connections could not be read") + return false + } let linked = storage.loadConnections().filter { $0.isLinked(toSSHProfile: profile.id) } guard !linked.isEmpty else { return true } @@ -194,10 +173,7 @@ final class SSHProfileStorage { connection.sshProfileId = nil } - /// The copies go back if the conversion did not land. A connection still in profile mode - /// reads its secrets from the profile, so the copy would sit in its inline namespace with - /// nothing reading it. Deleting is safe there because the form already clears that - /// namespace on every save a profile-linked connection makes. + // A connection still in profile mode never reads its inline namespace, so the copies go back. if !converted { for connection in linked { storage.deleteSSHPassword(for: connection.id) @@ -208,8 +184,6 @@ final class SSHProfileStorage { return converted } - /// A profile's secrets on their way into a connection's own keychain namespace, which is where - /// an inline tunnel reads them from. private struct ProfileSecrets { let password: String? let keyPassphrase: String? @@ -224,100 +198,92 @@ final class SSHProfileStorage { } } - private enum SecretRead { - case readable(String?) - case unreadable - } - - /// Nil when any of the three could not be read. A profile that simply has none reads as three - /// nils, which is correct for agent and keyless authentication. + // Nil when any of the three could not be read; agent and keyless profiles read as three nils. private func readSecrets(for profileId: UUID) -> ProfileSecrets? { - guard case .readable(let password) = readSecret(Self.passwordKey(profileId)), - case .readable(let keyPassphrase) = readSecret(Self.passphraseKey(profileId)), - case .readable(let totpSecret) = readSecret(Self.totpKey(profileId)) - else { return nil } - return ProfileSecrets(password: password, keyPassphrase: keyPassphrase, totpSecret: totpSecret) + var values: [SSHSecret: String] = [:] + for secret in SSHSecret.allCases { + switch readSecret(secret, for: profileId) { + case .found(let value): values[secret] = value + case .absent: break + case .unreadable: return nil + } + } + return ProfileSecrets( + password: values[.password], + keyPassphrase: values[.keyPassphrase], + totpSecret: values[.totpSecret] + ) } - private func readSecret(_ key: String) -> SecretRead { - switch keychain.readStringResult(forKey: key) { - case .found(let value): - return .readable(value.isEmpty ? nil : value) - case .notFound: - return .readable(nil) - case .locked, .userCancelled, .authFailed, .error: - return .unreadable + // Every Keychain item this type writes. A key missing here outlives its profile with nothing left to name it. + func deleteSecrets(for profileId: UUID) { + for secret in SSHSecret.allCases { + deleteSecret(secret, for: profileId) } } - /// Every keychain item this type writes, removed together. A key written here and missing from - /// this list is a secret that outlives its owner with nothing left that can name it. - func deleteSecrets(for profileId: UUID) { - deleteSSHPassword(for: profileId) - deleteKeyPassphrase(for: profileId) - deleteTOTPSecret(for: profileId) + func readSecret(_ secret: SSHSecret, for profileId: UUID) -> ProfileSecretRead { + ProfileSecretRead(keychain.readStringResult(forKey: Self.key(secret, profileId))) } - // MARK: - SSH Password Storage + @discardableResult + func saveSecret(_ value: String, _ secret: SSHSecret, for profileId: UUID) -> Bool { + keychain.writeString(value, forKey: Self.key(secret, profileId)) + } + + func deleteSecret(_ secret: SSHSecret, for profileId: UUID) { + keychain.delete(forKey: Self.key(secret, profileId)) + } - func saveSSHPassword(_ password: String, for profileId: UUID) { - keychain.writeString(password, forKey: Self.passwordKey(profileId)) + @discardableResult + func saveSSHPassword(_ password: String, for profileId: UUID) -> Bool { + saveSecret(password, .password, for: profileId) } func loadSSHPassword(for profileId: UUID) -> String? { - resolveString(label: "SSH profile password", profileId: profileId, forKey: Self.passwordKey(profileId)) + resolveString(label: "SSH profile password", profileId: profileId, secret: .password) } func deleteSSHPassword(for profileId: UUID) { - keychain.delete(forKey: Self.passwordKey(profileId)) + deleteSecret(.password, for: profileId) } - // MARK: - Key Passphrase Storage - - func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) { - keychain.writeString(passphrase, forKey: Self.passphraseKey(profileId)) + @discardableResult + func saveKeyPassphrase(_ passphrase: String, for profileId: UUID) -> Bool { + saveSecret(passphrase, .keyPassphrase, for: profileId) } func loadKeyPassphrase(for profileId: UUID) -> String? { - resolveString( - label: "SSH profile key passphrase", - profileId: profileId, - forKey: Self.passphraseKey(profileId) - ) + resolveString(label: "SSH profile key passphrase", profileId: profileId, secret: .keyPassphrase) } func deleteKeyPassphrase(for profileId: UUID) { - keychain.delete(forKey: Self.passphraseKey(profileId)) + deleteSecret(.keyPassphrase, for: profileId) } - // MARK: - TOTP Secret Storage - - func saveTOTPSecret(_ secret: String, for profileId: UUID) { - keychain.writeString(secret, forKey: Self.totpKey(profileId)) + @discardableResult + func saveTOTPSecret(_ secret: String, for profileId: UUID) -> Bool { + saveSecret(secret, .totpSecret, for: profileId) } func loadTOTPSecret(for profileId: UUID) -> String? { - resolveString(label: "SSH profile TOTP secret", profileId: profileId, forKey: Self.totpKey(profileId)) + resolveString(label: "SSH profile TOTP secret", profileId: profileId, secret: .totpSecret) } func deleteTOTPSecret(for profileId: UUID) { - keychain.delete(forKey: Self.totpKey(profileId)) - } - - private static func passwordKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.password.\(profileId.uuidString)" + deleteSecret(.totpSecret, for: profileId) } - private static func passphraseKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.keypassphrase.\(profileId.uuidString)" - } - - private static func totpKey(_ profileId: UUID) -> String { - "com.TablePro.sshprofile.totpsecret.\(profileId.uuidString)" + private static func key(_ secret: SSHSecret, _ profileId: UUID) -> String { + switch secret { + case .password: "com.TablePro.sshprofile.password.\(profileId.uuidString)" + case .keyPassphrase: "com.TablePro.sshprofile.keypassphrase.\(profileId.uuidString)" + case .totpSecret: "com.TablePro.sshprofile.totpsecret.\(profileId.uuidString)" + } } - private func resolveString(label: String, profileId: UUID, forKey key: String) -> String? { - keychain.readStringResult(forKey: key) + private func resolveString(label: String, profileId: UUID, secret: SSHSecret) -> String? { + keychain.readStringResult(forKey: Self.key(secret, profileId)) .value(label: "\(label) (profileId=\(profileId.uuidString))", logger: Self.logger) } } diff --git a/apple/TablePro/Models/Connection/CredentialProfile.swift b/apple/TablePro/Models/Connection/CredentialProfile.swift index 19813c912a..726a4e5fce 100644 --- a/apple/TablePro/Models/Connection/CredentialProfile.swift +++ b/apple/TablePro/Models/Connection/CredentialProfile.swift @@ -1,21 +1,10 @@ -// -// CredentialProfile.swift -// TablePro -// - import Foundation -/// Where a profile's password comes from, which is the same vocabulary a connection already has. -/// -/// The payload of `.source` never leaves this Mac. It can name a shell command, and a command that -/// arrived over iCloud or inside a shared export file would be one this Mac never agreed to run. +// The .source payload never leaves this Mac: it can name a shell command this Mac never agreed to run. enum CredentialPasswordMode: Hashable, Sendable { - /// In the Keychain, under the profile's own id. case stored - /// Asked for on every connect. case prompt case source(PasswordSource) - /// Looked up in `~/.pgpass` by host, port, database and username. case pgpass } @@ -38,8 +27,7 @@ extension CredentialPasswordMode: Codable { case .pgpass: self = .pgpass case .source: - /// A malformed payload becomes a prompt rather than failing the whole store: one - /// unreadable profile must not take every other profile down with it. + // A malformed payload becomes a prompt, so one bad profile does not fail the whole store. guard let source = PasswordSource.resilientlyDecoded(from: container, forKey: .source) else { self = .prompt return @@ -64,24 +52,14 @@ extension CredentialPasswordMode: Codable { } } -/// One set of database credentials, named, that any number of connections point at. -/// -/// The point of the type is that the secret exists once. A connection linked to a profile holds no -/// Keychain item of its own, so rotating the password is one edit rather than one edit per -/// connection, which is what issue #2853 asked for. +// The secret exists once: a linked connection holds no Keychain item of its own (#2853). struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { let id: UUID var name: String var username: String var passwordMode: CredentialPasswordMode - /// Plugin-declared secure fields this profile carries, such as an AWS secret access key. The - /// values are in the Keychain under the profile's id; only the ids are stored here. - /// - /// There is no database type on the profile, because a connection only ever reads the fields - /// its own type declares: `DatabaseDriverFactory.buildAdditionalFields` loops over - /// `secureConnectionFieldIds(for: connection.type)`, so a field another engine's profile - /// carries is never looked at. + // No database type here: a connection reads only the secure fields its own type declares. var secureFieldIds: [String] var sortOrder: Int @@ -115,7 +93,6 @@ struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { sortOrder = try container.decodeIfPresent(Int.self, forKey: .sortOrder) ?? 0 } - /// What the picker and the profile list show beside the name. var summary: String { let trimmed = username.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return passwordMode.displayName } @@ -123,18 +100,54 @@ struct CredentialProfile: Identifiable, Hashable, Codable, Sendable { } } -extension CredentialPasswordMode { +// One vocabulary for the editor's picker, the profile list and the connection form. +enum CredentialPasswordKind: String, CaseIterable, Identifiable, Sendable { + case stored, prompt, pgpass, source + + var id: String { rawValue } + var displayName: String { switch self { - case .stored: String(localized: "Saved password") - case .prompt: String(localized: "Ask every time") + case .stored: String(localized: "Saved in Keychain") + case .prompt: String(localized: "Ask Every Time") case .pgpass: String(localized: "~/.pgpass") - case .source(.vaultDatabaseRole): String(localized: "Vault database role") - case .source: String(localized: "Password source") + case .source: String(localized: "Password Source") } } - /// Whether this mode keeps a secret in the Keychain under the profile's id. + var help: String { + switch self { + case .stored: + String(localized: "Saved in the Keychain once and used by every connection on this profile.") + case .prompt: + String(localized: "Every connection using this profile asks for the password once each time TablePro runs.") + case .pgpass: + String(localized: """ + Looked up in ~/.pgpass by the host, port, database and username of the PostgreSQL-family connection \ + that is opening. Other connections ask for the password. + """) + case .source: + String(localized: "It stays on this Mac and never syncs, because it can name a command to run.") + } + } +} + +extension CredentialPasswordMode { + var kind: CredentialPasswordKind { + switch self { + case .stored: .stored + case .prompt: .prompt + case .pgpass: .pgpass + case .source: .source + } + } + + // A Vault role also supplies the username, so the row and the connection form name it. + var displayName: String { + if case .source(.vaultDatabaseRole) = self { return String(localized: "Vault database role") } + return kind.displayName + } + var usesStoredSecret: Bool { if case .stored = self { return true } return false diff --git a/apple/TablePro/Models/Connection/SSHServerDraft.swift b/apple/TablePro/Models/Connection/SSHServerDraft.swift new file mode 100644 index 0000000000..02049977ae --- /dev/null +++ b/apple/TablePro/Models/Connection/SSHServerDraft.swift @@ -0,0 +1,190 @@ +import Foundation +import TableProSSHConfig +import TableProSSHTransport + +extension SSHProfile { + // user@host, plus :port when it is not the default; host alone when there is no user. + var address: String { + let trimmedHost = host.trimmingCharacters(in: .whitespaces) + let trimmedUser = username.trimmingCharacters(in: .whitespaces) + var address = trimmedUser.isEmpty ? trimmedHost : "\(trimmedUser)@\(trimmedHost)" + if let port, port != 22 { + address += ":\(String(port))" + } + return address + } +} + +enum SSHSecret: CaseIterable, Hashable, Sendable { + case password + case keyPassphrase + case totpSecret +} + +struct SSHServerDraft: Equatable, Sendable { + var host = "" + var port = "" + var username = "" + var authMethod: SSHAuthMethod = .password + var password = "" + var privateKeyPath = "" + var keyPassphrase = "" + var agentSocketOption: SSHAgentSocketOption = .systemDefault + var customAgentSocketPath = "" + var selectedConfigHost = "" + var jumpHosts: [SSHJumpHost] = [] + var totpMode: TOTPMode = .none + var totpSecret = "" + var totpAlgorithm: TOTPAlgorithm = .sha1 + var totpDigits = 6 + var totpPeriod = 30 + + init() {} + + init(profile: SSHProfile) { + host = profile.host + port = profile.port.map(String.init) ?? "" + username = profile.username + authMethod = profile.authMethod + privateKeyPath = profile.privateKeyPath + jumpHosts = profile.jumpHosts + totpMode = profile.totpMode + totpAlgorithm = profile.totpAlgorithm + totpDigits = profile.totpDigits + totpPeriod = profile.totpPeriod + applyAgentSocketPath(profile.agentSocketPath) + } + + var trimmedHost: String { + host.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var trimmedUsername: String { + username.trimmingCharacters(in: .whitespacesAndNewlines) + } + + var portNumber: Int? { + Int(port.trimmingCharacters(in: .whitespaces)) + } + + var portIsValid: Bool { + let trimmed = port.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty else { return true } + return Int(trimmed).map { (1...65_535).contains($0) } ?? false + } + + var resolvedAgentSocketPath: String { + agentSocketOption.resolvedPath(customPath: customAgentSocketPath) + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedHost.isEmpty { + issues.append(String(localized: "SSH host is required")) + } + if !portIsValid { + issues.append(String(localized: "SSH port must be between 1 and 65535")) + } + if !jumpHosts.allSatisfy(\.isValid) { + issues.append(String(localized: "Jump host configuration is invalid")) + } + return issues + } + + func applies(_ secret: SSHSecret) -> Bool { + switch secret { + case .password: authMethod == .password || authMethod == .keyboardInteractive + case .keyPassphrase: authMethod == .privateKey + case .totpSecret: totpMode == .autoGenerate + } + } + + func value(of secret: SSHSecret) -> String { + switch secret { + case .password: password + case .keyPassphrase: keyPassphrase + case .totpSecret: totpSecret + } + } + + var filledSecrets: Set { + Set(SSHSecret.allCases.filter { !value(of: $0).isEmpty }) + } + + mutating func setValue(_ value: String, of secret: SSHSecret) { + switch secret { + case .password: password = value + case .keyPassphrase: keyPassphrase = value + case .totpSecret: totpSecret = value + } + } + + func configuration() -> SSHConfiguration { + SSHConfiguration( + enabled: true, + host: trimmedHost, + port: portNumber, + username: trimmedUsername, + authMethod: authMethod, + privateKeyPath: privateKeyPath, + agentSocketPath: resolvedAgentSocketPath, + jumpHosts: jumpHosts, + totpMode: totpMode, + totpAlgorithm: totpAlgorithm, + totpDigits: totpDigits, + totpPeriod: totpPeriod + ) + } + + func apply(to profile: inout SSHProfile) { + profile.host = trimmedHost + profile.port = portNumber + profile.username = trimmedUsername + profile.authMethod = authMethod + profile.privateKeyPath = privateKeyPath + profile.agentSocketPath = resolvedAgentSocketPath + profile.jumpHosts = jumpHosts + profile.totpMode = totpMode + profile.totpAlgorithm = totpAlgorithm + profile.totpDigits = totpDigits + profile.totpPeriod = totpPeriod + } + + var testCredentials: SSHTunnelCredentials { + SSHTunnelCredentials( + sshPassword: password.isEmpty ? nil : password, + keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, + totpSecret: totpSecret.isEmpty ? nil : totpSecret, + keyboardInteractivePromptProvider: nil + ) + } + + mutating func applyAgentSocketPath(_ socketPath: String) { + let option = SSHAgentSocketOption(socketPath: socketPath) + agentSocketOption = option + customAgentSocketPath = option == .custom ? socketPath.trimmingCharacters(in: .whitespacesAndNewlines) : "" + } + + // Picking a config host also points the server at it, in one write. + mutating func selectConfigHost(_ configHost: String) { + selectedConfigHost = configHost + if !configHost.isEmpty { + host = configHost + } + } + + mutating func addJumpHost() { + jumpHosts.append(SSHJumpHost()) + } + + mutating func removeJumpHost(id: UUID) { + jumpHosts.removeAll { $0.id == id } + } + + mutating func moveJumpHost(id: UUID, by offset: Int) { + guard let index = jumpHosts.firstIndex(where: { $0.id == id }) else { return } + let destination = index + offset + guard jumpHosts.indices.contains(destination) else { return } + jumpHosts.swapAt(index, destination) + } +} diff --git a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift b/apple/TablePro/Models/Connection/SSHTunnelFormState.swift index aad25c6c8f..24ebc6a1a5 100644 --- a/apple/TablePro/Models/Connection/SSHTunnelFormState.swift +++ b/apple/TablePro/Models/Connection/SSHTunnelFormState.swift @@ -1,26 +1,16 @@ -// -// SSHTunnelFormState.swift -// TablePro -// - import Foundation import TableProSSHConfig import TableProSSHTransport -/// Encapsulates all SSH tunnel UI state for the connection form. -/// Replaces the 23 scattered @State variables in ConnectionFormView. struct SSHTunnelFormState { - // Mode var enabled: Bool = false var profileId: UUID? var profiles: [SSHProfile] = [] - // Sheet presentation var showingCreateProfile: Bool = false var editingProfile: SSHProfile? var showingSaveAsProfile: Bool = false - // Inline config fields var host: String = "" var port: String = "" var username: String = "" @@ -39,21 +29,18 @@ struct SSHTunnelFormState { var totpDigits: Int = 6 var totpPeriod: Int = 30 - /// What the keychain held for the inline namespace when the form opened, so an emptied field - /// can be told apart from a keychain that could not be read. + // What the Keychain held when the form opened, so an emptied field is told apart from an unreadable Keychain. private(set) var storedPasswordState: ConnectionStorage.StoredSecretState = .absent private(set) var storedKeyPassphraseState: ConnectionStorage.StoredSecretState = .absent + private(set) var loadedTOTPSecret = false + // Secrets read from a profile's Keychain stay in the fields after a switch to inline. + private(set) var profileSecrets: Set = [] - // Remote database file var remoteFilePath: String = "" - /// New connections default to running on the server, which is what a user reaching for a remote - /// SQLite database wants; loading an existing connection overwrites this with its saved value, - /// and a connection saved before the live mode existed decodes as the read-only copy. + // New connections run on the server; a connection saved before the live mode existed decodes as the copy. var remoteFileAccess: RemoteFileAccess = .onServer - // MARK: - Computed Properties - var selectedProfile: SSHProfile? { guard let id = profileId else { return nil } return profiles.first { $0.id == id } @@ -63,7 +50,55 @@ struct SSHTunnelFormState { agentSocketOption.resolvedPath(customPath: customAgentSocketPath) } - // MARK: - Build Methods + var server: SSHServerDraft { + get { + var draft = SSHServerDraft() + draft.host = host + draft.port = port + draft.username = username + draft.authMethod = authMethod + draft.password = password + draft.privateKeyPath = privateKeyPath + draft.keyPassphrase = keyPassphrase + draft.agentSocketOption = agentSocketOption + draft.customAgentSocketPath = customAgentSocketPath + draft.selectedConfigHost = selectedConfigHost + draft.jumpHosts = jumpHosts + draft.totpMode = totpMode + draft.totpSecret = totpSecret + draft.totpAlgorithm = totpAlgorithm + draft.totpDigits = totpDigits + draft.totpPeriod = totpPeriod + return draft + } + set { + host = newValue.host + port = newValue.port + username = newValue.username + authMethod = newValue.authMethod + password = newValue.password + privateKeyPath = newValue.privateKeyPath + keyPassphrase = newValue.keyPassphrase + agentSocketOption = newValue.agentSocketOption + customAgentSocketPath = newValue.customAgentSocketPath + selectedConfigHost = newValue.selectedConfigHost + jumpHosts = newValue.jumpHosts + totpMode = newValue.totpMode + totpSecret = newValue.totpSecret + totpAlgorithm = newValue.totpAlgorithm + totpDigits = newValue.totpDigits + totpPeriod = newValue.totpPeriod + } + } + + // Revealing a secret the Keychain handed over asks for authentication first. + var savedSecrets: Set { + var secrets: Set = [] + if storedPasswordState != .absent { secrets.insert(.password) } + if storedKeyPassphraseState != .absent { secrets.insert(.keyPassphrase) } + if loadedTOTPSecret { secrets.insert(.totpSecret) } + return secrets.union(profileSecrets) + } func buildInlineConfig() -> SSHConfiguration { SSHConfiguration( @@ -84,9 +119,7 @@ struct SSHTunnelFormState { ) } - /// A profile describes a server, not a file, so the remote path is overlaid onto whichever - /// configuration is in play. Two connections through one bastion routinely name two different - /// databases, so the path cannot live on the profile. + // The remote path lives on the connection: two connections through one bastion name different files. func buildSSHConfig() -> SSHConfiguration { guard let profileId, let profile = profiles.first(where: { $0.id == profileId }) else { return buildInlineConfig() @@ -97,8 +130,6 @@ struct SSHTunnelFormState { return config } - // MARK: - Load Methods - mutating func load(from connection: DatabaseConnection) { switch connection.sshTunnelMode { case .disabled: @@ -122,22 +153,31 @@ struct SSHTunnelFormState { @MainActor mutating func loadSecrets(connectionId: UUID, storage: ConnectionStorage) { if case .profile(let profileId, _) = buildTunnelMode() { - // Profile-mode: load secrets from profile keychain namespace - password = SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" + adoptProfileSecrets( + password: SSHProfileStorage.shared.loadSSHPassword(for: profileId) ?? "", + keyPassphrase: SSHProfileStorage.shared.loadKeyPassphrase(for: profileId) ?? "", + totpSecret: SSHProfileStorage.shared.loadTOTPSecret(for: profileId) ?? "" + ) } else { - // Inline/disabled: load from connection keychain namespace + profileSecrets = [] storedPasswordState = storage.sshPasswordState(for: connectionId) storedKeyPassphraseState = storage.keyPassphraseState(for: connectionId) password = storage.loadSSHPassword(for: connectionId) ?? "" keyPassphrase = storage.loadKeyPassphrase(for: connectionId) ?? "" totpSecret = storage.loadTOTPSecret(for: connectionId) ?? "" + loadedTOTPSecret = !totpSecret.isEmpty } } - /// The user emptied an inline SSH secret that had a value. Without this the old secret stays in - /// the keychain and the next connect still authenticates with it. + mutating func adoptProfileSecrets(password: String, keyPassphrase: String, totpSecret: String) { + self.password = password + self.keyPassphrase = keyPassphrase + self.totpSecret = totpSecret + loadedTOTPSecret = false + profileSecrets = server.filledSecrets + } + + // Without this the old inline secret stays in the Keychain and the next connect still uses it. var clearsStoredPassword: Bool { password.isEmpty && storedPasswordState == .stored } @@ -146,7 +186,6 @@ struct SSHTunnelFormState { keyPassphrase.isEmpty && storedKeyPassphraseState == .stored } - /// Build the SSHTunnelMode for saving to the connection. func buildTunnelMode() -> SSHTunnelMode { guard enabled else { return .disabled } if let profileId, let profile = profiles.first(where: { $0.id == profileId }) { @@ -158,8 +197,6 @@ struct SSHTunnelFormState { return .inline(buildInlineConfig()) } - // MARK: - Mutation Methods - mutating func disable() { enabled = false profileId = nil @@ -179,6 +216,7 @@ struct SSHTunnelFormState { totpAlgorithm = .sha1 totpDigits = 6 totpPeriod = 30 + profileSecrets = [] } mutating func switchToInline(fromProfile profile: SSHProfile) { diff --git a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift index b989517cf0..719919896a 100644 --- a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift +++ b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift @@ -1,13 +1,32 @@ -// -// SSHProfileEditorView.swift -// TablePro -// - import SwiftUI import TableProSSHConfig import TableProSSHTransport +struct SSHProfileDraft: Equatable { + var name = "" + var server = SSHServerDraft() + + var trimmedName: String { + name.trimmingCharacters(in: .whitespaces) + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedName.isEmpty { + issues.append(String(localized: "A profile needs a name.")) + } + return issues + server.validationIssues + } +} + struct SSHProfileEditorView: View { + private enum TestState: Equatable { + case idle + case running + case succeeded + case failed(String) + } + @Environment(\.dismiss) private var dismiss let existingProfile: SSHProfile? @@ -17,551 +36,240 @@ struct SSHProfileEditorView: View { var onSave: ((SSHProfile) -> Void)? var onDelete: (() -> Void)? - @State private var profileName: String = "" - - @State private var host: String = "" - @State private var port: String = "22" - @State private var username: String = "" - - @State private var authMethod: SSHAuthMethod = .password - @State private var sshPassword: String = "" - @State private var privateKeyPath: String = "" - @State private var keyPassphrase: String = "" - @State private var agentSocketOption: SSHAgentSocketOption = .systemDefault - @State private var customAgentSocketPath: String = "" - - @State private var totpMode: TOTPMode = .none - @State private var totpSecret: String = "" - @State private var totpAlgorithm: TOTPAlgorithm = .sha1 - @State private var totpDigits: Int = 6 - @State private var totpPeriod: Int = 30 - - @State private var jumpHosts: [SSHJumpHost] = [] - - @State private var sshConfigEntries: [SSHConfigEntry] = [] - @State private var selectedSSHConfigHost: String = "" - - @State private var showingDeleteConfirmation = false + @State private var draft = SSHProfileDraft() + @State private var baseline = SSHProfileDraft() + @State private var hasLoaded = false + @State private var isStored = false + @State private var newProfileId = UUID() + @State private var secretReads: [SSHSecret: ProfileSecretRead] = [:] + @State private var inheritedSecrets: Set = [] + @State private var usageUnknown = false + @State private var configEntries: [SSHConfigEntry] = [] + @State private var pendingDeletion: PendingProfileDeletion? @State private var saveError: String? - @State private var connectionsUsingProfile = 0 - @State private var isTesting = false - @State private var testSucceeded = false - @State private var testError: String? + @State private var test = TestState.idle @State private var testTask: Task? - private var isStoredProfile: Bool { - guard let profile = existingProfile else { return false } - return SSHProfileStorage.shared.profile(for: profile.id) != nil - } + private var storage: SSHProfileStorage { .shared } - private var isValid: Bool { - let nameValid = !profileName.trimmingCharacters(in: .whitespaces).isEmpty - let hostValid = !host.trimmingCharacters(in: .whitespaces).isEmpty - let portValid = port.isEmpty || (Int(port).map { (1...65_535).contains($0) } ?? false) - let authValid = authMethod == .password || authMethod == .sshAgent - || authMethod == .keyboardInteractive || authMethod == .none || !privateKeyPath.isEmpty - let jumpValid = jumpHosts.allSatisfy(\.isValid) - return nameValid && hostValid && portValid && authValid && jumpValid + private var profileId: UUID { + existingProfile?.id ?? newProfileId } - private var resolvedAgentSocketPath: String { - agentSocketOption.resolvedPath(customPath: customAgentSocketPath) + private var savedSecrets: Set { + Set(secretReads.filter { $0.value != .absent }.map(\.key)).union(inheritedSecrets) } var body: some View { VStack(spacing: 0) { Form { Section(String(localized: "Profile")) { - TextField(String(localized: "Name"), text: $profileName, prompt: Text("My Server")) + TextField(String(localized: "Name"), text: $draft.name, prompt: Text("My Server")) + .accessibilityIdentifier("ssh-profile-name") } - - serverSection - authenticationSection - - if authMethod.supportsTwoFactorAuthentication { - totpSection + if secretReads.values.contains(.unreadable) { + Section { + NoticeLabel( + String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") + ) + } } - - jumpHostsSection + SSHServerFields( + draft: $draft.server, + configEntries: configEntries, + identifierPrefix: "ssh-profile", + savedSecrets: savedSecrets + ) } .formStyle(.grouped) Divider() bottomBar } - .frame(minWidth: 480, idealHeight: 500) - .onAppear { - loadExistingProfile() - } + .frame(minWidth: 520, idealWidth: 520, minHeight: 440, idealHeight: 560) + .onAppear(perform: load) .task { - let entries = await Task.detached { SSHConfigParser.parse() }.value - sshConfigEntries = entries + configEntries = await Task.detached { SSHConfigParser.parse() }.value + } + .onChange(of: draft) { _ in + cancelTest() } - .onChange(of: host) { _ in testSucceeded = false } - .onChange(of: port) { _ in testSucceeded = false } - .onChange(of: username) { _ in testSucceeded = false } - .onChange(of: authMethod) { _ in testSucceeded = false } - .onChange(of: sshPassword) { _ in testSucceeded = false } - .onChange(of: privateKeyPath) { _ in testSucceeded = false } - .onChange(of: keyPassphrase) { _ in testSucceeded = false } - .onChange(of: agentSocketOption) { _ in testSucceeded = false } - .onChange(of: customAgentSocketPath) { _ in testSucceeded = false } - .onChange(of: totpMode) { _ in testSucceeded = false } - .onChange(of: totpSecret) { _ in testSucceeded = false } - .onChange(of: jumpHosts) { _ in testSucceeded = false } .onDisappear { testTask?.cancel() } } - // MARK: - Server Section - - private var serverSection: some View { - Section(String(localized: "Server")) { - if !sshConfigEntries.isEmpty { - Picker(String(localized: "Config Host"), selection: $selectedSSHConfigHost) { - Text(String(localized: "Manual")).tag("") - ForEach(sshConfigEntries) { entry in - Text(entry.displayName).tag(entry.host) - } - } - .onChange(of: selectedSSHConfigHost) { _ in - applySSHConfigEntry(selectedSSHConfigHost) - } - } - if selectedSSHConfigHost.isEmpty || sshConfigEntries.isEmpty { - TextField(String(localized: "SSH Host"), text: $host, prompt: Text("ssh.example.com")) - } - TextField(String(localized: "SSH Port"), text: $port, prompt: Text("22")) - TextField(String(localized: "SSH User"), text: $username, prompt: Text("username")) - } - } - - // MARK: - Authentication Section - - private var authenticationSection: some View { - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $authMethod) { - ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if authMethod == .password { - SecureField(String(localized: "Password"), text: $sshPassword) - } else if authMethod == .sshAgent { - Picker(String(localized: "Agent Socket"), selection: $agentSocketOption) { - ForEach(SSHAgentSocketOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - if agentSocketOption == .custom { - TextField( - String(localized: "Custom Path"), - text: $customAgentSocketPath, - prompt: Text("/path/to/agent.sock") - ) - } - Text(agentSocketOption.explanation) - .font(.caption) - .foregroundStyle(.secondary) - LabeledContent(String(localized: "Identity File")) { - HStack { - TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_ed25519.pub")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) - } - } - Text(String(localized: """ - Offers the agent key matching this public key file first. With IdentitiesOnly yes \ - in ~/.ssh/config, only that key is offered. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } else if authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshPassword) - Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) - .font(.caption) - .foregroundStyle(.secondary) - } else if authMethod == .none { - Text("No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: $privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForPrivateKey() } - .controlSize(.small) - } - } - SecureField(String(localized: "Passphrase"), text: $keyPassphrase) - } - } - } - - // MARK: - TOTP Section - - private var totpSection: some View { - Section(String(localized: "Two-Factor Authentication")) { - Picker(String(localized: "TOTP"), selection: $totpMode) { - ForEach(TOTPMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - if totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $totpSecret) - .help(String(localized: "Base32-encoded secret from your authenticator setup")) - - Picker(String(localized: "Algorithm"), selection: $totpAlgorithm) { - ForEach(TOTPAlgorithm.allCases) { algo in - Text(algo.rawValue).tag(algo) - } - } - - Picker(String(localized: "Digits"), selection: $totpDigits) { - Text("6").tag(6) - Text("8").tag(8) - } - - Picker(String(localized: "Period"), selection: $totpPeriod) { - Text("30s").tag(30) - Text("60s").tag(60) + private var bottomBar: some View { + DialogFooter { + if isStored { + Button(String(localized: "Delete Profile"), role: .destructive) { + pendingDeletion = PendingProfileDeletion.make(kind: .ssh, id: profileId, name: baseline.trimmedName) } - } else { - Text(String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - // MARK: - Jump Hosts Section - - private var jumpHostsSection: some View { - Section { - DisclosureGroup(String(localized: "Jump Hosts")) { - ForEach(jumpHosts) { jumpHost in - let jumpHostBinding = $jumpHosts.element(jumpHost) - DisclosureGroup { - TextField(String(localized: "Host"), text: jumpHostBinding.host, prompt: Text("bastion.example.com")) - HStack { - TextField( - String(localized: "Port"), - text: Binding( - get: { jumpHostBinding.wrappedValue.port.map(String.init) ?? "" }, - set: { jumpHostBinding.wrappedValue.port = Int($0) } - ), - prompt: Text("22") - ) - .frame(width: 80) - TextField(String(localized: "Username"), text: jumpHostBinding.username, prompt: Text("admin")) - } - Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if jumpHost.authMethod == .privateKey { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: jumpHostBinding.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { - browseForJumpHostKey(jumpHost: jumpHostBinding) - } - .controlSize(.small) - } - } - } - } label: { - HStack { - Text( - jumpHost.host.isEmpty - ? String(localized: "New Jump Host") - : "\(jumpHost.username)@\(jumpHost.host)" - ) - .foregroundStyle(jumpHost.host.isEmpty ? .secondary : .primary) - Spacer() - Button { - let idToRemove = jumpHost.id - withMotion { jumpHosts.removeAll { $0.id == idToRemove } } - } label: { - Image(systemName: "minus.circle.fill") - .frame(width: 24, height: 24) - .foregroundStyle(.red) - } - .buttonStyle(.plain) - .accessibilityLabel(String(localized: "Remove jump host")) - } - } - } - .onMove { indices, destination in - jumpHosts.move(fromOffsets: indices, toOffset: destination) - } - - Button { - jumpHosts.append(SSHJumpHost()) - } label: { - Label(String(localized: "Add Jump Host"), systemImage: "plus") - } - - Text("Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps.") - .font(.caption) - .foregroundStyle(.secondary) + .disabled(usageUnknown) + .accessibilityIdentifier("ssh-profile-delete") + .profileDeletionAlert($pendingDeletion) { _ in deleteProfile() } } + statusLabel + } actions: { + Button(String(localized: "Test Connection"), action: testConnection) + .disabled(test == .running || !draft.server.validationIssues.isEmpty) + .accessibilityIdentifier("ssh-profile-test") + Button(String(localized: "Cancel")) { dismiss() } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ssh-profile-cancel") + Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } + .keyboardShortcut(.defaultAction) + .disabled(!draft.validationIssues.isEmpty) + .accessibilityIdentifier("ssh-profile-save") } + .padding() } - // MARK: - Bottom Bar - - private var bottomBar: some View { - HStack { - if isStoredProfile { - Button(role: .destructive) { - connectionsUsingProfile = ConnectionStorage.shared.loadConnections() - .filter { connection in - guard case .profile(let id, _) = connection.sshTunnelMode else { return false } - return id == existingProfile?.id - } - .count - showingDeleteConfirmation = true - } label: { - Text("Delete Profile") - } - .alert( - "Delete SSH Profile?", - isPresented: $showingDeleteConfirmation - ) { - Button("Delete", role: .destructive) { deleteProfile() } - Button("Cancel", role: .cancel) {} - } message: { - if connectionsUsingProfile > 0 { - Text("\(connectionsUsingProfile) connection(s) use this profile. They keep this configuration as their own SSH tunnel.") - } else { - Text("This profile will be permanently deleted.") - } - } - } - - Button(action: testSSHConnection) { + @ViewBuilder private var statusLabel: some View { + if let saveError { + NoticeLabel(saveError, severity: .error) + .lineLimit(2) + .truncationMode(.tail) + } else { + switch test { + case .running: HStack(spacing: 6) { - if isTesting { - ProgressView() - .controlSize(.small) - } else if testSucceeded { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(.green) - } else if testError != nil { - Image(systemName: "xmark.circle.fill") - .foregroundStyle(.red) - } else { - Image(systemName: "antenna.radiowaves.left.and.right") - .foregroundStyle(.secondary) - } - Text("Test Connection") + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + Text("Testing…") + .foregroundStyle(.secondary) } - } - .disabled(isTesting || !isValid) - - if let saveError { - NoticeLabel(saveError, severity: .error) - .font(.caption) - .lineLimit(2) - .truncationMode(.tail) - } else if testSucceeded { + case .succeeded: NoticeLabel(String(localized: "Connected"), severity: .success) - .font(.caption) - } else if let testError { - NoticeLabel(testError) - .font(.caption) + case .failed(let message): + NoticeLabel(message, severity: .error) .lineLimit(2) .truncationMode(.tail) + case .idle: + if hasLoaded, draft != baseline, let issue = draft.validationIssues.first { + NoticeLabel(issue) + .lineLimit(2) + } } - - Spacer() - - Button("Cancel") { dismiss() } - .keyboardShortcut(.cancelAction) - - Button(isStoredProfile ? "Save" : "Create") { saveProfile() } - .keyboardShortcut(.defaultAction) - .disabled(!isValid) } - .padding() } - // MARK: - Actions + private func load() { + guard !hasLoaded else { return } + hasLoaded = true - private func loadExistingProfile() { - guard let profile = existingProfile else { return } - profileName = profile.name - host = profile.host - port = profile.port.map(String.init) ?? "" - username = profile.username - authMethod = profile.authMethod - privateKeyPath = profile.privateKeyPath - jumpHosts = profile.jumpHosts - totpMode = profile.totpMode - totpAlgorithm = profile.totpAlgorithm - totpDigits = profile.totpDigits - totpPeriod = profile.totpPeriod + let stored = existingProfile.flatMap { storage.profile(for: $0.id) } + isStored = stored != nil + usageUnknown = ConnectionStorage.shared.isLibraryUnreadable - let option = SSHAgentSocketOption(socketPath: profile.agentSocketPath) - agentSocketOption = option - if option == .custom { - customAgentSocketPath = profile.agentSocketPath + var loaded = SSHProfileDraft() + if let record = stored ?? existingProfile { + loaded.name = record.name + loaded.server = SSHServerDraft(profile: record) } - - // Load secrets from Keychain, falling back to initial values (e.g. from "Save as Profile") - sshPassword = SSHProfileStorage.shared.loadSSHPassword(for: profile.id) ?? initialPassword ?? "" - keyPassphrase = SSHProfileStorage.shared.loadKeyPassphrase(for: profile.id) ?? initialKeyPassphrase ?? "" - totpSecret = SSHProfileStorage.shared.loadTOTPSecret(for: profile.id) ?? initialTOTPSecret ?? "" + // A profile not saved yet has no Keychain items; its secrets come from the connection that promoted it. + if let stored { + for secret in SSHSecret.allCases { + let read = storage.readSecret(secret, for: stored.id) + secretReads[secret] = read + loaded.server.setValue(read.value ?? "", of: secret) + } + } else { + loaded.server.password = initialPassword ?? "" + loaded.server.keyPassphrase = initialKeyPassphrase ?? "" + loaded.server.totpSecret = initialTOTPSecret ?? "" + // They came out of the connection's Keychain, so revealing them asks for authentication like a stored secret. + inheritedSecrets = loaded.server.filledSecrets + } + draft = loaded + baseline = loaded } private func saveProfile() { - let profileId = existingProfile?.id ?? UUID() - - let profile = SSHProfile( - id: profileId, - name: profileName.trimmingCharacters(in: .whitespaces), - host: host, - port: Int(port), - username: username, - authMethod: authMethod, - privateKeyPath: privateKeyPath, - agentSocketPath: resolvedAgentSocketPath, - jumpHosts: jumpHosts, - totpMode: totpMode, - totpAlgorithm: totpAlgorithm, - totpDigits: totpDigits, - totpPeriod: totpPeriod - ) - - let persisted = isStoredProfile - ? SSHProfileStorage.shared.updateProfile(profile) - : SSHProfileStorage.shared.addProfile(profile) - - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. Dismissing would also - /// report a save that did not happen. + // Read, then modify: the stored record may have changed since this sheet opened. + let stored = isStored ? storage.profile(for: profileId) : nil + var record = stored ?? SSHProfile(id: profileId, name: draft.trimmedName) + record.name = draft.trimmedName + draft.server.apply(to: &record) + + let persisted = isStored ? storage.updateProfile(record) : storage.addProfile(record) + // Keychain items are keyed by the profile id, so writing them for a profile that never reached disk strands them. guard persisted else { saveError = String(localized: "Could not save the profile. Reopen the SSH settings and try again.") return } - saveError = nil - - if (authMethod == .password || authMethod == .keyboardInteractive) && !sshPassword.isEmpty { - SSHProfileStorage.shared.saveSSHPassword(sshPassword, for: profileId) - } else { - SSHProfileStorage.shared.deleteSSHPassword(for: profileId) - } - - if authMethod == .privateKey && !keyPassphrase.isEmpty { - SSHProfileStorage.shared.saveKeyPassphrase(keyPassphrase, for: profileId) - } else { - SSHProfileStorage.shared.deleteKeyPassphrase(for: profileId) + isStored = true + + var secretsSaved = true + for secret in SSHSecret.allCases { + let before = secretReads[secret] ?? .absent + switch ProfileSecretChange.decide( + applies: draft.server.applies(secret), + value: draft.server.value(of: secret), + read: before + ) { + case .write(let value): + if storage.saveSecret(value, secret, for: profileId) { + secretReads[secret] = .found(value) + } else { + secretsSaved = false + } + case .keep: + break + case .delete: + storage.deleteSecret(secret, for: profileId) + secretReads[secret] = .absent + } } - - if totpMode == .autoGenerate && !totpSecret.isEmpty { - SSHProfileStorage.shared.saveTOTPSecret(totpSecret, for: profileId) - } else { - SSHProfileStorage.shared.deleteTOTPSecret(for: profileId) + guard secretsSaved else { + saveError = String(localized: "The profile was saved, but its password couldn't be saved to the Keychain.") + return } - - onSave?(profile) + saveError = nil + onSave?(record) dismiss() } - func testSSHConnection() { - isTesting = true - testSucceeded = false - testError = nil - - let config = SSHConfiguration( - enabled: true, - host: host, - port: Int(port), - username: username, - authMethod: authMethod, - privateKeyPath: privateKeyPath, - agentSocketPath: resolvedAgentSocketPath, - jumpHosts: jumpHosts, - totpMode: totpMode, - totpAlgorithm: totpAlgorithm, - totpDigits: totpDigits, - totpPeriod: totpPeriod - ) - - let credentials = SSHTunnelCredentials( - sshPassword: sshPassword.isEmpty ? nil : sshPassword, - keyPassphrase: keyPassphrase.isEmpty ? nil : keyPassphrase, - totpSecret: totpSecret.isEmpty ? nil : totpSecret, - keyboardInteractivePromptProvider: nil - ) - + private func testConnection() { + cancelTest() + test = .running + let config = draft.server.configuration() + let credentials = draft.server.testCredentials testTask = Task { do { - try await SSHTunnelManager.shared.testSSHProfile( - config: config, - credentials: credentials - ) - await MainActor.run { - isTesting = false - testSucceeded = true - } + try await SSHTunnelManager.shared.testSSHProfile(config: config, credentials: credentials) + guard !Task.isCancelled else { return } + test = .succeeded } catch { guard !Task.isCancelled else { return } - await MainActor.run { - isTesting = false - testSucceeded = false - testError = error.localizedDescription - } + test = .failed(error.localizedDescription) } } } - private func deleteProfile() { - guard let profile = existingProfile else { return } - guard SSHProfileStorage.shared.deleteProfile(profile) else { - saveError = String(localized: "Could not delete the profile. Reopen the SSH settings and try again.") - return - } - onDelete?() - dismiss() - } - - // MARK: - SSH Config Helpers - - private func applySSHConfigEntry(_ configHost: String) { - guard !configHost.isEmpty else { return } - host = configHost + // An edit makes the last result stale, and a test still running answers for values no longer on screen. + private func cancelTest() { + testTask?.cancel() + testTask = nil + test = .idle } - private func browseForPrivateKey() { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - privateKeyPath = url.path(percentEncoded: false) + private func deleteProfile() { + guard let stored = storage.profile(for: profileId) else { + guard storage.lastLoadFailed else { + onDelete?() + dismiss() + return } + saveError = ConnectionCountCopy.deleteFailedMessage + return } - } - - private func browseForJumpHostKey(jumpHost: Binding) { - guard let window = NSApp.keyWindow else { return } - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.beginSheetModal(for: window) { response in - if response == .OK, let url = panel.url { - jumpHost.wrappedValue.privateKeyPath = url.path(percentEncoded: false) - } + guard storage.deleteProfile(stored) else { + saveError = ConnectionCountCopy.deleteFailedMessage + return } + onDelete?() + dismiss() } } diff --git a/apple/TablePro/Views/Connection/SSHServerFields.swift b/apple/TablePro/Views/Connection/SSHServerFields.swift new file mode 100644 index 0000000000..936b4e0500 --- /dev/null +++ b/apple/TablePro/Views/Connection/SSHServerFields.swift @@ -0,0 +1,306 @@ +import AppKit +import SwiftUI +import TableProSSHConfig +import TableProSSHTransport + +// Server, Authentication, Two-Factor and Jump Hosts sections, shared by the SSH profile editor and the connection form. +struct SSHServerFields: View { + @Binding var draft: SSHServerDraft + let configEntries: [SSHConfigEntry] + let identifierPrefix: String + // Revealing a secret the Keychain handed over asks for authentication first. + var savedSecrets: Set = [] + + var body: some View { + serverSection + authenticationSection + if draft.authMethod.supportsTwoFactorAuthentication { + twoFactorSection + } + jumpHostsSection + ForEach(draft.jumpHosts) { hop in + jumpHostSection(hop) + } + } + + private var serverSection: some View { + Section(String(localized: "Server")) { + if !configEntries.isEmpty { + Picker(String(localized: "Config Host"), selection: configHost) { + Text("Manual").tag("") + ForEach(configEntries) { entry in + Text(verbatim: entry.displayName).tag(entry.host) + } + } + .accessibilityIdentifier("\(identifierPrefix)-config-host") + } + if draft.selectedConfigHost.isEmpty || configEntries.isEmpty { + TextField(String(localized: "Host"), text: $draft.host, prompt: Text(verbatim: "ssh.example.com")) + .accessibilityIdentifier("\(identifierPrefix)-host") + } + TextField(text: $draft.port, prompt: Text(verbatim: "22")) { + Text("Port") + if !draft.portIsValid { + NoticeLabel(String(localized: "SSH port must be between 1 and 65535"), severity: .error) + } + } + .accessibilityIdentifier("\(identifierPrefix)-port") + TextField(String(localized: "Username"), text: $draft.username, prompt: Text("username")) + .accessibilityIdentifier("\(identifierPrefix)-username") + } + } + + private var configHost: Binding { + Binding( + get: { draft.selectedConfigHost }, + set: { draft.selectConfigHost($0) } + ) + } + + private var authenticationSection: some View { + Section(String(localized: "Authentication")) { + Picker(selection: $draft.authMethod) { + ForEach(SSHAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } label: { + Text("Method") + if let help = methodHelp { + Text(help) + } + } + .accessibilityIdentifier("\(identifierPrefix)-auth-method") + + switch draft.authMethod { + case .password, .keyboardInteractive: + RevealablePasswordField( + title: String(localized: "Password"), + text: $draft.password, + requiresAuthentication: savedSecrets.contains(.password) + ) + case .sshAgent: + Picker(selection: $draft.agentSocketOption) { + ForEach(SSHAgentSocketOption.allCases) { option in + Text(option.displayName).tag(option) + } + } label: { + Text("Agent Socket") + Text(draft.agentSocketOption.explanation) + } + if draft.agentSocketOption == .custom { + TextField( + String(localized: "Custom Path"), + text: $draft.customAgentSocketPath, + prompt: Text(verbatim: "/path/to/agent.sock") + ) + } + keyFileRow( + title: String(localized: "Identity File"), + subtitle: String(localized: """ + Offers the agent key matching this public key file first. With IdentitiesOnly yes \ + in ~/.ssh/config, only that key is offered. + """), + path: $draft.privateKeyPath, + prompt: "~/.ssh/id_ed25519.pub", + panelMessage: String(localized: "Choose a public key file"), + identifier: "\(identifierPrefix)-identity-file" + ) + case .privateKey: + keyFileRow( + title: String(localized: "Key File"), + subtitle: draft.privateKeyPath.isEmpty + ? String(localized: "Auto-detects from ~/.ssh/config and default key locations.") + : nil, + path: $draft.privateKeyPath, + prompt: "~/.ssh/id_rsa", + panelMessage: String(localized: "Choose a private key file"), + identifier: "\(identifierPrefix)-key-file" + ) + RevealablePasswordField( + title: String(localized: "Passphrase"), + text: $draft.keyPassphrase, + requiresAuthentication: savedSecrets.contains(.keyPassphrase), + revealTitle: String(localized: "Show passphrase") + ) + case .none: + EmptyView() + } + } + } + + private var methodHelp: String? { + switch draft.authMethod { + case .keyboardInteractive: + String(localized: "Password is sent via keyboard-interactive challenge-response.") + case .none: + String(localized: "No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") + case .password, .privateKey, .sshAgent: + nil + } + } + + private var twoFactorSection: some View { + Section(String(localized: "Two-Factor Authentication")) { + Picker(String(localized: "TOTP"), selection: $draft.totpMode) { + ForEach(TOTPMode.allCases) { mode in + Text(mode.displayName).tag(mode) + } + } + .accessibilityIdentifier("\(identifierPrefix)-totp-mode") + + if draft.totpMode == .autoGenerate { + RevealablePasswordField( + title: String(localized: "TOTP Secret"), + subtitle: String(localized: "Base32-encoded secret from your authenticator setup"), + text: $draft.totpSecret, + requiresAuthentication: savedSecrets.contains(.totpSecret), + revealTitle: String(localized: "Show secret") + ) + Picker(String(localized: "Algorithm"), selection: $draft.totpAlgorithm) { + ForEach(TOTPAlgorithm.allCases) { algorithm in + Text(verbatim: algorithm.rawValue).tag(algorithm) + } + } + Picker(String(localized: "Digits"), selection: $draft.totpDigits) { + SettingsChoiceItems([6, 8], including: draft.totpDigits) { digits in + Text(verbatim: SettingsFormat.identifier(digits)) + } + } + Picker(String(localized: "Period"), selection: $draft.totpPeriod) { + SettingsChoiceItems([30, 60], including: draft.totpPeriod) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)) + } + } + } else { + SettingsHelpRow( + "If the SSH server asks for a verification code, TablePro prompts you for it when you connect." + ) + } + } + } + + private var jumpHostsSection: some View { + Section { + SettingsHelpRow( + "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." + ) + } header: { + Text("Jump Hosts") + } footer: { + SettingsSectionActions { + Button(String(localized: "Add Jump Host")) { + withMotion { draft.addJumpHost() } + } + .accessibilityIdentifier("\(identifierPrefix)-add-jump-host") + } + } + } + + private func jumpHostSection(_ hop: SSHJumpHost) -> some View { + let position = draft.jumpHosts.firstIndex { $0.id == hop.id } ?? 0 + let binding = $draft.jumpHosts.element(hop) + let identifier = "\(identifierPrefix)-jump-host-\(position + 1)" + return Section(String(format: String(localized: "Jump Host %lld"), Int64(position + 1))) { + TextField(String(localized: "Host"), text: binding.host, prompt: Text(verbatim: "bastion.example.com")) + .accessibilityIdentifier("\(identifier)-host") + TextField(String(localized: "Port"), text: Self.portText(binding.port), prompt: Text(verbatim: "22")) + .accessibilityIdentifier("\(identifier)-port") + TextField(String(localized: "Username"), text: binding.username, prompt: Text(verbatim: "admin")) + .accessibilityIdentifier("\(identifier)-username") + Picker(String(localized: "Authentication"), selection: binding.authMethod) { + ForEach(SSHJumpAuthMethod.allCases) { method in + Text(method.displayName).tag(method) + } + } + if hop.authMethod == .privateKey { + keyFileRow( + title: String(localized: "Key File"), + subtitle: nil, + path: binding.privateKeyPath, + prompt: "~/.ssh/id_rsa", + panelMessage: String(localized: "Choose a private key file"), + identifier: "\(identifier)-key-file" + ) + } + HStack(spacing: 8) { + Button { + withMotion { draft.moveJumpHost(id: hop.id, by: -1) } + } label: { + Label(String(localized: "Move Up"), systemImage: "chevron.up") + .labelStyle(.iconOnly) + } + .help(String(localized: "Move Up")) + .disabled(position == 0) + Button { + withMotion { draft.moveJumpHost(id: hop.id, by: 1) } + } label: { + Label(String(localized: "Move Down"), systemImage: "chevron.down") + .labelStyle(.iconOnly) + } + .help(String(localized: "Move Down")) + .disabled(position == draft.jumpHosts.count - 1) + Spacer() + Button(String(localized: "Remove Jump Host"), role: .destructive) { + withMotion { draft.removeJumpHost(id: hop.id) } + } + .accessibilityIdentifier("\(identifier)-remove") + } + .buttonStyle(.bordered) + } + } + + private static func portText(_ port: Binding) -> Binding { + Binding( + get: { port.wrappedValue.map(String.init) ?? "" }, + set: { port.wrappedValue = Int($0.trimmingCharacters(in: .whitespaces)) } + ) + } + + private func keyFileRow( + title: String, + subtitle: String?, + path: Binding, + prompt: String, + panelMessage: String, + identifier: String + ) -> some View { + LabeledContent { + HStack(spacing: 8) { + TextField(title, text: path, prompt: Text(verbatim: prompt)) + .labelsHidden() + .accessibilityIdentifier(identifier) + Button(String(localized: "Choose…")) { + Self.chooseKeyFile(message: panelMessage) { path.wrappedValue = $0 } + } + .accessibilityIdentifier("\(identifier)-choose") + } + } label: { + Text(verbatim: title) + if let subtitle { + Text(verbatim: subtitle) + } + } + } + + // A sheet on the window that asked, so the panel cannot slip behind it. + private static func chooseKeyFile(message: String, onSelect: @escaping (String) -> Void) { + let panel = NSOpenPanel() + panel.allowsMultipleSelection = false + panel.canChooseDirectories = false + panel.canChooseFiles = true + panel.showsHiddenFiles = true + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") + panel.message = message + guard let window = NSApp.keyWindow else { + panel.begin { response in + guard response == .OK, let url = panel.url else { return } + onSelect(url.path(percentEncoded: false)) + } + return + } + panel.beginSheetModal(for: window) { response in + guard response == .OK, let url = panel.url else { return } + onSelect(url.path(percentEncoded: false)) + } + } +} diff --git a/apple/TablePro/Views/Connection/SecretReveal.swift b/apple/TablePro/Views/Connection/SecretReveal.swift index ea1f9dd7b0..859072c7a8 100644 --- a/apple/TablePro/Views/Connection/SecretReveal.swift +++ b/apple/TablePro/Views/Connection/SecretReveal.swift @@ -1,8 +1,3 @@ -// -// SecretReveal.swift -// TablePro -// - import Combine import SwiftUI @@ -43,9 +38,10 @@ final class SecretReveal: ObservableObject { struct SecretRevealToggle: View { @ObservedObject var reveal: SecretReveal let requiresAuthentication: Bool + var title = String(localized: "Show password") var body: some View { - Toggle(String(localized: "Show password"), isOn: Binding( + Toggle(title, isOn: Binding( get: { reveal.isRevealed }, set: { newValue in Task { await reveal.setRevealed(newValue, requiresAuthentication: requiresAuthentication) } @@ -57,18 +53,41 @@ struct SecretRevealToggle: View { // NSSecureTextField has no reveal of its own, so revealing swaps in a plain field, as the system's password fields do. struct RevealablePasswordField: View { let title: String + let subtitle: String? @Binding var text: String let requiresAuthentication: Bool + let revealTitle: String @StateObject private var reveal = SecretReveal() + init( + title: String, + subtitle: String? = nil, + text: Binding, + requiresAuthentication: Bool, + revealTitle: String = String(localized: "Show password") + ) { + self.title = title + self.subtitle = subtitle + self._text = text + self.requiresAuthentication = requiresAuthentication + self.revealTitle = revealTitle + } + var body: some View { if reveal.isRevealed { - TextField(title, text: $text) + TextField(text: $text) { label } .autocorrectionDisabled() } else { - SecureField(title, text: $text) + SecureField(text: $text) { label } + } + SecretRevealToggle(reveal: reveal, requiresAuthentication: requiresAuthentication, title: revealTitle) + } + + @ViewBuilder private var label: some View { + Text(verbatim: title) + if let subtitle { + Text(verbatim: subtitle) } - SecretRevealToggle(reveal: reveal, requiresAuthentication: requiresAuthentication) } } diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift index 8e2e2e197a..14147b79f0 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift @@ -1,17 +1,8 @@ -// -// SSHServerSections.swift -// TablePro -// - import SwiftUI import TableProSSHConfig import TableProSSHTransport -/// Which SSH server to reach, and how to sign in to it. -/// -/// Sections rather than a `Form`, because the Network tab is the form. It used to wrap itself in -/// one and be embedded inside another by the Remote File pane, which is a grouped form nested in a -/// grouped form and inset twice. +// Sections, not a Form: the Network tab is the form, and the Remote File pane embeds these in it too. struct SSHServerSections: View { @Binding var sshState: SSHTunnelFormState @@ -26,18 +17,21 @@ struct SSHServerSections: View { } } } else if sshState.selectedProfile == nil { - sshInlineFields + SSHServerFields( + draft: $sshState.server, + configEntries: sshState.configEntries, + identifierPrefix: "connection-form-ssh", + savedSecrets: sshState.savedSecrets + ) } } - // MARK: - SSH Profile Section - private var sshProfileSection: some View { Section(String(localized: "Profile")) { Picker(String(localized: "Profile"), selection: $sshState.profileId) { Text("Inline Configuration").tag(UUID?.none) ForEach(sshState.profiles) { profile in - Text("\(profile.name) (\(profile.username)@\(profile.host))").tag(UUID?.some(profile.id)) + Text(verbatim: "\(profile.name) (\(profile.address))").tag(UUID?.some(profile.id)) } } @@ -65,9 +59,11 @@ struct SSHServerSections: View { if let profile = sshState.selectedProfile { DisclosureGroup(String(localized: "Profile Details")) { LabeledContent(String(localized: "Host"), value: profile.host) - LabeledContent(String(localized: "Port"), value: profile.port.map(String.init) ?? "22") + LabeledContent(String(localized: "Port")) { + Text(verbatim: SettingsFormat.identifier(profile.port ?? 22)) + } LabeledContent(String(localized: "Username"), value: profile.username) - LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.rawValue) + LabeledContent(String(localized: "Authentication Method"), value: profile.authMethod.displayName) if !profile.privateKeyPath.isEmpty { LabeledContent( profile.authMethod == .sshAgent @@ -77,7 +73,9 @@ struct SSHServerSections: View { ) } if !profile.jumpHosts.isEmpty { - LabeledContent(String(localized: "Jump Hosts"), value: "\(profile.jumpHosts.count)") + LabeledContent(String(localized: "Jump Hosts")) { + Text(profile.jumpHosts.count, format: .number) + } } } } @@ -133,241 +131,4 @@ struct SSHServerSections: View { totpPeriod: sshState.totpPeriod ) } - - // MARK: - SSH Inline Fields - - private var sshInlineFields: some View { - Group { - Section(String(localized: "Server")) { - if !sshState.configEntries.isEmpty { - Picker(String(localized: "Config Host"), selection: $sshState.selectedConfigHost) { - Text(String(localized: "Manual")).tag("") - ForEach(sshState.configEntries) { entry in - Text(entry.displayName).tag(entry.host) - } - } - .onChange(of: sshState.selectedConfigHost) { _ in - applySSHConfigEntry(sshState.selectedConfigHost) - } - } - if sshState.selectedConfigHost.isEmpty || sshState.configEntries.isEmpty { - TextField(String(localized: "SSH Host"), text: $sshState.host, prompt: Text("ssh.example.com")) - .accessibilityIdentifier("connection-form-ssh-host") - } - TextField(String(localized: "SSH Port"), text: $sshState.port, prompt: Text("22")) - TextField(String(localized: "SSH User"), text: $sshState.username, prompt: Text("username")) - } - - Section(String(localized: "Authentication")) { - Picker(String(localized: "Method"), selection: $sshState.authMethod) { - ForEach(SSHAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if sshState.authMethod == .password { - SecureField(String(localized: "Password"), text: $sshState.password) - } else if sshState.authMethod == .sshAgent { - Picker(String(localized: "Agent Socket"), selection: $sshState.agentSocketOption) { - ForEach(SSHAgentSocketOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - if sshState.agentSocketOption == .custom { - TextField( - String(localized: "Custom Path"), - text: $sshState.customAgentSocketPath, - prompt: Text("/path/to/agent.sock") - ) - } - Text(sshState.agentSocketOption.explanation) - .font(.caption) - .foregroundStyle(.secondary) - LabeledContent(String(localized: "Identity File")) { - HStack { - TextField( - "", - text: $sshState.privateKeyPath, - prompt: Text("~/.ssh/id_ed25519.pub") - ) - Button(String(localized: "Browse")) { - browseForKeyFile( - message: String(localized: "Choose a public key file") - ) { sshState.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - Text(String(localized: """ - Offers the agent key matching this public key file first. With IdentitiesOnly yes \ - in ~/.ssh/config, only that key is offered. - """)) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .keyboardInteractive { - SecureField(String(localized: "Password"), text: $sshState.password) - Text(String(localized: "Password is sent via keyboard-interactive challenge-response.")) - .font(.caption) - .foregroundStyle(.secondary) - } else if sshState.authMethod == .none { - Text("No credentials are sent. Use this when the server handles authentication itself, such as a Tailscale SSH host.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField("", text: $sshState.privateKeyPath, prompt: Text("~/.ssh/id_rsa")) - Button(String(localized: "Browse")) { browseForKeyFile { sshState.privateKeyPath = $0 } } - .controlSize(.small) - } - } - SecureField(String(localized: "Passphrase"), text: $sshState.keyPassphrase) - if sshState.privateKeyPath.isEmpty { - Text(String(localized: "Auto-detects from ~/.ssh/config and default key locations.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if sshState.authMethod.supportsTwoFactorAuthentication { - Section(String(localized: "Two-Factor Authentication")) { - Picker(String(localized: "TOTP"), selection: $sshState.totpMode) { - ForEach(TOTPMode.allCases) { mode in - Text(mode.displayName).tag(mode) - } - } - - if sshState.totpMode == .autoGenerate { - SecureField(String(localized: "TOTP Secret"), text: $sshState.totpSecret) - .help(String(localized: "Base32-encoded secret from your authenticator setup")) - Picker(String(localized: "Algorithm"), selection: $sshState.totpAlgorithm) { - ForEach(TOTPAlgorithm.allCases) { algo in - Text(algo.rawValue).tag(algo) - } - } - Picker(String(localized: "Digits"), selection: $sshState.totpDigits) { - Text("6").tag(6) - Text("8").tag(8) - } - Picker(String(localized: "Period"), selection: $sshState.totpPeriod) { - Text("30s").tag(30) - Text("60s").tag(60) - } - } else { - Text(String(localized: "If the SSH server asks for a verification code, TablePro prompts you for it when you connect.")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - Section { - DisclosureGroup(String(localized: "Jump Hosts")) { - ForEach(sshState.jumpHosts) { jumpHost in - let jumpHostBinding = $sshState.jumpHosts.element(jumpHost) - DisclosureGroup { - TextField( - String(localized: "Host"), - text: jumpHostBinding.host, - prompt: Text("bastion.example.com") - ) - HStack { - TextField( - String(localized: "Port"), - text: Binding( - get: { jumpHostBinding.wrappedValue.port.map(String.init) ?? "" }, - set: { jumpHostBinding.wrappedValue.port = Int($0) } - ), - prompt: Text("22") - ) - .frame(width: 80) - TextField( - String(localized: "Username"), - text: jumpHostBinding.username, - prompt: Text("admin") - ) - } - Picker(String(localized: "Auth"), selection: jumpHostBinding.authMethod) { - ForEach(SSHJumpAuthMethod.allCases) { method in - Text(method.rawValue).tag(method) - } - } - if jumpHost.authMethod == .privateKey { - LabeledContent(String(localized: "Key File")) { - HStack { - TextField( - "", - text: jumpHostBinding.privateKeyPath, - prompt: Text("~/.ssh/id_rsa") - ) - Button(String(localized: "Browse")) { - browseForKeyFile { jumpHostBinding.wrappedValue.privateKeyPath = $0 } - } - .controlSize(.small) - } - } - } - } label: { - HStack { - Text( - jumpHost.host.isEmpty - ? String(localized: "New Jump Host") - : "\(jumpHost.username)@\(jumpHost.host)" - ) - .foregroundStyle(jumpHost.host.isEmpty ? .secondary : .primary) - Spacer() - Button { - let idToRemove = jumpHost.id - withMotion { sshState.jumpHosts.removeAll { $0.id == idToRemove } } - } label: { - Image(systemName: "minus.circle") - } - .buttonStyle(.borderless) - .accessibilityLabel(String(localized: "Remove jump host")) - } - } - } - .onMove { indices, destination in - sshState.jumpHosts.move(fromOffsets: indices, toOffset: destination) - } - - Button { - sshState.jumpHosts.append(SSHJumpHost()) - } label: { - Label(String(localized: "Add Jump Host"), systemImage: "plus") - } - - Text( - "Jump hosts are connected in order before reaching the SSH server above. Only key and agent auth are supported for jumps." - ) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - } - - // MARK: - Helper Methods - - private func browseForKeyFile( - message: String = String(localized: "Choose a private key file"), - onSelect: @escaping (String) -> Void - ) { - let panel = NSOpenPanel() - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".ssh") - panel.showsHiddenFiles = true - panel.message = message - panel.begin { response in - if response == .OK, let url = panel.url { - onSelect(url.path(percentEncoded: false)) - } - } - } - - private func applySSHConfigEntry(_ host: String) { - guard !host.isEmpty else { return } - sshState.host = host - } } diff --git a/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift index e37d226012..a5edee6c32 100644 --- a/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/ProfilesSettingsEntry.swift @@ -2,18 +2,27 @@ import SwiftUI internal struct ProfilesSettingsEntry: View { internal let context: SettingsPaneContext + @ObservedObject private var visit: SettingsPaneVisit + @StateObject private var model = ProfilesSettingsModel() + + internal init(context: SettingsPaneContext) { + self.context = context + self._visit = ObservedObject(wrappedValue: context.visit) + } internal var body: some View { - ProfilesSettingsView() + ProfilesSettingsView(model: model, presentError: context.presentError) + .task(id: visit.count) { model.refresh() } } } +// Profiles owns no SettingsPage: its editors are sheets, so no route reaches this. internal struct ProfilesSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } diff --git a/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift b/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift new file mode 100644 index 0000000000..5057652cff --- /dev/null +++ b/apple/TablePro/Views/Settings/Profiles/ConnectionCountCopy.swift @@ -0,0 +1,131 @@ +import SwiftUI + +enum ProfileKind: Hashable, Sendable { + case credential + case ssh + + func isLinked(_ connection: DatabaseConnection, to profileId: UUID) -> Bool { + switch self { + case .credential: connection.credentialMode == .profile(id: profileId) + case .ssh: connection.isLinked(toSSHProfile: profileId) + } + } +} + +struct PendingProfileDeletion: Identifiable, Equatable, Sendable { + let kind: ProfileKind + let id: UUID + let name: String + let dependentCount: Int + let someConnectionsUnreadable: Bool + + // Nil while the connections can't be read: the count, and so the consequences, are unknown. + @MainActor + static func make( + kind: ProfileKind, + id: UUID, + name: String, + connectionStorage: ConnectionStorage = .shared + ) -> PendingProfileDeletion? { + let connections = connectionStorage.loadConnections() + guard !connectionStorage.lastLoadFailed else { return nil } + return PendingProfileDeletion( + kind: kind, + id: id, + name: name, + dependentCount: connections.filter { kind.isLinked($0, to: id) }.count, + someConnectionsUnreadable: !connectionStorage.unreadableConnectionIds.isEmpty + ) + } + + var title: String { + String(format: String(localized: "Delete “%@”?"), name) + } + + var message: String { + let consequence = ConnectionCountCopy.deletionConsequence(kind: kind, dependentCount: dependentCount) + guard someConnectionsUnreadable else { return consequence } + let unknown = String(localized: "TablePro can't read some saved connections, so it can't tell whether they use this profile.") + return "\(consequence) \(unknown)" + } +} + +enum ConnectionCountCopy { + static func usage(_ count: Int) -> String { + switch count { + case 0: String(localized: "Not used") + case 1: String(format: String(localized: "%lld connection"), Int64(count)) + default: String(format: String(localized: "%lld connections"), Int64(count)) + } + } + + static func deletionConsequence(kind: ProfileKind, dependentCount: Int) -> String { + switch (kind, dependentCount) { + case (_, 0): + String(localized: "This profile will be permanently deleted.") + case (.credential, 1): + String(localized: "1 connection uses this profile. It keeps these credentials as its own.") + case (.credential, _): + String( + format: String(localized: "%lld connections use this profile. They keep these credentials as their own."), + Int64(dependentCount) + ) + case (.ssh, 1): + String(localized: "1 connection uses this profile. It keeps this configuration as its own SSH tunnel.") + case (.ssh, _): + String( + format: String(localized: "%lld connections use this profile. They keep this configuration as their own SSH tunnel."), + Int64(dependentCount) + ) + } + } + + static func unreadableProfiles(_ count: Int) -> String { + switch count { + case 1: + String(localized: "1 profile was saved by a newer version of TablePro and can't be shown here.") + default: + String( + format: String(localized: "%lld profiles were saved by a newer version of TablePro and can't be shown here."), + Int64(count) + ) + } + } + + static var deleteFailedTitle: String { + String(localized: "Couldn't Delete Profile") + } + + static var deleteFailedMessage: String { + String(localized: "Its saved secrets or the connections that use it couldn't be updated, so nothing was deleted.") + } + + static var duplicateFailedTitle: String { + String(localized: "Couldn't Duplicate Profile") + } + + static var duplicateFailedMessage: String { + String(localized: "Its saved secrets couldn't be read or copied, so no copy was made.") + } +} + +extension View { + func profileDeletionAlert( + _ pending: Binding, + onDelete: @escaping (PendingProfileDeletion) -> Void + ) -> some View { + alert( + pending.wrappedValue?.title ?? "", + isPresented: Binding( + get: { pending.wrappedValue != nil }, + set: { if !$0 { pending.wrappedValue = nil } } + ), + presenting: pending.wrappedValue + ) { item in + Button(String(localized: "Delete"), role: .destructive) { onDelete(item) } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { item in + Text(verbatim: item.message) + } + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift index a7b87f66f0..2ea6e2c09a 100644 --- a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift +++ b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift @@ -1,266 +1,349 @@ -// -// CredentialProfileEditorSheet.swift -// TablePro -// - import SwiftUI import TableProPluginKit -/// One credential profile: the name every connection picks it by, the username, and where the -/// password comes from. +struct CredentialProfileDraft: Equatable { + var name = "" + var username = "" + var passwordKind: CredentialPasswordKind = .stored + var password = "" + var sourceKind: PasswordSourceKind = .file + var sourceValue = "" + var sourceField = "" + var commandReuseSeconds: Int? + var vaultAccess = VaultAccessDraft() + var secureFieldValues: [String: String] = [:] + var takenNames: [String] = [] + + var trimmedName: String { + name.trimmingCharacters(in: .whitespaces) + } + + var trimmedUsername: String { + username.trimmingCharacters(in: .whitespaces) + } + + // Two profiles with one name are indistinguishable in every picker that offers them. + var nameIsTaken: Bool { + !trimmedName.isEmpty && takenNames.contains { ProfileNames.matches($0, trimmedName) } + } + + var usernameComesFromSource: Bool { + passwordKind == .source && sourceKind.suppliesUsername + } + + var testedSource: PasswordSource? { + guard !sourceValue.trimmingCharacters(in: .whitespaces).isEmpty else { return nil } + if sourceKind == .vaultDatabaseRole { + guard !sourceField.trimmingCharacters(in: .whitespaces).isEmpty, vaultAccess.isComplete else { return nil } + } + return sourceKind.source(value: sourceValue, field: sourceField, reuseSeconds: nil, vaultAccess: vaultAccess) + } + + var passwordMode: CredentialPasswordMode { + switch passwordKind { + case .stored: .stored + case .prompt: .prompt + case .pgpass: .pgpass + case .source: + .source(sourceKind.source( + value: sourceValue, + field: sourceField, + reuseSeconds: commandReuseSeconds, + vaultAccess: vaultAccess + )) + } + } + + var validationIssues: [String] { + var issues: [String] = [] + if trimmedName.isEmpty { + issues.append(String(localized: "A profile needs a name.")) + } else if nameIsTaken { + issues.append(String(localized: "Another profile already has this name.")) + } + if passwordKind == .source, testedSource == nil { + issues.append(String(localized: "Enter where the password is read from.")) + } + return issues + } + + mutating func apply(_ mode: CredentialPasswordMode) { + passwordKind = mode.kind + guard case .source(let source) = mode else { return } + (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) + if case .command(_, let reuseSeconds) = source { + commandReuseSeconds = reuseSeconds + } + if let role = source.vaultDatabaseRole { + vaultAccess = VaultAccessDraft(role) + } + } +} + struct CredentialProfileEditorSheet: View { @Environment(\.dismiss) private var dismiss let existingProfile: CredentialProfile? var initialPassword: String? - /// Which engine's secrets to offer first, so a profile promoted from a Postgres connection - /// does not open on MySQL's fields. + // A profile promoted from a Postgres connection opens on Postgres's secrets, not MySQL's. var initialDatabaseType: DatabaseType? var onSave: ((CredentialProfile) -> Void)? var onDelete: (() -> Void)? - @State private var name: String = "" - @State private var username: String = "" - @State private var passwordKind: PasswordKind = .stored - @State private var password: String = "" - @State private var passwordWasPrefilled = false - @State private var sourceKind: PasswordSourceKind = .file - @State private var sourceValue: String = "" - @State private var sourceField: String = "" - @State private var commandReuseSeconds: Int? - @State private var vaultAccess = VaultAccessDraft() + @State private var draft = CredentialProfileDraft() + @State private var baseline = CredentialProfileDraft() + @State private var hasLoaded = false + @State private var isStored = false // A new profile keeps this id when saved, so its first connect signs in as the user Test Source leased. @State private var draftProfileId = UUID() + @State private var storedPasswordMode: CredentialPasswordMode? + @State private var passwordRead: ProfileSecretRead = .absent + @State private var fieldReads: [String: ProfileSecretRead] = [:] + @State private var passwordWasPrefilled = false + @State private var usageUnknown = false + @State private var vaultAddressPrompt = "https://vault.example.com:8200" + @State private var secureFieldTypes: [DatabaseType] = [] + @State private var secureFieldsByType: [DatabaseType: [ConnectionField]] = [:] @State private var secureFieldType: DatabaseType = .mysql - @State private var secureFieldValues: [String: String] = [:] - @State private var showingDeleteConfirmation = false - @State private var dependentCount = 0 + @State private var pendingDeletion: PendingProfileDeletion? @State private var saveError: String? - /// Read once when the sheet opens. `body` reads `nameIsUnique` and `isStored` several times per - /// pass, and each one used to decode the whole profiles file off disk, on every keystroke. - @State private var otherProfileNames: [String] = [] - @State private var isStored = false - @State private var secureFields: [ConnectionField] = [] - /// False when a keychain read failed rather than finding nothing. Saving then must not - /// treat an empty field as the user clearing a secret: a rename while the keychain was - /// locked would delete the password of every connection on the profile. - @State private var secretsWereReadable = true - private var storage: CredentialProfileStorage { .shared } - private var trimmedName: String { name.trimmingCharacters(in: .whitespaces) } - - private var isValid: Bool { - guard !trimmedName.isEmpty else { return false } - guard nameIsUnique else { return false } - if passwordKind == .source { - return testedSource != nil - } - return true - } - - private var usernameComesFromSource: Bool { - passwordKind == .source && sourceKind.suppliesUsername + private var profileId: UUID { + existingProfile?.id ?? draftProfileId } - /// Two profiles with one name are indistinguishable in every picker that offers them, which is - /// the reason the system's own profile editors refuse it. - private var nameIsUnique: Bool { - !otherProfileNames.contains { - $0.compare(trimmedName, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame - } + // A rename while the Keychain was locked must not read an empty field as the user clearing a secret. + private var secretsWereReadable: Bool { + passwordRead != .unreadable && !fieldReads.values.contains(.unreadable) } var body: some View { VStack(spacing: 0) { Form { - Section(String(localized: "Profile")) { - TextField(String(localized: "Name"), text: $name, prompt: Text("Production reader")) - .accessibilityIdentifier("credential-profile-name") - if !trimmedName.isEmpty && !nameIsUnique { - NoticeLabel(String(localized: "Another profile already has this name.")) - .font(.caption) - } - TextField( - String(localized: "Username"), - text: $username, - prompt: usernameComesFromSource ? Text("Generated by Vault") : Text("app_reader") - ) - .disabled(usernameComesFromSource) - .accessibilityIdentifier("credential-profile-username") - } - + profileSection if !secretsWereReadable { Section { NoticeLabel( String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") ) - .font(.caption) } } passwordSection - secureFieldsSection + if !secureFieldTypes.isEmpty { + secureFieldsSection + } } .formStyle(.grouped) Divider() bottomBar } - .frame(minWidth: 480, minHeight: 420, idealHeight: 460) + .frame(minWidth: 520, idealWidth: 520, minHeight: 440, idealHeight: 560) .onAppear(perform: load) } - // MARK: - Password + private var profileSection: some View { + Section(String(localized: "Profile")) { + TextField(text: $draft.name, prompt: Text("Production reader")) { + Text("Name") + if draft.nameIsTaken { + NoticeLabel(String(localized: "Another profile already has this name.")) + } + } + .accessibilityIdentifier("credential-profile-name") + TextField( + String(localized: "Username"), + text: $draft.username, + prompt: draft.usernameComesFromSource ? Text("Generated by Vault") : Text(verbatim: "app_reader") + ) + .disabled(draft.usernameComesFromSource) + .accessibilityIdentifier("credential-profile-username") + } + } - @ViewBuilder private var passwordSection: some View { Section(String(localized: "Password")) { - Picker(String(localized: "Source"), selection: $passwordKind) { - ForEach(PasswordKind.allCases) { kind in + Picker(selection: $draft.passwordKind) { + ForEach(CredentialPasswordKind.allCases) { kind in Text(kind.displayName).tag(kind) } + } label: { + Text("Source") + Text(passwordKindHelp) } .accessibilityIdentifier("credential-profile-password-kind") - switch passwordKind { + switch draft.passwordKind { case .stored: RevealablePasswordField( title: String(localized: "Password"), - text: $password, + text: $draft.password, requiresAuthentication: passwordWasPrefilled ) - case .prompt: - Text("Every connection using this profile asks for the password once each time TablePro runs.") - .font(.caption) - .foregroundStyle(.secondary) - case .pgpass: - Text("Looked up in ~/.pgpass by the host, port, database and username of the PostgreSQL-family connection that is opening. Other connections ask for the password.") - .font(.caption) - .foregroundStyle(.secondary) + case .prompt, .pgpass: + EmptyView() case .source: - Picker(String(localized: "Read From"), selection: $sourceKind) { - ForEach(PasswordSourceKind.allCases) { kind in - Text(kind.displayName).tag(kind) - } - } - TextField(sourceKind.valueLabel, text: $sourceValue, prompt: Text(sourceKind.placeholder)) - if let fieldLabel = sourceKind.fieldLabel { - TextField(fieldLabel, text: $sourceField, prompt: Text(sourceKind.fieldPlaceholder)) - } - if sourceKind == .vaultDatabaseRole { - vaultAccessRows - } - if sourceKind == .command { - Picker(String(localized: "Reuse Result For"), selection: $commandReuseSeconds) { - Text("Never").tag(Int?.none) - ForEach(Self.reuseChoices(including: commandReuseSeconds), id: \.self) { seconds in - Text(Self.reuseLabel(seconds)).tag(Int?.some(seconds)) - } - } - .accessibilityIdentifier("credential-profile-command-reuse") - Text(String(localized: """ - {host}, {port}, {user} and {database} become the opening connection's values, \ - already quoted. The command also gets them as TABLEPRO_HOST, TABLEPRO_PORT, \ - TABLEPRO_USER and TABLEPRO_DATABASE. - """)) - .font(.caption) - .foregroundStyle(.secondary) + sourceRows + } + } + } + + private var passwordKindHelp: String { + switch draft.passwordKind { + case .source where draft.sourceKind == .vaultDatabaseRole: + String(localized: "It stays on this Mac and never syncs, because it names where your Vault token is sent.") + default: + draft.passwordKind.help + } + } + + @ViewBuilder private var sourceRows: some View { + Picker(selection: $draft.sourceKind) { + ForEach(PasswordSourceKind.allCases) { kind in + Text(kind.displayName).tag(kind) + } + } label: { + Text("Read From") + if draft.sourceKind == .vaultDatabaseRole { + Text(String(localized: """ + Connections on this profile share one database user. TablePro renews its lease while in use, revokes it \ + once the last connection disconnects or after 10 minutes unused, and never saves the generated password. + """)) + } + } + TextField(text: $draft.sourceValue, prompt: Text(verbatim: draft.sourceKind.placeholder)) { + Text(verbatim: draft.sourceKind.valueLabel) + if draft.sourceKind == .command { + Text(String(localized: """ + {host}, {port}, {user} and {database} become the opening connection's values, \ + already quoted. The command also gets them as TABLEPRO_HOST, TABLEPRO_PORT, \ + TABLEPRO_USER and TABLEPRO_DATABASE. + """)) + } + } + if let fieldLabel = draft.sourceKind.fieldLabel { + TextField(fieldLabel, text: $draft.sourceField, prompt: Text(verbatim: draft.sourceKind.fieldPlaceholder)) + } + if draft.sourceKind == .vaultDatabaseRole { + vaultAccessRows + } + if draft.sourceKind == .command { + Picker(String(localized: "Reuse Result For"), selection: $draft.commandReuseSeconds) { + Text("Never").tag(Int?.none) + ForEach(Self.reuseChoices(including: draft.commandReuseSeconds), id: \.self) { seconds in + Text(verbatim: SettingsFormat.duration(seconds: seconds)).tag(Int?.some(seconds)) } - Text(sourceKind == .vaultDatabaseRole - ? String(localized: "It stays on this Mac and never syncs, because it names where your Vault token is sent.") - : String(localized: "It stays on this Mac and never syncs, because it can name a command to run.")) - .font(.caption) - .foregroundStyle(.secondary) - if let testedSource { - PasswordSourceTestView( - source: testedSource, - context: { testContext }, - leaseOwner: { profileId }, - refusal: { - Self.testRefusal( - for: testedSource, - storedSource: storedSource, - storeIsTrusted: storage.storeIsTrusted - ) - } + } + .accessibilityIdentifier("credential-profile-command-reuse") + } + if let testedSource = draft.testedSource { + PasswordSourceTestView( + source: testedSource, + context: { testContext }, + leaseOwner: { profileId }, + refusal: { + Self.testRefusal( + for: testedSource, + storedSource: storedSource, + storeIsTrusted: storage.storeIsTrusted ) - if sourceKind == .command, mentionsConnectionDetails { - Text("A test here has no connection to take the host, port and database from.") - .font(.caption) - .foregroundStyle(.secondary) - } } + ) + if draft.sourceKind == .command, mentionsConnectionDetails { + SettingsHelpRow("A test here has no connection to take the host, port and database from.") } } } - @ViewBuilder - private var vaultAccessRows: some View { + @ViewBuilder private var vaultAccessRows: some View { TextField( String(localized: "Vault Address"), - text: $vaultAccess.address, - prompt: Text(verbatim: ProcessInfo.processInfo.environment["VAULT_ADDR"] ?? "https://vault.example.com:8200") + text: $draft.vaultAccess.address, + prompt: Text(verbatim: vaultAddressPrompt) ) .accessibilityIdentifier("credential-profile-vault-address") - Picker(String(localized: "Sign In With"), selection: Binding( - get: { vaultAccess.method }, - set: { vaultAccess.selectMethod($0) } - )) { + Picker(selection: vaultMethod) { ForEach(VaultAccessDraft.Method.allCases) { method in Text(method.displayName).tag(method) } + } label: { + Text("Sign In With") + switch draft.vaultAccess.method { + case .token: + Text("Reads VAULT_TOKEN, or ~/.vault-token from vault login.") + case .oidc: + Text("Your browser opens to sign in once per launch. The role must allow http://localhost:8250/oidc/callback.") + case .appRole: + EmptyView() + } } .accessibilityIdentifier("credential-profile-vault-method") - switch vaultAccess.method { + switch draft.vaultAccess.method { case .token: - Text("Reads VAULT_TOKEN, or ~/.vault-token from vault login.") - .font(.caption) - .foregroundStyle(.secondary) + EmptyView() case .appRole: - TextField(String(localized: "Role ID"), text: $vaultAccess.roleId) + TextField(String(localized: "Role ID"), text: $draft.vaultAccess.roleId) .accessibilityIdentifier("credential-profile-vault-role-id") TextField( String(localized: "Secret ID File"), - text: $vaultAccess.secretIdPath, + text: $draft.vaultAccess.secretIdPath, prompt: Text(verbatim: "~/.vault/approle-secret-id") ) .accessibilityIdentifier("credential-profile-vault-secret-id-path") - TextField(String(localized: "Auth Mount"), text: $vaultAccess.mount, prompt: Text(verbatim: VaultAuthMethod.defaultAppRoleMount)) + TextField( + String(localized: "Auth Mount"), + text: $draft.vaultAccess.mount, + prompt: Text(verbatim: VaultAuthMethod.defaultAppRoleMount) + ) case .oidc: - TextField(String(localized: "OIDC Role"), text: $vaultAccess.oidcRole, prompt: Text("Default role")) - TextField(String(localized: "Auth Mount"), text: $vaultAccess.mount, prompt: Text(verbatim: VaultAuthMethod.defaultOIDCMount)) - Text("Your browser opens to sign in once per launch. The role must allow http://localhost:8250/oidc/callback.") - .font(.caption) - .foregroundStyle(.secondary) + TextField(String(localized: "OIDC Role"), text: $draft.vaultAccess.oidcRole, prompt: Text("Default role")) + TextField( + String(localized: "Auth Mount"), + text: $draft.vaultAccess.mount, + prompt: Text(verbatim: VaultAuthMethod.defaultOIDCMount) + ) } - Text(String(localized: """ - Connections on this profile share one database user. TablePro renews its lease while in use, revokes it \ - once the last connection disconnects or after 10 minutes unused, and never saves the generated password. - """)) - .font(.caption) - .foregroundStyle(.secondary) } - // MARK: - Test Source + // Choosing a method also resets the fields it does not use, in one write. + private var vaultMethod: Binding { + Binding( + get: { draft.vaultAccess.method }, + set: { draft.vaultAccess.selectMethod($0) } + ) + } - private var testedSource: PasswordSource? { - guard !sourceValue.trimmingCharacters(in: .whitespaces).isEmpty else { return nil } - if sourceKind == .vaultDatabaseRole { - guard !sourceField.trimmingCharacters(in: .whitespaces).isEmpty, vaultAccess.isComplete else { return nil } + private var secureFieldsSection: some View { + Section(String(localized: "Additional Secrets")) { + Picker(selection: $secureFieldType) { + ForEach(secureFieldTypes, id: \.self) { type in + Text(verbatim: type.displayName).tag(type) + } + } label: { + Text("Database") + Text("A connection reads only the secrets its own database type declares, so one profile can carry several engines' keys.") + } + .accessibilityIdentifier("credential-profile-secure-field-type") + ForEach(secureFieldsByType[secureFieldType] ?? [], id: \.id) { field in + ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) + } } - return sourceKind.source(value: sourceValue, field: sourceField, reuseSeconds: nil, vaultAccess: vaultAccess) } - private var storedSource: PasswordSource? { - guard isStored, case .source(let source) = existingProfile?.passwordMode else { return nil } - return source + private func secureFieldBinding(for field: ConnectionField) -> Binding { + Binding( + get: { draft.secureFieldValues[field.id] ?? "" }, + set: { draft.secureFieldValues[field.id] = $0 } + ) } - private var profileId: UUID { - existingProfile?.id ?? draftProfileId + private var storedSource: PasswordSource? { + guard isStored, case .source(let source) = storedPasswordMode else { return nil } + return source } private var testContext: ConnectionScriptContext { @@ -269,13 +352,13 @@ struct CredentialProfileEditorSheet: View { connectionName: "", host: "", port: 0, - user: username.trimmingCharacters(in: .whitespaces), + user: draft.trimmedUsername, database: "" ) } private var mentionsConnectionDetails: Bool { - sourceValue.contains("TABLEPRO_") || testContext.substitutingPlaceholders(in: sourceValue) != sourceValue + draft.sourceValue.contains("TABLEPRO_") || testContext.substitutingPlaceholders(in: draft.sourceValue) != draft.sourceValue } // A source typed here is the user's own; one read back unchanged from a profiles file something else wrote is not. @@ -295,238 +378,205 @@ struct CredentialProfileEditorSheet: View { return kind.source(value: value, field: field, reuseSeconds: nil, vaultAccess: vaultAccess) } - // MARK: - Secure fields - - @ViewBuilder - private var secureFieldsSection: some View { - Section { - Picker(String(localized: "For"), selection: $secureFieldType) { - ForEach(DatabaseType.allKnownTypes, id: \.self) { type in - Text(type.rawValue).tag(type) - } - } - .onChange(of: secureFieldType) { _ in reloadSecureFields() } - if secureFields.isEmpty { - Text("This database type signs in with the username and password above.") - .font(.caption) - .foregroundStyle(.secondary) - } else { - ForEach(secureFields, id: \.id) { field in - ConnectionFieldRow(field: field, value: secureFieldBinding(for: field)) - } - } - } header: { - Text(String(localized: "Additional Secrets")) - } footer: { - Text("A connection reads only the secrets its own database type declares, so one profile can carry several engines' keys.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private func reloadSecureFields() { - secureFields = PluginManager.shared.additionalConnectionFields(for: secureFieldType).filter(\.isSecure) - } - - private func secureFieldBinding(for field: ConnectionField) -> Binding { - Binding( - get: { secureFieldValues[field.id] ?? "" }, - set: { secureFieldValues[field.id] = $0 } - ) - } - - // MARK: - Bottom bar - private var bottomBar: some View { - HStack { + DialogFooter { if isStored { - Button(role: .destructive) { - dependentCount = storage.connectionsUsing(existingProfile?.id ?? UUID()).count - showingDeleteConfirmation = true - } label: { - Text("Delete Profile") + Button(String(localized: "Delete Profile"), role: .destructive) { + pendingDeletion = PendingProfileDeletion.make(kind: .credential, id: profileId, name: baseline.trimmedName) } + .disabled(usageUnknown) .accessibilityIdentifier("credential-profile-delete") - .alert(String(localized: "Delete Credential Profile?"), isPresented: $showingDeleteConfirmation) { - Button(String(localized: "Delete"), role: .destructive) { deleteProfile() } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - if dependentCount > 0 { - Text("^[\(dependentCount) connection](inflect: true) use this profile. They keep these credentials as their own.") - } else { - Text("This profile will be permanently deleted.") - } - } + .profileDeletionAlert($pendingDeletion) { _ in deleteProfile() } } - - if let saveError { - NoticeLabel(saveError, severity: .error) - .font(.caption) - .lineLimit(2) - } - - Spacer() - + statusLabel + } actions: { Button(String(localized: "Cancel")) { dismiss() } .keyboardShortcut(.cancelAction) .accessibilityIdentifier("credential-profile-cancel") Button(isStored ? String(localized: "Save") : String(localized: "Create")) { saveProfile() } .keyboardShortcut(.defaultAction) - .disabled(!isValid) + .disabled(!draft.validationIssues.isEmpty) .accessibilityIdentifier("credential-profile-save") } .padding() } - // MARK: - Actions + @ViewBuilder private var statusLabel: some View { + if let saveError { + NoticeLabel(saveError, severity: .error) + .lineLimit(2) + } else if hasLoaded, draft != baseline, let issue = draft.validationIssues.first { + NoticeLabel(issue) + .lineLimit(2) + } + } private func load() { + guard !hasLoaded else { return } + hasLoaded = true + let profiles = storage.loadProfiles() - otherProfileNames = profiles.filter { $0.id != existingProfile?.id }.map { $0.name } - isStored = existingProfile.map { candidate in profiles.contains { $0.id == candidate.id } } ?? false - if let initialDatabaseType { - secureFieldType = initialDatabaseType + let stored = existingProfile.flatMap { existing in profiles.first { $0.id == existing.id } } + isStored = stored != nil + usageUnknown = ConnectionStorage.shared.isLibraryUnreadable + if let address = ProcessInfo.processInfo.environment["VAULT_ADDR"] { + vaultAddressPrompt = address } - reloadSecureFields() - guard let profile = existingProfile else { return } - name = profile.name - username = profile.username - for fieldId in profile.secureFieldIds { - if let value = storage.loadSecureField(fieldId: fieldId, for: profile.id) { - secureFieldValues[fieldId] = value - } else { - secretsWereReadable = false - } + var loaded = CredentialProfileDraft() + loaded.takenNames = profiles.filter { $0.id != profileId }.map(\.name) + let record = stored ?? existingProfile + if let record { + loaded.name = record.name + loaded.username = record.username + loaded.apply(record.passwordMode) } + storedPasswordMode = stored?.passwordMode - switch profile.passwordMode { - case .stored: - passwordKind = .stored - if let stored = storage.loadPassword(for: profile.id) { - password = stored - } else if let initialPassword { - password = initialPassword - } else if isStored { - secretsWereReadable = false + // A profile not saved yet has no Keychain items; its secrets come from the connection that promoted it. + if let stored { + if stored.passwordMode.usesStoredSecret { + passwordRead = storage.readPassword(for: stored.id) + loaded.password = passwordRead.value ?? "" } - passwordWasPrefilled = !password.isEmpty - case .prompt: - passwordKind = .prompt - case .pgpass: - passwordKind = .pgpass - case .source(let source): - passwordKind = .source - (sourceKind, sourceValue, sourceField) = PasswordSourceKind.decompose(source) - if case .command(_, let reuseSeconds) = source { - commandReuseSeconds = reuseSeconds - } - if let role = source.vaultDatabaseRole { - vaultAccess = VaultAccessDraft(role) + for fieldId in stored.secureFieldIds { + let read = storage.readSecureField(fieldId: fieldId, for: stored.id) + fieldReads[fieldId] = read + if let value = read.value { + loaded.secureFieldValues[fieldId] = value + } } + } else { + loaded.password = initialPassword ?? "" + } + passwordWasPrefilled = !loaded.password.isEmpty + + loadSecureFieldTypes(holding: Set(record?.secureFieldIds ?? [])) + draft = loaded + baseline = loaded + } + + private func loadSecureFieldTypes(holding heldFieldIds: Set) { + var types: [DatabaseType] = [] + var fieldsByType: [DatabaseType: [ConnectionField]] = [:] + for type in DatabaseType.allKnownTypes where fieldsByType[type] == nil { + let fields = PluginManager.shared.additionalConnectionFields(for: type).filter(\.isSecure) + guard !fields.isEmpty else { continue } + types.append(type) + fieldsByType[type] = fields + } + secureFieldTypes = types + secureFieldsByType = fieldsByType + if let initialDatabaseType, fieldsByType[initialDatabaseType] != nil { + secureFieldType = initialDatabaseType + } else if let held = types.first(where: { type in + fieldsByType[type, default: []].contains { heldFieldIds.contains($0.id) } + }) { + secureFieldType = held + } else if let first = types.first { + secureFieldType = first } } private func saveProfile() { - let liveFields = secureFieldValues.filter { !$0.value.isEmpty } - let profile = CredentialProfile( - id: profileId, - name: trimmedName, - username: username.trimmingCharacters(in: .whitespaces), - passwordMode: buildPasswordMode(), - secureFieldIds: secretsWereReadable - ? liveFields.keys.sorted() - : Array(Set(existingProfile?.secureFieldIds ?? []).union(liveFields.keys)).sorted(), - sortOrder: existingProfile?.sortOrder ?? 0 + // Read, then modify: the stored record may have changed since this sheet opened. + let stored = isStored ? storage.profile(for: profileId) : nil + var record = stored ?? CredentialProfile(id: profileId, name: draft.trimmedName) + record.name = draft.trimmedName + record.username = draft.trimmedUsername + record.passwordMode = draft.passwordMode + + let passwordChange = ProfileSecretChange.decide( + applies: draft.passwordKind == .stored, + value: draft.password, + read: passwordRead ) + let heldFieldIds = Set(record.secureFieldIds) + var fieldChanges: [String: ProfileSecretChange] = [:] + for fieldId in heldFieldIds.union(draft.secureFieldValues.keys) { + // A field that arrived after this sheet read the Keychain was never shown, so it is kept unless retyped. + let read = fieldReads[fieldId] ?? (heldFieldIds.contains(fieldId) ? .unreadable : .absent) + fieldChanges[fieldId] = .decide(applies: true, value: draft.secureFieldValues[fieldId] ?? "", read: read) + } + record.secureFieldIds = fieldChanges + .filter { fieldId, change in + if case .write = change { return true } + return change == .keep && heldFieldIds.contains(fieldId) + } + .map(\.key) + .sorted() - let persisted = isStored ? storage.updateProfile(profile) : storage.addProfile(profile) - /// The keychain writes below are keyed by the profile id, so running them for a profile - /// that never reached disk would leave secrets nothing can name. + let persisted = isStored ? storage.updateProfile(record) : storage.addProfile(record) + // Keychain items are keyed by the profile id, so writing them for a profile that never reached disk strands them. guard persisted else { saveError = String(localized: "Could not save the profile. Check disk space and permissions, then try again.") return } - saveError = nil + isStored = true + storedPasswordMode = record.passwordMode - if case .stored = profile.passwordMode, !password.isEmpty { - guard storage.savePassword(password, for: profileId) else { - saveError = String(localized: "Could not save the password to the Keychain. Nothing was changed.") - return - } - } else if secretsWereReadable { + var secretsSaved = apply(passwordChange, write: { storage.savePassword($0, for: profileId) }, delete: { storage.deletePassword(for: profileId) - } - - /// Only what was read back is eligible for deletion. A field whose value could not be read - /// is still there and still in use. - if secretsWereReadable { - let removed = Set(existingProfile?.secureFieldIds ?? []).subtracting(liveFields.keys) - for fieldId in removed { + }) + passwordRead = Self.read(after: passwordChange, before: passwordRead, saved: secretsSaved) + for (fieldId, change) in fieldChanges.sorted(by: { $0.key < $1.key }) { + let saved = apply(change, write: { storage.saveSecureField($0, fieldId: fieldId, for: profileId) }, delete: { storage.deleteSecureField(fieldId: fieldId, for: profileId) - } + }) + fieldReads[fieldId] = Self.read(after: change, before: fieldReads[fieldId] ?? .absent, saved: saved) + secretsSaved = secretsSaved && saved } - for (fieldId, value) in liveFields where !storage.saveSecureField(value, fieldId: fieldId, for: profileId) { - saveError = String(localized: "Could not save a secret to the Keychain. Nothing was changed.") + guard secretsSaved else { + saveError = String(localized: "The profile was saved, but its password couldn't be saved to the Keychain.") return } - - onSave?(profile) + saveError = nil + onSave?(record) dismiss() } - private func buildPasswordMode() -> CredentialPasswordMode { - switch passwordKind { - case .stored: .stored - case .prompt: .prompt - case .pgpass: .pgpass - case .source: - .source(sourceKind.source( - value: sourceValue, - field: sourceField, - reuseSeconds: commandReuseSeconds, - vaultAccess: vaultAccess - )) + private func apply(_ change: ProfileSecretChange, write: (String) -> Bool, delete: () -> Void) -> Bool { + switch change { + case .write(let value): + return write(value) + case .keep: + return true + case .delete: + delete() + return true } } - private static let reusePresets = [300, 900, 3_600, 28_800] - - private static func reuseChoices(including current: Int?) -> [Int] { - guard let current, !reusePresets.contains(current) else { return reusePresets } - return (reusePresets + [current]).sorted() - } - - private static func reuseLabel(_ seconds: Int) -> String { - Duration.seconds(seconds).formatted(.units(allowed: [.hours, .minutes, .seconds], width: .wide)) + private static func read(after change: ProfileSecretChange, before: ProfileSecretRead, saved: Bool) -> ProfileSecretRead { + switch change { + case .write(let value): saved ? .found(value) : before + case .keep: before + case .delete: .absent + } } private func deleteProfile() { - guard let profile = existingProfile else { return } - guard storage.deleteProfile(profile) else { - saveError = String(localized: "Could not delete the profile. Check disk space and permissions, then try again.") + guard let stored = storage.profile(for: profileId) else { + guard storage.lastLoadFailed else { + onDelete?() + dismiss() + return + } + saveError = ConnectionCountCopy.deleteFailedMessage + return + } + guard storage.deleteProfile(stored) else { + saveError = ConnectionCountCopy.deleteFailedMessage return } onDelete?() dismiss() } -} -// MARK: - Kinds - -extension CredentialProfileEditorSheet { - enum PasswordKind: String, CaseIterable, Identifiable { - case stored, prompt, pgpass, source - - var id: String { rawValue } + private static let reusePresets = [300, 900, 3_600, 28_800] - var displayName: String { - switch self { - case .stored: String(localized: "Saved in the Keychain") - case .prompt: String(localized: "Ask every time") - case .pgpass: String(localized: "~/.pgpass") - case .source: String(localized: "Read from elsewhere") - } - } + private static func reuseChoices(including current: Int?) -> [Int] { + guard let current, !reusePresets.contains(current) else { return reusePresets } + return (reusePresets + [current]).sorted() } } diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift new file mode 100644 index 0000000000..f26c1a2524 --- /dev/null +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsModel.swift @@ -0,0 +1,224 @@ +import Combine +import Foundation +import os + +enum ProfileNames { + // Every picker offers a profile by name alone, so a copy never reuses one. + static func available(basedOn name: String, taken: [String]) -> String { + let base = name.trimmingCharacters(in: .whitespacesAndNewlines) + let first = String(format: String(localized: "%@ (Copy)"), base) + guard isTaken(first, in: taken) else { return first } + for index in 2...(taken.count + 2) { + let candidate = String(format: String(localized: "%1$@ (Copy %2$lld)"), base, Int64(index)) + if !isTaken(candidate, in: taken) { return candidate } + } + return first + } + + static func matches(_ lhs: String, _ rhs: String) -> Bool { + lhs.trimmingCharacters(in: .whitespacesAndNewlines) + .compare( + rhs.trimmingCharacters(in: .whitespacesAndNewlines), + options: [.caseInsensitive, .diacriticInsensitive] + ) == .orderedSame + } + + private static func isTaken(_ name: String, in taken: [String]) -> Bool { + taken.contains { matches($0, name) } + } +} + +@MainActor +final class ProfilesSettingsModel: ObservableObject { + private static let logger = Logger(subsystem: "com.TablePro", category: "ProfilesSettingsModel") + + @Published private(set) var credentialProfiles: [CredentialProfile] = [] + @Published private(set) var sshProfiles: [SSHProfile] = [] + @Published private(set) var usage: [UUID: Int] = [:] + @Published private(set) var credentialLoadFailed = false + @Published private(set) var sshLoadFailed = false + @Published private(set) var unreadableProfileCount = 0 + @Published private(set) var usageUnknown = false + @Published private(set) var someConnectionsUnreadable = false + @Published private(set) var isLoaded = false + + private let credentialStorage: CredentialProfileStorage + private let sshStorage: SSHProfileStorage + private let connectionStorage: ConnectionStorage + private var cancellables: Set = [] + + init( + credentialStorage: CredentialProfileStorage = .shared, + sshStorage: SSHProfileStorage = .shared, + connectionStorage: ConnectionStorage = .shared, + appEvents: AppEvents = .shared, + notificationCenter: NotificationCenter = .default + ) { + self.credentialStorage = credentialStorage + self.sshStorage = sshStorage + self.connectionStorage = connectionStorage + + // Profiles also change from a connection window and from sync while this pane is on screen. + notificationCenter.publisher(for: .credentialProfilesDidChange) + .merge(with: notificationCenter.publisher(for: .sshProfilesDidChange)) + .map { _ in () } + .debounce(for: .milliseconds(100), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.reloadProfiles() } + .store(in: &cancellables) + appEvents.connectionUpdated + .map { _ in () } + .debounce(for: .milliseconds(100), scheduler: DispatchQueue.main) + .sink { [weak self] in self?.recountUsage() } + .store(in: &cancellables) + } + + func refresh() { + reloadProfiles() + recountUsage() + if !isLoaded { isLoaded = true } + } + + func reloadProfiles() { + let credentials = credentialStorage.loadProfiles() + let credentialsFailed = credentialStorage.lastLoadFailed + let unreadable = credentialsFailed ? 0 : credentialStorage.unreadableProfileIds.count + let ssh = sshStorage.loadProfiles() + let sshFailed = sshStorage.lastLoadFailed + + // Refresh in place: an unchanged value never publishes, so the list does not redraw on every visit. + if credentialProfiles != credentials { credentialProfiles = credentials } + if credentialLoadFailed != credentialsFailed { credentialLoadFailed = credentialsFailed } + if unreadableProfileCount != unreadable { unreadableProfileCount = unreadable } + if sshProfiles != ssh { sshProfiles = ssh } + if sshLoadFailed != sshFailed { sshLoadFailed = sshFailed } + } + + func recountUsage() { + let connections = connectionStorage.loadConnections() + let unknown = connectionStorage.lastLoadFailed + var counts: [UUID: Int] = [:] + for connection in connections { + if let id = connection.credentialMode.profileId { + counts[id, default: 0] += 1 + } + if case .profile(let id, _) = connection.sshTunnelMode { + counts[id, default: 0] += 1 + } + } + let unreadable = unknown ? false : !connectionStorage.unreadableConnectionIds.isEmpty + + if usage != counts { usage = counts } + if usageUnknown != unknown { usageUnknown = unknown } + if someConnectionsUnreadable != unreadable { someConnectionsUnreadable = unreadable } + } + + func usageCount(for profileId: UUID) -> Int? { + usageUnknown ? nil : usage[profileId, default: 0] + } + + func pendingDeletion(of kind: ProfileKind, id: UUID, name: String) -> PendingProfileDeletion? { + guard !usageUnknown else { return nil } + return PendingProfileDeletion.make(kind: kind, id: id, name: name, connectionStorage: connectionStorage) + } + + func delete(_ pending: PendingProfileDeletion) -> Bool { + defer { refresh() } + switch pending.kind { + case .credential: + guard let stored = credentialStorage.profile(for: pending.id) else { return !credentialStorage.lastLoadFailed } + return credentialStorage.deleteProfile(stored) + case .ssh: + guard let stored = sshStorage.profile(for: pending.id) else { return !sshStorage.lastLoadFailed } + return sshStorage.deleteProfile(stored) + } + } + + func duplicateCredentialProfile(id: UUID) -> Bool { + defer { refresh() } + let profiles = credentialStorage.loadProfiles() + guard !credentialStorage.lastLoadFailed, let source = profiles.first(where: { $0.id == id }) else { return false } + + // Every secret is read before anything is written, so a locked Keychain leaves no half-made copy. + var password: String? + if source.passwordMode.usesStoredSecret { + switch credentialStorage.readPassword(for: source.id) { + case .found(let value): password = value + case .absent: break + case .unreadable: return false + } + } + var fields: [String: String] = [:] + for fieldId in source.secureFieldIds { + switch credentialStorage.readSecureField(fieldId: fieldId, for: source.id) { + case .found(let value): fields[fieldId] = value + case .absent: break + case .unreadable: return false + } + } + + let copy = CredentialProfile( + name: ProfileNames.available(basedOn: source.name, taken: profiles.map(\.name)), + username: source.username, + passwordMode: source.passwordMode, + secureFieldIds: source.secureFieldIds + ) + guard credentialStorage.addProfile(copy) else { return false } + + var written = true + if let password { + written = credentialStorage.savePassword(password, for: copy.id) + } + for (fieldId, value) in fields.sorted(by: { $0.key < $1.key }) where written { + written = credentialStorage.saveSecureField(value, fieldId: fieldId, for: copy.id) + } + guard written else { + Self.logger.error("Removing the copy of credential profile \(id.uuidString, privacy: .public): a secret could not be copied") + credentialStorage.deleteProfile(copy) + return false + } + return true + } + + func duplicateSSHProfile(id: UUID) -> Bool { + defer { refresh() } + let profiles = sshStorage.loadProfiles() + guard !sshStorage.lastLoadFailed, let source = profiles.first(where: { $0.id == id }) else { return false } + + var secrets: [SSHSecret: String] = [:] + for secret in SSHSecret.allCases { + switch sshStorage.readSecret(secret, for: source.id) { + case .found(let value): secrets[secret] = value + case .absent: break + case .unreadable: return false + } + } + + let copy = SSHProfile( + name: ProfileNames.available(basedOn: source.name, taken: profiles.map(\.name)), + host: source.host, + port: source.port, + username: source.username, + authMethod: source.authMethod, + privateKeyPath: source.privateKeyPath, + agentSocketPath: source.agentSocketPath, + jumpHosts: source.jumpHosts, + totpMode: source.totpMode, + totpAlgorithm: source.totpAlgorithm, + totpDigits: source.totpDigits, + totpPeriod: source.totpPeriod + ) + guard sshStorage.addProfile(copy) else { return false } + + var written = true + for secret in SSHSecret.allCases where written { + guard let value = secrets[secret] else { continue } + written = sshStorage.saveSecret(value, secret, for: copy.id) + } + guard written else { + Self.logger.error("Removing the copy of SSH profile \(id.uuidString, privacy: .public): a secret could not be copied") + sshStorage.deleteProfile(copy) + return false + } + return true + } +} diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift index 4fbe361abe..906820a6ad 100644 --- a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift @@ -1,25 +1,27 @@ -// -// ProfilesSettingsView.swift -// TablePro -// - import SwiftUI -/// The profiles a connection can point at, in one place. -/// -/// Both kinds used to be reachable only from inside a connection form's Network tab, through three -/// small buttons, with no list of them anywhere and no way to see which connections used one. -struct ProfilesSettingsView: View { - @State private var credentialProfiles: [CredentialProfile] = [] - @State private var sshProfiles: [SSHProfile] = [] +enum ProfileEditorRoute: Identifiable { + case newCredential + case credential(CredentialProfile) + case newSSH + case ssh(SSHProfile) + + var id: String { + switch self { + case .newCredential: "new-credential" + case .credential(let profile): "credential-\(profile.id.uuidString)" + case .newSSH: "new-ssh" + case .ssh(let profile): "ssh-\(profile.id.uuidString)" + } + } +} - @State private var editingCredentialProfile: CredentialProfile? - @State private var isAddingCredentialProfile = false - @State private var editingSSHProfile: SSHProfile? - @State private var isAddingSSHProfile = false +struct ProfilesSettingsView: View { + @ObservedObject var model: ProfilesSettingsModel + let presentError: @MainActor (_ title: String, _ message: String) -> Void - @State private var connectionCounts: [UUID: Int] = [:] - @State private var hasLoaded = false + @State private var editor: ProfileEditorRoute? + @State private var pendingDeletion: PendingProfileDeletion? var body: some View { Form { @@ -27,207 +29,155 @@ struct ProfilesSettingsView: View { sshSection } .formStyle(.grouped) - // Load once, not on every re-add: reload() synchronously decodes the whole connections file - // on the main actor. The change notifications below keep the list fresh after that. - .onAppear { if !hasLoaded { hasLoaded = true; reload() } } - /// The Settings window is kept alive between openings, so a profile created from a - /// connection window has to reach this list while it is already on screen. - .onReceive(NotificationCenter.default.publisher(for: .credentialProfilesDidChange)) { _ in reload() } - .onReceive(NotificationCenter.default.publisher(for: .sshProfilesDidChange)) { _ in reload() } - .sheet(item: $editingCredentialProfile) { profile in - CredentialProfileEditorSheet( - existingProfile: profile, - onSave: { _ in reload() }, - onDelete: { reload() } - ) - } - .sheet(isPresented: $isAddingCredentialProfile) { - CredentialProfileEditorSheet(existingProfile: nil, onSave: { _ in reload() }) - } - .sheet(item: $editingSSHProfile) { profile in - SSHProfileEditorView( - existingProfile: profile, - onSave: { _ in reload() }, - onDelete: { reload() } - ) + .sheet(item: $editor) { route in + switch route { + case .newCredential: + CredentialProfileEditorSheet(existingProfile: nil) + case .credential(let profile): + CredentialProfileEditorSheet(existingProfile: profile) + case .newSSH: + SSHProfileEditorView(existingProfile: nil) + case .ssh(let profile): + SSHProfileEditorView(existingProfile: profile) + } } - .sheet(isPresented: $isAddingSSHProfile) { - SSHProfileEditorView(existingProfile: nil, onSave: { _ in reload() }) + .profileDeletionAlert($pendingDeletion) { pending in + let deleted = model.delete(pending) + guard !deleted else { return } + report(title: ConnectionCountCopy.deleteFailedTitle, message: ConnectionCountCopy.deleteFailedMessage) } } - // MARK: - Credential profiles - private var credentialSection: some View { Section { - if credentialProfiles.isEmpty { - emptyRow(String(localized: "No credential profiles yet.")) + if model.credentialLoadFailed { + NoticeLabel( + String(localized: "Credential profiles couldn't be read, so none are shown. TablePro won't save over them."), + severity: .error + ) } else { - ForEach(credentialProfiles) { profile in - row( - title: profile.name, - detail: profile.summary, - symbol: "key.fill", - usedBy: connectionCounts[profile.id] ?? 0, - identifier: "credential-profile-row-\(profile.id.uuidString)" - ) { - editingCredentialProfile = profile + if model.unreadableProfileCount > 0 { + NoticeLabel(ConnectionCountCopy.unreadableProfiles(model.unreadableProfileCount)) + } + if model.credentialProfiles.isEmpty { + if model.isLoaded { + Text("No credential profiles") + .foregroundStyle(.secondary) + .accessibilityIdentifier("credential-profiles-empty") } - .contextMenu { - Button(String(localized: "Edit…")) { editingCredentialProfile = profile } - Button(String(localized: "Duplicate")) { duplicate(profile) } + } else { + ForEach(model.credentialProfiles) { profile in + credentialRow(profile) } } } - Button { - isAddingCredentialProfile = true - } label: { - Label(String(localized: "Add Credential Profile…"), systemImage: "plus") - } - .accessibilityIdentifier("add-credential-profile") + SettingsHelpRow( + "Connections that use a profile sign in with its username and password. Edit it once to update them all." + ) } header: { - Text(String(localized: "Credential Profiles")) + Text("Credential Profiles") } footer: { - Text("One username and password, shared by any number of connections. Change it here and every connection using it signs in with the new one.") - .font(.caption) - .foregroundStyle(.secondary) + SettingsSectionActions { + Button(String(localized: "Add Credential Profile…")) { + editor = .newCredential + } + .disabled(model.credentialLoadFailed) + .accessibilityIdentifier("add-credential-profile") + } } } - // MARK: - SSH profiles - private var sshSection: some View { Section { - if sshProfiles.isEmpty { - emptyRow(String(localized: "No SSH servers yet.")) + if model.sshLoadFailed { + NoticeLabel( + String(localized: "SSH profiles couldn't be read, so none are shown. TablePro won't save over them."), + severity: .error + ) + } else if model.sshProfiles.isEmpty { + if model.isLoaded { + Text("No SSH profiles") + .foregroundStyle(.secondary) + .accessibilityIdentifier("ssh-profiles-empty") + } } else { - ForEach(sshProfiles) { profile in - row( - title: profile.name, - detail: sshDetail(profile), - symbol: "network", - usedBy: connectionCounts[profile.id] ?? 0, - identifier: "ssh-profile-row-\(profile.id.uuidString)" - ) { - editingSSHProfile = profile - } - .contextMenu { - Button(String(localized: "Edit…")) { editingSSHProfile = profile } - } + ForEach(model.sshProfiles) { profile in + sshRow(profile) } } - Button { - isAddingSSHProfile = true - } label: { - Label(String(localized: "Add SSH Server…"), systemImage: "plus") - } - .accessibilityIdentifier("add-ssh-profile") + SettingsHelpRow( + "Connections that use an SSH profile tunnel through its server. Changes reach every connection that uses it." + ) } header: { - Text(String(localized: "SSH Servers")) + Text("SSH Profiles") } footer: { - Text("One bastion, many connections. Editing the server or its credentials reaches every connection tunnelling through it.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private func sshDetail(_ profile: SSHProfile) -> String { - let user = profile.username.trimmingCharacters(in: .whitespaces) - guard !user.isEmpty else { return profile.host } - return "\(user)@\(profile.host)" - } - - // MARK: - Rows - - private func row( - title: String, - detail: String, - symbol: String, - usedBy: Int, - identifier: String, - action: @escaping () -> Void - ) -> some View { - Button(action: action) { - HStack(spacing: 10) { - Image(systemName: symbol) - .foregroundStyle(.secondary) - .frame(width: 18) - VStack(alignment: .leading, spacing: 2) { - Text(title) - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) + SettingsSectionActions { + Button(String(localized: "Add SSH Profile…")) { + editor = .newSSH } - Spacer(minLength: 8) - Text(usedByLabel(usedBy)) - .font(.caption) - .foregroundStyle(.secondary) + .disabled(model.sshLoadFailed) + .accessibilityIdentifier("add-ssh-profile") } - .contentShape(Rectangle()) } - .buttonStyle(.plain) - .accessibilityIdentifier(identifier) - .accessibilityLabel("\(title), \(detail), \(usedByLabel(usedBy))") } - private func usedByLabel(_ count: Int) -> String { - guard count > 0 else { return String(localized: "Unused") } - return String(format: String(localized: "Used by %lld"), Int64(count)) + private func credentialRow(_ profile: CredentialProfile) -> some View { + SettingsRecordRow( + title: profile.name, + subtitle: profile.summary, + value: usageValue(for: profile.id) + ) + .infoButton( + onEdit: { editor = .credential(profile) }, + onDuplicate: { duplicateCredential(profile) }, + removal: removal(of: .credential, id: profile.id, name: profile.name), + identifier: "credential-profile-edit-\(profile.id.uuidString)" + ) + .accessibilityIdentifier("credential-profile-row-\(profile.id.uuidString)") } - private func emptyRow(_ text: String) -> some View { - Text(text) - .foregroundStyle(.secondary) + private func sshRow(_ profile: SSHProfile) -> some View { + SettingsRecordRow( + title: profile.name, + subtitle: profile.address, + value: usageValue(for: profile.id) + ) + .infoButton( + onEdit: { editor = .ssh(profile) }, + onDuplicate: { duplicateSSH(profile) }, + removal: removal(of: .ssh, id: profile.id, name: profile.name), + identifier: "ssh-profile-edit-\(profile.id.uuidString)" + ) + .accessibilityIdentifier("ssh-profile-row-\(profile.id.uuidString)") } - // MARK: - Data - - private func reload() { - credentialProfiles = CredentialProfileStorage.shared.loadProfiles() - sshProfiles = SSHProfileStorage.shared.loadProfiles() + private func usageValue(for profileId: UUID) -> String? { + model.usageCount(for: profileId).map(ConnectionCountCopy.usage) + } - var counts: [UUID: Int] = [:] - for connection in ConnectionStorage.shared.loadConnections() { - if let id = connection.credentialMode.profileId { - counts[id, default: 0] += 1 - } - if case .profile(let id, _) = connection.sshTunnelMode { - counts[id, default: 0] += 1 - } + // Unknown usage means unknown consequences, so Delete is not offered until the connections read again. + private func removal(of kind: ProfileKind, id: UUID, name: String) -> SettingsRecordRemoval? { + guard !model.usageUnknown else { return nil } + return .delete { + pendingDeletion = model.pendingDeletion(of: kind, id: id, name: name) } - connectionCounts = counts } - /// The editor refuses two profiles with one name, so duplicating twice must not create them - /// either: every picker offers a profile by its name alone. - private func availableName(basedOn name: String) -> String { - let taken = Set(credentialProfiles.map { $0.name.lowercased() }) - let first = String(format: String(localized: "%@ (Copy)"), name) - guard taken.contains(first.lowercased()) else { return first } - for index in 2...99 { - let candidate = String(format: String(localized: "%1$@ (Copy %2$lld)"), name, Int64(index)) - if !taken.contains(candidate.lowercased()) { return candidate } - } - return first + private func duplicateCredential(_ profile: CredentialProfile) { + guard !model.duplicateCredentialProfile(id: profile.id) else { return } + report(title: ConnectionCountCopy.duplicateFailedTitle, message: ConnectionCountCopy.duplicateFailedMessage) } - private func duplicate(_ profile: CredentialProfile) { - let copy = CredentialProfile( - name: availableName(basedOn: profile.name), - username: profile.username, - passwordMode: profile.passwordMode, - secureFieldIds: profile.secureFieldIds - ) - guard CredentialProfileStorage.shared.addProfile(copy) else { return } - if case .stored = profile.passwordMode, - let password = CredentialProfileStorage.shared.loadPassword(for: profile.id) { - CredentialProfileStorage.shared.savePassword(password, for: copy.id) - } - for fieldId in profile.secureFieldIds { - if let value = CredentialProfileStorage.shared.loadSecureField(fieldId: fieldId, for: profile.id) { - CredentialProfileStorage.shared.saveSecureField(value, fieldId: fieldId, for: copy.id) - } + private func duplicateSSH(_ profile: SSHProfile) { + guard !model.duplicateSSHProfile(id: profile.id) else { return } + report(title: ConnectionCountCopy.duplicateFailedTitle, message: ConnectionCountCopy.duplicateFailedMessage) + } + + // A turn later, so the error sheet does not race the confirmation alert that is still closing. + private func report(title: String, message: String) { + let presentError = presentError + DispatchQueue.main.async { + presentError(title, message) } - reload() } } diff --git a/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift b/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift new file mode 100644 index 0000000000..5f4c37266e --- /dev/null +++ b/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift @@ -0,0 +1,312 @@ +import Foundation +import TableProSSHConfig +import TableProSyncTransport +import Testing + +@testable import TablePro + +@MainActor +struct ProfileStorageSafetyTests { + private let pool = EphemeralDefaultsPool() + private let directory: URL + private let keychain = InMemoryKeychain() + private let tracker: SyncChangeTracker + private let integrity: ConnectionStoreIntegrity + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + tracker = SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: try pool.make().defaults)) + integrity = ConnectionStoreIntegrity(keySource: StoredIntegrityKeySource(store: keychain)) + } + + private func makeConnections(unreadable: Bool = false, keychain: (any KeychainStoring)? = nil) throws -> ConnectionStorage { + let fileURL = directory.appendingPathComponent("connections.json") + if unreadable { + try Data("not json".utf8).write(to: fileURL) + } + return ConnectionStorage( + fileURL: fileURL, + userDefaults: try pool.make().defaults, + syncTracker: tracker, + keychain: keychain ?? self.keychain, + integrity: integrity + ) + } + + private func makeCredentialStorage( + connections: ConnectionStorage, + keychain: (any KeychainStoring)? = nil + ) -> CredentialProfileStorage { + CredentialProfileStorage( + fileURL: directory.appendingPathComponent("credentialProfiles.json"), + keychain: keychain ?? self.keychain, + syncTracker: tracker, + connectionStorage: connections, + integrity: integrity + ) + } + + private func makeSSHStorage( + connections: ConnectionStorage, + keychain: (any KeychainStoring)? = nil + ) throws -> SSHProfileStorage { + SSHProfileStorage( + userDefaults: try pool.make().defaults, + keychain: keychain ?? self.keychain, + syncTracker: tracker, + connectionStorage: connections + ) + } + + private func makeModel( + credentials: CredentialProfileStorage, + ssh: SSHProfileStorage, + connections: ConnectionStorage + ) -> ProfilesSettingsModel { + ProfilesSettingsModel( + credentialStorage: credentials, + sshStorage: ssh, + connectionStorage: connections, + appEvents: AppEvents(), + notificationCenter: NotificationCenter() + ) + } + + private func makeSSHProfile(name: String = "Bastion", host: String = "bastion.example.com") -> SSHProfile { + SSHProfile(name: name, host: host, port: 22, username: "deploy", authMethod: .password) + } + + @Test( + "A secret is written only when it applies and has a value, and an unreadable one is never deleted", + arguments: [ + (true, "new", ProfileSecretRead.absent, ProfileSecretChange.write("new")), + (true, "new", .found("old"), .write("new")), + (true, "same", .found("same"), .keep), + (true, "new", .unreadable, .write("new")), + (true, "", .found("old"), .delete), + (true, "", .unreadable, .keep), + (true, "", .absent, .delete), + (false, "typed", .found("old"), .delete), + (false, "", .unreadable, .keep), + (false, "", .absent, .delete), + ] + ) + func secretDecision(applies: Bool, value: String, read: ProfileSecretRead, expected: ProfileSecretChange) { + #expect(ProfileSecretChange.decide(applies: applies, value: value, read: read) == expected) + } + + @Test( + "A Keychain read sorts into found, absent and unreadable", + arguments: [ + (KeychainStringResult.found("hunter2"), ProfileSecretRead.found("hunter2")), + (.found(""), .absent), + (.notFound, .absent), + (.locked, .unreadable), + (.userCancelled, .unreadable), + (.authFailed, .unreadable), + (.error(-25_300), .unreadable), + ] + ) + func secretRead(result: KeychainStringResult, expected: ProfileSecretRead) { + #expect(ProfileSecretRead(result) == expected) + } + + @Test("A credential profile is not deleted while the connections that may use it can't be read") + func credentialDeleteRefusesUnreadableLibrary() throws { + let connections = try makeConnections(unreadable: true) + let storage = makeCredentialStorage(connections: connections) + let profile = CredentialProfile(name: "Prod reader", username: "app_reader") + #expect(storage.addProfile(profile)) + + #expect(!storage.unlinkConnections(from: profile)) + #expect(!storage.deleteProfile(profile)) + #expect(storage.profile(for: profile.id) != nil) + } + + @Test("An SSH profile is not deleted while the connections that may use it can't be read") + func sshDeleteRefusesUnreadableLibrary() throws { + let connections = try makeConnections(unreadable: true) + let storage = try makeSSHStorage(connections: connections) + let profile = makeSSHProfile() + #expect(storage.addProfile(profile)) + + #expect(!storage.unlinkConnections(fromProfile: profile)) + #expect(!storage.deleteProfile(profile)) + #expect(storage.profile(for: profile.id) != nil) + } + + @Test("Adding a credential profile under an id already taken is refused") + func credentialAddRefusesDuplicateId() throws { + let storage = makeCredentialStorage(connections: try makeConnections()) + let profile = CredentialProfile(name: "Prod reader") + #expect(storage.addProfile(profile)) + + var renamed = profile + renamed.name = "Replacement" + #expect(!storage.addProfile(renamed)) + #expect(storage.loadProfiles().map(\.name) == ["Prod reader"]) + } + + @Test("Adding an SSH profile under an id already taken is refused") + func sshAddRefusesDuplicateId() throws { + let storage = try makeSSHStorage(connections: try makeConnections()) + let profile = makeSSHProfile() + #expect(storage.addProfile(profile)) + + var moved = profile + moved.host = "elsewhere.example.com" + #expect(!storage.addProfile(moved)) + #expect(storage.loadProfiles().map(\.host) == ["bastion.example.com"]) + } + + @Test("Deleting with an out-of-date copy hands linked connections the stored SSH configuration") + func sshDeleteUsesTheStoredRecord() throws { + let connections = try makeConnections() + let storage = try makeSSHStorage(connections: connections) + var profile = makeSSHProfile(host: "old.example.com") + #expect(storage.addProfile(profile)) + let stale = profile + var connection = TestFixtures.makeConnection() + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + connection.sshConfig = profile.toSSHConfiguration() + connection.sshProfileId = profile.id + connections.addConnection(connection) + profile.host = "new.example.com" + #expect(storage.updateProfile(profile)) + + #expect(storage.deleteProfile(stale)) + + let converted = connections.loadConnection(id: connection.id) + #expect(converted?.sshProfileId == nil) + #expect(converted?.resolvedSSHConfig.host == "new.example.com") + } + + @Test("Deleting with an out-of-date copy still removes secrets the stored record gained") + func credentialDeleteUsesTheStoredRecord() throws { + let storage = makeCredentialStorage(connections: try makeConnections()) + var profile = CredentialProfile(name: "Prod reader") + #expect(storage.addProfile(profile)) + let stale = profile + profile.secureFieldIds = ["awsSecretAccessKey"] + #expect(storage.updateProfile(profile)) + #expect(storage.saveSecureField("secret", fieldId: "awsSecretAccessKey", for: profile.id)) + + #expect(storage.deleteProfile(stale)) + + #expect(storage.readSecureField(fieldId: "awsSecretAccessKey", for: profile.id) == .absent) + } + + @Test("A copy's name never matches another profile, ignoring case and accents") + func copyNamesAreFree() { + #expect(ProfileNames.available(basedOn: "Prod", taken: ["Prod"]) == "Prod (Copy)") + #expect(ProfileNames.available(basedOn: "Prod", taken: ["Prod", "prod (copy)"]) == "Prod (Copy 2)") + #expect(ProfileNames.available(basedOn: "Café", taken: ["Café", "CAFE (COPY)", "cafe (copy 2)"]) == "Café (Copy 3)") + } + + @Test("Duplicating a credential profile copies its password and secure fields under a new id") + func credentialDuplicateCopiesSecrets() throws { + let connections = try makeConnections() + let credentials = makeCredentialStorage(connections: connections) + let model = makeModel(credentials: credentials, ssh: try makeSSHStorage(connections: connections), connections: connections) + let source = CredentialProfile(name: "Prod reader", username: "app_reader", secureFieldIds: ["awsSecretAccessKey"]) + #expect(credentials.addProfile(source)) + #expect(credentials.savePassword("hunter2", for: source.id)) + #expect(credentials.saveSecureField("secret", fieldId: "awsSecretAccessKey", for: source.id)) + + #expect(model.duplicateCredentialProfile(id: source.id)) + + let copy = try #require(credentials.loadProfiles().first { $0.id != source.id }) + #expect(copy.name == "Prod reader (Copy)") + #expect(copy.username == "app_reader") + #expect(credentials.readPassword(for: copy.id) == .found("hunter2")) + #expect(credentials.readSecureField(fieldId: "awsSecretAccessKey", for: copy.id) == .found("secret")) + } + + @Test("A credential profile whose secrets can't be read is not duplicated") + func credentialDuplicateRefusesUnreadableSecrets() throws { + let locked = UnreadableSecretKeychain() + let connections = try makeConnections() + let credentials = makeCredentialStorage(connections: connections, keychain: locked) + let model = makeModel(credentials: credentials, ssh: try makeSSHStorage(connections: connections), connections: connections) + let source = CredentialProfile(name: "Prod reader", passwordMode: .stored) + #expect(credentials.addProfile(source)) + + #expect(!model.duplicateCredentialProfile(id: source.id)) + #expect(credentials.loadProfiles().count == 1) + } + + @Test("An SSH profile whose secrets can't be read is not duplicated") + func sshDuplicateRefusesUnreadableSecrets() throws { + let connections = try makeConnections() + let ssh = try makeSSHStorage(connections: connections, keychain: UnreadableSecretKeychain()) + let model = makeModel(credentials: makeCredentialStorage(connections: connections), ssh: ssh, connections: connections) + let source = makeSSHProfile() + #expect(ssh.addProfile(source)) + + #expect(!model.duplicateSSHProfile(id: source.id)) + #expect(ssh.loadProfiles().count == 1) + } + + @Test("Duplicating an SSH profile copies its configuration and all three secrets") + func sshDuplicateCopiesSecrets() throws { + let connections = try makeConnections() + let ssh = try makeSSHStorage(connections: connections) + let model = makeModel(credentials: makeCredentialStorage(connections: connections), ssh: ssh, connections: connections) + let source = makeSSHProfile() + #expect(ssh.addProfile(source)) + #expect(ssh.saveSSHPassword("pw", for: source.id)) + #expect(ssh.saveKeyPassphrase("phrase", for: source.id)) + #expect(ssh.saveTOTPSecret("JBSWY3DP", for: source.id)) + + #expect(model.duplicateSSHProfile(id: source.id)) + + let copy = try #require(ssh.loadProfiles().first { $0.id != source.id }) + #expect(copy.name == "Bastion (Copy)") + #expect(copy.host == source.host) + #expect(ssh.readSecret(.password, for: copy.id) == .found("pw")) + #expect(ssh.readSecret(.keyPassphrase, for: copy.id) == .found("phrase")) + #expect(ssh.readSecret(.totpSecret, for: copy.id) == .found("JBSWY3DP")) + } + + @Test("Usage is unknown, and Delete is not offered, while the connections can't be read") + func usageUnknownWithUnreadableLibrary() throws { + let connections = try makeConnections(unreadable: true) + let credentials = makeCredentialStorage(connections: connections) + let model = makeModel(credentials: credentials, ssh: try makeSSHStorage(connections: connections), connections: connections) + let profile = CredentialProfile(name: "Prod reader") + #expect(credentials.addProfile(profile)) + + model.refresh() + + #expect(model.usageUnknown) + #expect(model.usageCount(for: profile.id) == nil) + #expect(model.pendingDeletion(of: .credential, id: profile.id, name: profile.name) == nil) + } + + @Test("Usage counts each profile's linked connections") + func usageCountsLinkedConnections() throws { + let connections = try makeConnections() + let credentials = makeCredentialStorage(connections: connections) + let ssh = try makeSSHStorage(connections: connections) + let model = makeModel(credentials: credentials, ssh: ssh, connections: connections) + let credential = CredentialProfile(name: "Prod reader") + let server = makeSSHProfile() + #expect(credentials.addProfile(credential)) + #expect(ssh.addProfile(server)) + for _ in 0..<2 { + var connection = TestFixtures.makeConnection() + connection.credentialMode = .profile(id: credential.id) + connection.sshTunnelMode = .profile(id: server.id, snapshot: server.toSSHConfiguration()) + connections.addConnection(connection) + } + + model.refresh() + + #expect(model.usageCount(for: credential.id) == 2) + #expect(model.usageCount(for: server.id) == 2) + #expect(model.pendingDeletion(of: .ssh, id: server.id, name: server.name)?.dependentCount == 2) + } +} diff --git a/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift b/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift new file mode 100644 index 0000000000..d10db91265 --- /dev/null +++ b/apple/TableProTests/Models/Connection/SSHSecretRevealProvenanceTests.swift @@ -0,0 +1,43 @@ +import Foundation +import TableProSSHConfig +import Testing + +@testable import TablePro + +// A secret that came out of a Keychain must ask for authentication before the Show toggle reveals it. +struct SSHSecretRevealProvenanceTests { + @Test func profileSecretsStayProtectedAfterSwitchingToInline() { + var state = SSHTunnelFormState() + state.enabled = true + state.profileId = UUID() + state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") + + state.profileId = nil + + #expect(state.savedSecrets == [.password, .keyPassphrase, .totpSecret]) + } + + @Test func emptyProfileSecretsAreNotProtected() { + var state = SSHTunnelFormState() + state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "", totpSecret: "") + + #expect(state.savedSecrets == [.password]) + } + + @Test func disablingTheTunnelDropsProfileProvenance() { + var state = SSHTunnelFormState() + state.adoptProfileSecrets(password: "hunter2", keyPassphrase: "phrase", totpSecret: "JBSWY3DP") + + state.disable() + + #expect(state.savedSecrets.isEmpty) + } + + @Test func filledSecretsNamesOnlyNonEmptyValues() { + var draft = SSHServerDraft() + draft.password = "hunter2" + draft.totpSecret = "JBSWY3DP" + + #expect(draft.filledSecrets == [.password, .totpSecret]) + } +} diff --git a/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift b/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift index 568edea8f4..6fb078d974 100644 --- a/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift +++ b/apple/TableProTests/Views/ConnectionForm/ClearedSecretSaveTests.swift @@ -1,11 +1,10 @@ import Foundation +import TableProSSHConfig import Testing @testable import TablePro -/// Emptying a password field and saving has to delete the stored secret. Leaving it behind means -/// the next connect still authenticates with the old password, an encrypted export still carries -/// it, and a duplicate copies it. +// A secret left behind still authenticates the next connect, rides along in an export and is copied by a duplicate. @MainActor struct ClearedSecretSaveTests { private let suite: EphemeralDefaults @@ -128,4 +127,41 @@ struct ClearedSecretSaveTests { #expect(!state.clearsStoredPassword) #expect(!state.clearsStoredKeyPassphrase) } + + @Test("Showing an inline SSH secret the Keychain returned asks for authentication first") + func savedInlineSSHSecretsNeedAuthenticationToShow() { + var state = SSHTunnelFormState() + state.enabled = true + state.loadSecrets(connectionId: UUID(), storage: makeStorage(.found("secret"))) + + #expect(state.savedSecrets == [.password, .keyPassphrase, .totpSecret]) + } + + @Test("A connection with no inline SSH secrets has nothing to guard") + func absentInlineSSHSecretsNeedNoAuthentication() { + var state = SSHTunnelFormState() + state.enabled = true + state.loadSecrets(connectionId: UUID(), storage: makeStorage(.notFound)) + + #expect(state.savedSecrets.isEmpty) + } + + @Test("An edit through the shared SSH fields lands on the form state, secrets included") + func sharedFieldsWriteThrough() { + var state = SSHTunnelFormState() + var server = state.server + server.host = "bastion.example.com" + server.port = "2222" + server.authMethod = .privateKey + server.keyPassphrase = "phrase" + server.addJumpHost() + state.server = server + + #expect(state.host == "bastion.example.com") + #expect(state.port == "2222") + #expect(state.authMethod == .privateKey) + #expect(state.keyPassphrase == "phrase") + #expect(state.jumpHosts.count == 1) + #expect(state.server == server) + } } From 5427f89db6df5938b92a1f1afbdab00bbdb2187f Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:45:55 +0700 Subject: [PATCH 37/48] feat(settings): AI pane with provider pages and a Slash Commands page --- apple/TablePro/Core/AI/AISchemaContext.swift | 19 +- .../AI/Copilot/CopilotPreambleBuilder.swift | 7 +- .../Core/AI/Copilot/CopilotService.swift | 22 +- .../Core/Autocomplete/SQLSchemaProvider.swift | 70 +- .../TablePro/Core/Storage/AIKeyStorage.swift | 13 +- apple/TablePro/Models/AI/AIModels.swift | 86 +- .../TablePro/Models/AI/AIProviderStatus.swift | 19 +- .../AIChatViewModel+SchemaContext.swift | 8 +- .../Views/Editor/SQLEditorCoordinator.swift | 114 +-- .../Views/Settings/AI/AIModelListLoader.swift | 71 ++ .../Views/Settings/AI/AIProviderAddMenu.swift | 137 +++ .../Settings/AI/AIProviderAddSheet.swift | 122 +++ .../AI/AIProviderConnectionSheet.swift | 91 ++ .../Settings/AI/AIProviderEditorModel.swift | 422 ++++++++ .../AI/AIProviderEditorSections.swift | 554 +++++++++++ .../Views/Settings/AI/AIProviderPage.swift | 352 +++++++ .../Settings/AIProviderDetailSheet.swift | 915 ------------------ .../Views/Settings/AISettingsView.swift | 704 +++++++------- .../ClaudeAgentDisclosureSection.swift | 14 +- .../Components/AIProviderStatusLabel.swift | 19 +- .../Settings/CustomSlashCommandsSection.swift | 336 ++++--- .../Settings/Entries/AISettingsEntry.swift | 25 +- .../Core/AI/AIProviderDraftRulesTests.swift | 92 +- .../Models/AI/AISettingsMutationTests.swift | 132 +++ .../Models/AIProviderStatusTests.swift | 14 + .../Settings/AIProviderAddMenuTests.swift | 85 ++ 26 files changed, 2776 insertions(+), 1667 deletions(-) create mode 100644 apple/TablePro/Views/Settings/AI/AIModelListLoader.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift create mode 100644 apple/TablePro/Views/Settings/AI/AIProviderPage.swift delete mode 100644 apple/TablePro/Views/Settings/AIProviderDetailSheet.swift create mode 100644 apple/TableProTests/Models/AI/AISettingsMutationTests.swift create mode 100644 apple/TableProTests/Views/Settings/AIProviderAddMenuTests.swift diff --git a/apple/TablePro/Core/AI/AISchemaContext.swift b/apple/TablePro/Core/AI/AISchemaContext.swift index 1a495ae7a8..fb45df3550 100644 --- a/apple/TablePro/Core/AI/AISchemaContext.swift +++ b/apple/TablePro/Core/AI/AISchemaContext.swift @@ -1,17 +1,9 @@ -// -// AISchemaContext.swift -// TablePro -// -// Builds AI system prompt context from current database connection schema. -// - import Foundation import TableProAutocomplete import TableProPluginKit import TableProSQLGrammar -/// One table as the schema context describes it. The producer joins each table to its own columns -/// and foreign keys, because a lookup by name cannot tell two schemas' tables of the same name apart. +// Each table carries its own columns and foreign keys: a lookup by name cannot tell two schemas' tables apart. struct AISchemaTable: Sendable { let table: TableInfo let columns: [ColumnInfo] @@ -36,8 +28,6 @@ struct AISchemaRankingInput: Sendable { struct AISchemaContext { static let maxQueryLength = 2_000 - // MARK: - Public - static func buildSystemPrompt( databaseType: DatabaseType, databaseName: String, @@ -65,7 +55,7 @@ struct AISchemaContext { let schemaContext = buildSchemaSection( tables: tables, defaultSchema: defaultSchema, - maxTables: settings.maxSchemaTables, + maxTables: settings.clampedMaxSchemaTables, identifierQuote: identifierQuote ) if !schemaContext.isEmpty { @@ -117,10 +107,7 @@ struct AISchemaContext { return parts.joined(separator: "\n") } - // MARK: - Private - - /// A table outside `defaultSchema` is named with its schema, so two tables that share a name - /// read as two tables rather than one listed twice. + // A table outside defaultSchema is named with its schema, so two tables sharing a name read as two. static func buildSchemaSection( tables: [AISchemaTable], defaultSchema: String?, diff --git a/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift b/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift index 514cc3a350..9774db7567 100644 --- a/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift +++ b/apple/TablePro/Core/AI/Copilot/CopilotPreambleBuilder.swift @@ -1,8 +1,3 @@ -// -// CopilotPreambleBuilder.swift -// TablePro -// - import Foundation import os import TableProPluginKit @@ -58,7 +53,7 @@ final class CopilotPreambleBuilder { databaseType: DatabaseType, referencing documentText: String? = nil, grammar: SQLLexicalGrammar? = nil, - maxTables: Int = AppSettingsManager.shared.ai.maxSchemaTables + maxTables: Int = AppSettingsManager.shared.ai.clampedMaxSchemaTables ) async { try? FileManager.default.createDirectory(at: Self.contextDirectory, withIntermediateDirectories: true) diff --git a/apple/TablePro/Core/AI/Copilot/CopilotService.swift b/apple/TablePro/Core/AI/Copilot/CopilotService.swift index a1ea975ab0..663db1acdd 100644 --- a/apple/TablePro/Core/AI/Copilot/CopilotService.swift +++ b/apple/TablePro/Core/AI/Copilot/CopilotService.swift @@ -29,6 +29,8 @@ final class CopilotService: ObservableObject { @Published private(set) var status: Status = .stopped @Published private(set) var authState: AuthState = .signedOut @Published private(set) var statusMessage: String? + // Until the server answers, authState reads signedOut whether or not the user is signed in. + @Published private(set) var hasReportedAuthState = false private var lspClient: LSPClient? private var transport: LSPTransport? @@ -47,8 +49,7 @@ final class CopilotService: ObservableObject { } ) - /// Stops the LSP server if the user hasn't signed in within this window after start. - /// Avoids leaving a Node process idle for users who add a Copilot config but never authorise. + // Leaves no Node process idle for someone who adds Copilot and never signs in. private static let unauthenticatedTimeout: Duration = .seconds(5 * 60) private init() {} @@ -58,10 +59,7 @@ final class CopilotService: ObservableObject { var isAuthenticated: Bool { authState.isSignedIn } var generation: Int { serverGeneration } - // MARK: - Lifecycle - - /// Concurrent callers share one launch, so a caller that arrives mid-start waits for it rather - /// than finding no client. `stop()` drops the shared launch, so a caller after it starts afresh. + // Concurrent callers share one launch; stop() drops it, so a later caller starts afresh. func start() async { if let startTask { await startTask.value @@ -76,8 +74,7 @@ final class CopilotService: ObservableObject { } } - /// The client, starting the language server first when this is its first use. A turn that was - /// queued before AI was turned off or Copilot removed must not bring the server back. + // A turn queued before AI was turned off or Copilot removed must not bring the server back. func runningClient() async throws -> LSPClient { guard CopilotLifecycle.allowsRunning(AppSettingsManager.shared.ai) else { throw CopilotError.serverNotRunning @@ -187,8 +184,6 @@ final class CopilotService: ObservableObject { Self.logger.info("Copilot language server stopped") } - // MARK: - Authentication - func signIn() async throws { await start() guard let transport else { @@ -196,6 +191,7 @@ final class CopilotService: ObservableObject { } let result = try await authManager.initiateSignIn(transport: transport) authState = .signingIn(userCode: result.userCode, verificationURI: result.verificationURI) + hasReportedAuthState = true } func completeSignIn() async throws { @@ -204,6 +200,7 @@ final class CopilotService: ObservableObject { } let username = try await authManager.completeSignIn(transport: transport) authState = .signedIn(username: username) + hasReportedAuthState = true unauthenticatedStop.cancel() } @@ -211,11 +208,10 @@ final class CopilotService: ObservableObject { guard let transport else { return } await authManager.signOut(transport: transport) authState = .signedOut + hasReportedAuthState = true scheduleUnauthenticatedStopIfNeeded() } - // MARK: - Private - private func scheduleRestart() { restartAttempt += 1 let delay = min(Double(1 << min(restartAttempt, 6)), 60.0) @@ -248,6 +244,7 @@ final class CopilotService: ObservableObject { } catch { Self.logger.debug("Auth status check failed: \(error.localizedDescription)") } + hasReportedAuthState = true } private func scheduleUnauthenticatedStopIfNeeded() { @@ -266,6 +263,7 @@ final class CopilotService: ObservableObject { statusMessage = message if let message, message.lowercased().contains("sign") || message.lowercased().contains("expired") { authState = .signedOut + hasReportedAuthState = true scheduleUnauthenticatedStopIfNeeded() } case "Warning": diff --git a/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift b/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift index c709c3315e..d406f8f48d 100644 --- a/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift +++ b/apple/TablePro/Core/Autocomplete/SQLSchemaProvider.swift @@ -7,8 +7,7 @@ import TableProSQLGrammar actor SQLSchemaProvider { private static let logger = Logger(subsystem: "com.TablePro", category: "SQLSchemaProvider") - /// The cache's capacity in tables, and the largest schema one bulk column read fills: reading - /// every column and keeping a fraction is the waste the preload exists to avoid. + // Also the largest schema one bulk column read fills: reading every column to keep a fraction is waste. static let maxCachedTables = 300 // A column list belongs to a table, spelled as the catalog spells its schema and name: an engine can keep apart @@ -59,10 +58,10 @@ actor SQLSchemaProvider { enum Outcome { case loaded, skipped, failed } } - /// Each state keeps the table-list generation it answered, so a later list reads it as stale. + // Each state keeps the table-list generation it answered, so a later list reads it as stale. private var columnPreload: ColumnPreload = .idle private var tableListGeneration = 0 - /// Until a query editor asks, a no-reference completion never starts a bulk read. + // Until a query editor asks, a no-reference completion never starts a bulk read. private var hasEditorDemand = false struct ColumnMetadataSource: Sendable { @@ -94,9 +93,7 @@ actor SQLSchemaProvider { private var fieldPathCache: [ColumnCacheKey: [PluginFieldPath]] = [:] private var fieldPathTasks: [ColumnCacheKey: Task<[PluginFieldPath], Never>] = [:] - /// Another schema's tables, fetched when a statement names that schema and a dot. They are - /// held apart from `tables`, which the scope's owner writes and every unqualified reader - /// trusts, so completing `attendance.` cannot make `timesheet` an answer for a bare name. + // Kept apart from tables, so completing attendance. cannot make timesheet an answer for a bare name. private var onDemandSchemaTables: [CatalogName: [TableInfo]] = [:] private var onDemandSchemaTableTasks: [CatalogName: Task<[TableInfo]?, Never>] = [:] @@ -124,24 +121,21 @@ actor SQLSchemaProvider { private let metadataSource: ColumnMetadataSource? private var connectionInfo: DatabaseConnection? - /// The database this provider describes. A provider is per scope, so it can be a database the - /// sidebar is not browsing, and the AI schema context must name the one the tables came from. + // A provider is per scope, so this can be a database the sidebar is not browsing. private var scopeDatabase: String? init(metadataSource: ColumnMetadataSource? = nil) { self.metadataSource = metadataSource } - // MARK: - Public API - - /// Concurrent callers await the same in-flight Task instead of firing duplicate queries. + // Concurrent callers await the same in-flight Task instead of firing duplicate queries. func loadSchema(using driver: DatabaseDriver, connection: DatabaseConnection? = nil) async { if let existing = loadTask { Self.logger.debug("[schema] loadSchema awaiting existing in-flight task") let t0 = Date() if let connection { self.connectionInfo = connection } await existing.value - Self.logger.debug("[schema] loadSchema coalesced — awaited existing task ms=\(Int(Date().timeIntervalSince(t0) * 1_000)) tableCount=\(self.tables.count)") + Self.logger.debug("[schema] loadSchema coalesced, awaited existing task ms=\(Int(Date().timeIntervalSince(t0) * 1_000)) tableCount=\(self.tables.count)") return } @@ -312,8 +306,7 @@ actor SQLSchemaProvider { }) } - /// A lookup that names no schema reads the schema an unqualified fetch targets, which is the one - /// the column preload fills, so `orders` and `public.orders` on PostgreSQL share one entry. + // An unqualified lookup reads the schema the preload fills, so orders and public.orders share one entry. private func cacheKey(table: String, schema: String?) -> ColumnCacheKey { if let listed = listedSpelling(ofTable: table, schema: schema) { return cacheKey(listed) } return ColumnCacheKey( @@ -333,8 +326,7 @@ actor SQLSchemaProvider { return schema == CatalogName(key.isTyped ? Self.folded(defaultSchema) : schemaSpelling(defaultSchema) ?? defaultSchema) } - /// A table outside the default schema keeps its schema, so two cached tables of one name never - /// offer the same `orders.id` for columns of two different tables. + // A table outside the default schema keeps its schema, so two tables of one name never share orders.id. private func fallbackTableLabel(for key: ColumnCacheKey, listed: ListedName?) -> String { let name = listed?.name ?? key.name.text guard let schema = key.schema, !isDefaultSchema(key) else { return name } @@ -348,8 +340,7 @@ actor SQLSchemaProvider { return [.statement(schema.text, quoted: false), table] } - /// The schema a table can be named in without its schema: the engine's implicit schema when it - /// has one, otherwise the schema the driver was on when this scope loaded. + // The engine's implicit schema when it has one, otherwise the schema the driver was on when this scope loaded. func getDefaultSchema() -> String? { connectionInfo?.type.implicitSchemaName ?? eagerLoadSchema } @@ -416,7 +407,7 @@ actor SQLSchemaProvider { staleRereadsStarted.subtract(keys) } - /// Reads nothing. The next editor request or no-reference completion refills it. + // Reads nothing: the next editor request or no-reference completion refills it. func clearColumnCache() { if case .running(_, let task) = columnPreload { task.cancel() } columnPreload = .idle @@ -432,23 +423,19 @@ actor SQLSchemaProvider { fieldPathTasks.removeAll() } - // MARK: - Column Preload - - /// Only a query editor's `prepare` calls this. It joins a read in flight and retries a failed one. + // Only a query editor's prepare calls this. It joins a read in flight and retries a failed one. func requestColumnPreload() { hasEditorDemand = true startColumnPreloadIfStale(retryingFailure: true) } - /// Reads again for a table list written after a preload had served the previous one. func renewColumnPreload() { guard case .settled(let generation, .loaded) = columnPreload, generation != tableListGeneration else { return } startColumnPreloadIfStale(retryingFailure: false) } - /// The bulk read covers one schema while `tables` holds every expanded one. Zero means the list - /// names other schemas only, so a read sized by it would be a guess. + // The bulk read covers one schema; zero means the list names other schemas only, so its size is unknown. private var eagerLoadTableCount: Int { tables.filter { isInEagerLoadSchema($0) }.count } @@ -510,7 +497,7 @@ actor SQLSchemaProvider { columnPreload = .running(generation: generation, task: task) } - /// The pooled lease ignores cancellation, so a superseded read still completes and is stopped here. + // The pooled lease ignores cancellation, so a superseded read still completes and is stopped here. private func commitColumnPreload(_ result: Result<[CatalogName: [ColumnInfo]], any Error>, generation: Int) { guard case .running(let running, _) = columnPreload, running == generation else { return } switch result { @@ -526,8 +513,7 @@ actor SQLSchemaProvider { } } - /// A request the previous list had not served yet is served against this one. A settled preload - /// waits for the next request. + // A request the previous list had not served is served against this one; a settled preload waits. private func noteTableListWritten() { tableListGeneration &+= 1 unqualifiedTableItems = nil @@ -546,8 +532,7 @@ actor SQLSchemaProvider { } } - /// In the schema's own table order, so the tables kept under the cache limit are the same every - /// run. Only a table listed in the preload schema takes an entry from the read. + // In the schema's own order, so the tables kept under the cache limit are the same every run. private func populateColumnCache(_ allColumns: [CatalogName: [ColumnInfo]]) { var pending = allColumns // A read that spells a listed table otherwise, by case alone, still fills it when neither side has another @@ -589,8 +574,6 @@ actor SQLSchemaProvider { columnAccessOrder.append(key) } - // MARK: - Column Catalog - // Compared by bytes, like the catalog it names. private struct ListedName: Hashable { let schema: String? @@ -724,9 +707,7 @@ actor SQLSchemaProvider { return nil } - /// `tables` is every table the scope's owner loaded, which for the browse scope includes each - /// schema the sidebar has expanded. A bare name only reaches the schema unqualified names - /// resolve in, so only its tables may be offered or matched without their schema. + // tables includes every schema the sidebar expanded, but a bare name only reaches the unqualified one. private var tablesResolvableUnqualified: [TableInfo] { guard let defaultSchema = getDefaultSchema(), !defaultSchema.isEmpty else { return tables } let spelling = schemaSpelling(defaultSchema) @@ -736,8 +717,6 @@ actor SQLSchemaProvider { } } - // MARK: - AI Schema Context - // The tables the statement at the cursor reads take the column budget first. func buildSchemaContextForAI(settings: AISettings, editorText: String? = nil, cursorOffset: Int = 0) async -> String? { guard !tables.isEmpty, let connection = connectionInfo else { return nil } @@ -756,8 +735,9 @@ actor SQLSchemaProvider { return (resolvedName, quote, lang, langName, sessionGrammar) } + let budget = settings.clampedMaxSchemaTables var listedTables = tables - if let editorText, editorLanguage == .sql, listedTables.count > settings.maxSchemaTables { + if let editorText, editorLanguage == .sql, listedTables.count > budget { let statement = SQLStatementScanner.statementAtCursor( in: editorText, cursorPosition: cursorOffset, @@ -775,11 +755,11 @@ actor SQLSchemaProvider { var schemaTables: [AISchemaTable] = [] schemaTables.reserveCapacity(listedTables.count) - for table in listedTables.prefix(settings.maxSchemaTables) { + for table in listedTables.prefix(budget) { let columns = await getColumns(for: table.name, schema: table.schema) schemaTables.append(AISchemaTable(table: table, columns: columns)) } - schemaTables += listedTables.dropFirst(settings.maxSchemaTables).map { AISchemaTable(table: $0) } + schemaTables += listedTables.dropFirst(budget).map { AISchemaTable(table: $0) } return AISchemaContext.buildSystemPrompt( databaseType: dbType, @@ -795,8 +775,6 @@ actor SQLSchemaProvider { ) } - // MARK: - Completion Items - func tableCompletionItems() async -> [SQLCompletionItem] { let defaultSchema = getDefaultSchema() if let cached = unqualifiedTableItems, cached.defaultSchema == defaultSchema { return cached.items } @@ -916,8 +894,7 @@ actor SQLSchemaProvider { } } - /// Dotted field paths for a document-store collection, cached per collection. - /// Concurrent callers await the same sample instead of firing duplicate queries. + // Concurrent callers await the same sample instead of firing duplicate queries. func fieldPaths(for tableName: String, sampleSize: Int = 50) async -> [PluginFieldPath] { let key = cacheKey(table: tableName, schema: nil) if let cached = fieldPathCache[key] { return cached } @@ -940,8 +917,7 @@ actor SQLSchemaProvider { return paths } - /// Reads only the column cache, because completion runs per keystroke and must not add a fetch. - /// Until the preload or this statement's column completion has read the table, it offers nothing. + // Reads only the column cache: completion runs per keystroke and must not add a fetch. func allowedValues(forColumn column: String, in references: [TableReference]) -> [String] { let name = column.lowercased() let candidates = references.isEmpty diff --git a/apple/TablePro/Core/Storage/AIKeyStorage.swift b/apple/TablePro/Core/Storage/AIKeyStorage.swift index 22f302b535..09a4be3d9e 100644 --- a/apple/TablePro/Core/Storage/AIKeyStorage.swift +++ b/apple/TablePro/Core/Storage/AIKeyStorage.swift @@ -1,11 +1,3 @@ -// -// AIKeyStorage.swift -// TablePro -// -// Keychain storage for AI provider API keys. -// Follows ConnectionStorage.swift Keychain pattern. -// - import Foundation import os @@ -20,9 +12,10 @@ final class AIKeyStorage: Sendable { self.keychain = keychain } - func saveAPIKey(_ apiKey: String, for providerID: UUID) { + @discardableResult + func saveAPIKey(_ apiKey: String, for providerID: UUID) -> Bool { let key = "com.TablePro.aikey.\(providerID.uuidString)" - keychain.writeString(apiKey, forKey: key) + return keychain.writeString(apiKey, forKey: key) } func loadAPIKey(for providerID: UUID) -> String? { diff --git a/apple/TablePro/Models/AI/AIModels.swift b/apple/TablePro/Models/AI/AIModels.swift index d806eb1044..7ea2f4f765 100644 --- a/apple/TablePro/Models/AI/AIModels.swift +++ b/apple/TablePro/Models/AI/AIModels.swift @@ -1,12 +1,5 @@ -// -// AIModels.swift -// TablePro -// - import Foundation -// MARK: - AI Provider Type - enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { case copilot case chatgptCodex @@ -84,8 +77,7 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } - /// How the configured endpoint is turned into a request URL. Providers that reach a fixed - /// host ignore it, so they answer with `AIProviderFactory`'s own fallback transport. + // A provider that reaches a fixed host ignores it and answers with AIProviderFactory's fallback transport. var endpointStyle: AIEndpointStyle { switch self { case .claude: @@ -101,7 +93,6 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } - /// The types `OpenAICompatibleProvider` serves, which share one registration. static let openAICompatibleFamily: [AIProviderType] = [.openRouter, .openCode, .ollama, .llamaCpp, .mlx, .custom] var icon: BrandIcon { @@ -123,15 +114,11 @@ enum AIProviderType: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Provider Configuration - struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { let id: UUID var name: String var type: AIProviderType - /// Set on a `.custom` provider added from an `AIProviderPreset`. An id this build does not - /// know is kept as it stands, so a preset from a newer build survives a round trip through - /// this one and reads as a plain custom provider in the meantime. + // An id this build does not know is kept, so a newer build's preset survives a round trip through this one. var presetID: String? var model: String var endpoint: String @@ -161,14 +148,12 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { self.reasoningEffort = reasoningEffort } - /// The name is stored rather than derived, so a build without this preset still lists the - /// provider under the vendor's name. + // The name is stored, so a build without this preset still lists the provider under the vendor's name. init(preset: AIProviderPreset) { self.init(name: preset.displayName, type: .custom, presetID: preset.id) } - /// `id` and `type` are what make a row usable, so a row missing either one fails as a whole and - /// `AISettings` drops it. Every other field falls back on its own. + // A row missing its id or type fails as a whole and AISettings drops it; every other field falls back. init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(UUID.self, forKey: .id) @@ -188,7 +173,6 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { return AIProviderPreset.preset(withID: presetID) } - /// What kind of provider this is, as opposed to what the user named it. var kindName: String { preset?.displayName ?? type.displayName } var displayName: String { @@ -209,8 +193,6 @@ struct AIProviderConfig: Codable, Equatable, Identifiable, Sendable { } } -// MARK: - AI Connection Policy - enum AIConnectionPolicy: String, Codable, CaseIterable, Identifiable, Sendable { case alwaysAllow case askEachTime @@ -227,8 +209,6 @@ enum AIConnectionPolicy: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Chat Mode - enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { case ask case edit @@ -285,8 +265,6 @@ enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { } } -// MARK: - AI Settings - struct AISettings: Codable, Equatable, Sendable { var enabled: Bool var providers: [AIProviderConfig] @@ -302,14 +280,14 @@ struct AISettings: Codable, Equatable, Sendable { var maxToolRoundtripsEnabled: Bool var defaultConnectionPolicy: AIConnectionPolicy var chatMode: AIChatMode - /// Set from the composer's own context menu rather than the Settings window, because the only - /// place the highlight is worth thinking about is the field it wraps. + // Set from the composer's own context menu, not from Settings. var composerHighlightEnabled: Bool static let defaultInlineSuggestionDebounceMs: Int = 500 static let inlineSuggestionDebounceRange: ClosedRange = 100...3_000 static let defaultMaxToolRoundtrips: Int = 25 static let maxToolRoundtripsRange: ClosedRange = 5...200 + static let maxSchemaTablesRange: ClosedRange = 1...100 static let `default` = AISettings( enabled: true, @@ -413,13 +391,59 @@ struct AISettings: Codable, Equatable, Sendable { ) } - var effectiveMaxToolRoundtrips: Int? { - guard maxToolRoundtripsEnabled else { return nil } - return min( + var clampedMaxToolRoundtrips: Int { + min( max(maxToolRoundtrips, AISettings.maxToolRoundtripsRange.lowerBound), AISettings.maxToolRoundtripsRange.upperBound ) } + + var effectiveMaxToolRoundtrips: Int? { + guard maxToolRoundtripsEnabled else { return nil } + return clampedMaxToolRoundtrips + } + + // A synced or hand-edited value can be negative, and prefix(_:) traps on one. + var clampedMaxSchemaTables: Int { + min( + max(maxSchemaTables, AISettings.maxSchemaTablesRange.lowerBound), + AISettings.maxSchemaTablesRange.upperBound + ) + } + + func provider(withID id: UUID) -> AIProviderConfig? { + providers.first { $0.id == id } + } + + func upserting(_ provider: AIProviderConfig, makeActiveIfNone: Bool) -> AISettings { + var next = self + if let index = next.providers.firstIndex(where: { $0.id == provider.id }) { + next.providers[index] = provider + } else { + next.providers.append(provider) + } + if makeActiveIfNone, next.activeProvider == nil { + next.activeProviderID = provider.id + } + return next + } + + func removingProvider(_ id: UUID) -> AISettings { + var next = self + next.providers.removeAll { $0.id == id } + if next.activeProviderID == id { + next.activeProviderID = nil + } + return next + } + + // A provider another Mac removed stays removed: replacing never adds one back. + func replacingProvider(_ provider: AIProviderConfig) -> AISettings { + guard let index = providers.firstIndex(where: { $0.id == provider.id }) else { return self } + var next = self + next.providers[index] = provider + return next + } } struct AITokenUsage: Codable, Equatable, Sendable { diff --git a/apple/TablePro/Models/AI/AIProviderStatus.swift b/apple/TablePro/Models/AI/AIProviderStatus.swift index 84599b0fc4..6ae3a2ffda 100644 --- a/apple/TablePro/Models/AI/AIProviderStatus.swift +++ b/apple/TablePro/Models/AI/AIProviderStatus.swift @@ -1,12 +1,6 @@ -// -// AIProviderStatus.swift -// TablePro -// - import Foundation -// One answer to "can this provider answer right now", read by the Settings row, the provider sheet -// and the chat panel, so they never disagree. +// One answer to "can this provider answer right now", so the Settings row, the provider page and the chat panel agree. internal enum AIProviderStatus: Equatable, Sendable { case checking case ready(detail: String?) @@ -17,6 +11,7 @@ internal enum AIProviderStatus: Equatable, Sendable { case needsUpdate(version: String) case failed(message: String) case notConfigured + case notStarted internal var isReady: Bool { if case .ready = self { return true } @@ -34,13 +29,14 @@ internal enum AIProviderStatus: Equatable, Sendable { case .needsUpdate(let version): String(format: String(localized: "Claude Code %@ is too old"), version) case .failed(let message): message case .notConfigured: String(localized: "Not configured") + case .notStarted: String(localized: "Not started") } } // Only a state the user has to fix carries a symbol; a working or busy provider shows none. internal var severity: NoticeSeverity? { switch self { - case .checking, .ready, .signingIn: nil + case .checking, .ready, .signingIn, .notStarted: nil case .failed: .error case .needsAPIKey, .needsSignIn, .needsInstall, .needsUpdate, .notConfigured: .warning } @@ -51,7 +47,8 @@ internal enum AIProviderStatus: Equatable, Sendable { hasAPIKey: Bool, oauthState: OAuthAuthState?, serviceError: String?, - claudeAgent: ClaudeAgentService.InstallState + claudeAgent: ClaudeAgentService.InstallState, + serviceStopped: Bool = false ) -> AIProviderStatus { switch provider.authStyle { case .apiKey: @@ -61,8 +58,8 @@ internal enum AIProviderStatus: Equatable, Sendable { return endpointStatus(provider.endpoint.isEmpty ? provider.defaultEndpoint : provider.endpoint) case .oauth: if let serviceError, !serviceError.isEmpty { return .failed(message: serviceError) } - // No state yet: the sign-in lives in a service that has not answered. - guard let oauthState else { return .checking } + // No state yet: the sign-in lives in a service that has not answered, or has not been started. + guard let oauthState else { return serviceStopped ? .notStarted : .checking } switch oauthState { case .signedIn(let identity): return .ready(detail: identity.isEmpty diff --git a/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift b/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift index c89b794567..34a3fc3e8d 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel+SchemaContext.swift @@ -121,7 +121,7 @@ extension AIChatViewModel { let scope = schemaCacheScope let schema = browsedSchema(connId) let settings = services.appSettings.ai - let tablesToFetch = Array(orderedTables().prefix(settings.maxSchemaTables)) + let tablesToFetch = Array(orderedTables().prefix(settings.clampedMaxSchemaTables)) guard !tablesToFetch.isEmpty else { return } await withTaskGroup(of: (String, [ColumnInfo]).self) { group in @@ -208,7 +208,7 @@ extension AIChatViewModel { let section = AISchemaContext.buildSchemaSection( tables: schemaTables(), defaultSchema: connection.flatMap { defaultSchema(for: $0) }, - maxTables: settings.maxSchemaTables, + maxTables: settings.clampedMaxSchemaTables, identifierQuote: identifierQuote ) return section.isEmpty ? nil : section @@ -232,7 +232,7 @@ extension AIChatViewModel { question: question, queryReferences: editorQueryReferences(), defaultSchema: connection.flatMap { defaultSchema(for: $0) }, - maxTables: services.appSettings.ai.maxSchemaTables + maxTables: services.appSettings.ai.clampedMaxSchemaTables ) guard input.tables.count > input.maxTables else { return } let scope = schemaCacheScope @@ -257,7 +257,7 @@ extension AIChatViewModel { private func loadEveryColumnForRanking() async { guard let connection else { return } let tableCount = tables.count - guard tableCount > services.appSettings.ai.maxSchemaTables, + guard tableCount > services.appSettings.ai.clampedMaxSchemaTables, tableCount <= SQLSchemaProvider.maxCachedTables, bulkColumnReadTableCount != tableCount else { return } diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 816b4b1399..0cff4ab7fb 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -1,11 +1,3 @@ -// -// SQLEditorCoordinator.swift -// TablePro -// -// TextViewCoordinator for the TableProEditorKit-based SQL editor. -// Handles find panel workarounds and horizontal scrolling fix. -// - import AppKit import Combine import os @@ -15,15 +7,11 @@ import TableProPluginKit import TableProSQLGrammar import TableProTextEngine -/// Coordinator for the SQL editor — manages find panel, horizontal scrolling, and scroll-to-match @MainActor final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextViewDelegate { - // MARK: - Properties - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "SQLEditorCoordinator") - /// Above this document length inline AI features are suspended, at the same cutoff where syntax highlighting stops, - /// so a large document does not copy its whole contents to the assistant on every keystroke. + // Above this length inline AI is suspended, like highlighting, so a large document is not sent on every keystroke. private static let languageServiceLengthLimit = EditorHighlighting.maxHighlightableCharacters weak var controller: TextViewController? @@ -33,7 +21,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie clock: diagnosticsClock ) private let statementRunController = StatementRunController() - /// Shared schema provider for inline AI suggestions (avoids duplicate schema fetches) var schemaProvider: SQLSchemaProvider? var databaseScope: DatabaseScope? private let inlineAccessGate: AIConnectionAccessGate = .live @@ -47,15 +34,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie private var aiSettingsCancellable: AnyCancellable? private var connectionAccessCancellable: AnyCancellable? private var lastInlineSourceKind: InlineSuggestionSourceKind = .off - /// Debounce work item for frame-change notification to avoid - /// triggering syntax highlight viewport recalculation on every keystroke. + // Debounced so a keystroke does not recompute the highlight viewport. private var frameChangeTask: Task? private var isUppercasing = false private var wasEditorFocused = false private var didDestroy = false private var focusClaimPending = false - /// One way. `destroy()` runs when the editor is dismantled, which it never comes back from. + // One way: destroy() runs when the editor is dismantled, which it never comes back from. var isDestroyed: Bool { didDestroy } private var hasInstalledEditorServices = false @@ -80,12 +66,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie focusClaimPending = true } - /// Latches a saved selection to apply once, the moment the editor is in a window. - /// - /// The caller sets this from `body`, which runs many times before the text view exists, so the - /// setter is idempotent and the value is consumed exactly once in `installEditorServices`. - /// Pushing it through the SwiftUI cursor binding instead would fight live typing, because the - /// binding is written on every selection change the user makes. + // Set from body many times before the text view exists, so it latches once; the cursor binding would fight live typing. func scheduleCursorRestore(_ range: NSRange) { guard !hasInstalledEditorServices else { return } cursorRestorePending = range @@ -93,16 +74,13 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie private var foldRestorePending: [Range]? - /// Collapsed folds are replayed once, the same way the cursor is, because the fold state the editor reports back - /// is written on every collapse the user makes. + // Replayed once, like the cursor, because the fold state reported back is written on every collapse. func scheduleFoldRestore(_ ranges: [Range]) { guard !hasInstalledEditorServices, !ranges.isEmpty else { return } foldRestorePending = ranges } - /// Query tabs share one editor, so a tab switch replays the incoming tab's collapsed regions over a document the - /// editor has just been handed. The outgoing tab's folds are already gone: replacing the document drops them, - /// which is what keeps this from having to clear anything and from reporting a collapse the reader never made. + // Replacing the document already dropped the outgoing tab's folds, so nothing is cleared or reported here. func repointFolds(to ranges: [Range]?) { guard let controller else { foldRestorePending = ranges @@ -126,7 +104,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimEngine.restoreDocumentMarks(marks) } - /// Vim mode for UI observation @Published private(set) var vimMode: VimMode = .normal private var vimEngine: VimEngine? // Vim is installed once the editor is in a window, so marks restored before that wait here. @@ -149,18 +126,14 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie var tabID: UUID? var connectionId: UUID? var sourceFileURL: URL? - /// The connection's execution grammar, which `SQLEditorController` sets from the live session. + // SQLEditorController sets this from the live session. private(set) var sessionGrammar: SQLLexicalGrammar? var lexicalGrammar: SQLLexicalGrammar { sessionGrammar ?? (databaseType ?? .mysql).lexicalGrammar } - /// Whether the editor text view is currently the first responder. - /// Used to guard cursor propagation — when the find panel highlights - /// a match it changes the selection programmatically, and propagating - /// that to SwiftUI triggers a re-render that disrupts the find panel's - /// @FocusState. + // Guards cursor propagation: a find-panel highlight that reached SwiftUI would re-render and break its focus. var isEditorFirstResponder: Bool { guard let textView = controller?.textView else { return false } return textView.window?.firstResponder === textView @@ -178,8 +151,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie frameChangeTask = nil } - // MARK: - TextViewCoordinator - func prepareCoordinator(controller: TextViewController) { self.controller = controller @@ -379,8 +350,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie cleanupMonitors() } - // MARK: - AI Context Menu - private func installFoldPreview(controller: TextViewController) { foldPreview.language = PluginManager.shared .editorLanguage(for: databaseType ?? .mysql) @@ -398,7 +367,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie statementRunController.install(on: controller) } - /// Moves the run controls and diagnostics to `grammar`, as a connect, a reconnect or a `SET` changes it. func setSessionGrammar(_ grammar: SQLLexicalGrammar) { guard grammar != sessionGrammar else { return } sessionGrammar = grammar @@ -413,31 +381,23 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie ) } - /// Turns the run controls off for the length of a query, because a tab runs one at a time. + // A tab runs one query at a time. func setStatementRunControlsEnabled(_ isEnabled: Bool) { statementRunController.setEnabled(isEnabled, in: controller) } - /// Follows the Settings toggle, so turning the band off also stops resolving the caret's statement for it. + // Turning the band off also stops resolving the caret's statement for it. func setStatementHighlightEnabled(_ isEnabled: Bool) { guard statementRunController.isHighlightEnabled != isEnabled else { return } statementRunController.isHighlightEnabled = isEnabled statementRunController.refreshHighlight(in: controller) } - /// Moves the caret to the neighbouring statement. func moveCursorToStatement(_ direction: StatementNavigationDirection) { statementRunController.moveCursor(direction, in: controller) } - /// Takes the reader to the statement a result came from. - /// - /// Resolved here rather than by the caller because the anchor has to be matched against the text this editor is - /// showing, which the tab's binding can lag behind by a keystroke. A statement that has since been edited away - /// resolves to nothing and the caret stays where it is, which is the right answer: there is nowhere to go. - /// - /// Reports whether it moved, so the caller can retire the request either way and a statement that is gone does - /// not leave one pending forever. + // Matched against the text this editor shows, which the tab's binding can lag; an edited-away statement resolves to nothing. @discardableResult func jumpToStatement(_ anchor: StatementAnchor) -> Bool { guard let controller, let textView = controller.textView else { return false } @@ -452,13 +412,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie return true } - /// Runs the statement the caret is in, then moves the caret to the next one. - /// - /// Both halves go through this one editor. Reading the SQL here and executing it somewhere else would let the two - /// name different editors: a window hosts a workspace per connection and their editors all stay registered, so a - /// command that resolves its text through the window and its execution through the selected workspace can send - /// one connection's statement to another connection's database. `onRunStatement` is the same callback the gutter - /// control uses, and the view binds it to the coordinator that owns this editor. + // Reading and running through this one editor keeps one connection's statement out of another connection's database. func runStatementAtCursorAndAdvance() { guard let statement = statementRunController.statementAtCursor(in: controller), let run = onRunStatement else { @@ -521,7 +475,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie controller?.unfoldAll() } - /// Whether the fold containing the cursor is collapsed. `nil` when the cursor is not inside a fold. + // nil when the cursor is not inside a fold. func foldStateAtCursor() -> Bool? { controller?.foldStateAtCursor() } @@ -585,8 +539,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie ) } - // MARK: - Inline Suggestion Manager - private func installInlineSuggestionManager(controller: TextViewController) { let manager = InlineSuggestionManager() manager.install(controller: controller, sourceResolver: { [weak self] in @@ -690,7 +642,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie databaseName: databaseName, databaseType: databaseType, grammar: lexicalGrammar, - budget: max(AppSettingsManager.shared.ai.maxSchemaTables, 0) + budget: AppSettingsManager.shared.ai.clampedMaxSchemaTables ) } @@ -708,8 +660,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Key Bindings - private func applyKeyBindings(controller: TextViewController) { let keyBindings = AppSettingsManager.shared.editor.keyBindings if keyBindings != .vim, vimKeyInterceptor != nil { @@ -733,8 +683,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie emacsKeyInterceptor = nil } - // MARK: - Vim Mode - private func installVimKeyInterceptor(controller: TextViewController) { guard let textView = controller.textView else { return } @@ -787,15 +735,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimMode = .normal } - /// Takes Vim out of the editor without touching `vimMode`, which is what teardown needs. - /// - /// `destroy()` runs from `dismantleNSViewController`, and when the editor goes because its - /// `NSHostingView` is deallocated, SwiftUI calls that while `GraphHost.invalidate()` holds exclusive - /// access to the host. A `@Published` write there reaches a view in the same host, whose subscriber - /// asks that host for a transaction, and Swift aborts with "Fatal access conflict detected". That - /// shipped as a crash on switching away from a query tab on macOS 26, where the write happened even - /// with Vim mode off because `@Published` notifies on every assignment. Nothing reads the mode of an - /// editor that is being destroyed. + // No @Published write during teardown: it ran inside GraphHost.invalidate() and aborted with an access conflict. private func removeVimKeyInterceptor() { vimKeyInterceptor?.uninstall() vimCursorManager?.uninstall() @@ -804,14 +744,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimEngine = nil } - // MARK: - Menu Escape Routing - - /// Called by `EditorEventRouter.handleEscapeFromMenu()` when the "Clear Selection" menu item is - /// chosen with the pointer, which is the only way that item fires: an unmodified Escape is - /// never dispatched as a key equivalent and reaches the editor's own key chain instead. - /// Dismisses an open completion popup, hands the keystroke to Vim when it is mid-command, and - /// restores first responder and the caret when this editor was the focused surface. Returns - /// whether the editor consumed the escape so the menu skips its cancelOperation fallback. + // The Clear Selection item fires only from a pointer click; returns whether the editor consumed the escape. @discardableResult func handleEscapeFromMenu() -> Bool { let wasFocused = wasEditorFocused @@ -829,15 +762,12 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie vimKeyInterceptor?.handleEscapeFromExternalSource() ?? false } - /// Restores editor focus after another view in the same window took it. private func reclaimFirstResponder() { guard let controller, let textView = controller.textView, let window = textView.window, window.firstResponder !== textView else { return } _ = window.makeFirstResponder(textView) } - // MARK: - First Responder Tracking - func checkFirstResponderChange() { let focused = isEditorFirstResponder guard focused != wasEditorFocused else { return } @@ -852,8 +782,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Editor Settings Observer - private func installEditorSettingsObserver(controller: TextViewController) { editorSettingsCancellable = AppEvents.shared.editorSettingsChanged .receive(on: RunLoop.main) @@ -884,13 +812,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie lastInlineSourceKind = kind } - // MARK: - Keyword Case - - /// Rewrites the keyword just completed by a word boundary to the configured case. - /// - /// Only the two absolute `SQLKeywordCase` values rewrite what the user typed. Under either - /// `matchTyped` value this does nothing, so an accepted lowercase completion is not flipped - /// back to uppercase by the next space. + // Only the two absolute SQLKeywordCase values rewrite typed text, so matchTyped never flips an accepted completion. private func uppercaseKeywordIfNeeded(textView: TextView, range: NSRange, string: String) { let keywordCase = AppSettingsManager.shared.editor.keywordCase guard !isUppercasing, @@ -934,8 +856,6 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie } } - // MARK: - Find Panel - func showFindPanel() { controller?.showFindPanel() } diff --git a/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift b/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift new file mode 100644 index 0000000000..92d6708300 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIModelListLoader.swift @@ -0,0 +1,71 @@ +import Combine +import Foundation + +@MainActor +final class AIModelListLoader: ObservableObject { + private struct Connection: Equatable { + let providerID: UUID + let endpoint: String + let apiKey: String + } + + @Published private(set) var models: [AIModelInfo] = [] + @Published private(set) var isLoading = false + @Published private(set) var error: String? + @Published private(set) var blocker: AIModelListFetchGate.Blocker? + // True once a list loaded for the key and Base URL of the last request. + @Published private(set) var isCurrent = false + + private var loadedFor: Connection? + private var generation = 0 + + func load(config: AIProviderConfig, apiKey: String) async { + generation += 1 + let mine = generation + let descriptor = AIProviderRegistry.shared.descriptor(for: config.type.rawValue) + let connection = Connection(providerID: config.id, endpoint: config.endpoint, apiKey: apiKey) + + if let blocked = AIProviderDraftRules.modelListBlocker(descriptor: descriptor, draft: config, apiKey: apiKey) { + blocker = blocked + models = [] + isCurrent = false + loadedFor = nil + error = nil + isLoading = false + return + } + + blocker = nil + error = nil + isLoading = true + let transport = AIProviderFactory.makeUncachedProvider(for: config, apiKey: apiKey) + do { + let fetched = try await transport.fetchAvailableModels() + guard mine == generation else { return } + models = fetched + loadedFor = connection + isCurrent = true + isLoading = false + } catch { + guard mine == generation else { return } + // A list from another key or Base URL does not describe the server that just failed. + if loadedFor != connection { + models = [] + isCurrent = false + loadedFor = nil + } + self.error = error.localizedDescription + isLoading = false + } + } + + // The draft's key or Base URL changed, so the list on screen no longer answers for it. + func markStale() { + isCurrent = false + } + + func cancel() { + generation += 1 + isLoading = false + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift b/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift new file mode 100644 index 0000000000..43538471de --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderAddMenu.swift @@ -0,0 +1,137 @@ +import SwiftUI + +enum AIProviderAddChoice: Hashable, Identifiable { + case type(AIProviderType) + case preset(String) + case custom + + var id: String { + switch self { + case .type(let type): "type.\(type.rawValue)" + case .preset(let id): "preset.\(id)" + case .custom: "custom" + } + } + + var preset: AIProviderPreset? { + guard case .preset(let id) = self else { return nil } + return AIProviderPreset.preset(withID: id) + } + + var title: String { + switch self { + case .type(let type): type.displayName + case .preset: preset?.displayName ?? AIProviderType.custom.displayName + case .custom: String(localized: "Custom Provider") + } + } + + var icon: BrandIcon { + switch self { + case .type(let type): type.icon + case .preset: preset?.icon ?? AIProviderType.custom.icon + case .custom: AIProviderType.custom.icon + } + } + + func makeProvider(descriptor: (AIProviderType) -> AIProviderDescriptor?) -> AIProviderConfig { + switch self { + case .type(let type): + return AIProviderConfig( + type: type, + endpoint: type.defaultEndpoint, + telemetryEnabled: descriptor(type)?.defaultTelemetryEnabled ?? false + ) + case .preset: + guard let preset else { return AIProviderConfig(type: .custom) } + return AIProviderConfig(preset: preset) + case .custom: + return AIProviderConfig( + type: .custom, + telemetryEnabled: descriptor(.custom)?.defaultTelemetryEnabled ?? false + ) + } + } +} + +enum AIProviderAddMenu { + struct Groups: Equatable { + var signIn: [AIProviderAddChoice] = [] + var apiKey: [AIProviderAddChoice] = [] + var onThisMac: [AIProviderAddChoice] = [] + var includesCustom = false + } + + static func groups(registry: AIProviderRegistry = .shared) -> Groups { + groups { registry.descriptor(for: $0.rawValue) != nil } + } + + static func groups( + isRegistered: (AIProviderType) -> Bool, + presets: [AIProviderPreset] = AIProviderPreset.all + ) -> Groups { + var groups = Groups() + for type in AIProviderType.allCases where type != .custom && isRegistered(type) { + if type.authStyle == .oauth || type == .claudeAgent { + groups.signIn.append(.type(type)) + } else if type.authStyle.usesAPIKey { + groups.apiKey.append(.type(type)) + } else { + groups.onThisMac.append(.type(type)) + } + } + if isRegistered(.custom) { + groups.apiKey += presets.map { .preset($0.id) } + groups.includesCustom = true + } + return groups + } +} + +struct AIProviderAddMenuButton: View { + let onChoose: (AIProviderAddChoice) -> Void + + var body: some View { + let groups = AIProviderAddMenu.groups() + Menu { + if !groups.signIn.isEmpty { + Section(String(localized: "Sign In With an Account")) { items(groups.signIn) } + } + if !groups.apiKey.isEmpty { + Section(String(localized: "API Key")) { items(groups.apiKey) } + } + if !groups.onThisMac.isEmpty { + Section(String(localized: "On This Mac")) { items(groups.onThisMac) } + } + if groups.includesCustom { + Divider() + item(.custom) + } + } label: { + Text("Add Provider") + } + .menuStyle(.button) + .buttonStyle(.bordered) + .fixedSize() + .accessibilityIdentifier("settings-ai-add-provider") + } + + private func items(_ choices: [AIProviderAddChoice]) -> some View { + ForEach(choices) { choice in + item(choice) + } + } + + private func item(_ choice: AIProviderAddChoice) -> some View { + Button { + onChoose(choice) + } label: { + Label { + Text(verbatim: "\(choice.title)…") + } icon: { + choice.icon.menuImage() + } + .labelStyle(.titleAndIcon) + } + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift b/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift new file mode 100644 index 0000000000..00cc18a3d1 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderAddSheet.swift @@ -0,0 +1,122 @@ +import Combine +import SwiftUI + +struct AIProviderAddSession: Identifiable { + let provider: AIProviderConfig + + var id: UUID { provider.id } +} + +struct AIProviderAddSheet: View { + @StateObject private var model: AIProviderEditorModel + private let onAdd: (AIProviderConfig, Bool) -> Void + + init(session: AIProviderAddSession, onAdd: @escaping (_ provider: AIProviderConfig, _ hasKey: Bool) -> Void) { + self._model = StateObject(wrappedValue: AIProviderEditorModel(provider: session.provider, isNew: true)) + self.onAdd = onAdd + } + + var body: some View { + AIProviderAddSheetContent(model: model, loader: model.loader, onAdd: onAdd) + } +} + +private struct AIProviderAddSheetContent: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: AIProviderEditorModel + @ObservedObject var loader: AIModelListLoader + let onAdd: (AIProviderConfig, Bool) -> Void + + var body: some View { + VStack(spacing: 0) { + Form { + Section { + header + } + AIProviderEditorSections(model: model, parts: .all) + } + .formStyle(.grouped) + + Divider() + + DialogFooter { + if let error = model.saveError { + NoticeLabel(error, severity: .error) + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + model.cancelTasks() + dismiss() + } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ai-provider-cancel") + + Button(String(localized: "Add")) { + add() + } + .keyboardShortcut(.defaultAction) + .disabled(!model.canAdd) + .accessibilityIdentifier("ai-provider-save") + } + .padding() + } + .frame(minWidth: 520, minHeight: 480) + .task { + model.prepare() + switch model.draft.type { + case .copilot: + await CopilotService.shared.start() + case .chatgptCodex: + await ChatGPTCodexService.shared.refreshAuthState() + case .claudeAgent: + await ClaudeAgentService.shared.performRefresh() + default: + break + } + await model.fetchModels() + } + .onDisappear { + model.cancelTasks() + CopilotService.shared.stopIfDisallowed(by: AppSettingsManager.shared.aiSlice.value) + } + } + + private var header: some View { + HStack(spacing: 12) { + BrandIconView(icon: model.draft.icon) + .foregroundStyle(.secondary) + .frame(width: 32, height: 32) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: String(format: String(localized: "Add %@"), model.draft.kindName)) + .font(.headline) + if let subtitle { + Text(verbatim: subtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + } + .accessibilityElement(children: .combine) + } + + private var subtitle: String? { + if let host = URL(string: model.draft.endpoint.trimmingCharacters(in: .whitespacesAndNewlines))?.host, + !host.isEmpty { + return host + } + switch model.draft.type { + case .copilot, .chatgptCodex, .claudeAgent: + return String(localized: "Signs in with your account") + default: + return nil + } + } + + private func add() { + guard model.canAdd, let provider = model.providerToAdd() else { return } + onAdd(provider, provider.authStyle.usesAPIKey && !model.apiKey.isEmpty) + AIProviderFactory.invalidateCache(for: provider.id) + AppEvents.shared.aiProviderSaved.send(provider.id) + dismiss() + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift b/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift new file mode 100644 index 0000000000..cea20fc71e --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderConnectionSheet.swift @@ -0,0 +1,91 @@ +import Combine +import SwiftUI + +struct AIProviderConnectionSaved: Equatable { + let connectionChanged: Bool + let hasKey: Bool +} + +// Edits the name, Base URL and key of a saved provider; the page commits everything else live. +struct AIProviderConnectionSheet: View { + @StateObject private var model: AIProviderEditorModel + private let slice: SettingsSlice + private let onSaved: (AIProviderConnectionSaved) -> Void + + init( + provider: AIProviderConfig, + slice: SettingsSlice, + onSaved: @escaping (AIProviderConnectionSaved) -> Void + ) { + self._model = StateObject(wrappedValue: AIProviderEditorModel(provider: provider, isNew: false)) + self.slice = slice + self.onSaved = onSaved + } + + var body: some View { + AIProviderConnectionSheetContent(model: model, slice: slice, onSaved: onSaved) + } +} + +private struct AIProviderConnectionSheetContent: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: AIProviderEditorModel + let slice: SettingsSlice + let onSaved: (AIProviderConnectionSaved) -> Void + + var body: some View { + VStack(spacing: 0) { + Form { + AIProviderEditorSections(model: model, parts: [.connection, .apiKey]) + } + .formStyle(.grouped) + + Divider() + + DialogFooter { + if let error = model.saveError { + NoticeLabel(error, severity: .error) + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + model.cancelTasks() + dismiss() + } + .keyboardShortcut(.cancelAction) + .accessibilityIdentifier("ai-provider-cancel") + + Button(String(localized: "Save")) { + save() + } + .keyboardShortcut(.defaultAction) + .disabled(!model.canSaveConnection) + .accessibilityIdentifier("ai-provider-save") + } + .padding() + } + .frame(minWidth: 480, minHeight: 320) + .task { + await model.loadKey() + } + .onDisappear { + model.cancelTasks() + } + } + + private func save() { + guard model.canSaveConnection else { return } + guard let current = slice.value.provider(withID: model.draft.id) else { + model.saveError = String(localized: "This provider was removed.") + return + } + guard let saved = model.connectionSave(current: current) else { return } + if saved.connectionChanged { + AIModelCatalog.shared.remove(providerID: current.id) + } + slice.value = slice.value.replacingProvider(saved.provider) + AIProviderFactory.invalidateCache(for: current.id) + AppEvents.shared.aiProviderSaved.send(current.id) + onSaved(AIProviderConnectionSaved(connectionChanged: saved.connectionChanged, hasKey: saved.hasKey)) + dismiss() + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift b/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift new file mode 100644 index 0000000000..168743bf53 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderEditorModel.swift @@ -0,0 +1,422 @@ +import Combine +import Foundation + +enum AIModelSelection: Hashable { + case curated(String) + case fetched(String) + case custom +} + +struct AIModelChoices: Equatable { + let curated: [CuratedModel] + let fetched: [String] + + init(curated: [CuratedModel], fetched: [AIModelInfo]) { + self.curated = curated + let curatedIDs = Set(curated.map(\.id)) + self.fetched = fetched.map(\.id).filter { !curatedIDs.contains($0) } + } + + func contains(_ modelID: String) -> Bool { + curated.contains { $0.id == modelID } || fetched.contains(modelID) + } + + func selection(for modelID: String, choseOther: Bool) -> AIModelSelection { + if choseOther { return .custom } + if curated.contains(where: { $0.id == modelID }) { return .curated(modelID) } + if fetched.contains(modelID) { return .fetched(modelID) } + return .custom + } +} + +// The rules the Edit Connection sheet saves by, kept pure so they can be tested. +enum AIProviderConnectionRules { + enum KeyWrite: Equatable { + case keep + case save(String) + case delete + } + + // A key that failed to load or was never touched is never written over. + static func keyWrite(edited: Bool, typed: String) -> KeyWrite { + guard edited else { return .keep } + return typed.isEmpty ? .delete : .save(typed) + } + + static func canSave(isKeyLoaded: Bool, authStyle: AIProviderType.AuthStyle, apiKey: String) -> Bool { + guard isKeyLoaded else { return false } + guard authStyle == .apiKey else { return true } + return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + // Only the fields this sheet edits move; the model and the rest keep what the page committed meanwhile. + static func merged( + _ current: AIProviderConfig, + with draft: AIProviderConfig, + allowsName: Bool, + allowsEndpoint: Bool + ) -> AIProviderConfig { + var merged = current + if allowsName { merged.name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines) } + if allowsEndpoint { merged.endpoint = draft.endpoint } + return merged + } + + static func connectionChanged( + from current: AIProviderConfig, + to merged: AIProviderConfig, + keyWrite: KeyWrite, + savedKey: String + ) -> Bool { + if current.endpoint != merged.endpoint { return true } + switch keyWrite { + case .keep: return false + case .save(let key): return key != savedKey + case .delete: return !savedKey.isEmpty + } + } +} + +enum AIProviderKeychain { + @concurrent + static func key(for providerID: UUID) async -> String? { + AIKeyStorage.shared.loadAPIKey(for: providerID) + } + + @concurrent + static func providersWithKey(_ providerIDs: [UUID]) async -> Set { + var found: Set = [] + for id in providerIDs { + if let key = AIKeyStorage.shared.loadAPIKey(for: id), !key.isEmpty { + found.insert(id) + } + } + return found + } +} + +// The draft behind the Add Provider and Edit Connection sheets. Nothing reaches settings or the Keychain before Save. +@MainActor +final class AIProviderEditorModel: ObservableObject { + enum TestResult: Equatable { + case success + case failure(String) + } + + private struct FetchInputs: Equatable { + let endpoint: String + let apiKey: String + } + + let loader: AIModelListLoader + + @Published var draft: AIProviderConfig + @Published var maxOutputTokensText: String + @Published var saveError: String? + @Published private(set) var apiKey = "" + @Published private(set) var keyEdited = false + @Published private(set) var isKeyLoaded: Bool + @Published private(set) var choseOtherModel = false + @Published private(set) var isTesting = false + @Published private(set) var testResult: TestResult? + + private let savedEndpoint: String + private var savedAPIKey = "" + private var lastFetch: FetchInputs? + private var connectionRevision = 0 + private var testTask: Task? + + init(provider: AIProviderConfig, isNew: Bool, loader: AIModelListLoader = AIModelListLoader()) { + self.loader = loader + self.draft = provider + self.savedEndpoint = provider.endpoint + self.maxOutputTokensText = provider.maxOutputTokens.map(String.init) ?? "" + self.isKeyLoaded = isNew || !provider.authStyle.usesAPIKey + } + + var descriptor: AIProviderDescriptor? { + AIProviderRegistry.shared.descriptor(for: draft.type.rawValue) + } + + var allowsName: Bool { descriptor?.allowsNameConfiguration == true } + var allowsEndpoint: Bool { descriptor?.allowsEndpointConfiguration == true } + var usesAPIKey: Bool { draft.authStyle.usesAPIKey } + var showsMaxOutputTokens: Bool { descriptor?.allowsMaxOutputTokens == true } + var showsTelemetryToggle: Bool { descriptor?.showsTelemetryToggle == true } + var fetchesModelList: Bool { descriptor?.fetchesModelList == true } + + var normalizedDraft: AIProviderConfig { + var provider = draft + provider.name = draft.name.trimmingCharacters(in: .whitespacesAndNewlines) + provider.model = draft.model.trimmingCharacters(in: .whitespacesAndNewlines) + provider.endpoint = AIProviderDraftRules.endpoint(draft.endpoint, defaultEndpoint: draft.defaultEndpoint) + provider.maxOutputTokens = Self.maxOutputTokens(from: maxOutputTokensText) + return provider + } + + // Empty or below 1 means the provider's default. + nonisolated static func maxOutputTokens(from text: String) -> Int? { + guard let value = SettingsIntegerInput.parse(text), value > 0 else { return nil } + return value + } + + var resolvedEndpoint: AIEndpoint? { + AIEndpoint(normalizedDraft.endpoint, style: draft.type.endpointStyle) + } + + var resolvedChatURL: String? { + resolvedEndpoint?.chatURL(model: draft.model, style: draft.type.endpointStyle)?.absoluteString + } + + // Keyless local servers send no authorization header, so the key is named only when one goes out. + var cleartextCaution: String? { + guard resolvedEndpoint?.isPlaintextToRemoteHost == true else { return nil } + guard usesAPIKey, !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return String(localized: "Requests to this host are sent unencrypted over http.") + } + return String(localized: "Your API key is sent unencrypted over http to this host.") + } + + var curatedModels: [CuratedModel] { + descriptor?.curatedModels(for: draft.preset) ?? [] + } + + var choices: AIModelChoices { + AIModelChoices(curated: curatedModels, fetched: loader.models) + } + + var modelSelection: AIModelSelection { + choices.selection(for: draft.model, choseOther: choseOtherModel) + } + + var isCustomModel: Bool { + modelSelection == .custom + } + + func reasoning(forModelID id: String) -> AIReasoningSupport { + descriptor?.reasoning( + forModelID: id, + fetched: loader.models.first { $0.id == id }, + preset: draft.preset + ) ?? .unsupported + } + + var reasoningForCurrentModel: AIReasoningSupport { + reasoning(forModelID: draft.model) + } + + var showsReasoningPicker: Bool { + descriptor?.supportsReasoning == true && !reasoningForCurrentModel.effortLevels.isEmpty + } + + var needsModelChoice: Bool { + AIProviderDraftRules.needsModelChoice(model: draft.model, fetched: loader.models) + } + + var canAdd: Bool { + guard !needsModelChoice else { return false } + guard draft.authStyle == .apiKey else { return true } + return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var canSaveConnection: Bool { + AIProviderConnectionRules.canSave(isKeyLoaded: isKeyLoaded, authStyle: draft.authStyle, apiKey: apiKey) + } + + var keyWrite: AIProviderConnectionRules.KeyWrite { + AIProviderConnectionRules.keyWrite(edited: keyEdited, typed: apiKey) + } + + func loadKey() async { + guard !isKeyLoaded else { return } + let key = await AIProviderKeychain.key(for: draft.id) ?? "" + savedAPIKey = key + if !keyEdited { apiKey = key } + isKeyLoaded = true + } + + func editKey(_ typed: String) { + guard typed != apiKey else { return } + apiKey = typed + keyEdited = true + connectionEdited() + } + + func connectionEdited() { + connectionRevision += 1 + testResult = nil + loader.markStale() + } + + func select(_ selection: AIModelSelection) { + switch selection { + case .curated(let id), .fetched(let id): + choseOtherModel = false + selectModel(id, picked: true) + case .custom: + choseOtherModel = true + if choices.contains(draft.model) { + selectModel("", picked: false) + } + } + } + + func typeModel(_ typed: String) { + choseOtherModel = true + selectModel(typed, picked: false) + } + + // The model and the effort it allows change together, in one write. + func selectModel(_ id: String, picked: Bool) { + var next = draft + next.model = id + next.reasoningEffort = picked + ? AIProviderDraftRules.effort( + afterPicking: draft.reasoningEffort, + reasoning: reasoning(forModelID: id), + curated: curatedModels.first { $0.id == id } + ) + : AIProviderDraftRules.effort(keeping: draft.reasoningEffort, reasoning: reasoning(forModelID: id)) + draft = next + } + + func selectInitialModel() { + guard draft.model.isEmpty, !choseOtherModel, + let initial = AIProviderDraftRules.initialModel(curated: curatedModels, fetched: loader.models) + else { return } + selectModel(initial, picked: false) + } + + // Before any fetch, so a provider whose list cannot load yet still starts on its curated default. + func prepare() { + selectInitialModel() + selectModel(draft.model, picked: false) + } + + // The automatic fetch reads the Base URL as typed: resolving an empty field to the default would send the key elsewhere. + func fetchModels(force: Bool = false) async { + var config = normalizedDraft + if allowsEndpoint { + config.endpoint = draft.endpoint.trimmingCharacters(in: .whitespacesAndNewlines) + } + let inputs = FetchInputs(endpoint: config.endpoint, apiKey: apiKey) + guard force || inputs != lastFetch else { return } + lastFetch = inputs + let revision = connectionRevision + await loader.load(config: config, apiKey: apiKey) + // An edit made while the list loaded leaves it describing the previous key or Base URL. + if revision != connectionRevision { + loader.markStale() + } + selectInitialModel() + } + + func test() { + if draft.authStyle == .apiKey, apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + testResult = .failure(String(localized: "API key is required")) + return + } + let transport = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) + isTesting = true + testResult = nil + testTask?.cancel() + testTask = Task { [weak self] in + let outcome: TestResult + do { + outcome = try await transport.testConnection() + ? .success + : .failure(String(localized: "Connection test failed")) + } catch { + outcome = .failure(error.localizedDescription) + } + guard !Task.isCancelled, let self else { return } + self.isTesting = false + self.testResult = outcome + } + } + + func cancelTasks() { + testTask?.cancel() + testTask = nil + isTesting = false + loader.cancel() + } + + // The sheet's list reaches the shared catalog only on Save, and only if it describes what was saved. + func commitModelList() { + let saved = normalizedDraft + let update = AIProviderDraftRules.catalogUpdate( + listIsCurrent: loader.isCurrent, + listIsEmpty: loader.models.isEmpty, + connectionChanged: saved.endpoint != savedEndpoint || apiKey != savedAPIKey + ) + switch update { + case .store: + AIModelCatalog.shared.store(providerID: saved.id, models: loader.models) + case .remove: + AIModelCatalog.shared.remove(providerID: saved.id) + case .refetch: + AIModelCatalog.shared.remove(providerID: saved.id) + guard fetchesModelList else { return } + let transport = AIProviderFactory.makeUncachedProvider(for: saved, apiKey: apiKey) + let providerID = saved.id + Task { await AIModelCatalog.shared.refresh(providerID: providerID, using: transport) } + case .keep: + break + } + } + + // Returns the provider to store, or nil when the Keychain refused the key and the sheet stays open. + func providerToAdd() -> AIProviderConfig? { + let provider = normalizedDraft + let key = apiKey + if provider.authStyle.usesAPIKey, !key.isEmpty { + guard AIKeyStorage.shared.saveAPIKey(key, for: provider.id) else { + saveError = String(localized: "The API key could not be saved to the Keychain.") + return nil + } + } + cancelTasks() + commitModelList() + return provider + } + + struct ConnectionSave: Equatable { + let provider: AIProviderConfig + let connectionChanged: Bool + let hasKey: Bool + } + + func connectionSave(current: AIProviderConfig) -> ConnectionSave? { + let write = keyWrite + switch write { + case .keep: + break + case .save(let key): + guard AIKeyStorage.shared.saveAPIKey(key, for: current.id) else { + saveError = String(localized: "The API key could not be saved to the Keychain.") + return nil + } + case .delete: + AIKeyStorage.shared.deleteAPIKey(for: current.id) + } + cancelTasks() + let merged = AIProviderConnectionRules.merged( + current, + with: normalizedDraft, + allowsName: allowsName, + allowsEndpoint: allowsEndpoint + ) + let changed = AIProviderConnectionRules.connectionChanged( + from: current, + to: merged, + keyWrite: write, + savedKey: savedAPIKey + ) + return ConnectionSave( + provider: merged, + connectionChanged: changed, + hasKey: !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ) + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift b/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift new file mode 100644 index 0000000000..613d86c9f5 --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderEditorSections.swift @@ -0,0 +1,554 @@ +import SwiftUI + +struct AIProviderEditorParts: OptionSet { + let rawValue: Int + + static let connection = AIProviderEditorParts(rawValue: 1 << 0) + static let apiKey = AIProviderEditorParts(rawValue: 1 << 1) + static let account = AIProviderEditorParts(rawValue: 1 << 2) + static let model = AIProviderEditorParts(rawValue: 1 << 3) + static let advanced = AIProviderEditorParts(rawValue: 1 << 4) + + static let all: AIProviderEditorParts = [.connection, .apiKey, .account, .model, .advanced] +} + +// Shared by the Add Provider and Edit Connection sheets; every edit stays in the model's draft until Save. +struct AIProviderEditorSections: View { + private enum Field: Hashable { + case apiKey + case endpoint + } + + @ObservedObject private var model: AIProviderEditorModel + @ObservedObject private var loader: AIModelListLoader + private let parts: AIProviderEditorParts + + @FocusState private var focus: Field? + @State private var focusedField: Field? + + init(model: AIProviderEditorModel, parts: AIProviderEditorParts) { + self._model = ObservedObject(wrappedValue: model) + self._loader = ObservedObject(wrappedValue: model.loader) + self.parts = parts + } + + var body: some View { + Group { + if parts.contains(.connection), model.allowsName || model.allowsEndpoint { + connectionSection + } + if parts.contains(.apiKey), model.usesAPIKey { + apiKeySection + } + if parts.contains(.account), !model.usesAPIKey { + AIProviderAccountSections(type: model.draft.type) + } + if parts.contains(.model) { + modelSection + } + if parts.contains(.advanced), model.showsMaxOutputTokens || model.showsTelemetryToggle { + advancedSection + } + } + .onChange(of: focus) { newFocus in + // Leaving the key or Base URL field commits it, which is when the model list loads. + if focusedField != nil, newFocus != focusedField { + commitConnection() + } + focusedField = newFocus + } + } + + private func commitConnection() { + guard parts.contains(.model) else { return } + Task { await model.fetchModels() } + } + + private var connectionSection: some View { + Section { + if model.allowsName { + TextField(text: $model.draft.name, prompt: Text(verbatim: model.draft.kindName)) { + Text("Name") + } + .accessibilityIdentifier("ai-provider-name") + } + if model.allowsEndpoint { + TextField(text: endpointBinding, prompt: Text(verbatim: endpointPrompt)) { + Text("Base URL") + Text("Include the version segment your server uses, such as /v1 or /v4.") + } + .focused($focus, equals: .endpoint) + .onSubmit(commitConnection) + .accessibilityIdentifier("ai-provider-base-url") + + if let url = model.resolvedChatURL { + LabeledContent("Requests go to") { + Text(verbatim: url) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(url) + } + } + if let caution = model.cleartextCaution { + NoticeLabel(caution) + } + } + } header: { + Text("Connection") + } + } + + private var endpointPrompt: String { + model.draft.defaultEndpoint.isEmpty ? "https://" : model.draft.defaultEndpoint + } + + private var endpointBinding: Binding { + let model = model + return Binding( + get: { model.draft.endpoint }, + set: { typed in + guard typed != model.draft.endpoint else { return } + model.draft.endpoint = typed + model.connectionEdited() + } + ) + } + + private var apiKeySection: some View { + Section { + SecureField(text: keyBinding, prompt: model.draft.authStyle == .apiKey ? Text("Required") : Text("Optional")) { + Text("API key") + } + .focused($focus, equals: .apiKey) + .onSubmit(commitConnection) + .disabled(!model.isKeyLoaded) + .accessibilityIdentifier("ai-provider-api-key") + + LabeledContent { + HStack(spacing: 6) { + if model.isTesting { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } + Button("Test Connection") { + model.test() + } + .disabled(!canTest) + .accessibilityIdentifier("ai-provider-test") + } + } label: { + Text("Connection test") + testResultLine + } + } header: { + Text("Authentication") + } + } + + private var canTest: Bool { + guard model.isKeyLoaded, !model.isTesting else { return false } + guard model.draft.authStyle == .apiKey else { return true } + return !model.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + @ViewBuilder + private var testResultLine: some View { + switch model.testResult { + case .success: + NoticeLabel(String(localized: "Connection successful"), severity: .success) + case .failure(let message): + NoticeLabel(message, severity: .error) + case nil: + if model.isTesting { + Text("Testing…") + } else { + Text("Sends one short request with this key and Base URL.") + } + } + } + + private var keyBinding: Binding { + let model = model + return Binding( + get: { model.apiKey }, + set: { model.editKey($0) } + ) + } + + private var modelSection: some View { + Section { + Picker(selection: selectionBinding) { + AIModelPickerItems(choices: model.choices) + } label: { + Text("Model") + AIModelListSubtitle(loader: loader, needsChoice: model.needsModelChoice) + } + .pickerStyle(.menu) + .accessibilityIdentifier("ai-provider-model") + + if model.isCustomModel { + TextField(text: typedModelBinding, prompt: Text(verbatim: "model-id")) { + Text("Model ID") + } + } + if model.showsReasoningPicker { + Picker(selection: $model.draft.reasoningEffort) { + AIReasoningPickerItems(reasoning: model.reasoningForCurrentModel) + } label: { + Text("Reasoning") + } + .pickerStyle(.menu) + } + if model.fetchesModelList { + LabeledContent("Model list") { + Button("Reload") { + Task { await model.fetchModels(force: true) } + } + .disabled(loader.isLoading) + } + } + } header: { + Text("Model") + } + } + + private var selectionBinding: Binding { + let model = model + return Binding( + get: { model.modelSelection }, + set: { model.select($0) } + ) + } + + private var typedModelBinding: Binding { + let model = model + return Binding( + get: { model.draft.model }, + set: { model.typeModel($0) } + ) + } + + private var advancedSection: some View { + Section { + if model.showsMaxOutputTokens { + TextField(text: $model.maxOutputTokensText, prompt: Text("Default")) { + Text("Maximum output tokens") + } + } + if model.showsTelemetryToggle { + Toggle("Send telemetry to GitHub", isOn: $model.draft.telemetryEnabled) + } + } header: { + Text("Advanced") + } + } +} + +struct AIModelPickerItems: View { + let choices: AIModelChoices + + var body: some View { + if !choices.curated.isEmpty { + Section { + ForEach(choices.curated) { model in + Text(verbatim: model.displayName).tag(AIModelSelection.curated(model.id)) + } + } + } + if !choices.fetched.isEmpty { + Section { + ForEach(choices.fetched, id: \.self) { id in + Text(verbatim: id).tag(AIModelSelection.fetched(id)) + } + } + } + Text("Other…").tag(AIModelSelection.custom) + } +} + +struct AIReasoningPickerItems: View { + let reasoning: AIReasoningSupport + + var body: some View { + if !reasoning.isMandatory { + Text("Off").tag(ReasoningEffort?.none) + } + ForEach(reasoning.effortLevels) { effort in + Text(effort.displayName).tag(ReasoningEffort?.some(effort)) + } + } +} + +// The second line of the Model picker's label: one state at a time. +struct AIModelListSubtitle: View { + @ObservedObject var loader: AIModelListLoader + var needsChoice = false + + var body: some View { + if loader.isLoading { + Label { + Text("Loading models…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + } else if let error = loader.error { + NoticeLabel(error, severity: .error) + } else if loader.blocker == .missingAPIKey { + Text("Add an API key to load this provider's models.") + } else if needsChoice { + Text("Pick a model to add this provider.") + } + } +} + +// The sign-in part of an account-based provider, the same on the provider page and in the Add sheet. +struct AIProviderAccountSections: View { + let type: AIProviderType + + var body: some View { + switch type { + case .copilot: + CopilotAccountSection() + case .chatgptCodex: + ChatGPTAccountSection() + case .claudeAgent: + ClaudeAgentAccountSection() + default: + EmptyView() + } + } +} + +private struct CopilotAccountSection: View { + @ObservedObject private var copilot = CopilotService.shared + @State private var signInError: String? + + var body: some View { + Section { + switch copilot.authState { + case .signedOut: + LabeledContent { + Button("Sign In…") { + Task { await signIn() } + } + .disabled(copilot.status != .running) + } label: { + Text("GitHub account") + accountNote(otherwise: String(localized: "Not signed in")) + } + case .signingIn(let userCode, _): + LabeledContent("Code") { + HStack(spacing: 8) { + Text(verbatim: userCode) + .font(.system(.title3, design: .monospaced).weight(.semibold)) + .textSelection(.enabled) + Button("Copy") { + ClipboardService.shared.writeText(userCode) + } + } + } + LabeledContent { + HStack(spacing: 8) { + Button("Cancel") { + Task { await copilot.signOut() } + } + Button("Complete Sign In") { + Task { await completeSignIn() } + } + } + } label: { + Text("Enter the code on GitHub") + accountNote(otherwise: String(localized: "It was copied to the clipboard and expires in 15 minutes.")) + } + case .signedIn(let username): + LabeledContent { + Button("Sign Out") { + Task { await copilot.signOut() } + } + } label: { + Text("GitHub account") + accountNote(otherwise: username) + } + } + } header: { + Text("GitHub Account") + } + } + + @ViewBuilder + private func accountNote(otherwise fallback: String) -> some View { + if let message = signInError ?? copilot.statusMessage { + NoticeLabel(message, severity: .error) + } else { + switch copilot.status { + case .starting: + Label { + Text("Starting…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + case .stopped where !copilot.authState.isSignedIn: + Text("Not started") + case .error(let message): + NoticeLabel(message, severity: .error) + default: + Text(verbatim: fallback) + } + } + } + + private func signIn() async { + signInError = nil + do { + try await copilot.signIn() + } catch { + signInError = error.localizedDescription + } + } + + private func completeSignIn() async { + signInError = nil + do { + try await copilot.completeSignIn() + } catch { + signInError = error.localizedDescription + } + } +} + +private struct ChatGPTAccountSection: View { + @ObservedObject private var service = ChatGPTCodexService.shared + + var body: some View { + Section { + switch service.authState { + case .signedOut: + LabeledContent { + HStack(spacing: 8) { + Button("Import from Codex CLI") { + Task { await service.importFromCodexCLI() } + } + Button("Sign In…") { + Task { await service.signIn() } + } + } + } label: { + Text("ChatGPT account") + accountNote(otherwise: String(localized: "Not signed in")) + } + case .signingIn: + LabeledContent { + EmptyView() + } label: { + Text("ChatGPT account") + Label { + Text("Waiting for your browser…") + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) + } + } + case .signedIn(let email, let planType): + LabeledContent { + Button("Sign Out") { + Task { await service.signOut() } + } + } label: { + Text("ChatGPT account") + accountNote(otherwise: email.isEmpty ? String(localized: "Signed in") : email) + } + if let planType, !planType.isEmpty { + LabeledContent("Plan") { + Text(verbatim: planType) + } + } + } + SettingsHelpRow( + "Uses your Plus, Pro, Business or Enterprise subscription under OpenAI's terms. This interface is unofficial and may change." + ) + } header: { + Text("ChatGPT Account") + } + } + + @ViewBuilder + private func accountNote(otherwise fallback: String) -> some View { + if let message = service.errorMessage { + NoticeLabel(message, severity: .error) + } else { + Text(verbatim: fallback) + } + } +} + +private struct ClaudeAgentAccountSection: View { + @ObservedObject private var service = ClaudeAgentService.shared + + var body: some View { + Section { + LabeledContent { + Button("Check Again") { + service.refreshStatus() + } + .disabled(service.isRefreshing) + } label: { + Text("Status") + AIProviderStatusLabel(status: status) + } + if let plan { + LabeledContent("Plan") { + Text(verbatim: plan) + } + } + if let command = service.remedyCommand { + LabeledContent { + Button("Copy") { + ClipboardService.shared.writeText(command) + } + } label: { + Text(verbatim: command) + .font(.system(.body, design: .monospaced)) + .textSelection(.enabled) + if let requirement { + Text(verbatim: requirement) + } + } + } + SettingsHelpRow( + "Runs the claude command line tool, so chat bills against your Claude subscription. Database tools need the MCP server, in Settings > MCP." + ) + } header: { + Text("Claude Agent") + } + + ClaudeAgentDisclosureSection() + } + + private var status: AIProviderStatus { + AIProviderStatus.resolve( + provider: AIProviderConfig(type: .claudeAgent), + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: service.state + ) + } + + private var plan: String? { + guard case .signedIn(_, let plan?) = service.state, !plan.isEmpty else { return nil } + return plan + } + + private var requirement: String? { + guard case .outdated = service.state else { return nil } + return String(format: String(localized: "Version %@ or newer is required."), ClaudeAgentCLI.minimumVersion) + } +} diff --git a/apple/TablePro/Views/Settings/AI/AIProviderPage.swift b/apple/TablePro/Views/Settings/AI/AIProviderPage.swift new file mode 100644 index 0000000000..585a3f454c --- /dev/null +++ b/apple/TablePro/Views/Settings/AI/AIProviderPage.swift @@ -0,0 +1,352 @@ +import Combine +import SwiftUI + +// One provider's live settings. Opening it never writes: only a user edit commits, one whole-provider write at a time. +struct AIProviderPage: View { + let providerID: UUID + @ObservedObject var slice: SettingsSlice + + @EnvironmentObject private var paneModel: AISettingsPaneModel + @StateObject private var loader = AIModelListLoader() + @State private var loadedKey: String? + @State private var loadToken = 0 + @State private var choseOtherModel = false + @State private var isEditingConnection = false + + var body: some View { + Group { + if let provider = slice.value.provider(withID: providerID) { + form(provider) + } else { + UnavailableStateView(String(localized: "This provider was removed."), systemImage: "sparkles") + } + } + .task(id: loadToken) { + await loadModels() + } + .task { + guard slice.value.enabled, let type = slice.value.provider(withID: providerID)?.type else { return } + await paneModel.refreshAccounts(AIProviderAccountProbes.probedTypes.intersection([type])) + } + .onDisappear { + CopilotService.shared.stopIfDisallowed(by: slice.value) + } + .sheet(isPresented: $isEditingConnection) { + if let provider = slice.value.provider(withID: providerID) { + AIProviderConnectionSheet(provider: provider, slice: slice) { saved in + loadedKey = nil + paneModel.setHasKey(saved.hasKey, for: providerID) + if saved.connectionChanged { + loadToken += 1 + } + } + } + } + } + + private func form(_ provider: AIProviderConfig) -> some View { + let descriptor = AIProviderRegistry.shared.descriptor(for: provider.type.rawValue) + let showsAdvanced = descriptor?.allowsMaxOutputTokens == true || descriptor?.showsTelemetryToggle == true + return Form { + if !provider.authStyle.usesAPIKey { + AIProviderAccountSections(type: provider.type) + } + if showsConnection(provider, descriptor: descriptor) { + connectionSection(provider, descriptor: descriptor) + } + modelSection(provider, descriptor: descriptor, isLast: !showsAdvanced) + if showsAdvanced { + advancedSection(provider, descriptor: descriptor) + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-ai-provider") + } + + // A search result can open this page with AI off, which starts no service and sends no key. + private func loadModels() async { + guard slice.value.enabled, let provider = slice.value.provider(withID: providerID) else { return } + if provider.type == .copilot, CopilotLifecycle.allowsRunning(slice.value) { + await CopilotService.shared.start() + } + var key = "" + if provider.authStyle.usesAPIKey { + key = await AIProviderKeychain.key(for: providerID) ?? "" + loadedKey = key + paneModel.setHasKey(!key.isEmpty, for: providerID) + } + guard let current = slice.value.provider(withID: providerID) else { return } + await loader.load(config: current, apiKey: key) + guard loader.isCurrent, loader.error == nil else { return } + switch AIProviderDraftRules.catalogUpdate(listIsCurrent: true, listIsEmpty: loader.models.isEmpty, connectionChanged: false) { + case .store: + AIModelCatalog.shared.store(providerID: providerID, models: loader.models) + case .remove: + AIModelCatalog.shared.remove(providerID: providerID) + case .refetch, .keep: + break + } + } + + private func commit(_ change: (inout AIProviderConfig) -> Void) { + guard var updated = slice.value.provider(withID: providerID) else { return } + let original = updated + change(&updated) + guard updated != original else { return } + slice.value = slice.value.replacingProvider(updated) + AIProviderFactory.invalidateCache(for: providerID) + AppEvents.shared.aiProviderSaved.send(providerID) + } + + private func hasKey(_ provider: AIProviderConfig) -> Bool { + if let loadedKey { return !loadedKey.isEmpty } + return paneModel.hasKey(provider.id) + } + + private func showsConnection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> Bool { + descriptor?.allowsNameConfiguration == true + || descriptor?.allowsEndpointConfiguration == true + || provider.authStyle.usesAPIKey + } + + private func connectionSection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> some View { + Section { + if descriptor?.allowsNameConfiguration == true { + LabeledContent("Name") { + Text(verbatim: provider.displayName) + } + } + if descriptor?.allowsEndpointConfiguration == true { + LabeledContent("Base URL") { + Text(verbatim: provider.endpoint) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(provider.endpoint) + } + } + if provider.authStyle.usesAPIKey { + LabeledContent("API key") { + hasKey(provider) ? Text("Set") : Text("Not set") + } + } + if let caution = cleartextCaution(provider) { + NoticeLabel(caution) + } + } header: { + Text("Connection") + } footer: { + SettingsSectionActions { + Button("Edit Connection…") { + isEditingConnection = true + } + .accessibilityIdentifier("ai-provider-edit-connection") + } + } + } + + private func cleartextCaution(_ provider: AIProviderConfig) -> String? { + guard AIEndpoint(provider.endpoint, style: provider.type.endpointStyle)?.isPlaintextToRemoteHost == true else { + return nil + } + guard provider.authStyle.usesAPIKey, hasKey(provider) else { + return String(localized: "Requests to this host are sent unencrypted over http.") + } + return String(localized: "Your API key is sent unencrypted over http to this host.") + } + + private func modelSection( + _ provider: AIProviderConfig, + descriptor: AIProviderDescriptor?, + isLast: Bool + ) -> some View { + let choices = AIModelChoices(curated: descriptor?.curatedModels(for: provider.preset) ?? [], fetched: loader.models) + let selection = choices.selection(for: provider.model, choseOther: choseOtherModel) + let reasoning = reasoning(for: provider, modelID: provider.model, descriptor: descriptor) + return Section { + Picker(selection: selectionBinding(choices: choices, descriptor: descriptor)) { + AIModelPickerItems(choices: choices) + } label: { + Text("Model") + AIModelListSubtitle(loader: loader) + } + .pickerStyle(.menu) + .accessibilityIdentifier("ai-provider-model") + + if selection == .custom { + SettingsTextField( + "Model ID", + text: modelIDBinding(descriptor: descriptor), + prompt: Text(verbatim: "model-id"), + normalize: { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + ) + .accessibilityIdentifier("ai-provider-model-id") + } + if descriptor?.supportsReasoning == true, !reasoning.effortLevels.isEmpty { + Picker(selection: reasoningBinding(reasoning)) { + AIReasoningPickerItems(reasoning: reasoning) + } label: { + Text("Reasoning") + } + .pickerStyle(.menu) + } + if descriptor?.fetchesModelList == true { + LabeledContent("Model list") { + Button("Reload") { + loadToken += 1 + } + .disabled(loader.isLoading) + } + } + } header: { + Text("Model") + } footer: { + if isLast { + removeAction(provider) + } + } + } + + private func advancedSection(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> some View { + Section { + if descriptor?.allowsMaxOutputTokens == true { + SettingsTextField( + "Maximum output tokens", + text: maxOutputTokensBinding, + prompt: Text("Default"), + validate: { text in + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, SettingsIntegerInput.parse(trimmed) == nil else { return nil } + return String(localized: "Enter a whole number.") + }, + normalize: { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + ) + } + if descriptor?.showsTelemetryToggle == true { + Toggle("Send telemetry to GitHub", isOn: telemetryBinding) + } + } header: { + Text("Advanced") + } footer: { + removeAction(provider) + } + } + + private func removeAction(_ provider: AIProviderConfig) -> some View { + SettingsSectionActions { + Button(String(localized: "Remove Provider…"), role: .destructive) { + paneModel.pendingRemoval = provider + } + .accessibilityIdentifier("ai-provider-remove") + } + } + + private func reasoning( + for provider: AIProviderConfig, + modelID: String, + descriptor: AIProviderDescriptor? + ) -> AIReasoningSupport { + descriptor?.reasoning( + forModelID: modelID, + fetched: loader.models.first { $0.id == modelID }, + preset: provider.preset + ) ?? .unsupported + } + + // What the Reasoning picker shows for a saved effort the model does not take; it is written only when picked. + private func displayedEffort(_ provider: AIProviderConfig, descriptor: AIProviderDescriptor?) -> ReasoningEffort? { + AIProviderDraftRules.effort( + keeping: provider.reasoningEffort, + reasoning: reasoning(for: provider, modelID: provider.model, descriptor: descriptor) + ) + } + + // The model and the effort it allows change together, in one write. + private func selectModel(_ id: String, picked: Bool, descriptor: AIProviderDescriptor?) { + commit { provider in + let current = displayedEffort(provider, descriptor: descriptor) + let reasoning = reasoning(for: provider, modelID: id, descriptor: descriptor) + provider.reasoningEffort = picked + ? AIProviderDraftRules.effort( + afterPicking: current, + reasoning: reasoning, + curated: descriptor?.curatedModel(forID: id, preset: provider.preset) + ) + : AIProviderDraftRules.effort(keeping: current, reasoning: reasoning) + provider.model = id + } + } + + private func selectionBinding(choices: AIModelChoices, descriptor: AIProviderDescriptor?) -> Binding { + let slice = slice + let providerID = providerID + let choseOther = choseOtherModel + return Binding( + get: { choices.selection(for: slice.value.provider(withID: providerID)?.model ?? "", choseOther: choseOther) }, + set: { selection in + switch selection { + case .curated(let id), .fetched(let id): + choseOtherModel = false + selectModel(id, picked: true, descriptor: descriptor) + case .custom: + choseOtherModel = true + } + } + ) + } + + // An empty Model ID is never committed: the field reads the saved model back. + private func modelIDBinding(descriptor: AIProviderDescriptor?) -> Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.model ?? "" }, + set: { typed in + let trimmed = typed.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + selectModel(trimmed, picked: false, descriptor: descriptor) + } + ) + } + + private func reasoningBinding(_ reasoning: AIReasoningSupport) -> Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { + AIProviderDraftRules.effort( + keeping: slice.value.provider(withID: providerID)?.reasoningEffort, + reasoning: reasoning + ) + }, + set: { effort in + commit { $0.reasoningEffort = effort } + } + ) + } + + private var maxOutputTokensBinding: Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.maxOutputTokens.map(String.init) ?? "" }, + set: { typed in + let value = AIProviderEditorModel.maxOutputTokens(from: typed) + commit { $0.maxOutputTokens = value } + } + ) + } + + private var telemetryBinding: Binding { + let slice = slice + let providerID = providerID + return Binding( + get: { slice.value.provider(withID: providerID)?.telemetryEnabled ?? false }, + set: { enabled in + commit { $0.telemetryEnabled = enabled } + } + ) + } +} diff --git a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift b/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift deleted file mode 100644 index 2f02da8516..0000000000 --- a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift +++ /dev/null @@ -1,915 +0,0 @@ -// -// AIProviderDetailSheet.swift -// TablePro -// -// Drill-down detail sheet for configuring a single AI provider. -// - -import AppKit -import SwiftUI - -struct AIProviderDetailSheet: View { - let isNew: Bool - let onSave: (AIProviderConfig, String) -> Void - let onDelete: (() -> Void)? - let onCancel: () -> Void - - private let savedEndpoint: String - private let savedAPIKey: String - - @State private var draft: AIProviderConfig - @State private var apiKey: String - @State private var fetched: [AIModelInfo] = [] - @State private var fetchedListIsCurrent = false - @State private var isFetchingModels = false - @State private var modelFetchError: String? - @State private var modelFetchTask: Task? - @State private var choseOtherModel = false - - @State private var isTesting = false - @State private var testResult: TestResult? - @State private var testTask: Task? - - @ObservedObject private var copilotService = CopilotService.shared - @State private var copilotErrorMessage: String? - - @ObservedObject private var chatGPTCodexService = ChatGPTCodexService.shared - - @ObservedObject private var claudeAgentService = ClaudeAgentService.shared - - @State private var showRemoveConfirmation = false - - enum TestResult: Equatable { - case success - case failure(String) - } - - init( - provider: AIProviderConfig, - initialAPIKey: String, - isNew: Bool, - onSave: @escaping (AIProviderConfig, String) -> Void, - onDelete: (() -> Void)? = nil, - onCancel: @escaping () -> Void - ) { - self.savedEndpoint = provider.endpoint - self.savedAPIKey = initialAPIKey - self._draft = State(initialValue: provider) - self._apiKey = State(initialValue: initialAPIKey) - self.isNew = isNew - self.onSave = onSave - self.onDelete = onDelete - self.onCancel = onCancel - } - - var body: some View { - NavigationStack { - Form { - authSection - connectionSection - modelSection - advancedSection - if let onDelete, !isNew { - deleteSection(onDelete: onDelete) - } - } - .formStyle(.grouped) - .navigationTitle(navigationTitle) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button(String(localized: "Cancel")) { - cancelTasks() - onCancel() - } - .keyboardShortcut(.cancelAction) - } - ToolbarItem(placement: .confirmationAction) { - Button(String(localized: "Save")) { - cancelTasks() - commitModelList() - onSave(normalizedDraft, apiKey) - } - .keyboardShortcut(.defaultAction) - .disabled(!isSaveEnabled) - .accessibilityIdentifier("ai-provider-save") - } - } - .onAppear { - // Before any fetch, so a provider whose list cannot load yet still starts on its curated default. - selectInitialModel() - selectModel(draft.model, picked: false) - if draft.type == .copilot { - Task { - await ensureCopilotRunning() - fetchModels() - } - } else { - if draft.type == .chatgptCodex { - Task { await chatGPTCodexService.refreshAuthState() } - } - if draft.type == .claudeAgent { - Task { await claudeAgentService.performRefresh() } - } - fetchModels() - } - } - .onDisappear { - cancelTasks() - if draft.type == .copilot { - copilotService.stopIfDisallowed(by: AppSettingsManager.shared.ai) - } - } - } - .frame(minWidth: 520, minHeight: 480) - .confirmationDialog( - String(format: String(localized: "Remove “%@”?"), draft.displayName), - isPresented: $showRemoveConfirmation, - titleVisibility: .visible - ) { - Button(String(localized: "Remove Provider"), role: .destructive) { - onDelete?() - } - Button(String(localized: "Cancel"), role: .cancel) {} - } message: { - Text(String(localized: "The provider configuration and stored API key will be deleted.")) - } - } - - private var navigationTitle: String { - if isNew { - return String(format: String(localized: "Add %@"), draft.kindName) - } - return draft.displayName - } - - private var needsModelChoice: Bool { - AIProviderDraftRules.needsModelChoice(model: draft.model, fetched: fetched) - } - - private var isSaveEnabled: Bool { - guard !needsModelChoice else { return false } - switch draft.authStyle { - case .apiKey: - return !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - case .optionalApiKey, .oauth, .none: - return true - } - } - - private var normalizedDraft: AIProviderConfig { - var provider = draft - provider.model = draft.model.trimmingCharacters(in: .whitespacesAndNewlines) - provider.endpoint = AIProviderDraftRules.endpoint(draft.endpoint, defaultEndpoint: draft.defaultEndpoint) - return provider - } - - // MARK: - Auth - - @ViewBuilder - private var authSection: some View { - switch draft.authStyle { - case .apiKey, .optionalApiKey: - apiKeyAuthSection - case .oauth: - switch descriptor?.oauthFlowKind { - case .deviceCode: - copilotAuthSection - case .browserRedirect: - chatGPTCodexAuthSection - case .none: - EmptyView() - } - case .none: - if draft.type == .claudeAgent { - claudeAgentAuthSection - } else { - EmptyView() - } - } - } - - @ViewBuilder - private var claudeAgentAuthSection: some View { - Section { - HStack(spacing: 8) { - AIProviderStatusLabel(status: claudeAgentStatus) - .font(.callout) - Spacer() - Button(String(localized: "Recheck")) { - claudeAgentService.refreshStatus() - } - .disabled(claudeAgentService.isRefreshing) - } - switch claudeAgentService.state { - case .signedIn(_, let plan?) where !plan.isEmpty: - Text(String(format: String(localized: "Plan: %@"), plan)) - .font(.caption) - .foregroundStyle(.secondary) - case .outdated: - Text(String(format: String(localized: "Version %@ or newer is required."), ClaudeAgentCLI.minimumVersion)) - .font(.caption) - .foregroundStyle(.secondary) - default: - EmptyView() - } - if let command = claudeAgentService.remedyCommand { - HStack { - Text(command) - .font(.system(.caption, design: .monospaced)) - .textSelection(.enabled) - Spacer() - Button(String(localized: "Copy")) { - copyToPasteboard(command) - } - } - } - } header: { - Text("Claude Code") - } footer: { - Text("Runs the claude command line tool so chat bills against your Claude subscription. Database tools need the MCP server turned on in Settings > MCP.") - .font(.caption) - .foregroundStyle(.secondary) - } - - ClaudeAgentDisclosureSection() - } - - private var claudeAgentStatus: AIProviderStatus { - AIProviderStatus.resolve( - provider: draft, - hasAPIKey: false, - oauthState: nil, - serviceError: nil, - claudeAgent: claudeAgentService.state - ) - } - - private var apiKeyAuthSection: some View { - Section { - SecureField(String(localized: "API Key"), text: $apiKey) - .onChange(of: apiKey) { _ in - scheduleFetchModels() - testResult = nil - } - HStack { - Spacer() - Button { - testProvider() - } label: { - HStack(spacing: 6) { - if isTesting { - ProgressView().controlSize(.small) - } - Text("Test Connection") - } - } - .disabled(isTesting || (draft.authStyle == .apiKey && apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)) - } - if case .success = testResult { - NoticeLabel(String(localized: "Connection successful"), severity: .success) - .font(.caption) - } else if case .failure(let message) = testResult { - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(3) - } - } header: { - Text("Authentication") - } - } - - private func copyToPasteboard(_ string: String) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(string, forType: .string) - } - - private var copilotAuthSection: some View { - Section { - switch copilotService.authState { - case .signedOut: - signInRow - - case .signingIn(let userCode, _): - VStack(alignment: .leading, spacing: 8) { - Text("Enter this code on GitHub:") - Text(userCode) - .font(.system(.title2, design: .monospaced)) - .fontWeight(.bold) - .textSelection(.enabled) - Text("The code has been copied to your clipboard.") - .font(.caption) - .foregroundStyle(.secondary) - Text("The code expires in 15 minutes.") - .font(.caption) - .foregroundStyle(.secondary) - HStack(spacing: 8) { - Button("Complete Sign In") { - Task { await completeCopilotSignIn() } - } - .buttonStyle(.borderedProminent) - Button(String(localized: "Cancel"), role: .cancel) { - Task { await copilotService.signOut() } - } - } - } - - case .signedIn(let username): - HStack { - NoticeLabel(String(format: String(localized: "Signed in as %@"), username), severity: .success) - Spacer() - Button(String(localized: "Sign Out")) { - Task { await copilotService.signOut() } - } - } - } - - if let message = copilotErrorMessage ?? copilotService.statusMessage { - NoticeLabel(message, severity: .error) - .font(.caption) - } - - statusRow - } header: { - Text("Account") - } - } - - private var signInRow: some View { - HStack { - Text("Authentication required") - .foregroundStyle(.secondary) - Spacer() - Button(String(localized: "Sign in with GitHub")) { - Task { await copilotSignIn() } - } - .disabled(copilotService.status != .running) - } - } - - private var chatGPTCodexAuthSection: some View { - Section { - switch chatGPTCodexService.authState { - case .signedOut: - chatGPTCodexSignInRows - - case .signingIn: - HStack(spacing: 8) { - ProgressView().controlSize(.small) - Text("Opening your browser to sign in…") - .font(.caption) - .foregroundStyle(.secondary) - } - - case .signedIn(let email, let planType): - VStack(alignment: .leading, spacing: 6) { - HStack { - NoticeLabel(chatGPTCodexSignedInLabel(email: email), severity: .success) - Spacer() - Button(String(localized: "Sign Out")) { - Task { await chatGPTCodexService.signOut() } - } - } - if let planType, !planType.isEmpty { - Text(String(format: String(localized: "Plan: %@"), planType)) - .font(.caption) - .foregroundStyle(.secondary) - } - } - } - - if let message = chatGPTCodexService.errorMessage { - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(3) - } - } header: { - Text("Account") - } footer: { - Text("Access uses your ChatGPT subscription (Plus, Pro, Business, or Enterprise) and follows OpenAI's terms. This is an unofficial interface that may change.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - private var chatGPTCodexSignInRows: some View { - VStack(alignment: .leading, spacing: 8) { - HStack { - Text("Sign in to use your ChatGPT subscription") - .foregroundStyle(.secondary) - Spacer() - Button(String(localized: "Sign in with ChatGPT")) { - Task { await chatGPTCodexService.signIn() } - } - .buttonStyle(.borderedProminent) - } - Button(String(localized: "Import from Codex CLI")) { - Task { await chatGPTCodexService.importFromCodexCLI() } - } - .buttonStyle(.borderless) - .controlSize(.small) - } - } - - private func chatGPTCodexSignedInLabel(email: String) -> String { - email.isEmpty - ? String(localized: "Signed in") - : String(format: String(localized: "Signed in as %@"), email) - } - - @ViewBuilder - private var statusRow: some View { - switch copilotService.status { - case .stopped: - Label("Service stopped", systemImage: "circle") - .foregroundStyle(.secondary) - .font(.caption) - case .starting: - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text("Starting service…") - .font(.caption) - .foregroundStyle(.secondary) - } - case .running: - EmptyView() - case .error(let message): - NoticeLabel(message, severity: .error) - .font(.caption) - .lineLimit(2) - } - } - - // MARK: - Connection - - @ViewBuilder - private var connectionSection: some View { - if shouldShowConnectionSection { - Section { - if allowsNameField { - TextField(String(localized: "Name"), text: $draft.name) - .accessibilityIdentifier("ai-provider-name") - } - if allowsEndpointField { - TextField( - String(localized: "Base URL"), - text: $draft.endpoint, - prompt: Text(draft.defaultEndpoint) - ) - .accessibilityIdentifier("ai-provider-base-url") - .onChange(of: draft.endpoint) { _ in - scheduleFetchModels() - testResult = nil - } - endpointFootnote - } - } header: { - Text("Connection") - } - } - } - - /// Placeholder text disappears as soon as the field is typed in, so the rule the server's own - /// documentation follows is spelled out beside the field, and the URL it resolves to is shown - /// back rather than left to be inferred. - @ViewBuilder - private var endpointFootnote: some View { - VStack(alignment: .leading, spacing: 2) { - Text("Include the version segment your server uses, such as /v1 or /v4.") - .font(.caption) - .foregroundStyle(.secondary) - if let resolvedChatURL { - Text(resolvedChatURL) - .textSelection(.enabled) - .font(.caption) - .foregroundStyle(.secondary) - } - if resolvedEndpoint?.isPlaintextToRemoteHost == true { - NoticeLabel(cleartextCaution) - .font(.caption) - .lineLimit(2) - } - } - } - - private var modelListBlocker: AIModelListFetchGate.Blocker? { - AIProviderDraftRules.modelListBlocker(descriptor: descriptor, draft: draft, apiKey: apiKey) - } - - /// Ollama, llama.cpp, MLX and a keyless Custom server send no authorization header at all, so - /// naming the key there would warn about something that is not happening. - private var cleartextCaution: String { - guard draft.authStyle.usesAPIKey, - !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - else { - return String(localized: "Requests to this host are sent unencrypted over http.") - } - return String(localized: "Your API key is sent unencrypted over http to this host.") - } - - private var resolvedEndpoint: AIEndpoint? { - AIEndpoint(normalizedDraft.endpoint, style: draft.type.endpointStyle) - } - - private var resolvedChatURL: String? { - let style = draft.type.endpointStyle - guard let url = resolvedEndpoint?.chatURL(model: draft.model, style: style) else { return nil } - return url.absoluteString - } - - private var allowsNameField: Bool { - descriptor?.allowsNameConfiguration == true - } - - private var allowsEndpointField: Bool { - descriptor?.allowsEndpointConfiguration == true - } - - private var shouldShowConnectionSection: Bool { - allowsNameField || allowsEndpointField - } - - // MARK: - Model - - private var descriptor: AIProviderDescriptor? { - AIProviderRegistry.shared.descriptor(for: draft.type.rawValue) - } - - private var curatedModels: [CuratedModel] { - descriptor?.curatedModels(for: draft.preset) ?? [] - } - - private var fetchedModels: [String] { - fetched.map(\.id) - } - - private func reasoning(forModelID id: String) -> AIReasoningSupport { - descriptor?.reasoning( - forModelID: id, - fetched: fetched.first(where: { $0.id == id }), - preset: draft.preset - ) ?? .unsupported - } - - private var reasoningForCurrentModel: AIReasoningSupport { - reasoning(forModelID: draft.model) - } - - private var effortLevelsForCurrentModel: [ReasoningEffort] { - reasoningForCurrentModel.effortLevels - } - - private var showsReasoningPicker: Bool { - guard descriptor?.supportsReasoning == true else { return false } - return !effortLevelsForCurrentModel.isEmpty - } - - private var isCustomModel: Bool { - !curatedModels.contains(where: { $0.id == draft.model }) - && !fetchedModels.contains(draft.model) - } - - private var modelSection: some View { - Section { - modelPicker - if isCustomModel { - TextField(String(localized: "Model ID"), text: typedModelBinding) - .textFieldStyle(.roundedBorder) - } - if showsReasoningPicker { - reasoningPicker - } - modelFetchStatus - } header: { - Text("Model") - } - } - - private var modelPicker: some View { - Picker(String(localized: "Model"), selection: modelSelectionBinding) { - if !curatedModels.isEmpty { - Section { - ForEach(curatedModels) { model in - Text(model.displayName).tag(ModelSelection.curated(model.id)) - } - } - } - let fetchedFiltered = fetchedModels.filter { id in - !curatedModels.contains(where: { $0.id == id }) - } - if !fetchedFiltered.isEmpty { - Section { - ForEach(fetchedFiltered, id: \.self) { id in - Text(id).tag(ModelSelection.fetched(id)) - } - } - } - Text(String(localized: "Other…")).tag(ModelSelection.custom) - } - .pickerStyle(.menu) - } - - private enum ModelSelection: Hashable { - case curated(String) - case fetched(String) - case custom - } - - private var modelSelectionBinding: Binding { - Binding( - get: { - if curatedModels.contains(where: { $0.id == draft.model }) { - return .curated(draft.model) - } - if fetchedModels.contains(draft.model) { - return .fetched(draft.model) - } - return .custom - }, - set: { newValue in - switch newValue { - case .curated(let id), .fetched(let id): - choseOtherModel = false - selectModel(id, picked: true) - case .custom: - choseOtherModel = true - if curatedModels.contains(where: { $0.id == draft.model }) || fetchedModels.contains(draft.model) { - selectModel("", picked: false) - } - } - } - ) - } - - private var typedModelBinding: Binding { - Binding( - get: { draft.model }, - set: { typed in - choseOtherModel = true - selectModel(typed, picked: false) - } - ) - } - - // The model and the effort it allows change together, in one write. - private func selectModel(_ id: String, picked: Bool) { - var next = draft - next.model = id - next.reasoningEffort = picked - ? AIProviderDraftRules.effort( - afterPicking: draft.reasoningEffort, - reasoning: reasoning(forModelID: id), - curated: curatedModels.first(where: { $0.id == id }) - ) - : AIProviderDraftRules.effort(keeping: draft.reasoningEffort, reasoning: reasoning(forModelID: id)) - draft = next - } - - private var reasoningPicker: some View { - Picker(String(localized: "Reasoning"), selection: $draft.reasoningEffort) { - if !reasoningForCurrentModel.isMandatory { - Text(String(localized: "Off")).tag(ReasoningEffort?.none) - } - ForEach(effortLevelsForCurrentModel) { effort in - Text(effort.displayName).tag(Optional(effort)) - } - } - .pickerStyle(.menu) - } - - @ViewBuilder - private var modelFetchStatus: some View { - if isFetchingModels { - HStack(spacing: 6) { - ProgressView().controlSize(.small) - Text(String(localized: "Fetching models…")) - .font(.caption) - .foregroundStyle(.secondary) - } - } - if let modelFetchError { - HStack { - NoticeLabel(modelFetchError, severity: .error) - .font(.caption) - .lineLimit(2) - Spacer() - Button(String(localized: "Reload")) { - fetchModels() - } - .buttonStyle(.borderless) - .controlSize(.small) - } - } - if modelListBlocker == .missingAPIKey { - Text("Enter an API key to load this provider's models.") - .font(.caption) - .foregroundStyle(.secondary) - } - if needsModelChoice { - Text("Pick a model to save this provider.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - - // MARK: - Advanced - - @ViewBuilder - private var advancedSection: some View { - if showsMaxOutputTokens || showsTelemetryToggle { - Section { - if showsMaxOutputTokens { - LabeledContent("Max output tokens") { - TextField("", text: maxOutputTokensBinding) - .frame(width: 100) - .multilineTextAlignment(.trailing) - } - } - if showsTelemetryToggle { - Toggle("Send telemetry to GitHub", isOn: $draft.telemetryEnabled) - } - } header: { - Text("Advanced") - } - } - } - - private var showsMaxOutputTokens: Bool { - descriptor?.allowsMaxOutputTokens == true - } - - private var showsTelemetryToggle: Bool { - descriptor?.showsTelemetryToggle == true - } - - private var maxOutputTokensBinding: Binding { - Binding( - get: { - guard let value = draft.maxOutputTokens else { return "" } - return String(value) - }, - set: { newValue in - let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { - draft.maxOutputTokens = nil - } else if let value = Int(trimmed), value > 0 { - draft.maxOutputTokens = value - } - } - ) - } - - // MARK: - Delete - - private func deleteSection(onDelete: @escaping () -> Void) -> some View { - Section { - Button(role: .destructive) { - showRemoveConfirmation = true - } label: { - Label(String(localized: "Remove Provider"), systemImage: "trash") - .frame(maxWidth: .infinity) - } - } - } - - // MARK: - Tasks - - private func cancelTasks() { - modelFetchTask?.cancel() - modelFetchTask = nil - testTask?.cancel() - testTask = nil - } - - private func ensureCopilotRunning() async { - await copilotService.start() - } - - private func copilotSignIn() async { - copilotErrorMessage = nil - do { - try await copilotService.signIn() - } catch { - copilotErrorMessage = error.localizedDescription - } - } - - private func completeCopilotSignIn() async { - copilotErrorMessage = nil - do { - try await copilotService.completeSignIn() - } catch { - copilotErrorMessage = error.localizedDescription - } - } - - private func commitModelList() { - let update = AIProviderDraftRules.catalogUpdate( - listIsCurrent: fetchedListIsCurrent, - listIsEmpty: fetched.isEmpty, - connectionChanged: normalizedDraft.endpoint != savedEndpoint || apiKey != savedAPIKey - ) - switch update { - case .store: - AIModelCatalog.shared.store(providerID: draft.id, models: fetched) - case .remove: - AIModelCatalog.shared.remove(providerID: draft.id) - case .refetch: - AIModelCatalog.shared.remove(providerID: draft.id) - guard descriptor?.fetchesModelList == true else { return } - let providerID = draft.id - let transport = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - Task { await AIModelCatalog.shared.refresh(providerID: providerID, using: transport) } - case .keep: - break - } - } - - private func scheduleFetchModels() { - fetchedListIsCurrent = false - modelFetchTask?.cancel() - modelFetchTask = Task { - try? await Task.sleep(nanoseconds: 500_000_000) - guard !Task.isCancelled else { return } - fetchModels() - } - } - - private func fetchModels() { - switch modelListBlocker { - case .notFetchable: - fetched = [] - fetchedListIsCurrent = false - modelFetchError = nil - isFetchingModels = false - selectInitialModel() - return - case .missingEndpoint, .missingAPIKey: - fetched = [] - fetchedListIsCurrent = false - modelFetchError = nil - isFetchingModels = false - return - case nil: - break - } - - let provider = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - isFetchingModels = true - modelFetchError = nil - - modelFetchTask?.cancel() - modelFetchTask = Task { - do { - let models = try await provider.fetchAvailableModels() - guard !Task.isCancelled else { return } - fetched = models - fetchedListIsCurrent = true - selectInitialModel() - isFetchingModels = false - } catch { - guard !Task.isCancelled else { return } - /// The list on screen was fetched with the previous key or Base URL, so it does not - /// describe the server that just failed. - fetched = [] - fetchedListIsCurrent = false - modelFetchError = error.localizedDescription - isFetchingModels = false - } - } - } - - private func selectInitialModel() { - guard draft.model.isEmpty, !choseOtherModel, - let initial = AIProviderDraftRules.initialModel(curated: curatedModels, fetched: fetched) - else { return } - selectModel(initial, picked: false) - } - - func testProvider() { - let trimmed = apiKey.trimmingCharacters(in: .whitespacesAndNewlines) - if draft.authStyle == .apiKey, trimmed.isEmpty { - testResult = .failure(String(localized: "API key is required")) - return - } - - let provider = AIProviderFactory.makeUncachedProvider(for: normalizedDraft, apiKey: apiKey) - isTesting = true - testResult = nil - - testTask?.cancel() - testTask = Task { - do { - let success = try await provider.testConnection() - guard !Task.isCancelled else { return } - isTesting = false - testResult = success - ? .success - : .failure(String(localized: "Connection test failed")) - } catch { - guard !Task.isCancelled else { return } - isTesting = false - testResult = .failure(error.localizedDescription) - } - } - } -} diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index de3289c96d..457a2f0fbe 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -1,23 +1,117 @@ -// -// AISettingsView.swift -// TablePro -// - import Combine import SwiftUI +// Shared by the AI root and its provider pages for the window's life: key presence, account checks, the pending removal. +@MainActor +final class AISettingsPaneModel: ObservableObject { + @Published var pendingRemoval: AIProviderConfig? + @Published private(set) var providersWithKey: Set = [] + + private var accountChecks: [AIProviderType: Date] = [:] + private let now: () -> Date + + static let accountCheckInterval: TimeInterval = 60 + + init(now: @escaping () -> Date = Date.init) { + self.now = now + } + + func hasKey(_ providerID: UUID) -> Bool { + providersWithKey.contains(providerID) + } + + func setHasKey(_ hasKey: Bool, for providerID: UUID) { + if hasKey { + providersWithKey.insert(providerID) + } else { + providersWithKey.remove(providerID) + } + } + + // No Keychain read while AI is off. + func refreshKeys(for settings: AISettings) async { + guard settings.enabled else { return } + let ids = settings.providers.filter { $0.authStyle.usesAPIKey }.map(\.id) + let found = await AIProviderKeychain.providersWithKey(ids) + if found != providersWithKey { + providersWithKey = found + } + } + + // A check spawns the claude tool or reads the ChatGPT tokens, so a revisit within a minute reuses the last answer. + func claimAccountChecks(_ types: Set) -> Set { + let current = now() + let due = types.filter { type in + guard let last = accountChecks[type] else { return true } + return current.timeIntervalSince(last) >= Self.accountCheckInterval + } + for type in due { + accountChecks[type] = current + } + return due + } + + func refreshAccounts(_ types: Set) async { + let due = claimAccountChecks(types) + guard !due.isEmpty else { return } + let chatGPT = ChatGPTCodexService.shared + let claudeAgent = ClaudeAgentService.shared + await withTaskGroup(of: Void.self) { group in + if due.contains(.chatgptCodex) { + group.addTask { await chatGPT.refreshAuthState() } + } + if due.contains(.claudeAgent) { + group.addTask { await claudeAgent.performRefresh() } + } + } + } + + func remove(_ provider: AIProviderConfig, from slice: SettingsSlice, navigation: SettingsNavigationModel) { + let id = provider.id + AIKeyStorage.shared.deleteAPIKey(for: id) + AIProviderFactory.invalidateCache(for: id) + AIModelCatalog.shared.remove(providerID: id) + slice.value = slice.value.removingProvider(id) + providersWithKey.remove(id) + navigation.removeRoute(.aiProvider(id)) + } +} + +extension View { + func aiProviderRemovalAlert( + pending: Binding, + onConfirm: @escaping (AIProviderConfig) -> Void + ) -> some View { + alert( + pending.wrappedValue.map { String(format: String(localized: "Remove “%@”?"), $0.displayName) } ?? "", + isPresented: Binding( + get: { pending.wrappedValue != nil }, + set: { if !$0 { pending.wrappedValue = nil } } + ), + presenting: pending.wrappedValue + ) { provider in + Button(String(localized: "Remove"), role: .destructive) { + pending.wrappedValue = nil + onConfirm(provider) + } + Button(String(localized: "Cancel"), role: .cancel) { + pending.wrappedValue = nil + } + } message: { provider in + Text(verbatim: provider.authStyle.usesAPIKey + ? String(localized: "Its settings are removed from every Mac that syncs settings, and its API key is deleted from the Keychain.") + : String(localized: "Its settings are removed from every Mac that syncs settings.")) + } + } +} + struct AISettingsView: View { @Binding var settings: AISettings + @ObservedObject var visit: SettingsPaneVisit - @State private var editingProviderID: UUID? - @State private var addingProvider: AIProviderConfig? - @State private var pendingDeleteID: UUID? - // Probed on appear, not on every body pass (the whole AI form re-evaluates on any settings change). - @State private var appleIntelligence: AppleIntelligenceAvailability = .unavailable(.unknown) - @ObservedObject private var chatGPTCodexService = ChatGPTCodexService.shared - @ObservedObject private var claudeAgentService = ClaudeAgentService.shared - @ObservedObject private var copilotService = CopilotService.shared - @State private var providersWithKey: Set = [] + @EnvironmentObject private var paneModel: AISettingsPaneModel + @State private var addSession: AIProviderAddSession? + @State private var appleIntelligence: AppleIntelligenceAvailability? var body: some View { Form { @@ -25,459 +119,411 @@ struct AISettingsView: View { if settings.enabled { activeProviderSection providersSection - appleIntelligenceSection + if showsAppleIntelligence { + appleIntelligenceSection + } inlineSuggestionsSection agentSection contextSection - CustomSlashCommandsSection(storage: CustomSlashCommandStorage.shared) - privacySection + Section { + SlashCommandsDrillRow(storage: CustomSlashCommandStorage.shared) + } } + privacySection } .formStyle(.grouped) - .task(id: settings.enabled ? settings.providers.map(\.id) : []) { refreshKeyAvailability() } - .task(id: AIProviderAccountProbes.types(toProbe: settings)) { - await refreshAccountStatus(of: AIProviderAccountProbes.types(toProbe: settings)) + .task(id: visit.count) { + appleIntelligence = SystemOnDeviceLanguageModel().availability } - .sheet(item: editingProviderBinding) { provider in - AIProviderDetailSheet( - provider: provider, - initialAPIKey: AIKeyStorage.shared.loadAPIKey(for: provider.id) ?? "", - isNew: false, - onSave: { saved, apiKey in - saveProvider(saved, apiKey: apiKey, isNew: false) - editingProviderID = nil - }, - // The sheet already asked; the parent alert is for the context menu only. - onDelete: { - removeProvider(provider.id) - editingProviderID = nil - }, - onCancel: { - editingProviderID = nil - } - ) + .task(id: KeyRefresh(visit: visit.count, enabled: settings.enabled, providerIDs: settings.providers.map(\.id))) { + await paneModel.refreshKeys(for: settings) } - .sheet(item: $addingProvider) { provider in - AIProviderDetailSheet( - provider: provider, - initialAPIKey: "", - isNew: true, - onSave: { saved, apiKey in - saveProvider(saved, apiKey: apiKey, isNew: true) - addingProvider = nil - }, - onDelete: nil, - onCancel: { - addingProvider = nil - } - ) + .task(id: AccountRefresh(visit: visit.count, types: AIProviderAccountProbes.types(toProbe: settings))) { + await paneModel.refreshAccounts(AIProviderAccountProbes.types(toProbe: settings)) } - .alert(deleteAlertTitle, isPresented: deleteAlertBinding) { - Button(String(localized: "Remove"), role: .destructive) { - if let id = pendingDeleteID { - removeProvider(id) - } - pendingDeleteID = nil + .sheet(item: $addSession) { session in + AIProviderAddSheet(session: session) { provider, hasKey in + settings = settings.upserting(provider, makeActiveIfNone: true) + paneModel.setHasKey(hasKey, for: provider.id) } - Button(String(localized: "Cancel"), role: .cancel) { - pendingDeleteID = nil - } - } message: { - Text(String(localized: "The API key will be permanently deleted.")) } } - // MARK: - Enable + private struct KeyRefresh: Equatable { + let visit: Int + let enabled: Bool + let providerIDs: [UUID] + } + + private struct AccountRefresh: Equatable { + let visit: Int + let types: Set + } private var enableSection: some View { Section { - Toggle("Enable AI Features", isOn: $settings.enabled) + Toggle(isOn: $settings.enabled) { + Text("Enable AI features") + Text("Chat, Agent mode, inline suggestions and query actions such as Explain and Optimize.") + } + .accessibilityIdentifier("settings-ai-enabled") } } - // MARK: - Active Provider - private var activeProviderSection: some View { Section { - Picker("Active Provider", selection: $settings.activeProviderID) { + Picker(selection: activeProviderBinding) { Text("None").tag(UUID?.none) ForEach(settings.providers) { provider in Label { - Text(provider.displayName) + Text(verbatim: provider.displayName) } icon: { provider.icon.menuImage() } .labelStyle(.titleAndIcon) .tag(UUID?.some(provider.id)) } + } label: { + Text("Active provider") } .pickerStyle(.menu) .disabled(settings.providers.isEmpty) + .accessibilityIdentifier("settings-ai-active-provider") } } - // MARK: - Providers + // An id whose provider another Mac removed reads as None, the provider that answers. + private var activeProviderBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.activeProvider?.id }, + set: { settings.wrappedValue.activeProviderID = $0 } + ) + } private var providersSection: some View { Section { if settings.providers.isEmpty { - emptyProvidersRow + VStack(alignment: .leading, spacing: 2) { + Text("No providers") + Text("Add one to use chat and Agent mode.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) } else { ForEach(settings.providers) { provider in - Button { - editingProviderID = provider.id - } label: { - providerRow(provider) - } - .buttonStyle(.plain) - .contentShape(Rectangle()) - .contextMenu { - Button(String(localized: "Edit")) { - editingProviderID = provider.id - } - Button(String(localized: "Set as Active")) { - settings.activeProviderID = provider.id - } - .disabled(settings.activeProviderID == provider.id) - Divider() - Button(String(localized: "Remove"), role: .destructive) { - pendingDeleteID = provider.id - } - } + providerLink(provider) } } - addProviderMenu } header: { Text("Providers") + } footer: { + SettingsSectionActions { + AIProviderAddMenuButton { choice in + let registry = AIProviderRegistry.shared + addSession = AIProviderAddSession( + provider: choice.makeProvider { registry.descriptor(for: $0.rawValue) } + ) + } + } } } - private var emptyProvidersRow: some View { - HStack { - Spacer() - Text("No providers configured") - .foregroundStyle(.secondary) - .font(.callout) - Spacer() + private func providerLink(_ provider: AIProviderConfig) -> some View { + let isActive = provider.id == settings.activeProvider?.id + return NavigationLink(value: SettingsRoute.aiProvider(provider.id)) { + AIProviderRow(provider: provider, isActive: isActive, hasKey: paneModel.hasKey(provider.id)) } - .padding(.vertical, 6) - } - - private func providerRow(_ provider: AIProviderConfig) -> some View { - HStack(spacing: 10) { - ZStack { - if provider.id == settings.activeProviderID { - Image(systemName: "checkmark") - .font(.caption.bold()) - .foregroundStyle(Color.accentColor) - .accessibilityLabel(String(localized: "Active")) - } + .contextMenu { + Button(String(localized: "Set as Active")) { + settings.activeProviderID = provider.id } - .frame(width: 14) - - BrandIconView(icon: provider.icon) - .foregroundStyle(.secondary) - .frame(width: 16, height: 16) - .frame(width: 20) - - VStack(alignment: .leading, spacing: 2) { - Text(provider.displayName) - .fontWeight(.regular) - AIProviderStatusLabel(status: status(for: provider), showsReadySymbol: false) - .font(.caption) + .disabled(isActive) + Divider() + Button(String(localized: "Remove…"), role: .destructive) { + paneModel.pendingRemoval = provider } - - Spacer() } - .padding(.vertical, 2) - .task { - // Sign-in state lives in the language server, so a configured Copilot row has nothing - // true to show until it runs. - guard provider.type == .copilot else { return } - await copilotService.start() - } - } - - private var addProviderMenu: some View { - Menu { - ForEach(orderedAddableTypes, id: \.self) { type in - Button { - addingProvider = makeNewProvider(type: type) - } label: { - Label { - Text(type.displayName) - } icon: { - type.icon.menuImage() - } - .labelStyle(.titleAndIcon) - } - } - ForEach(AIProviderPreset.all) { preset in - Button { - addingProvider = AIProviderConfig(preset: preset) - } label: { - Label { - Text(preset.displayName) - } icon: { - preset.icon.menuImage() - } - .labelStyle(.titleAndIcon) + .accessibilityActions { + if !isActive { + Button(String(localized: "Set as Active")) { + settings.activeProviderID = provider.id } } - Divider() - Button { - addingProvider = makeNewProvider(type: .custom) - } label: { - Label(String(localized: "Add Custom Provider…"), systemImage: AIProviderType.custom.icon.fallbackSystemImage) - .labelStyle(.titleAndIcon) + Button(String(localized: "Remove")) { + paneModel.pendingRemoval = provider } - } label: { - Label(String(localized: "Add Provider…"), systemImage: "plus") } - .menuStyle(.button) - .buttonStyle(.borderless) - .fixedSize() + .accessibilityIdentifier("settings-ai-provider-\(provider.id.uuidString)") } - private var orderedAddableTypes: [AIProviderType] { - AIProviderType.allCases.filter { type in - type != .custom && AIProviderRegistry.shared.descriptor(for: type.rawValue) != nil + private var showsAppleIntelligence: Bool { + if settings.useAppleIntelligence { return true } + switch appleIntelligence { + case nil, .unavailable(.requiresNewerMacOS), .unavailable(.deviceNotEligible): + return false + default: + return true } } - // MARK: - Apple Intelligence - private var appleIntelligenceSection: some View { Section { - Toggle("Use for inline suggestions and query actions", isOn: $settings.useAppleIntelligence) - .disabled(!appleIntelligence.isAvailable && !settings.useAppleIntelligence) + Toggle(isOn: $settings.useAppleIntelligence) { + Text("Use for inline suggestions and query actions") + if let appleIntelligence { + Text(verbatim: appleIntelligence.unavailableExplanation + ?? String(localized: "Runs on this Mac and sends nothing over the network. Chat and Agent mode keep the active provider.")) + } + } + .disabled(appleIntelligence?.isAvailable == false && !settings.useAppleIntelligence) + .accessibilityIdentifier("settings-ai-apple-intelligence") } header: { - Text(AppleIntelligenceAvailability.displayName) - } footer: { - Text(Self.appleIntelligenceFooter(appleIntelligence)) + Text(verbatim: AppleIntelligenceAvailability.displayName) } - .onAppear { appleIntelligence = SystemOnDeviceLanguageModel().availability } - } - - private static func appleIntelligenceFooter(_ availability: AppleIntelligenceAvailability) -> String { - if let unavailable = availability.unavailableExplanation { return unavailable } - return String(localized: "Inline suggestions and Review, Explain, Optimize and Fix run on this Mac and send nothing over the network.") - + " " + String(localized: "The chat and Agent mode keep the active provider.") } - // MARK: - Inline Suggestions - private var canSuggestInline: Bool { settings.hasActiveProvider || settings.useAppleIntelligence } private var inlineSuggestionsSection: some View { Section { - Toggle("Enable inline suggestions while typing", isOn: $settings.inlineSuggestionsEnabled) - .disabled(!canSuggestInline) - .help(canSuggestInline - ? "" - : String(localized: "Configure an active provider or turn on Apple Intelligence to enable inline suggestions.")) - Stepper( - String(format: String(localized: "Debounce: %d ms"), settings.inlineSuggestionDebounceMs), - value: $settings.inlineSuggestionDebounceMs, - in: AISettings.inlineSuggestionDebounceRange, - step: 50 + Toggle(isOn: $settings.inlineSuggestionsEnabled) { + Text("Suggest SQL while typing") + if canSuggestInline { + Text("Press Tab to accept, Escape to dismiss.") + } else { + Text("Choose an active provider or turn on Apple Intelligence first.") + } + } + .disabled(!canSuggestInline && !settings.inlineSuggestionsEnabled) + .accessibilityIdentifier("settings-ai-inline") + + SettingsNumberField( + "Delay", + value: debounceBinding, + range: AISettings.inlineSuggestionDebounceRange, + step: 50, + unit: "ms", + identifier: "settings-ai-inline-delay" ) .disabled(!settings.inlineSuggestionsEnabled) } header: { Text("Inline Suggestions") - } footer: { - Text("Inline SQL suggestions appear as you type. Press Tab to accept, Escape to dismiss.") - .font(.caption) - .foregroundStyle(.secondary) } } - // MARK: - Agent + private var debounceBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedInlineSuggestionDebounceMs }, + set: { settings.wrappedValue.inlineSuggestionDebounceMs = $0 } + ) + } private var agentSection: some View { Section { - Toggle("Limit tool calls per reply", isOn: $settings.maxToolRoundtripsEnabled) - Stepper( - String(format: String(localized: "Tool call limit: %d"), settings.maxToolRoundtrips), - value: $settings.maxToolRoundtrips, - in: AISettings.maxToolRoundtripsRange, - step: 5 + Toggle(isOn: $settings.maxToolRoundtripsEnabled) { + Text("Limit tool calls per reply") + Text("Agent mode pauses at the limit so you can continue. A higher limit uses more tokens per reply.") + } + .accessibilityIdentifier("settings-ai-tool-limit-enabled") + + SettingsNumberField( + "Tool call limit", + value: toolLimitBinding, + range: AISettings.maxToolRoundtripsRange, + step: 5, + identifier: "settings-ai-tool-limit" ) .disabled(!settings.maxToolRoundtripsEnabled) } header: { Text("Agent") - } footer: { - Text("Agent mode calls tools in a loop until it finishes or hits this limit, then pauses so you can continue. Raising it costs more tokens per reply.") - .font(.caption) - .foregroundStyle(.secondary) } } - // MARK: - Context + private var toolLimitBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedMaxToolRoundtrips }, + set: { settings.wrappedValue.maxToolRoundtrips = $0 } + ) + } private var contextSection: some View { Section { Toggle("Include database schema", isOn: $settings.includeSchema) + .accessibilityIdentifier("settings-ai-include-schema") + SettingsNumberField( + "Maximum tables", + subtitle: "Used for chat context, {{schema}} commands and Copilot suggestions.", + value: maxTablesBinding, + range: AISettings.maxSchemaTablesRange, + step: 1, + identifier: "settings-ai-max-tables" + ) Toggle("Include current query", isOn: $settings.includeCurrentQuery) + .accessibilityIdentifier("settings-ai-include-query") Toggle("Include query results", isOn: $settings.includeQueryResults) - Stepper( - String(format: String(localized: "Max schema tables: %d"), settings.maxSchemaTables), - value: $settings.maxSchemaTables, - in: 1...100 - ) + .accessibilityIdentifier("settings-ai-include-results") } header: { Text("Context") } } - // MARK: - Privacy + private var maxTablesBinding: Binding { + let settings = $settings + return Binding( + get: { settings.wrappedValue.clampedMaxSchemaTables }, + set: { settings.wrappedValue.maxSchemaTables = $0 } + ) + } + // Shown with AI off too: MCP clients read the same policy. private var privacySection: some View { Section { - Picker("Connection policy", selection: $settings.defaultConnectionPolicy) { + Picker(selection: $settings.defaultConnectionPolicy) { ForEach(AIConnectionPolicy.allCases) { policy in - Text(policy.displayName).tag(policy) + Text(verbatim: policy.displayName).tag(policy) } + } label: { + Text("Default AI policy") + Text("Applies to connections set to Use Default, in AI features and for MCP clients.") } .pickerStyle(.menu) + .accessibilityIdentifier("settings-ai-connection-access") } header: { Text("Privacy") } } +} - // MARK: - Bindings +private struct SlashCommandsDrillRow: View { + @ObservedObject var storage: CustomSlashCommandStorage - private var editingProviderBinding: Binding { - Binding( - get: { - guard let id = editingProviderID else { return nil } - return settings.providers.first(where: { $0.id == id }) - }, - set: { newValue in - editingProviderID = newValue?.id - } + var body: some View { + SettingsDrillRow( + route: SettingsRoute.page(.slashCommands), + title: SettingsPage.slashCommands.title, + value: SettingsFormat.count(storage.commands.count) ) } +} - private var deleteAlertBinding: Binding { - Binding( - get: { pendingDeleteID != nil }, - set: { isPresented in - if !isPresented { - pendingDeleteID = nil - } - } - ) - } +// Each row observes only the service its own status comes from, and starts nothing. +private struct AIProviderRow: View { + let provider: AIProviderConfig + let isActive: Bool + let hasKey: Bool - private var deleteAlertTitle: String { - guard let id = pendingDeleteID, - let provider = settings.providers.first(where: { $0.id == id }) else { - return String(localized: "Remove Provider?") + var body: some View { + HStack(spacing: 10) { + BrandIconView(icon: provider.icon) + .foregroundStyle(.secondary) + .frame(width: 20, height: 20) + .frame(width: 24, height: 24) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: provider.displayName) + AIProviderRowStatus(provider: provider, hasKey: hasKey) + .font(.subheadline) + } + Spacer(minLength: 8) + if isActive { + Text("Active") + .foregroundStyle(.secondary) + } } - return String(format: String(localized: "Remove %@?"), provider.displayName) - } - - // MARK: - Status - - private func status(for provider: AIProviderConfig) -> AIProviderStatus { - AIProviderStatus.resolve( - provider: provider, - hasAPIKey: providersWithKey.contains(provider.id), - oauthState: oauthState(for: provider.type), - serviceError: serviceError(for: provider.type), - claudeAgent: claudeAgentService.state - ) + .accessibilityElement(children: .combine) } +} - // Copilot's sign-in is known only once its language server answers, which this row starts. A - // server stopped after it answered keeps the state it reported. - private func oauthState(for type: AIProviderType) -> OAuthAuthState? { - if type == .copilot, copilotService.status == .starting { return nil } - return OAuthProviderRegistry.service(for: type)?.oauthState - } +private struct AIProviderRowStatus: View { + let provider: AIProviderConfig + let hasKey: Bool - private func serviceError(for type: AIProviderType) -> String? { - switch type { + var body: some View { + switch provider.type { case .copilot: - if case .error(let message) = copilotService.status { return message } - return copilotService.statusMessage + CopilotRowStatus(provider: provider) case .chatgptCodex: - return chatGPTCodexService.errorMessage + ChatGPTRowStatus(provider: provider) + case .claudeAgent: + ClaudeAgentRowStatus(provider: provider) default: - return nil + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: hasKey, + oauthState: nil, + serviceError: nil, + claudeAgent: .unknown + ), + showsReadySymbol: false + ) } } +} - private func refreshAccountStatus(of types: Set) async { - let chatGPT = chatGPTCodexService - let claudeAgent = claudeAgentService - await withTaskGroup(of: Void.self) { group in - if types.contains(.chatgptCodex) { - group.addTask { await chatGPT.refreshAuthState() } - } - if types.contains(.claudeAgent) { - group.addTask { await claudeAgent.performRefresh() } - } - } +private struct CopilotRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var copilot = CopilotService.shared + + var body: some View { + AIProviderStatusLabel(status: status, showsReadySymbol: false) } - private func refreshKeyAvailability() { - guard settings.enabled else { return } - var ids: Set = [] - for provider in settings.providers where provider.authStyle.usesAPIKey { - if let key = AIKeyStorage.shared.loadAPIKey(for: provider.id), !key.isEmpty { - ids.insert(provider.id) - } + // The sign-in is known only once the language server answers; a server stopped after that keeps its answer. + private var status: AIProviderStatus { + var serviceError = copilot.statusMessage + if case .error(let message) = copilot.status { + serviceError = message } - providersWithKey = ids + let reported = copilot.hasReportedAuthState && copilot.status != .starting + return AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: reported ? copilot.oauthState : nil, + serviceError: serviceError, + claudeAgent: .unknown, + serviceStopped: copilot.status == .stopped + ) } +} - // MARK: - Mutations +private struct ChatGPTRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var service = ChatGPTCodexService.shared - private func makeNewProvider(type: AIProviderType) -> AIProviderConfig { - let descriptor = AIProviderRegistry.shared.descriptor(for: type.rawValue) - return AIProviderConfig( - id: UUID(), - name: "", - type: type, - model: "", - endpoint: type.defaultEndpoint, - maxOutputTokens: nil, - telemetryEnabled: descriptor?.defaultTelemetryEnabled ?? false + var body: some View { + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: service.oauthState, + serviceError: service.errorMessage, + claudeAgent: .unknown + ), + showsReadySymbol: false ) } +} - private func saveProvider(_ provider: AIProviderConfig, apiKey: String, isNew: Bool) { - if provider.authStyle.usesAPIKey { - AIKeyStorage.shared.saveAPIKey(apiKey, for: provider.id) - } - - if let index = settings.providers.firstIndex(where: { $0.id == provider.id }) { - settings.providers[index] = provider - } else { - settings.providers.append(provider) - } - - AIProviderFactory.invalidateCache(for: provider.id) - refreshKeyAvailability() - - if isNew, settings.activeProviderID == nil { - settings.activeProviderID = provider.id - } - AppEvents.shared.aiProviderSaved.send(provider.id) - } +private struct ClaudeAgentRowStatus: View { + let provider: AIProviderConfig + @ObservedObject private var service = ClaudeAgentService.shared - private func removeProvider(_ id: UUID) { - AIKeyStorage.shared.deleteAPIKey(for: id) - AIProviderFactory.invalidateCache(for: id) - AIModelCatalog.shared.remove(providerID: id) - settings.providers.removeAll { $0.id == id } - if settings.activeProviderID == id { - settings.activeProviderID = nil - } - refreshKeyAvailability() + var body: some View { + AIProviderStatusLabel( + status: AIProviderStatus.resolve( + provider: provider, + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: service.state + ), + showsReadySymbol: false + ) } } diff --git a/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift b/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift index 919d189762..8da2a7fd1d 100644 --- a/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift +++ b/apple/TablePro/Views/Settings/ClaudeAgentDisclosureSection.swift @@ -1,8 +1,3 @@ -// -// ClaudeAgentDisclosureSection.swift -// TablePro -// - import SwiftUI struct ClaudeAgentDisclosureSection: View { @@ -10,22 +5,19 @@ struct ClaudeAgentDisclosureSection: View { Section { ForEach(ClaudeAgentDisclosure.notes) { note in Label { - Text(note.text) - .font(.callout) + Text(verbatim: note.text) .foregroundStyle(note.severity == .caution ? Color.primary : Color.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: note.severity.symbolName) .foregroundStyle(note.severity == .caution ? Color.orange : Color.secondary) + .accessibilityHidden(true) } .accessibilityElement(children: .combine) } + SettingsHelpRow(ClaudeAgentDisclosure.supportedAlternative) } header: { Text("Tradeoffs") - } footer: { - Text(ClaudeAgentDisclosure.supportedAlternative) - .font(.caption) - .foregroundStyle(.secondary) } } } diff --git a/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift index c3329020ea..9dc796176b 100644 --- a/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift +++ b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift @@ -1,8 +1,3 @@ -// -// AIProviderStatusLabel.swift -// TablePro -// - import SwiftUI internal struct AIProviderStatusLabel: View { @@ -12,19 +7,21 @@ internal struct AIProviderStatusLabel: View { var body: some View { switch status { case .checking, .signingIn: - HStack(spacing: 6) { - ProgressView() - .controlSize(.small) - Text(status.title) + Label { + Text(verbatim: status.title) .foregroundStyle(.secondary) + } icon: { + ProgressView() + .controlSize(.mini) + .accessibilityHidden(true) } default: if let severity = status.severity { NoticeLabel(status.title, severity: severity) - } else if showsReadySymbol { + } else if showsReadySymbol, status.isReady { NoticeLabel(status.title, severity: .success) } else { - Text(status.title) + Text(verbatim: status.title) .foregroundStyle(.secondary) } } diff --git a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift index 07487a6fac..5bc84ffe18 100644 --- a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift +++ b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift @@ -1,211 +1,261 @@ -// -// CustomSlashCommandsSection.swift -// TablePro -// - import SwiftUI -struct CustomSlashCommandsSection: View { +struct SlashCommandsPage: View { + private struct Editing: Identifiable { + let command: CustomSlashCommand + let isNew: Bool + + var id: UUID { command.id } + } + @ObservedObject var storage: CustomSlashCommandStorage - @State private var editing: CustomSlashCommand? - @State private var isCreating = false - @State private var saveError: String? + @State private var editing: Editing? @State private var pendingDelete: CustomSlashCommand? var body: some View { - Section { - if storage.commands.isEmpty { - emptyState - } else { - ForEach(storage.commands) { command in - row(for: command) + Form { + Section { + if storage.commands.isEmpty { + VStack(alignment: .leading, spacing: 2) { + Text("No slash commands") + Text("Add one to reuse a prompt in the chat.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + .accessibilityElement(children: .combine) + } else { + ForEach(storage.commands) { command in + row(command) + } } - } - HStack { - Spacer() - Button { - editing = CustomSlashCommand() - isCreating = true - } label: { - Label(String(localized: "Add Command"), systemImage: "plus") + SettingsHelpRow("Type / in the chat to run one. A template can use {{query}}, {{schema}}, {{database}} and {{body}}.") + } footer: { + SettingsSectionActions { + Button("Add Command…") { + editing = Editing(command: CustomSlashCommand(), isNew: true) + } + .accessibilityIdentifier("slash-command-add") } - .controlSize(.small) } - } header: { - Text(String(localized: "Custom Slash Commands")) - } footer: { - Text(String( - localized: "Create your own slash commands. Use {{query}}, {{schema}}, {{database}}, or {{body}} in the template to insert chat context at runtime." - )) - .font(.caption) - .foregroundStyle(.secondary) } - .sheet(item: $editing) { command in + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.slashCommands.pageIdentifier) + .sheet(item: $editing) { editing in CustomSlashCommandEditorSheet( - initial: command, - isCreating: isCreating, - onSave: { updated in - do { - if isCreating { - try storage.add(updated) - } else { - try storage.update(updated) - } - editing = nil - isCreating = false - } catch { - saveError = error.localizedDescription - } - }, - onCancel: { - editing = nil - isCreating = false - } + initial: editing.command, + isCreating: editing.isNew, + isDuplicate: { name in storage.isDuplicate(name, excluding: editing.isNew ? nil : editing.command.id) }, + onSave: { command in save(command, isNew: editing.isNew) }, + onDelete: editing.isNew ? nil : { storage.delete(id: editing.command.id) } ) } - .alert( - String(localized: "Cannot Save Command"), - isPresented: Binding( - get: { saveError != nil }, - set: { if !$0 { saveError = nil } } - ), - presenting: saveError - ) { _ in - Button(String(localized: "OK"), role: .cancel) { saveError = nil } - } message: { message in - Text(message) - } .alert( pendingDelete.map { String(format: String(localized: "Delete “/%@”?"), $0.name) } ?? "", - isPresented: Binding( - get: { pendingDelete != nil }, - set: { if !$0 { pendingDelete = nil } } - ), + isPresented: deleteBinding, presenting: pendingDelete ) { command in Button(String(localized: "Delete"), role: .destructive) { storage.delete(id: command.id) pendingDelete = nil } - Button(String(localized: "Cancel"), role: .cancel) { pendingDelete = nil } + Button(String(localized: "Cancel"), role: .cancel) { + pendingDelete = nil + } } message: { _ in - Text(String(localized: "The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.")) + Text("The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.") } } - @ViewBuilder - private var emptyState: some View { - Text(String(localized: "No custom commands yet.")) - .font(.caption) - .foregroundStyle(.secondary) + private func row(_ command: CustomSlashCommand) -> some View { + SettingsRecordRow( + title: "/\(command.name)", + subtitle: command.description.isEmpty ? nil : command.description + ) + .infoButton( + onEdit: { editing = Editing(command: command, isNew: false) }, + removal: .delete { pendingDelete = command }, + identifier: "slash-command-edit-\(command.id.uuidString)" + ) + .accessibilityIdentifier("slash-command-\(command.id.uuidString)") } - @ViewBuilder - private func row(for command: CustomSlashCommand) -> some View { - HStack(alignment: .firstTextBaseline) { - VStack(alignment: .leading, spacing: 2) { - Text("/\(command.name)") - .font(.body) - if !command.description.isEmpty { - Text(command.description) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(1) - } - } - Spacer() - Button(String(localized: "Edit")) { - editing = command - isCreating = false - } - .controlSize(.small) - Button(role: .destructive) { - pendingDelete = command - } label: { - Image(systemName: "trash") + private var deleteBinding: Binding { + Binding( + get: { pendingDelete != nil }, + set: { if !$0 { pendingDelete = nil } } + ) + } + + // Returns the error to show in the sheet, or nil once the command is stored. + private func save(_ command: CustomSlashCommand, isNew: Bool) -> String? { + do { + if isNew { + try storage.add(command) + } else { + try storage.update(command) } - .controlSize(.small) - .accessibilityLabel(String(format: String(localized: "Delete /%@"), command.name)) - .help(String(localized: "Delete")) + editing = nil + return nil + } catch { + return error.localizedDescription } } } struct CustomSlashCommandEditorSheet: View { - @State var draft: CustomSlashCommand - let isCreating: Bool - let onSave: (CustomSlashCommand) -> Void - let onCancel: () -> Void + @Environment(\.dismiss) private var dismiss + @State private var draft: CustomSlashCommand + @State private var saveError: String? + @State private var confirmsDelete = false + + private let isCreating: Bool + private let isDuplicate: (String) -> Bool + private let onSave: (CustomSlashCommand) -> String? + private let onDelete: (() -> Void)? init( initial: CustomSlashCommand, isCreating: Bool, - onSave: @escaping (CustomSlashCommand) -> Void, - onCancel: @escaping () -> Void + isDuplicate: @escaping (String) -> Bool, + onSave: @escaping (CustomSlashCommand) -> String?, + onDelete: (() -> Void)? ) { _draft = State(initialValue: initial) self.isCreating = isCreating + self.isDuplicate = isDuplicate self.onSave = onSave - self.onCancel = onCancel + self.onDelete = onDelete + } + + // A leading slash is what the chat types, not part of the name. + static func normalizedName(_ name: String) -> String { + var trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("/") { + trimmed.removeFirst() + } + return trimmed + } + + private var name: String { + Self.normalizedName(draft.name) + } + + private var duplicates: Bool { + !name.isEmpty && isDuplicate(name) + } + + private var canSave: Bool { + var normalized = draft + normalized.name = name + return normalized.isValid && !duplicates } var body: some View { VStack(spacing: 0) { Form { Section { - LabeledContent(String(localized: "Name")) { - TextField("summarize", text: $draft.name) - .textFieldStyle(.roundedBorder) - } - LabeledContent(String(localized: "Description")) { - TextField(String(localized: "Optional one-line description"), text: $draft.description) - .textFieldStyle(.roundedBorder) + TextField(text: $draft.name, prompt: Text(verbatim: "summarize")) { + Text("Name") + nameNotice } - } footer: { - if SlashCommand.isBuiltIn(name: draft.name) { - NoticeLabel(String( - format: String(localized: "/%@ is a built-in command. Typing it runs the built-in; this one runs only from the command menu."), - draft.name.trimmingCharacters(in: .whitespaces).lowercased() - )) - .font(.caption) + .accessibilityIdentifier("slash-command-name") + TextField(text: $draft.description, prompt: Text("Optional")) { + Text("Description") } + .accessibilityIdentifier("slash-command-description") } Section { TextEditor(text: $draft.promptTemplate) .font(.body.monospaced()) .frame(minHeight: 140) - .overlay( - RoundedRectangle(cornerRadius: 4) - .stroke(Color(nsColor: .separatorColor)) - ) - } header: { - Text(String(localized: "Prompt template")) - } footer: { - Text(String(localized: """ + .accessibilityLabel(String(localized: "Prompt template")) + .accessibilityIdentifier("slash-command-template") + SettingsHelpRow( + """ Use {{query}} for the current editor query, {{schema}} for the active schema, \ - {{database}} for the active database name, and {{body}} for any text typed \ - after the command. - """)) - .font(.caption) - .foregroundStyle(.secondary) + {{database}} for the active database name, and {{body}} for any text typed after the command. + """ + ) + } header: { + Text("Prompt Template") } } .formStyle(.grouped) Divider() - HStack { - Spacer() - Button(String(localized: "Cancel"), action: onCancel) - .keyboardShortcut(.cancelAction) + DialogFooter { + if onDelete != nil { + Button(String(localized: "Delete Command…"), role: .destructive) { + confirmsDelete = true + } + .accessibilityIdentifier("slash-command-delete") + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) Button(isCreating ? String(localized: "Add") : String(localized: "Save")) { - onSave(draft) + save() } .keyboardShortcut(.defaultAction) - .disabled(!draft.isValid) + .disabled(!canSave) + .accessibilityIdentifier("slash-command-save") + } + .padding() + } + .frame(minWidth: 480, minHeight: 400) + .alert( + String(localized: "Couldn't Save the Command"), + isPresented: saveErrorBinding, + presenting: saveError + ) { _ in + Button(String(localized: "OK"), role: .cancel) { + saveError = nil + } + } message: { message in + Text(verbatim: message) + } + .alert( + String(format: String(localized: "Delete “/%@”?"), name), + isPresented: $confirmsDelete + ) { + Button(String(localized: "Delete"), role: .destructive) { + onDelete?() + dismiss() } - .padding(12) + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("The command is removed from this Mac and from every Mac that syncs settings. This cannot be undone.") + } + } + + @ViewBuilder + private var nameNotice: some View { + if duplicates { + NoticeLabel(String(format: String(localized: "A command named “/%@” already exists."), name)) + } else if SlashCommand.isBuiltIn(name: name) { + NoticeLabel(String( + format: String(localized: "/%@ is a built-in command. Typing it runs the built-in; this one runs only from the command menu."), + name.lowercased() + )) } - .frame(minWidth: 480, minHeight: 360) + } + + private var saveErrorBinding: Binding { + Binding( + get: { saveError != nil }, + set: { if !$0 { saveError = nil } } + ) + } + + private func save() { + var command = draft + command.name = name + command.description = draft.description.trimmingCharacters(in: .whitespacesAndNewlines) + guard command.isValid, !duplicates else { return } + saveError = onSave(command) } } diff --git a/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift index 2b72d9629f..4984b2364a 100644 --- a/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/AISettingsEntry.swift @@ -10,7 +10,7 @@ internal struct AISettingsEntry: View { } internal var body: some View { - AISettingsView(settings: $ai.value) + AISettingsView(settings: $ai.value, visit: context.visit) } } @@ -18,21 +18,38 @@ internal struct AISettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext + internal init(route: SettingsRoute, context: SettingsPaneContext) { + self.route = route + self.context = context + } + + // A route of another pane never reaches this stack. internal var body: some View { switch route { case .page(.slashCommands): - Form { CustomSlashCommandsSection(storage: CustomSlashCommandStorage.shared) } - .formStyle(.grouped) + SlashCommandsPage(storage: CustomSlashCommandStorage.shared) + case .aiProvider(let id): + AIProviderPage(providerID: id, slice: context.settings.aiSlice) default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } +// Root and provider pages share the removal alert and the pane model, so both live on the stack. internal struct AIStackPresentations: ViewModifier { internal let context: SettingsPaneContext + @StateObject private var paneModel = AISettingsPaneModel() + + internal init(context: SettingsPaneContext) { + self.context = context + } internal func body(content: Content) -> some View { content + .environmentObject(paneModel) + .aiProviderRemovalAlert(pending: $paneModel.pendingRemoval) { provider in + paneModel.remove(provider, from: context.settings.aiSlice, navigation: context.navigation) + } } } diff --git a/apple/TableProTests/Core/AI/AIProviderDraftRulesTests.swift b/apple/TableProTests/Core/AI/AIProviderDraftRulesTests.swift index 65f13bf00d..870bf98d34 100644 --- a/apple/TableProTests/Core/AI/AIProviderDraftRulesTests.swift +++ b/apple/TableProTests/Core/AI/AIProviderDraftRulesTests.swift @@ -1,8 +1,3 @@ -// -// AIProviderDraftRulesTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -12,8 +7,7 @@ struct AIProviderDraftRulesTests { ids.map { AIModelInfo(id: $0) } } - /// The reported defect: a router answers with several hundred models sorted by name, and the - /// sheet put a new provider on the first of them without being asked. + // A router answers with hundreds of models sorted by name; the first of them is no choice. @Test("A fetched list with several models picks none of them") func severalFetchedModelsPickNone() { let fetched = models(["alibaba/qwen-max", "anthropic/claude-sonnet-5", "openai/gpt-5.5"]) @@ -57,15 +51,13 @@ struct AIProviderDraftRulesTests { #expect(!AIProviderDraftRules.needsModelChoice(model: "typed-by-hand", fetched: fetched)) } - /// A provider whose list is blocked, failed, or waits on a sign-in has nothing to pick from, and - /// requiring a model there would leave Save dimmed with no way forward. + // With no list to pick from, requiring a model would leave Save dimmed with no way forward. @Test("Save does not wait for a model when no list is available") func saveDoesNotWaitWithoutAList() { #expect(!AIProviderDraftRules.needsModelChoice(model: "", fetched: [])) } - /// The fetch runs on a timer while the field is edited. Resolving an emptied Base URL to the - /// default sent the key typed for a gateway to the vendor's own host with no click. + // Resolving an emptied Base URL to the default sent a gateway's key to the vendor's host with no click. @Test("The automatic model fetch waits while the Base URL field is empty") func emptiedBaseURLBlocksTheFetch() { AIProviderRegistration.registerAll() @@ -80,8 +72,7 @@ struct AIProviderDraftRulesTests { ) } - /// The reported defect: clearing the field saved an empty endpoint under a placeholder that - /// showed the default, and every request failed until the next launch. + // An empty endpoint saved under a placeholder showing the default failed every request until relaunch. @Test("A cleared Base URL saves as the default the placeholder shows") func clearedEndpointSavesAsTheDefault() { let fallback = AIProviderPreset.requesty.endpoint @@ -118,9 +109,7 @@ struct AIProviderDraftRulesTests { ) } - /// The list on record was fetched with the old key or Base URL, so it describes a server the - /// saved provider no longer points at. Open chat windows never refetch on their own, so Save - /// fetches it again rather than leaving them with no list. + // Open chat windows never refetch on their own, so Save fetches for the new server. @Test("Save fetches the list again when the key or Base URL changed and the new one did not load") func staleListIsFetchedAgainWhenTheConnectionChanged() { #expect( @@ -163,8 +152,7 @@ struct AIProviderDraftRulesTests { #expect(AIProviderDraftRules.effort(afterPicking: .xhigh, reasoning: optional, curated: nil) == nil) } - /// Meta runs its most expensive level when the effort is left out, so Off there was the - /// costliest choice in the picker. + // Meta runs its most expensive level when the effort is left out. @Test("A model that always reasons never ends up with no effort") func mandatoryReasoningAlwaysHasAnEffort() { #expect(AIProviderDraftRules.effort(afterPicking: nil, reasoning: mandatory, curated: nil) == .high) @@ -174,8 +162,7 @@ struct AIProviderDraftRulesTests { #expect(AIProviderDraftRules.effort(afterPicking: .xhigh, reasoning: narrow, curated: nil) == .medium) } - /// Typing a model id under Other… used to keep the effort as it stood. A rule that cleared it - /// on every keystroke turned Extra High into Off before the id was complete. + // A rule that cleared the effort on every keystroke turned Extra High into Off before the id was complete. @Test("Typing, preselecting or reopening keeps the effort, except that a model that always reasons gets one") func keptEffortChangesOnlyForMandatoryReasoning() { #expect(AIProviderDraftRules.effort(keeping: .xhigh, reasoning: optional) == .xhigh) @@ -188,4 +175,69 @@ struct AIProviderDraftRulesTests { func noReasoningNoEffort() { #expect(AIProviderDraftRules.effort(afterPicking: .high, reasoning: .unsupported, curated: curated) == nil) } + + // A key that failed to load shows as empty, so writing it back would erase the real one. + @Test("Edit Connection writes the key only when the field was edited") + func keyIsWrittenOnlyWhenEdited() { + #expect(AIProviderConnectionRules.keyWrite(edited: false, typed: "") == .keep) + #expect(AIProviderConnectionRules.keyWrite(edited: false, typed: "sk-loaded") == .keep) + #expect(AIProviderConnectionRules.keyWrite(edited: true, typed: "sk-new") == .save("sk-new")) + #expect(AIProviderConnectionRules.keyWrite(edited: true, typed: "") == .delete) + } + + @Test("Edit Connection saves only once the key has loaded") + func saveWaitsForTheKey() { + #expect(!AIProviderConnectionRules.canSave(isKeyLoaded: false, authStyle: .optionalApiKey, apiKey: "sk")) + #expect(!AIProviderConnectionRules.canSave(isKeyLoaded: true, authStyle: .apiKey, apiKey: " ")) + #expect(AIProviderConnectionRules.canSave(isKeyLoaded: true, authStyle: .apiKey, apiKey: "sk")) + #expect(AIProviderConnectionRules.canSave(isKeyLoaded: true, authStyle: .optionalApiKey, apiKey: "")) + } + + @Test("Edit Connection moves only the name and Base URL onto the saved provider") + func mergeKeepsLiveEdits() { + let current = AIProviderConfig(name: "Gateway", type: .custom, model: "picked-on-the-page", endpoint: "https://a.example/v1") + var draft = current + draft.name = " Renamed " + draft.endpoint = "https://b.example/v1" + draft.model = "stale" + let merged = AIProviderConnectionRules.merged(current, with: draft, allowsName: true, allowsEndpoint: true) + #expect(merged.name == "Renamed") + #expect(merged.endpoint == "https://b.example/v1") + #expect(merged.model == "picked-on-the-page") + + let fixed = AIProviderConnectionRules.merged(current, with: draft, allowsName: false, allowsEndpoint: false) + #expect(fixed == current) + } + + @Test("A new Base URL or key counts as a new connection, an untouched key does not") + func connectionChange() { + let current = AIProviderConfig(type: .openAI, endpoint: "https://api.openai.com") + var moved = current + moved.endpoint = "https://proxy.example" + #expect(AIProviderConnectionRules.connectionChanged(from: current, to: moved, keyWrite: .keep, savedKey: "sk")) + #expect(!AIProviderConnectionRules.connectionChanged(from: current, to: current, keyWrite: .keep, savedKey: "sk")) + #expect(!AIProviderConnectionRules.connectionChanged(from: current, to: current, keyWrite: .save("sk"), savedKey: "sk")) + #expect(AIProviderConnectionRules.connectionChanged(from: current, to: current, keyWrite: .save("sk-2"), savedKey: "sk")) + #expect(AIProviderConnectionRules.connectionChanged(from: current, to: current, keyWrite: .delete, savedKey: "sk")) + #expect(!AIProviderConnectionRules.connectionChanged(from: current, to: current, keyWrite: .delete, savedKey: "")) + } + + @Test("Output tokens below 1 or not a number mean the provider's default") + func maxOutputTokensParsing() { + #expect(AIProviderEditorModel.maxOutputTokens(from: "") == nil) + #expect(AIProviderEditorModel.maxOutputTokens(from: "0") == nil) + #expect(AIProviderEditorModel.maxOutputTokens(from: "-5") == nil) + #expect(AIProviderEditorModel.maxOutputTokens(from: "many") == nil) + #expect(AIProviderEditorModel.maxOutputTokens(from: " 4096 ") == 4096) + } + + @Test("The model picker shows a listed model as itself and anything else as Other") + func modelSelection() { + let choices = AIModelChoices(curated: [curated], fetched: models(["gpt-5.5", "gpt-4.1"])) + #expect(choices.fetched == ["gpt-4.1"]) + #expect(choices.selection(for: "gpt-5.5", choseOther: false) == .curated("gpt-5.5")) + #expect(choices.selection(for: "gpt-4.1", choseOther: false) == .fetched("gpt-4.1")) + #expect(choices.selection(for: "typed-by-hand", choseOther: false) == .custom) + #expect(choices.selection(for: "gpt-4.1", choseOther: true) == .custom) + } } diff --git a/apple/TableProTests/Models/AI/AISettingsMutationTests.swift b/apple/TableProTests/Models/AI/AISettingsMutationTests.swift new file mode 100644 index 0000000000..b6287cb223 --- /dev/null +++ b/apple/TableProTests/Models/AI/AISettingsMutationTests.swift @@ -0,0 +1,132 @@ +import Combine +import Foundation +@testable import TablePro +import Testing + +struct AISettingsMutationTests { + private let first = AIProviderConfig(name: "First", type: .openAI) + private let second = AIProviderConfig(name: "Second", type: .claude) + + @Test("Upserting a new provider appends it and makes it active when none is") + func upsertingAppendsAndActivates() { + let settings = AISettings(providers: [first]).upserting(second, makeActiveIfNone: true) + #expect(settings.providers.map(\.id) == [first.id, second.id]) + #expect(settings.activeProviderID == second.id) + } + + @Test("Upserting keeps the active provider that already answers") + func upsertingKeepsTheActiveProvider() { + let settings = AISettings(providers: [first], activeProviderID: first.id) + .upserting(second, makeActiveIfNone: true) + #expect(settings.activeProviderID == first.id) + } + + // Another Mac can remove the active provider, which leaves an id that answers to nothing. + @Test("Upserting replaces an active id whose provider is gone") + func upsertingReplacesADanglingActiveID() { + let settings = AISettings(providers: [], activeProviderID: UUID()) + .upserting(first, makeActiveIfNone: true) + #expect(settings.activeProviderID == first.id) + } + + @Test("Upserting without activation leaves the active provider alone") + func upsertingWithoutActivation() { + let settings = AISettings(providers: []).upserting(first, makeActiveIfNone: false) + #expect(settings.providers == [first]) + #expect(settings.activeProviderID == nil) + } + + @Test("Upserting a saved provider replaces it in place") + func upsertingReplacesInPlace() { + var renamed = first + renamed.name = "Renamed" + let settings = AISettings(providers: [first, second]).upserting(renamed, makeActiveIfNone: false) + #expect(settings.providers.map(\.name) == ["Renamed", "Second"]) + } + + @Test("Removing the active provider clears the active id in the same value") + func removingTheActiveProvider() { + let settings = AISettings(providers: [first, second], activeProviderID: second.id).removingProvider(second.id) + #expect(settings.providers == [first]) + #expect(settings.activeProviderID == nil) + } + + @Test("Removing another provider keeps the active one") + func removingAnotherProvider() { + let settings = AISettings(providers: [first, second], activeProviderID: first.id).removingProvider(second.id) + #expect(settings.providers == [first]) + #expect(settings.activeProviderID == first.id) + } + + @Test("Replacing a provider changes only that provider") + func replacingAProvider() { + var edited = second + edited.model = "claude-opus-5" + let settings = AISettings(providers: [first, second], activeProviderID: first.id).replacingProvider(edited) + #expect(settings.providers == [first, edited]) + #expect(settings.activeProviderID == first.id) + } + + // A page still open on a provider another Mac removed must not bring it back with its next edit. + @Test("Replacing a provider that is gone changes nothing") + func replacingAMissingProvider() { + let settings = AISettings(providers: [first]) + #expect(settings.replacingProvider(second) == settings) + } + + @Test("The schema table limit stays inside its range") + func schemaTableLimitIsClamped() { + #expect(AISettings(maxSchemaTables: -5).clampedMaxSchemaTables == 1) + #expect(AISettings(maxSchemaTables: 0).clampedMaxSchemaTables == 1) + #expect(AISettings(maxSchemaTables: 20).clampedMaxSchemaTables == 20) + #expect(AISettings(maxSchemaTables: 5_000).clampedMaxSchemaTables == 100) + } + + // prefix(_:) traps on a negative count, and a synced value can be anything. + @Test("A negative schema table limit never reaches prefix") + func negativeSchemaTableLimitDoesNotTrap() { + let tables = Array(0..<10) + let settings = AISettings(maxSchemaTables: -1) + #expect(tables.prefix(settings.clampedMaxSchemaTables) == [0]) + } + + @MainActor + @Test("Removing a provider is one settings write that also closes its page") + func paneRemovalWritesOnceAndPops() { + let slice = SettingsSlice(AISettings(providers: [first, second], activeProviderID: second.id)) + let navigation = SettingsNavigationModel(initial: SettingsLocation(route: .aiProvider(second.id))) + var writes = 0 + let observation = slice.objectWillChange.sink { _ in writes += 1 } + let model = AISettingsPaneModel() + model.setHasKey(true, for: second.id) + + model.remove(second, from: slice, navigation: navigation) + + #expect(slice.value.providers == [first]) + #expect(slice.value.activeProviderID == nil) + #expect(writes == 1) + #expect(navigation.location == .root(.ai)) + #expect(!model.hasKey(second.id)) + observation.cancel() + } + + @MainActor + @Test("An account is checked again only after a minute") + func accountChecksAreThrottled() { + var clock = Date(timeIntervalSince1970: 1_000) + let model = AISettingsPaneModel(now: { clock }) + #expect(model.claimAccountChecks([.claudeAgent, .chatgptCodex]) == [.claudeAgent, .chatgptCodex]) + clock += 30 + #expect(model.claimAccountChecks([.claudeAgent, .chatgptCodex]).isEmpty) + clock += 31 + #expect(model.claimAccountChecks([.claudeAgent]) == [.claudeAgent]) + } + + @Test("The tool call limit stays inside its range") + func toolCallLimitIsClamped() { + #expect(AISettings(maxToolRoundtrips: 0).clampedMaxToolRoundtrips == AISettings.maxToolRoundtripsRange.lowerBound) + #expect(AISettings(maxToolRoundtrips: 9_999).clampedMaxToolRoundtrips == AISettings.maxToolRoundtripsRange.upperBound) + #expect(AISettings(maxToolRoundtrips: 40, maxToolRoundtripsEnabled: false).effectiveMaxToolRoundtrips == nil) + #expect(AISettings(maxToolRoundtrips: 40).effectiveMaxToolRoundtrips == 40) + } +} diff --git a/apple/TableProTests/Models/AIProviderStatusTests.swift b/apple/TableProTests/Models/AIProviderStatusTests.swift index 20283cde74..c134be4b44 100644 --- a/apple/TableProTests/Models/AIProviderStatusTests.swift +++ b/apple/TableProTests/Models/AIProviderStatusTests.swift @@ -53,6 +53,20 @@ struct AIProviderStatusTests { #expect(status(.chatgptCodex, oauthState: .signedIn(identity: "me@example.com")).isReady) } + @Test("A Copilot service that was never started reads Not started, quietly") + func stoppedServiceIsNotStarted() { + let stopped = AIProviderStatus.resolve( + provider: AIProviderConfig(name: "", type: .copilot), + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: .unknown, + serviceStopped: true + ) + #expect(stopped == .notStarted) + #expect(stopped.severity == nil) + } + @Test("Claude Code states map one to one") func claudeAgentStates() { #expect(status(.claudeAgent, claudeAgent: .unknown) == .checking) diff --git a/apple/TableProTests/Views/Settings/AIProviderAddMenuTests.swift b/apple/TableProTests/Views/Settings/AIProviderAddMenuTests.swift new file mode 100644 index 0000000000..2dc85d48ba --- /dev/null +++ b/apple/TableProTests/Views/Settings/AIProviderAddMenuTests.swift @@ -0,0 +1,85 @@ +import Foundation +@testable import TablePro +import Testing + +struct AIProviderAddMenuTests { + private let everything = AIProviderAddMenu.groups { _ in true } + + @Test("Account sign-ins come first, Claude Agent with them") + func signInGroup() { + #expect(everything.signIn == [.type(.copilot), .type(.chatgptCodex), .type(.claudeAgent)]) + } + + @Test("API key providers list the built-in types, then the presets") + func apiKeyGroup() { + let types = AIProviderType.allCases + .filter { $0 != .custom && $0.authStyle.usesAPIKey } + .map(AIProviderAddChoice.type) + let presets = AIProviderPreset.all.map { AIProviderAddChoice.preset($0.id) } + #expect(everything.apiKey == types + presets) + #expect(everything.apiKey.contains(.type(.openCode))) + } + + @Test("Local servers go under On This Mac") + func onThisMacGroup() { + #expect(everything.onThisMac == [.type(.ollama), .type(.llamaCpp), .type(.mlx)]) + } + + @Test("Custom is offered once, last, and in no group") + func customIsLast() { + #expect(everything.includesCustom) + let grouped = everything.signIn + everything.apiKey + everything.onThisMac + #expect(!grouped.contains(.type(.custom))) + #expect(!grouped.contains(.custom)) + } + + @Test("Every registered type is offered exactly once") + func everyTypeOnce() { + let grouped = everything.signIn + everything.apiKey + everything.onThisMac + for type in AIProviderType.allCases where type != .custom { + #expect(grouped.filter { $0 == .type(type) }.count == 1) + } + } + + @Test("A type with no registered descriptor is not offered") + func unregisteredTypesAreDropped() { + let groups = AIProviderAddMenu.groups { $0 != .copilot && $0 != .ollama } + #expect(!groups.signIn.contains(.type(.copilot))) + #expect(!groups.onThisMac.contains(.type(.ollama))) + } + + // Presets are stored as .custom, so without the custom descriptor neither they nor Custom can be added. + @Test("Presets and Custom need the custom descriptor") + func presetsNeedCustom() { + let groups = AIProviderAddMenu.groups { $0 != .custom } + #expect(!groups.includesCustom) + #expect(!groups.apiKey.contains { $0.preset != nil }) + } + + @Test("A preset choice makes a custom provider carrying the preset") + func presetChoiceMakesACustomProvider() { + let preset = AIProviderPreset.requesty + let provider = AIProviderAddChoice.preset(preset.id).makeProvider { _ in nil } + #expect(provider.type == .custom) + #expect(provider.presetID == preset.id) + #expect(provider.endpoint == preset.endpoint) + #expect(provider.displayName == preset.displayName) + } + + @Test("A type choice starts on the type's default endpoint and an empty model") + func typeChoiceUsesDefaults() { + let provider = AIProviderAddChoice.type(.ollama).makeProvider { _ in nil } + #expect(provider.type == .ollama) + #expect(provider.endpoint == AIProviderType.ollama.defaultEndpoint) + #expect(provider.model.isEmpty) + #expect(!provider.telemetryEnabled) + } + + @Test("Every choice makes a provider with a fresh id") + func choicesMakeFreshIDs() { + let one = AIProviderAddChoice.custom.makeProvider { _ in nil } + let two = AIProviderAddChoice.custom.makeProvider { _ in nil } + #expect(one.id != two.id) + #expect(one.type == .custom) + } +} From 28f56955ee8c3096e90e41ba5b087777c255696c Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:45:56 +0700 Subject: [PATCH 38/48] feat(settings): MCP pane with Tokens and Approved Connections pages --- .../Clients/MCPClientRowPresentation.swift | 2 +- .../Core/MCP/Lifecycle/MCPServerManager.swift | 23 +- apple/TablePro/Core/MCP/MCPTokenStore.swift | 65 ++- .../Core/MCP/Outside/MCPServerStore.swift | 58 ++- .../Settings/MCPConnectionApproval.swift | 13 +- .../Models/Settings/MCPSettings.swift | 8 + .../Models/Settings/TokenExpiry.swift | 51 +++ .../IntegrationsActivityLogPane.swift | 3 +- .../Settings/Entries/MCPSettingsEntry.swift | 51 ++- .../Views/Settings/MCPSettingsView.swift | 182 +++++++- .../Sections/ConnectionAllowlistSection.swift | 72 ++++ .../Settings/Sections/MCPGrantListView.swift | 129 +++--- .../Sections/MCPOutsideServerSheet.swift | 334 ++++++++++----- .../Sections/MCPOutsideServersSection.swift | 122 ++---- .../Views/Settings/Sections/MCPSection.swift | 399 +++++++----------- .../Sections/MCPTokenCreateSheet.swift | 291 ++++++------- .../Settings/Sections/MCPTokenListView.swift | 381 +++++++++++------ .../Sections/MCPTokenRevealSheet.swift | 199 ++++----- .../Sections/PairingApprovalSheet.swift | 283 +++++-------- .../Core/MCP/MCPSettingsTests.swift | 60 +++ .../Core/MCP/MCPTokenStoreTests.swift | 88 +++- .../MCP/Outside/MCPServerStoreTests.swift | 110 ++++- .../MCPConnectClientUITests.swift | 67 +++ 23 files changed, 1844 insertions(+), 1147 deletions(-) create mode 100644 apple/TablePro/Models/Settings/TokenExpiry.swift create mode 100644 apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift diff --git a/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift index 21a1f29426..af963ec3c9 100644 --- a/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift +++ b/apple/TablePro/Core/MCP/Clients/MCPClientRowPresentation.swift @@ -232,7 +232,7 @@ enum MCPClientDetailText { String(format: String(localized: "TablePro is turned off in %1$@. Turn it on in %1$@'s MCP settings to use it."), name) case .usesToken: String( - format: String(localized: "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is."), + format: String(localized: "%@ connects with a token from Settings > MCP > Tokens, which can limit what it reaches. TablePro leaves it as is."), name ) case .unreadable: diff --git a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift index ea8ab78310..e6bd5f0e71 100644 --- a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift +++ b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift @@ -68,18 +68,21 @@ internal final class MCPServerManager: ObservableObject { @Published internal private(set) var connectedClients: [SessionSnapshot] = [] @Published internal private(set) var tokenStore: MCPTokenStore? + // Fires when Settings forgets an approval or a revocation withdraws one; a new approval waits for the next visit. + internal let grantChanges = MCPChangeSignal() + private let lifecycle = MCPServerLifecycleQueue() private let handshake: MCPHandshakeFile private let isEnabled: @MainActor () -> Bool - @Published private(set) var composition: MCPServerComposition? - @Published private var bridgeCredential: BridgeCredential? - @Published private var instanceId = "" - @Published private var generation = 0 - @Published private var revocationObserverId: UUID? - @Published private var dispatchTask: Task? - @Published private var stateTask: Task? - @Published private var tokenRenewalTask: Task? + private(set) var composition: MCPServerComposition? + private var bridgeCredential: BridgeCredential? + private var instanceId = "" + private var generation = 0 + private var revocationObserverId: UUID? + private var dispatchTask: Task? + private var stateTask: Task? + private var tokenRenewalTask: Task? internal var isRunning: Bool { if case .running = state { return true } @@ -149,10 +152,12 @@ internal final class MCPServerManager: ObservableObject { internal func forgetGrant(subject: String, connectionId: UUID) async { await approvalPolicy().revokeGrant(subject: subject, connectionId: connectionId) + grantChanges.send() } internal func forgetEveryGrant() async { await approvalPolicy().forgetEveryGrant() + grantChanges.send() } private func approvalPolicy() -> MCPAuthPolicy { @@ -193,6 +198,7 @@ internal final class MCPServerManager: ObservableObject { let withdrawn = stored?.subjectWithdrawnWhenEnded ?? .token(tokenId) let persisted = await revokeToken(id: tokenId) await composition.authPolicy.clearApprovals(subject: withdrawn) + grantChanges.send() await composition.activityLedger.forget(tokenId: tokenId) await refreshClients() return persisted @@ -468,6 +474,7 @@ internal final class MCPServerManager: ObservableObject { let cancelled = await dispatcher.cancelInflight(matchingTokenId: tokenId) if let subject { await composition?.authPolicy.clearApprovals(subject: subject) + grantChanges.send() } guard cancelled > 0 else { return } Self.logger.info( diff --git a/apple/TablePro/Core/MCP/MCPTokenStore.swift b/apple/TablePro/Core/MCP/MCPTokenStore.swift index f0e1da94c2..69a6a7cf7d 100644 --- a/apple/TablePro/Core/MCP/MCPTokenStore.swift +++ b/apple/TablePro/Core/MCP/MCPTokenStore.swift @@ -62,6 +62,9 @@ struct MCPAuthToken: Codable, Identifiable, Sendable { var isEffectivelyActive: Bool { isActive && !isExpired } + // TablePro mints the bridge and Claude Agent tokens itself, so Settings and the activity window leave them out. + var isUserManaged: Bool { !isBridgeCredential && !isClaudeAgentCredential } + func renamed(_ name: String) -> MCPAuthToken { MCPAuthToken( id: id, @@ -238,6 +241,17 @@ enum TokenPermissions: String, Codable, Sendable, CaseIterable, Identifiable { } } + var summary: String { + switch self { + case .readOnly: + String(localized: "Read schema and run SELECT queries.") + case .readWrite: + String(localized: "Read schema and run any non-destructive query, including INSERT, UPDATE, and DELETE.") + case .fullAccess: + String(localized: "Full access including destructive DDL after explicit confirmation.") + } + } + var scopes: Set { switch self { case .readOnly: @@ -258,6 +272,9 @@ actor MCPTokenStore { private static let logger = Logger(subsystem: "com.TablePro", category: "MCPTokenStore") + // Fires when a user-managed token is added, revoked or removed; never for a last-used stamp. + nonisolated let membershipChanges = MCPChangeSignal() + private var tokens: [MCPAuthToken] = [] // Stored entries this build cannot decode, kept as JSON so a save writes them back. private var undecodedEntries: [Data] = [] @@ -363,6 +380,9 @@ actor MCPTokenStore { Self.logger.info("Generated MCP token '\(name, privacy: .private(mask: .hash))'") MCPAuditLogger.logTokenCreated(tokenId: token.id, tokenName: name) + if token.isUserManaged { + membershipChanges.send() + } return (token, plaintext) } @@ -391,8 +411,12 @@ actor MCPTokenStore { tokens[index].isActive = false let revokedName = tokens[index].name let withdrawn = tokens[index].subjectWithdrawnWhenEnded + let isUserManaged = tokens[index].isUserManaged let persisted = save() notifyRevocationObservers(tokenId: tokenId, withdrawing: withdrawn) + if isUserManaged { + membershipChanges.send() + } Self.logger.info("Revoked MCP token '\(revokedName, privacy: .private(mask: .hash))'") MCPAuditLogger.logTokenRevoked(tokenId: tokenId, tokenName: revokedName) @@ -444,9 +468,13 @@ actor MCPTokenStore { let name = tokens[index].name let withdrawn = withdrawsApprovals ? tokens[index].subjectWithdrawnWhenEnded : nil + let isUserManaged = tokens[index].isUserManaged tokens.remove(at: index) let persisted = save() notifyRevocationObservers(tokenId: tokenId, withdrawing: withdrawn) + if isUserManaged { + membershipChanges.send() + } Self.logger.info("Deleted MCP token '\(name, privacy: .private(mask: .hash))'") return persisted @@ -500,17 +528,26 @@ actor MCPTokenStore { let staleCount = tokens.filter(Self.isStaleBridge).count tokens.removeAll(where: Self.isStaleBridge) + let expiredAgentCount = tokens.filter(Self.isExpiredAgentToken).count + tokens.removeAll(where: Self.isExpiredAgentToken) let renamedCount = tokens.filter(Self.claimsAgentName).count tokens = tokens.map(Self.releasingAgentName) - guard staleCount > 0 || renamedCount > 0 else { return } + guard staleCount > 0 || expiredAgentCount > 0 || renamedCount > 0 else { return } save() - Self.logger.info("Cleaned up \(staleCount) stale bridge token(s), renamed \(renamedCount) client token(s)") + Self.logger.info( + "Cleaned up \(staleCount) stale bridge and \(expiredAgentCount) expired agent token(s), renamed \(renamedCount) client token(s)" + ) } private static func isStaleBridge(_ token: MCPAuthToken) -> Bool { token.isBridgeCredential || token.name == stdioBridgeTokenName } + // A turn that crashed never retired its token; once expired it opens nothing and only clutters the list. + private static func isExpiredAgentToken(_ token: MCPAuthToken) -> Bool { + token.isClaudeAgentCredential && token.isExpired + } + // Builds before the agent's name was reserved let a pairing client take it. private static func claimsAgentName(_ token: MCPAuthToken) -> Bool { token.name == claudeAgentTokenName && !token.isClaudeAgentCredential @@ -575,7 +612,7 @@ actor MCPTokenStore { storedTokensUnread = false let minted = Set(tokens.map(\.id)) tokens = stored.tokens - .filter { !minted.contains($0.id) && !Self.isStaleBridge($0) } + .filter { !minted.contains($0.id) && !Self.isStaleBridge($0) && !Self.isExpiredAgentToken($0) } .map(Self.releasingAgentName) + tokens undecodedEntries = stored.undecoded Self.logger.info("Read the stored MCP tokens after an earlier failure") @@ -677,6 +714,28 @@ actor MCPTokenStore { } } +// Fans one change out to every listener; a listener that falls behind holds one pending change, not each. +final class MCPChangeSignal: Sendable { + private let listeners = OSAllocatedUnfairLock<[UUID: AsyncStream.Continuation]>(initialState: [:]) + + func changes() -> AsyncStream { + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + let id = UUID() + listeners.withLock { $0[id] = continuation } + continuation.onTermination = { [weak self] _ in + self?.listeners.withLock { _ = $0.removeValue(forKey: id) } + } + return stream + } + + func send() { + let current = listeners.withLock { Array($0.values) } + for continuation in current { + continuation.yield() + } + } +} + enum MCPTokenBlob: Sendable, Equatable { case found(Data) case missing diff --git a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift index cc1534bc6f..205c81e4f9 100644 --- a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift +++ b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift @@ -1,12 +1,14 @@ -// -// MCPServerStore.swift -// TablePro -// - import Combine import Foundation import TableProMCP +internal enum MCPServerSaveError: Error, Equatable, Sendable { + case invalid(MCPServerConfigurationError) + // A new server, or a saved one pointed at another scheme, host or port, must bring its own token. + case tokenRequired + case tokenNotSaved +} + // Device-local and never synced: a server this Mac reaches may not be reachable from another. @MainActor internal final class MCPServerStore: ObservableObject { @@ -30,8 +32,6 @@ internal final class MCPServerStore: ObservableObject { servers = defaults.read(Self.serversKey).value ?? [] } - // MARK: - Reads - internal func server(id: UUID) -> MCPServerConfiguration? { servers.first { $0.id == id } } @@ -51,27 +51,33 @@ internal final class MCPServerStore: ObservableObject { servers.first { toolName.hasPrefix($0.toolNamespace) } } - // MARK: - Writes - + // The token is written first, so a Keychain refusal leaves the list and the saved token as they were. @discardableResult internal func upsert( _ configuration: MCPServerConfiguration, token: String? - ) -> MCPServerConfigurationError? { + ) -> MCPServerSaveError? { if let error = MCPServerConfigurationValidator.validate( name: configuration.name, endpoint: configuration.endpoint ) { - return error + return .invalid(error) } - if let index = servers.firstIndex(where: { $0.id == configuration.id }) { - servers[index] = configuration - } else { - servers.append(configuration) + let newToken = token.flatMap { $0.isEmpty ? nil : $0 } + if newToken == nil { + guard let saved = server(id: configuration.id), + Self.sharesOrigin(saved.endpoint, configuration.endpoint) else { return .tokenRequired } + } + if let newToken, !keychain.writeString(newToken, forKey: Self.tokenKey(configuration.id)) { + return .tokenNotSaved } - if let token, !token.isEmpty { - _ = keychain.writeString(token, forKey: Self.tokenKey(configuration.id)) + var next = servers + if let index = next.firstIndex(where: { $0.id == configuration.id }) { + next[index] = configuration + } else { + next.append(configuration) } + servers = next persist() return nil } @@ -115,7 +121,23 @@ internal final class MCPServerStore: ObservableObject { return token } - // MARK: - Storage + // A saved token may follow a path change, never a move to another scheme, host or port. + nonisolated internal static func sharesOrigin(_ lhs: URL, _ rhs: URL) -> Bool { + guard let lhsScheme = lhs.scheme?.lowercased(), let rhsScheme = rhs.scheme?.lowercased(), + let lhsHost = lhs.host?.lowercased(), let rhsHost = rhs.host?.lowercased() else { return false } + return lhsScheme == rhsScheme + && lhsHost == rhsHost + && effectivePort(lhs, scheme: lhsScheme) == effectivePort(rhs, scheme: rhsScheme) + } + + nonisolated private static func effectivePort(_ url: URL, scheme: String) -> Int? { + if let port = url.port { return port } + switch scheme { + case "https": return 443 + case "http": return 80 + default: return nil + } + } private static func tokenKey(_ serverId: UUID) -> String { "mcp.outsideServer.\(serverId.uuidString)" diff --git a/apple/TablePro/Models/Settings/MCPConnectionApproval.swift b/apple/TablePro/Models/Settings/MCPConnectionApproval.swift index c4a5e17901..96b6d8dbfe 100644 --- a/apple/TablePro/Models/Settings/MCPConnectionApproval.swift +++ b/apple/TablePro/Models/Settings/MCPConnectionApproval.swift @@ -1,14 +1,7 @@ import Foundation -/// How the MCP server asks before a client may reach a saved connection. -/// -/// This is MCP's own decision and is deliberately not `AIConnectionPolicy`. That policy answers a -/// different question, whether a connection's schema may be sent to a model provider, and the -/// connection form describes it as governing in-app AI agents. Both of its controls disappear when -/// AI features are off, which left the MCP prompt with no control at all. -/// -/// `alwaysApprove` is the permissive end. `AIConnectionPolicy.never` is the restrictive end of the -/// other policy and still denies here, so the two spellings of "never" never meet. +// MCP's own gate. AIConnectionPolicy answers whether a schema may reach a model provider, and its +// controls hide when AI is off, so it cannot be this one. Its "never" still denies here. enum MCPConnectionApproval: String, Codable, CaseIterable, Identifiable, Sendable { case everyTime case oncePerConnection @@ -29,7 +22,7 @@ enum MCPConnectionApproval: String, Codable, CaseIterable, Identifiable, Sendabl case .everyTime: return String(localized: "Every call that reaches a connection asks first.") case .oncePerConnection: - return String(localized: "The first call asks. The answer is remembered for that client until you revoke it.") + return String(localized: "The first call asks. The answer is remembered for that client until you forget it.") case .alwaysApprove: return String(localized: "Connections are reached without asking.") } diff --git a/apple/TablePro/Models/Settings/MCPSettings.swift b/apple/TablePro/Models/Settings/MCPSettings.swift index 2738d6364e..fb257a6be1 100644 --- a/apple/TablePro/Models/Settings/MCPSettings.swift +++ b/apple/TablePro/Models/Settings/MCPSettings.swift @@ -87,4 +87,12 @@ struct MCPSettings: Codable, Equatable { var requestableRowLimitRange: ClosedRange { SettingsValidationRules.mcpRowLimitRange.lowerBound...validatedMaxRowLimit } + + // One write, so a lowered maximum never leaves the default above it for a moment. + func withMaxRowLimit(_ newValue: Int) -> MCPSettings { + var next = self + next.maxRowLimit = newValue.clamped(to: SettingsValidationRules.mcpRowLimitRange) + next.defaultRowLimit = min(next.defaultRowLimit, next.maxRowLimit) + return next + } } diff --git a/apple/TablePro/Models/Settings/TokenExpiry.swift b/apple/TablePro/Models/Settings/TokenExpiry.swift new file mode 100644 index 0000000000..6a2ef16f3b --- /dev/null +++ b/apple/TablePro/Models/Settings/TokenExpiry.swift @@ -0,0 +1,51 @@ +import Foundation + +enum TokenExpiry: String, CaseIterable, Identifiable, Sendable { + case never + case oneDay + case sevenDays + case thirtyDays + case sixtyDays + case ninetyDays + case custom + + var id: String { rawValue } + + var displayName: String { + switch self { + case .never: String(localized: "Never") + case .oneDay: String(localized: "1 day") + case .sevenDays: String(localized: "7 days") + case .thirtyDays: String(localized: "30 days") + case .sixtyDays: String(localized: "60 days") + case .ninetyDays: String(localized: "90 days") + case .custom: String(localized: "Custom") + } + } + + var days: Int? { + switch self { + case .never, .custom: nil + case .oneDay: 1 + case .sevenDays: 7 + case .thirtyDays: 30 + case .sixtyDays: 60 + case .ninetyDays: 90 + } + } + + static func defaultCustomDate(from now: Date = .now, calendar: Calendar = .current) -> Date { + calendar.date(byAdding: .day, value: 30, to: now) ?? now + } + + func resolvedDate(custom: Date, from now: Date = .now, calendar: Calendar = .current) -> Date? { + switch self { + case .never: + nil + case .custom: + custom + case .oneDay, .sevenDays, .thirtyDays, .sixtyDays, .ninetyDays: + days.flatMap { calendar.date(byAdding: .day, value: $0, to: now) } + } + } +} diff --git a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift index 427480ed39..99dc81fd8a 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift @@ -222,8 +222,7 @@ struct IntegrationsActivityLogPane: View { } if let store = mcpServerManager.tokenStore { - // TablePro mints these afresh every rotation and every agent turn, so they are filtered by name. - tokens = await store.list().filter { !$0.isBridgeCredential && !$0.isClaudeAgentCredential } + tokens = await store.list().filter(\.isUserManaged) } connections = ConnectionStorage.shared.loadConnections() diff --git a/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift index 2114e7aeb6..bcc25c6932 100644 --- a/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/MCPSettingsEntry.swift @@ -3,6 +3,7 @@ import SwiftUI internal struct MCPSettingsEntry: View { internal let context: SettingsPaneContext @ObservedObject private var mcp: SettingsSlice + @EnvironmentObject private var model: MCPSettingsModel internal init(context: SettingsPaneContext) { self.context = context @@ -10,29 +11,71 @@ internal struct MCPSettingsEntry: View { } internal var body: some View { - MCPSettingsView(settings: $mcp.value) + MCPSettingsView(settings: $mcp.value, model: model) { + context.navigation.open(.root(.ai), recordsHistory: true) + } } } internal struct MCPSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext + @EnvironmentObject private var model: MCPSettingsModel internal var body: some View { switch route { case .page(.mcpApprovals): - Form { Section { MCPGrantListView() } } - .formStyle(.grouped) + MCPApprovalsPage(context: context, model: model) + case .page(.mcpTokens): + MCPTokenListView(model: model) { + context.settings.mcpSlice.value.port + } default: - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + EmptyView() } } } +// The approval mode lives in the MCP slice, so only this page observes it. +private struct MCPApprovalsPage: View { + @ObservedObject private var mcp: SettingsSlice + @ObservedObject var model: MCPSettingsModel + + init(context: SettingsPaneContext, model: MCPSettingsModel) { + self._mcp = ObservedObject(wrappedValue: context.settings.mcpSlice) + self.model = model + } + + var body: some View { + MCPGrantListView(model: model, approval: mcp.value.connectionApproval) + } +} + +// The model sits on the stack, so the root and both pages share one load and keep it across pushes. internal struct MCPStackPresentations: ViewModifier { internal let context: SettingsPaneContext + @StateObject private var model = MCPSettingsModel() + + internal init(context: SettingsPaneContext) { + self.context = context + } internal func body(content: Content) -> some View { content + .environmentObject(model) + .modifier(MCPVisitRefresh(visit: context.visit, model: model)) + } +} + +private struct MCPVisitRefresh: ViewModifier { + @ObservedObject var visit: SettingsPaneVisit + let model: MCPSettingsModel + + func body(content: Content) -> some View { + content + .task(id: visit.count) { + model.activate() + await model.refresh() + } } } diff --git a/apple/TablePro/Views/Settings/MCPSettingsView.swift b/apple/TablePro/Views/Settings/MCPSettingsView.swift index 5a0ccf2f2f..81ae132f6e 100644 --- a/apple/TablePro/Views/Settings/MCPSettingsView.swift +++ b/apple/TablePro/Views/Settings/MCPSettingsView.swift @@ -1,18 +1,188 @@ +import Combine import SwiftUI +import TableProMCP + +// One per Settings window, shared by the pane root and its pages, so a push or a pane switch keeps the rows. +@MainActor +final class MCPSettingsModel: ObservableObject { + @Published private(set) var tokenStore: MCPTokenStore? + @Published private(set) var tokens: [MCPAuthToken] = [] + @Published private(set) var hasLoadedTokens = false + @Published private(set) var grants: [MCPConnectionGrant] = [] + @Published private(set) var hasLoadedGrants = false + @Published private(set) var connectionNames: [UUID: String] = [:] + @Published private(set) var tokenNames: [UUID: String] = [:] + + private let manager: MCPServerManager + private var storeSubscription: AnyCancellable? + private var tokenTask: Task? + private var grantTask: Task? + private var tokenGeneration = 0 + private var grantGeneration = 0 + + init(manager: MCPServerManager) { + self.manager = manager + } + + convenience init() { + self.init(manager: .shared) + } + + deinit { + tokenTask?.cancel() + grantTask?.cancel() + } + + var activeTokenCount: Int { + tokens.filter { $0.isEffectivelyActive }.count + } + + func activate() { + guard storeSubscription == nil else { return } + let grantChanges = manager.grantChanges.changes() + grantTask = Task { [weak self] in + for await _ in grantChanges { + await self?.reloadGrants() + } + } + storeSubscription = manager.$tokenStore + .removeDuplicates { $0 === $1 } + .sink { [weak self] store in self?.adopt(store) } + } + + func refresh() async { + await reloadTokens() + await reloadGrants() + } + + func reloadTokens() async { + tokenGeneration += 1 + let generation = tokenGeneration + guard let store = tokenStore else { return } + let listed = await store.list() + guard generation == tokenGeneration, store === tokenStore else { return } + tokens = listed.filter(\.isUserManaged) + hasLoadedTokens = true + } + + func reloadGrants() async { + grantGeneration += 1 + let generation = grantGeneration + let loaded = await manager.connectionGrants() + let named = await tokenStore?.list() ?? [] + guard generation == grantGeneration else { return } + grants = loaded.sorted { $0.grantedAt > $1.grantedAt } + tokenNames = Dictionary(named.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) + connectionNames = Dictionary( + ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, + uniquingKeysWith: { first, _ in first } + ) + hasLoadedGrants = true + } + + func forgetGrant(_ grant: MCPConnectionGrant) async { + await manager.forgetGrant(subject: grant.subject, connectionId: grant.connectionId) + await reloadGrants() + } + + func forgetEveryGrant() async { + await manager.forgetEveryGrant() + await reloadGrants() + } + + func generate(_ request: MCPTokenRequest, configuredPort: Int) async -> Result { + guard let store = tokenStore else { + return .failure(MCPTokenCreateFailure( + message: String(localized: "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again."), + endsSheet: true + )) + } + let access: ConnectionAccess = request.connectionIds.map { .limited($0) } ?? .all + do { + let result = try await store.generate( + name: request.name, + permissions: request.permissions, + connectionAccess: access, + expiresAt: request.expiresAt, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + await reloadTokens() + let port = manager.listeningPort ?? configuredPort + return .success(MCPTokenReveal( + plaintext: result.plaintext, + setup: MCPHTTPClientSetup(port: port), + port: port, + configuredPort: configuredPort + )) + } catch { + return .failure(MCPTokenCreateFailure(message: Self.generateFailureMessage(error), endsSheet: false)) + } + } + + func revoke(_ ids: Set) async -> MCPTokenAlert? { + guard tokenStore != nil else { return .serverNotRunning } + var allSaved = true + for id in ids { + let saved = await manager.revokeToken(id: id) + allSaved = allSaved && saved + } + await reloadTokens() + return allSaved ? nil : .revocationNotSaved + } + + func delete(_ ids: Set) async -> MCPTokenAlert? { + guard let store = tokenStore else { return .serverNotRunning } + var allSaved = true + for id in ids { + let saved = await store.delete(tokenId: id) + allSaved = allSaved && saved + } + await reloadTokens() + return allSaved ? nil : .deletionNotSaved + } + + private func adopt(_ store: MCPTokenStore?) { + tokenStore = store + tokenTask?.cancel() + tokenTask = nil + guard let store else { return } + let changes = store.membershipChanges.changes() + tokenTask = Task { [weak self] in + await self?.reloadTokens() + await self?.reloadGrants() + for await _ in changes { + await self?.reloadTokens() + await self?.reloadGrants() + } + } + } + + private static func generateFailureMessage(_ error: Error) -> String { + switch error as? MCPTokenStoreError { + case .storedTokensUnreadable?: + String(localized: "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again.") + case .randomGenerationFailed?: + String(localized: "macOS could not generate a secure token. Try again.") + case .keychainUnavailable?, .notSaved?, nil: + String(localized: "TablePro could not save the token to the Keychain, so it was not created. Try again.") + } + } +} struct MCPSettingsView: View { @Binding var settings: MCPSettings + @ObservedObject var model: MCPSettingsModel + let onChangeAIPolicy: () -> Void var body: some View { Form { - MCPSection(settings: $settings) + MCPSection(settings: $settings, model: model, onChangeAIPolicy: onChangeAIPolicy) MCPOutsideServersSection() } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-mcp") } } - -#Preview { - MCPSettingsView(settings: .constant(.default)) - .frame(width: 520, height: 540) -} diff --git a/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift b/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift new file mode 100644 index 0000000000..92f78fc559 --- /dev/null +++ b/apple/TablePro/Views/Settings/Sections/ConnectionAllowlistSection.swift @@ -0,0 +1,72 @@ +import SwiftUI + +// Rows only, so each sheet puts them in its own card under its own header. +struct ConnectionAllowlistSection: View { + @Binding var selection: Set + let connections: [DatabaseConnection] + let showsSelectAll: Bool + + @State private var search = "" + + var body: some View { + if connections.isEmpty { + Text("No saved connections") + .foregroundStyle(.secondary) + } else { + HStack(spacing: 8) { + NativeSearchField( + text: $search, + placeholder: String(localized: "Search connections"), + accessibilityIdentifier: "connection-allowlist-search" + ) + if showsSelectAll { + Button(String(localized: "Select All")) { + selection.formUnion(filtered.map(\.id)) + } + .disabled(filtered.isEmpty) + .accessibilityIdentifier("connection-allowlist-select-all") + Button(String(localized: "Select None")) { + selection.subtract(filtered.map(\.id)) + } + .disabled(filtered.isEmpty) + .accessibilityIdentifier("connection-allowlist-select-none") + } + } + + if filtered.isEmpty { + Text("No matching connections") + .foregroundStyle(.secondary) + } else { + ForEach(filtered) { connection in + Toggle(isOn: binding(for: connection.id)) { + Text(verbatim: connection.name) + Text(verbatim: connection.type.displayName) + } + .toggleStyle(.checkbox) + } + } + } + } + + private var filtered: [DatabaseConnection] { + let query = search.trimmingCharacters(in: .whitespacesAndNewlines) + guard !query.isEmpty else { return connections } + return connections.filter { connection in + connection.name.localizedStandardContains(query) + || connection.type.displayName.localizedStandardContains(query) + } + } + + private func binding(for id: UUID) -> Binding { + Binding( + get: { selection.contains(id) }, + set: { isOn in + if isOn { + selection.insert(id) + } else { + selection.remove(id) + } + } + ) + } +} diff --git a/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift b/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift index 55efe881c7..b073b94f20 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPGrantListView.swift @@ -1,47 +1,91 @@ -// -// MCPGrantListView.swift -// TablePro -// - import SwiftUI import TableProMCP -/// The approvals the user has already given, so a remembered answer stays visible and revocable. +// The Approved Connections page: a remembered answer stays visible here and can be forgotten. struct MCPGrantListView: View { - @ObservedObject private var mcpServerManager = MCPServerManager.shared - @State private var grants: [MCPConnectionGrant] = [] - @State private var connectionNames: [UUID: String] = [:] - @State private var tokenNames: [UUID: String] = [:] + @ObservedObject var model: MCPSettingsModel + let approval: MCPConnectionApproval + + @State private var isConfirmingForgetAll = false var body: some View { - Group { - if grants.isEmpty { - Text("No connections are approved yet.") - .foregroundStyle(.secondary) - } else { - ForEach(grants) { grant in - LabeledContent { - Button(String(localized: "Forget")) { - forget(grant) - } - } label: { - Text(name(for: grant)) - if let client = Self.clientName(forSubject: grant.subject, tokenNames: tokenNames) { - Text(client) + Form { + if approval != .oncePerConnection { + Section { + SettingsHelpRow(String( + format: String(localized: "Approval is set to “%@”, so these approvals are not used now. They apply again if you choose Ask Once for Each Connection."), + approval.displayName + )) + } + } + + Section { + if model.grants.isEmpty { + if model.hasLoadedGrants { + Text("No approved connections. A connection a client may reach without asking again appears here.") + .foregroundStyle(.secondary) + } + } else { + ForEach(model.grants) { grant in + row(grant) + } + } + } footer: { + if !model.grants.isEmpty { + SettingsSectionActions { + Button(String(localized: "Forget All…"), role: .destructive) { + isConfirmingForgetAll = true } + .accessibilityIdentifier("mcp-grants-forget-all") } } + } + } + .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.mcpApprovals.pageIdentifier) + .alert(String(localized: "Forget All Approvals?"), isPresented: $isConfirmingForgetAll) { + Button(String(localized: "Forget All"), role: .destructive) { + Task { await model.forgetEveryGrant() } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text("Clients ask again the next time they reach a connection.") + } + } - Button(String(localized: "Forget All"), role: .destructive) { - forgetAll() - } + private func row(_ grant: MCPConnectionGrant) -> some View { + let connection = model.connectionNames[grant.connectionId] ?? String(localized: "Deleted connection") + let client = Self.clientName(forSubject: grant.subject, tokenNames: model.tokenNames) + let forgetLabel = client.map { + String(format: String(localized: "Forget %1$@ for %2$@"), connection, $0) + } ?? String(format: String(localized: "Forget %@"), connection) + return LabeledContent { + Button(String(localized: "Forget")) { + forget(grant) } + .accessibilityLabel(forgetLabel) + } label: { + Text(verbatim: connection) + Text(verbatim: Self.detail(client: client, grantedAt: grant.grantedAt)) } - .task { await refresh() } + .contextMenu { + Button(String(localized: "Forget")) { + forget(grant) + } + } + } + + private func forget(_ grant: MCPConnectionGrant) { + Task { await model.forgetGrant(grant) } } - private func name(for grant: MCPConnectionGrant) -> String { - connectionNames[grant.connectionId] ?? String(localized: "Deleted connection") + private static func detail(client: String?, grantedAt: Date) -> String { + let date = grantedAt.formatted(date: .abbreviated, time: .omitted) + guard let client else { + return String(format: String(localized: "Approved %@"), date) + } + return String(format: String(localized: "%1$@, approved %2$@"), client, date) } // Two clients approved for one connection would otherwise show as two identical rows. @@ -55,29 +99,4 @@ struct MCPGrantListView: View { return UUID(uuidString: subject).flatMap { tokenNames[$0] }.map(IntegrationsFormatting.displayTokenName) } } - - private func forget(_ grant: MCPConnectionGrant) { - Task { - await MCPServerManager.shared.forgetGrant(subject: grant.subject, connectionId: grant.connectionId) - await refresh() - } - } - - private func forgetAll() { - Task { - await MCPServerManager.shared.forgetEveryGrant() - await refresh() - } - } - - private func refresh() async { - grants = await mcpServerManager.connectionGrants() - .sorted { $0.grantedAt > $1.grantedAt } - connectionNames = Dictionary( - ConnectionStorage.shared.loadConnections().map { ($0.id, $0.name) }, - uniquingKeysWith: { first, _ in first } - ) - let tokens = await mcpServerManager.tokenStore?.list() ?? [] - tokenNames = Dictionary(tokens.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) - } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift index c957e0ccbf..4cb1c71ac6 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift @@ -1,140 +1,237 @@ -// -// MCPOutsideServerSheet.swift -// TablePro -// - +import AppKit import SwiftUI import TableProMCP -/// Adds or edits one outside MCP server, and says which connections may reach it. -/// -/// The allowlist is in the same sheet as the address rather than behind a second screen, because a -/// server with no connections allowed does nothing and a reader who does not see the list has no -/// reason to look for it. Nothing is written until Save: Test uses the token typed into the field, -/// so checking an address you got wrong does not leave a server in the list you never meant to add. +// The allowlist sits beside the address: a server allowed on no connection does nothing. Nothing is written until Save. internal struct MCPOutsideServerSheet: View { internal let server: MCPServerConfiguration? + private enum TestState: Equatable { + case idle + case running + case succeeded(toolCount: Int) + case failed(message: String) + } + @Environment(\.dismiss) private var dismiss - @ObservedObject private var store = MCPServerStore.shared + @State private var newServerId = UUID() @State private var name = "" @State private var endpointText = "" @State private var token = "" @State private var allowedConnectionIds: Set = [] - @State private var validationError: MCPServerConfigurationError? + @State private var saveError: MCPServerSaveError? @State private var testState: TestState = .idle + @State private var testTask: Task? @State private var connections: [DatabaseConnection] = [] - - private enum TestState: Equatable { - case idle - case running - case succeeded(toolCount: Int) - case failed(message: String) - } + @State private var hasLoaded = false + @State private var isConfirmingRemoval = false var body: some View { - VStack(alignment: .leading, spacing: 0) { + VStack(spacing: 0) { Form { serverSection - connectionsSection + allowedOnSection } .formStyle(.grouped) Divider() - buttonBar + + footer + .padding() } - .frame(width: 520, height: 520) + .frame(width: 520, height: Self.height) .onAppear(perform: load) + .onDisappear { + testTask?.cancel() + } + .onChange(of: name) { _ in resetFeedback() } + .onChange(of: endpointText) { _ in resetFeedback() } + .onChange(of: token) { _ in resetFeedback() } + .alert(String(localized: "Remove Server?"), isPresented: $isConfirmingRemoval) { + Button(String(localized: "Remove"), role: .destructive, action: remove) + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { + Text(String( + format: String(localized: "“%@” and its token are removed from this Mac. Sessions lose its tools."), + server?.name ?? "" + )) + } + } + + private static var height: CGFloat { + min(560, (NSScreen.main?.visibleFrame.height ?? 640) - 80) } private var serverSection: some View { Section { - TextField(String(localized: "Name"), text: $name) - TextField(String(localized: "Address"), text: $endpointText, prompt: Text(verbatim: "https://example.com/mcp")) - .autocorrectionDisabled() - SecureField(String(localized: "Token"), text: $token, prompt: tokenPrompt) - - HStack(spacing: 8) { - Button(String(localized: "Test"), action: runTest) - .disabled(testState == .running || token.isEmpty) - DelayedProgressIndicator(isActive: testState == .running) + TextField(text: $name, prompt: nil) { + Text("Name") + if let nameError { + NoticeLabel(nameError, severity: .error) + } + } + .accessibilityIdentifier("mcp-outside-server-name") + + TextField(text: $endpointText, prompt: Text(verbatim: "https://example.com/mcp")) { + Text("Address") + if let addressError { + NoticeLabel(addressError, severity: .error) + } + } + .autocorrectionDisabled() + .accessibilityIdentifier("mcp-outside-server-address") + + SecureField(text: $token, prompt: tokenPrompt) { + Text("Token") + if let tokenError { + NoticeLabel(tokenError, severity: .error) + } + } + .accessibilityIdentifier("mcp-outside-server-token") + + LabeledContent { + HStack(spacing: 8) { + DelayedProgressIndicator(isActive: testState == .running) + .accessibilityHidden(true) + Button(String(localized: "Test"), action: runTest) + .disabled(testState == .running || !canTest) + .accessibilityIdentifier("mcp-outside-server-test") + } + } label: { + Text("Connection test") testResult - Spacer(minLength: 0) } + + SettingsHelpRow("The address has to be HTTPS unless the server runs on this Mac. The token is kept in your Keychain and never synced.") } header: { Text("Server") - } footer: { - if let validationError { - NoticeLabel(message(for: validationError), severity: .error) - .font(.caption) - } else { - Text("The address has to be HTTPS unless the server runs on this Mac. The token is kept in your Keychain and never synced.") - .font(.caption) - .foregroundStyle(.secondary) - } } } @ViewBuilder private var testResult: some View { switch testState { - case .idle, .running: + case .idle: EmptyView() + case .running: + Text("Testing…") case .succeeded(let toolCount): - Text(toolCount == 1 - ? String(localized: "Answered with 1 tool.") - : String(format: String(localized: "Answered with %d tools."), toolCount)) - .font(.callout) - .foregroundStyle(.secondary) + Text("Answered with ^[\(toolCount) tool](inflect: true).") case .failed(let message): NoticeLabel(message, severity: .error) - .font(.callout) - .lineLimit(2) } } - private var connectionsSection: some View { + private var allowedOnSection: some View { Section { - if connections.isEmpty { - Text("No connections saved yet.") - .foregroundStyle(.secondary) - } else { - ForEach(connections) { connection in - Toggle(connection.name, isOn: binding(for: connection.id)) - } - } + ConnectionAllowlistSection( + selection: $allowedConnectionIds, + connections: connections, + showsSelectAll: false + ) + + // swiftlint:disable:next line_length + SettingsHelpRow("A session can call this server's tools only from a connection you tick. It is offered on no others, and a tool it once saw cannot be called by name from one.") } header: { Text("Allowed On") - } footer: { - Text("A session can call this server's tools only from a connection you tick. It is offered on no others, and a tool it once saw cannot be called by name from one.") - .font(.caption) - .foregroundStyle(.secondary) } } - private var buttonBar: some View { - HStack { - Spacer() - Button(String(localized: "Cancel"), role: .cancel) { dismiss() } - .keyboardShortcut(.cancelAction) + private var footer: some View { + DialogFooter { + if server != nil { + Button(String(localized: "Remove Server…"), role: .destructive) { + isConfirmingRemoval = true + } + .accessibilityIdentifier("mcp-outside-server-remove") + } + } actions: { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) + Button(String(localized: "Save"), action: save) .keyboardShortcut(.defaultAction) - .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || endpointText.isEmpty) + .disabled(!canSave) + .accessibilityIdentifier("mcp-outside-server-save") } - .padding(16) } - /// An existing server's token is not read back into the field. The Keychain has it, the sheet - /// does not need it, and putting a live credential into a text field so it can be typed over is - /// how one ends up in a screenshot. + // The saved token is never read back into the field, so it cannot end up in a screenshot. private var tokenPrompt: Text { - server == nil - ? Text(String(localized: "Required")) - : Text(String(localized: "Leave blank to keep the saved token")) + keepsSavedToken + ? Text("Leave blank to keep the saved token") + : Text("Required") + } + + private var trimmedName: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var trimmedEndpoint: String { + endpointText.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var typedEndpoint: URL? { + trimmedEndpoint.isEmpty ? nil : URL(string: trimmedEndpoint) + } + + // The saved token goes only where it was saved for: the same scheme, host and port. + private var keepsSavedToken: Bool { + guard let server, let typedEndpoint else { return false } + return MCPServerStore.sharesOrigin(server.endpoint, typedEndpoint) + } + + private var canTest: Bool { + !trimmedEndpoint.isEmpty && (!token.isEmpty || keepsSavedToken) + } + + private var canSave: Bool { + !trimmedName.isEmpty && !trimmedEndpoint.isEmpty && (!token.isEmpty || keepsSavedToken) + } + + private var nameError: String? { + guard case .invalid(let error)? = saveError else { return nil } + switch error { + case .emptyName: + return String(localized: "Give the server a name.") + case .reservedName: + return String(localized: "That name belongs to TablePro's own tools. Choose another.") + case .invalidEndpoint, .insecureEndpoint, .credentialsInEndpoint: + return nil + } + } + + private var addressError: String? { + guard case .invalid(let error)? = saveError else { return nil } + switch error { + case .invalidEndpoint: + return String(localized: "That is not an HTTP address.") + case .insecureEndpoint: + return String(localized: "A server on another machine has to be HTTPS.") + case .credentialsInEndpoint: + return String(localized: "Put the credential in the Token field, not in the address.") + case .emptyName, .reservedName: + return nil + } + } + + private var tokenError: String? { + switch saveError { + case .tokenRequired?: + return String(localized: "Type the server's token. A saved token stays with the address it was saved for.") + case .tokenNotSaved?: + return String(localized: "TablePro could not save the token to the Keychain, so the server was not saved. Try again.") + case .invalid?, nil: + return nil + } } private func load() { + guard !hasLoaded else { return } + hasLoaded = true connections = ConnectionStorage.shared.loadConnections() .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } guard let server else { return } @@ -143,44 +240,45 @@ internal struct MCPOutsideServerSheet: View { allowedConnectionIds = server.allowedConnectionIds } - private func binding(for connectionId: UUID) -> Binding { - Binding( - get: { allowedConnectionIds.contains(connectionId) }, - set: { isOn in - if isOn { - allowedConnectionIds.insert(connectionId) - } else { - allowedConnectionIds.remove(connectionId) - } - } - ) + private func resetFeedback() { + testTask?.cancel() + testTask = nil + testState = .idle + saveError = nil } - private func draft() -> MCPServerConfiguration { - MCPServerConfiguration( - id: server?.id ?? UUID(), - name: name.trimmingCharacters(in: .whitespacesAndNewlines), - endpoint: URL(string: endpointText.trimmingCharacters(in: .whitespacesAndNewlines)) - ?? URL(fileURLWithPath: "/"), + private func draft() -> MCPServerConfiguration? { + guard let typedEndpoint else { return nil } + return MCPServerConfiguration( + id: server?.id ?? newServerId, + name: trimmedName, + endpoint: typedEndpoint, allowedConnectionIds: allowedConnectionIds ) } private func runTest() { - let configuration = draft() + guard let configuration = draft() else { + saveError = .invalid(.invalidEndpoint) + return + } if let error = MCPServerConfigurationValidator.validate( name: configuration.name, - endpoint: URL(string: endpointText.trimmingCharacters(in: .whitespacesAndNewlines)) + endpoint: configuration.endpoint ) { - validationError = error - testState = .idle + saveError = .invalid(error) return } - validationError = nil + guard let probeToken = probeToken() else { + testState = .failed(message: String(localized: "TablePro could not read the saved token. Type it to test.")) + return + } + saveError = nil testState = .running - let probeToken = token - Task { @MainActor in + testTask?.cancel() + testTask = Task { let result = await MCPRemoteToolCoordinator.shared.probe(configuration, token: probeToken) + guard !Task.isCancelled else { return } switch result { case .success(let tools): testState = .succeeded(toolCount: tools.count) @@ -190,27 +288,29 @@ internal struct MCPOutsideServerSheet: View { } } + // Read at the click, never in the body: the typed token first, else the saved one for the saved origin. + private func probeToken() -> String? { + if !token.isEmpty { return token } + guard keepsSavedToken, let server else { return nil } + return MCPServerStore.shared.token(for: server.id) + } + private func save() { - let configuration = draft() - if let error = store.upsert(configuration, token: token.isEmpty ? nil : token) { - validationError = error + guard canSave else { return } + guard let configuration = draft() else { + saveError = .invalid(.invalidEndpoint) + return + } + if let error = MCPServerStore.shared.upsert(configuration, token: token.isEmpty ? nil : token) { + saveError = error return } dismiss() } - private func message(for error: MCPServerConfigurationError) -> String { - switch error { - case .emptyName: - String(localized: "Give the server a name.") - case .reservedName: - String(localized: "That name belongs to TablePro's own tools. Choose another.") - case .invalidEndpoint: - String(localized: "That is not an HTTP address.") - case .insecureEndpoint: - String(localized: "A server on another machine has to be HTTPS.") - case .credentialsInEndpoint: - String(localized: "Put the credential in the Token field, not in the address.") - } + private func remove() { + guard let server else { return } + MCPServerStore.shared.remove(id: server.id) + dismiss() } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift b/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift index e2eb35543a..63fae29db7 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPOutsideServersSection.swift @@ -1,57 +1,55 @@ -// -// MCPOutsideServersSection.swift -// TablePro -// - import SwiftUI import TableProMCP -/// Below the built-in server's sections because it is the opposite direction: what TablePro may ask -/// of an outside server. It works whether or not the built-in server is on. +// The opposite direction from the server above it, what TablePro may ask of an outside server, so it shows whether or not the server is on. internal struct MCPOutsideServersSection: View { + private struct SheetTarget: Identifiable { + let id: UUID + let server: MCPServerConfiguration? + } + @ObservedObject private var store = MCPServerStore.shared - @State private var editing: MCPServerConfiguration? - @State private var isAdding = false - @State private var deleteCandidate: MCPServerConfiguration? + @State private var sheet: SheetTarget? + @State private var removalCandidate: MCPServerConfiguration? var body: some View { Section { if store.servers.isEmpty { - emptyState + Text("No servers") + .foregroundStyle(.secondary) } else { ForEach(store.servers) { server in row(server) } } - Button { - isAdding = true - } label: { - Label(String(localized: "Add Server…"), systemImage: "plus") - } + // swiftlint:disable:next line_length + SettingsHelpRow("A session can call tools on a server you add here once you allow it on a connection. Every call waits for you to approve it, and the arguments leave this Mac.") } header: { Text("Outside MCP Servers") } footer: { - Text("A session can call tools on a server you add here once you allow it on a connection. Every call waits for you to approve it, and the arguments leave this Mac.") - .font(.caption) - .foregroundStyle(.secondary) - } - .sheet(isPresented: $isAdding) { - MCPOutsideServerSheet(server: nil) + SettingsSectionActions { + Button(String(localized: "Add Server…")) { + sheet = SheetTarget(id: UUID(), server: nil) + } + .accessibilityIdentifier("mcp-outside-server-add") + } } - .sheet(item: $editing) { server in - MCPOutsideServerSheet(server: server) + .sheet(item: $sheet) { target in + MCPOutsideServerSheet(server: target.server) } .alert( - String(localized: "Remove server?"), - isPresented: deleteAlertBinding, - presenting: deleteCandidate + String(localized: "Remove Server?"), + isPresented: removalBinding, + presenting: removalCandidate ) { server in - Button(String(localized: "Cancel"), role: .cancel) { deleteCandidate = nil } Button(String(localized: "Remove"), role: .destructive) { store.remove(id: server.id) - deleteCandidate = nil + removalCandidate = nil + } + Button(String(localized: "Cancel"), role: .cancel) { + removalCandidate = nil } } message: { server in Text(String( @@ -62,61 +60,29 @@ internal struct MCPOutsideServersSection: View { } private func row(_ server: MCPServerConfiguration) -> some View { - Button { - editing = server - } label: { - HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 3) { - Text(server.name) - Text(server.endpoint.absoluteString) - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - } - Spacer(minLength: 8) - Text(reachText(server)) - .font(.caption) - .foregroundStyle(.secondary) - Image(systemName: "chevron.right") - .font(.caption) - .foregroundStyle(.tertiary) - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityLabel(server.name) - .accessibilityValue(reachText(server)) - .contextMenu { - Button(String(localized: "Edit…")) { editing = server } - Divider() - Button(role: .destructive) { - deleteCandidate = server - } label: { - Text(String(localized: "Remove…")) - } - } + SettingsRecordRow( + title: server.name, + subtitle: server.endpoint.absoluteString, + value: Self.reach(of: server) + ) + .infoButton( + onEdit: { sheet = SheetTarget(id: server.id, server: server) }, + removal: .remove { removalCandidate = server }, + identifier: "mcp-outside-server-edit-\(server.id.uuidString)" + ) } - /// How far the server reaches, which is the one thing about it worth reading at a glance. A - /// server allowed nowhere is inert, and saying so is more use than a status dot that would have - /// to connect to mean anything. - private func reachText(_ server: MCPServerConfiguration) -> String { + // How far a server reaches is the one thing worth reading at a glance: one allowed nowhere is inert. + static func reach(of server: MCPServerConfiguration) -> String { let count = server.allowedConnectionIds.count - if count == 0 { return String(localized: "No connections") } - if count == 1 { return String(localized: "1 connection") } - return String(format: String(localized: "%d connections"), count) - } - - private var emptyState: some View { - Text("No servers yet.") - .foregroundStyle(.secondary) + guard count > 0 else { return String(localized: "No connections") } + return String(AttributedString(localized: "^[\(count) connection](inflect: true)").characters) } - private var deleteAlertBinding: Binding { + private var removalBinding: Binding { Binding( - get: { deleteCandidate != nil }, - set: { if !$0 { deleteCandidate = nil } } + get: { removalCandidate != nil }, + set: { if !$0 { removalCandidate = nil } } ) } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPSection.swift b/apple/TablePro/Views/Settings/Sections/MCPSection.swift index 96d67c7902..dcab3216aa 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPSection.swift @@ -1,296 +1,173 @@ -import AppKit import SwiftUI import TableProMCP struct MCPSection: View { @Binding var settings: MCPSettings - @ObservedObject private var manager = MCPServerManager.shared - @State private var tokenList: [MCPAuthToken] = [] - @State private var showSetupSheet = false - @State private var showCreateSheet = false - @State private var showRevealSheet = false - @State private var revealedPlaintext: String = "" - @State private var tokenAlert: MCPTokenAlert? - @State private var rejectedPort: Int? + @ObservedObject var model: MCPSettingsModel + let onChangeAIPolicy: () -> Void + + @State private var showsClientSetup = false var body: some View { Section { - Toggle(String(localized: "Enable MCP Server"), isOn: $settings.enabled) - .accessibilityIdentifier("mcp-enable-server-toggle") + Toggle(isOn: $settings.enabled) { + Text("MCP server") + Text("Lets AI apps such as Claude and Cursor work with your connections through TablePro.") + } + .accessibilityIdentifier("mcp-enable-server-toggle") if settings.enabled { MCPStatusRow(configuredPort: settings.port) + + LabeledContent { + Button(String(localized: "Connect a Client…")) { + showsClientSetup = true + } + .accessibilityIdentifier("mcp-connect-client") + } label: { + Text("Clients") + Text("Add TablePro to Claude, Cursor and other apps on this Mac.") + } + + LabeledContent { + Button(String(localized: "View Activity…")) { + WindowOpener.shared.openIntegrationsActivity() + } + .accessibilityIdentifier("mcp-view-activity") + } label: { + Text("Activity") + Text("Requests, approvals and connected clients.") + } } } + .sheet(isPresented: $showsClientSetup) { + MCPClientSetupSheet() + } if settings.enabled { - configurationSection - connectionAccessSection - authenticationSection - helpSection + accessSection + serverSection } } - private var connectionAccessSection: some View { + private var accessSection: some View { Section { - Picker(String(localized: "Approval"), selection: $settings.connectionApproval) { + Picker(selection: $settings.connectionApproval) { ForEach(MCPConnectionApproval.allCases) { approval in Text(approval.displayName).tag(approval) } + } label: { + Text("Approval") + Text(settings.connectionApproval.explanation) } .pickerStyle(.menu) + .accessibilityIdentifier("mcp-approval-picker") - Text(settings.connectionApproval.explanation) - .foregroundStyle(.secondary) - .font(.callout) + NavigationLink(value: SettingsRoute.page(.mcpApprovals)) { + LabeledContent { + if let approvalsValue { + Text(approvalsValue) + .foregroundStyle(.secondary) + } + } label: { + Text("Approved connections") + if settings.connectionApproval != .oncePerConnection { + Text("Used only with Ask Once for Each Connection.") + } + } + } + .accessibilityIdentifier(SettingsPage.mcpApprovals.drillIdentifier) - MCPGrantListView() + SettingsDrillRow(route: SettingsRoute.page(.mcpTokens), title: "Tokens", value: tokensValue) - Toggle( - String(localized: "Allow apps to list connections hidden from AI"), - isOn: $settings.allowsHiddenConnectionListing - ) + MCPDefaultAIPolicyRow(onChange: onChangeAIPolicy) + + Toggle(isOn: $settings.allowsHiddenConnectionListing) { + Text("Allow apps to list connections hidden from AI") + // swiftlint:disable:next line_length + Text("A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once.") + } .accessibilityIdentifier("mcp-hidden-connection-listing-toggle") // swiftlint:disable:next line_length - Text(String(localized: "A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once.")) - .foregroundStyle(.secondary) - .font(.callout) + SettingsHelpRow("Approval is separate from what a client may reach. A connection blocked for external clients stays blocked, a read-only one stays read only, and Safe Mode still confirms destructive statements.") } header: { - Text("Connection Access") - } footer: { - // swiftlint:disable:next line_length - Text("Approval is separate from what a client may reach. A connection blocked for external clients stays blocked, a read-only one stays read only, and Safe Mode still confirms destructive statements.") - .font(.caption) - .foregroundStyle(.secondary) + Text("Access") } } - private var configurationSection: some View { + private var serverSection: some View { Section { - LabeledContent(String(localized: "Port")) { - TextField("", value: portBinding, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - .accessibilityIdentifier("mcp-port-field") - } + SettingsNumberField( + "Port", + value: $settings.port, + range: MCPSettings.portRange, + width: 64, + invalid: .reject(String( + format: String(localized: "Choose a port from %d to %d."), + MCPSettings.portRange.lowerBound, + MCPSettings.portRange.upperBound + )), + identifier: "mcp-port-field" + ) - LabeledContent(String(localized: "Default row limit")) { - TextField("", value: $settings.defaultRowLimit, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - } + SettingsNumberField( + "Default row limit", + subtitle: "Rows a query returns when the client sets no limit.", + value: $settings.defaultRowLimit, + range: settings.requestableRowLimitRange, + step: 100, + unit: "rows", + width: 72, + identifier: "mcp-default-row-limit-field" + ) - LabeledContent(String(localized: "Maximum row limit")) { - TextField("", value: $settings.maxRowLimit, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - } + SettingsNumberField( + "Maximum row limit", + subtitle: "The most rows a client can ask for.", + value: maxRowLimit, + range: SettingsValidationRules.mcpRowLimitRange, + step: 1_000, + unit: "rows", + width: 72, + identifier: "mcp-max-row-limit-field" + ) - LabeledContent(String(localized: "Query timeout")) { - HStack(spacing: 4) { - TextField("", value: $settings.queryTimeoutSeconds, format: .number.grouping(.never)) - .frame(width: 80) - .multilineTextAlignment(.trailing) - Text(String(localized: "seconds")) - .foregroundStyle(.secondary) - } - } + SettingsNumberField( + "Query timeout", + value: $settings.queryTimeoutSeconds, + range: SettingsValidationRules.mcpQueryTimeoutRange, + step: 5, + unit: "seconds", + width: 56, + identifier: "mcp-query-timeout-field" + ) - Toggle(String(localized: "Log MCP queries in history"), isOn: $settings.logQueriesInHistory) + Toggle("Log MCP queries in history", isOn: $settings.logQueriesInHistory) + .accessibilityIdentifier("mcp-log-queries-toggle") } header: { - Text(String(localized: "Server Configuration")) - } footer: { - if let rejectedPort { - NoticeLabel( - String( - format: String(localized: "Port %d cannot be used. Choose a port from %d to %d."), - rejectedPort, - MCPSettings.portRange.lowerBound, - MCPSettings.portRange.upperBound - ), - severity: .error - ) - .font(.caption) - } + Text("Server") } } - // An out-of-range port is kept out of the settings, so the server never binds a port the field did not show. - private var portBinding: Binding { + // A lower maximum pulls the default down with it in the same write. + private var maxRowLimit: Binding { Binding( - get: { settings.port }, - set: { newValue in - if MCPSettings.portRange.contains(newValue) { - rejectedPort = nil - settings.port = newValue - } else { - rejectedPort = newValue - } - } + get: { settings.maxRowLimit }, + set: { settings = settings.withMaxRowLimit($0) } ) } - private var authenticationSection: some View { - Section(String(localized: "Authentication")) { - MCPTokenListView( - tokens: tokenList, - isStoreAvailable: manager.tokenStore != nil, - onGenerate: { showCreateSheet = true }, - onRevoke: { id in revoke(id) }, - onDelete: { ids in delete(ids) } - ) - } - .task(id: manager.tokenStore.map { ObjectIdentifier($0) }) { await refreshTokens() } - .sheet(isPresented: $showCreateSheet) { - MCPTokenCreateSheet { name, permissions, connectionIds, expiresAt in - await generate(name: name, permissions: permissions, connectionIds: connectionIds, expiresAt: expiresAt) - } - } - .sheet(isPresented: $showRevealSheet) { - if !revealedPlaintext.isEmpty { - MCPTokenRevealSheet( - plaintext: revealedPlaintext, - port: manager.listeningPort ?? settings.port, - configuredPort: settings.port - ) - } - } - .alert(tokenAlert?.title ?? "", isPresented: tokenAlertBinding, presenting: tokenAlert) { _ in - Button(String(localized: "OK")) {} - } message: { alert in - Text(verbatim: alert.message) - } + private var approvalsValue: String? { + guard model.hasLoadedGrants else { return nil } + return model.grants.isEmpty ? String(localized: "None") : SettingsFormat.count(model.grants.count) } - private var tokenAlertBinding: Binding { - Binding( - get: { tokenAlert != nil }, - set: { isPresented in - if !isPresented { - tokenAlert = nil - } - } - ) - } - - private var helpSection: some View { - Section { - Button(String(localized: "Connect a Client…")) { - showSetupSheet = true - } - .accessibilityIdentifier("mcp-connect-client") - Button(String(localized: "View Activity…")) { - WindowOpener.shared.openIntegrationsActivity() - } - .accessibilityIdentifier("mcp-view-activity") - } - .sheet(isPresented: $showSetupSheet) { - MCPClientSetupSheet() - } - } - - private func generate( - name: String, - permissions: TokenPermissions, - connectionIds: Set?, - expiresAt: Date? - ) async -> MCPTokenCreateFailure? { - guard let store = manager.tokenStore else { - return MCPTokenCreateFailure( - message: String(localized: "The MCP server is not running, so TablePro cannot save a token now. Start the server, then try again."), - endsSheet: true - ) - } - let access: ConnectionAccess = connectionIds.map { .limited($0) } ?? .all - do { - let result = try await store.generate( - name: name, - permissions: permissions, - connectionAccess: access, - expiresAt: expiresAt, - isBridgeCredential: false, - isClaudeAgentCredential: false, - extraScopes: [] - ) - revealedPlaintext = result.plaintext - showCreateSheet = false - showRevealSheet = true - await refreshTokens() - return nil - } catch { - return MCPTokenCreateFailure(message: Self.generateFailureMessage(error), endsSheet: false) - } - } - - private static func generateFailureMessage(_ error: Error) -> String { - switch error as? MCPTokenStoreError { - case .storedTokensUnreadable?: - String(localized: "TablePro could not read the tokens saved in the Keychain, so it will not save a new one over them. Restart TablePro and try again.") - case .randomGenerationFailed?: - String(localized: "macOS could not generate a secure token. Try again.") - case .keychainUnavailable?, .notSaved?, nil: - String(localized: "TablePro could not save the token to the Keychain, so it was not created. Try again.") - } - } - - private func revoke(_ id: UUID) { - Task { - guard manager.tokenStore != nil else { - tokenAlert = .serverNotRunning - return - } - if !(await manager.revokeToken(id: id)) { - tokenAlert = .revocationNotSaved - } - await refreshTokens() - } - } - - private func delete(_ ids: Set) { - Task { - guard let store = manager.tokenStore else { - tokenAlert = .serverNotRunning - return - } - var allSaved = true - for id in ids { - let saved = await store.delete(tokenId: id) - allSaved = allSaved && saved - } - if !allSaved { - tokenAlert = .deletionNotSaved - } - await refreshTokens() - } - } - - private func refreshTokens() async { - guard let store = manager.tokenStore else { return } - tokenList = await store.list().filter { !$0.isBridgeCredential } - } -} - -private enum MCPTokenAlert: Equatable { - case serverNotRunning - case revocationNotSaved - case deletionNotSaved - - var title: String { - switch self { - case .serverNotRunning: String(localized: "MCP Server Not Running") - case .revocationNotSaved: String(localized: "Couldn't Save the Revocation") - case .deletionNotSaved: String(localized: "Couldn't Save the Deletion") - } - } - - var message: String { - switch self { - case .serverNotRunning: - String(localized: "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again.") - case .revocationNotSaved, .deletionNotSaved: - String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.") - } + private var tokensValue: String? { + guard model.tokenStore != nil else { return String(localized: "Unavailable") } + guard model.hasLoadedTokens else { return nil } + if model.tokens.isEmpty { return String(localized: "None") } + return String(format: String(localized: "%lld active"), model.activeTokenCount) } } @@ -300,24 +177,42 @@ private struct MCPStatusRow: View { var body: some View { let presentation = MCPServerStatusPresentation(state: manager.state, configuredPort: configuredPort) - LabeledContent(String(localized: "Status")) { + LabeledContent { HStack(spacing: 8) { IntegrationStatusIndicator(status: presentation.status, label: presentation.title) if presentation.offersRetry { Button(String(localized: "Try Again")) { manager.retry() } - .controlSize(.small) .accessibilityIdentifier("mcp-status-try-again") } } + } label: { + Text("Status") + if let detail = presentation.detail { + Text(verbatim: detail) + .textSelection(.enabled) + } } - if let detail = presentation.detail { - Text(detail) - .font(.caption) - .foregroundStyle(.secondary) - .textSelection(.enabled) - .fixedSize(horizontal: false, vertical: true) + } +} + +// Read only: the policy belongs to AI, and MCP enforces it for connections without their own. +private struct MCPDefaultAIPolicyRow: View { + @ObservedObject private var ai = AppSettingsManager.shared.aiSlice + let onChange: () -> Void + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + Text(ai.value.defaultConnectionPolicy.displayName) + .foregroundStyle(.secondary) + Button(String(localized: "Change…"), action: onChange) + .accessibilityIdentifier("mcp-default-ai-policy-change") + } + } label: { + Text("Default AI policy") + Text("Connections without their own AI Policy use it. Clients cannot query a connection set to Never.") } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift index 7e8b296c7b..5b94e21e6d 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenCreateSheet.swift @@ -1,48 +1,147 @@ import SwiftUI -struct MCPTokenCreateFailure: Equatable, Sendable { +struct MCPTokenCreateFailure: Error, Equatable, Sendable { let message: String // Nothing in this sheet can fix a server that is not running, so the alert closes it. let endsSheet: Bool } +struct MCPTokenRequest: Equatable, Sendable { + let name: String + let permissions: TokenPermissions + let connectionIds: Set? + let expiresAt: Date? +} + +struct MCPTokenReveal: Sendable { + let plaintext: String + let setup: MCPHTTPClientSetup + let port: Int + let configuredPort: Int +} + +// One sheet, the form and then the token, so the plaintext lives only in this sheet's state and goes with it. struct MCPTokenCreateSheet: View { private enum Field: Hashable { case name } + private enum Access: Hashable { + case all + case selected + } + @Environment(\.dismiss) private var dismiss - let onGenerate: (String, TokenPermissions, Set?, Date?) async -> MCPTokenCreateFailure? + let onGenerate: (MCPTokenRequest) async -> Result - @State private var tokenName = "" + @State private var name = "" @State private var permissions: TokenPermissions = .readOnly - @State private var connectionAccess: ConnectionAccessMode = .all + @State private var access: Access = .all @State private var selectedConnectionIds: Set = [] - @State private var expirationOption: ExpirationOption = .never - @State private var customExpirationDate = Calendar.current.date(byAdding: .day, value: 30, to: .now) ?? .now + @State private var expiry: TokenExpiry = .never + @State private var customExpiry = TokenExpiry.defaultCustomDate() @State private var connections: [DatabaseConnection] = [] @State private var isGenerating = false @State private var failure: MCPTokenCreateFailure? + @State private var reveal: MCPTokenReveal? @FocusState private var focused: Field? var body: some View { + Group { + if let reveal { + MCPTokenRevealSheet(reveal: reveal) { + dismiss() + } + } else { + createForm + } + } + .frame(minWidth: 540, minHeight: 520) + } + + private var createForm: some View { VStack(spacing: 0) { Form { - nameSection - permissionsSection - connectionAccessSection - expirationSection + Section { + TextField(text: $name, prompt: Text("Cursor on my Mac")) { + Text("Name") + } + .focused($focused, equals: .name) + .accessibilityIdentifier("mcp-token-name-field") + + Picker(selection: $permissions) { + ForEach(TokenPermissions.allCases) { permission in + Text(permission.displayName).tag(permission) + } + } label: { + Text("Permissions") + Text(permissions.summary) + } + .pickerStyle(.segmented) + .accessibilityIdentifier("mcp-token-permissions-picker") + } + + Section { + Picker(selection: $access) { + Text("All").tag(Access.all) + Text("Selected").tag(Access.selected) + } label: { + Text("Connections") + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-connections-picker") + + if access == .selected { + ConnectionAllowlistSection( + selection: $selectedConnectionIds, + connections: connections, + showsSelectAll: true + ) + } + } + + Section { + Picker(selection: $expiry) { + ForEach(TokenExpiry.allCases) { option in + Text(option.displayName).tag(option) + } + } label: { + Text("Expires") + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-expiry-picker") + + if expiry == .custom { + DatePicker( + String(localized: "Expiration date"), + selection: $customExpiry, + in: Date.now..., + displayedComponents: .date + ) + } + } } .formStyle(.grouped) + .defaultFocus($focused, .name) Divider() - actionBar - .padding() + DialogFooter { + Button(String(localized: "Cancel"), role: .cancel) { + dismiss() + } + .keyboardShortcut(.cancelAction) + + Button(String(localized: "Generate"), action: generate) + .keyboardShortcut(.defaultAction) + .disabled(!canGenerate) + .accessibilityIdentifier("mcp-token-generate") + } + .padding() } - .frame(minWidth: 480, minHeight: 520) .task { connections = ConnectionStorage.shared.loadConnections() + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } .alert( String(localized: "Couldn't Create the Token"), @@ -60,6 +159,14 @@ struct MCPTokenCreateSheet: View { } } + private var trimmedName: String { + name.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var canGenerate: Bool { + !isGenerating && !trimmedName.isEmpty && !(access == .selected && selectedConnectionIds.isEmpty) + } + private var failureBinding: Binding { Binding( get: { failure != nil }, @@ -71,148 +178,24 @@ struct MCPTokenCreateSheet: View { ) } - private var nameSection: some View { - Section(String(localized: "Token Name")) { - TextField(String(localized: "e.g., Cursor on my Mac"), text: $tokenName) - .focused($focused, equals: .name) - } - } - - private var permissionsSection: some View { - Section(String(localized: "Permission Level")) { - Picker(String(localized: "Permission"), selection: $permissions) { - ForEach(TokenPermissions.allCases) { permission in - Text(permission.displayName).tag(permission) - } - } - .pickerStyle(.segmented) - .labelsHidden() - } - } - - private var connectionAccessSection: some View { - Section(String(localized: "Connection Access")) { - Picker(String(localized: "Access"), selection: $connectionAccess) { - Text(String(localized: "All Connections")).tag(ConnectionAccessMode.all) - Text(String(localized: "Select Connections")).tag(ConnectionAccessMode.selected) - } - .labelsHidden() - - if connectionAccess == .selected { - connectionList - } - } - } - - @ViewBuilder - private var connectionList: some View { - if connections.isEmpty { - Text(String(localized: "No saved connections")) - .foregroundStyle(.secondary) - } else { - ForEach(connections) { connection in - Toggle(isOn: connectionBinding(for: connection.id)) { - HStack(spacing: 6) { - Text(connection.name) - Text(connection.type.displayName) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .toggleStyle(.checkbox) - } - } - } - - private var expirationSection: some View { - Section(String(localized: "Expiration")) { - Picker(String(localized: "Expires"), selection: $expirationOption) { - ForEach(ExpirationOption.allCases) { option in - Text(option.displayName).tag(option) - } - } - .labelsHidden() - - if expirationOption == .custom { - DatePicker( - String(localized: "Expiration date"), - selection: $customExpirationDate, - in: Date.now..., - displayedComponents: .date - ) - } - } - } - - private var actionBar: some View { - DialogFooter { - Button(String(localized: "Cancel"), role: .cancel) { - dismiss() - } - .keyboardShortcut(.cancelAction) - - Button(String(localized: "Generate")) { - let connectionIds: Set? = connectionAccess == .selected ? selectedConnectionIds : nil - isGenerating = true - Task { - failure = await onGenerate(tokenName, permissions, connectionIds, resolvedExpirationDate) - isGenerating = false - } - } - .keyboardShortcut(.defaultAction) - .disabled(isGenerating - || tokenName.trimmingCharacters(in: .whitespaces).isEmpty - || (connectionAccess == .selected && selectedConnectionIds.isEmpty)) - } - } - - private func connectionBinding(for id: UUID) -> Binding { - Binding( - get: { selectedConnectionIds.contains(id) }, - set: { isSelected in - if isSelected { - selectedConnectionIds.insert(id) - } else { - selectedConnectionIds.remove(id) - } - } + private func generate() { + guard canGenerate else { return } + let request = MCPTokenRequest( + name: trimmedName, + permissions: permissions, + connectionIds: access == .selected ? selectedConnectionIds : nil, + expiresAt: expiry.resolvedDate(custom: customExpiry) ) - } - - private var resolvedExpirationDate: Date? { - switch expirationOption { - case .never: nil - case .thirtyDays: Calendar.current.date(byAdding: .day, value: 30, to: .now) - case .sixtyDays: Calendar.current.date(byAdding: .day, value: 60, to: .now) - case .ninetyDays: Calendar.current.date(byAdding: .day, value: 90, to: .now) - case .custom: customExpirationDate - } - } -} - -private enum ConnectionAccessMode: String, Identifiable { - case all - case selected - - var id: String { rawValue } -} - -private enum ExpirationOption: String, CaseIterable, Identifiable { - case never - case thirtyDays - case sixtyDays - case ninetyDays - case custom - - var id: String { rawValue } - - var displayName: String { - switch self { - case .never: String(localized: "Never") - case .thirtyDays: String(localized: "30 days") - case .sixtyDays: String(localized: "60 days") - case .ninetyDays: String(localized: "90 days") - case .custom: String(localized: "Custom") + isGenerating = true + Task { + let result = await onGenerate(request) + isGenerating = false + switch result { + case .success(let issued): + reveal = issued + case .failure(let failed): + failure = failed + } } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift index 8f1e0f9ad9..784465c4dd 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift @@ -1,143 +1,247 @@ -import AppKit import SwiftUI import TableProMCP +enum MCPTokenAlert: Equatable { + case serverNotRunning + case revocationNotSaved + case deletionNotSaved + + var title: String { + switch self { + case .serverNotRunning: String(localized: "MCP Server Not Running") + case .revocationNotSaved: String(localized: "Couldn't Save the Revocation") + case .deletionNotSaved: String(localized: "Couldn't Save the Deletion") + } + } + + var message: String { + switch self { + case .serverNotRunning: + String(localized: "The MCP server is not running, so TablePro cannot change its tokens now. Start the server, then try again.") + case .revocationNotSaved, .deletionNotSaved: + String(localized: "TablePro could not save the change to the Keychain. The token works again after TablePro restarts.") + } + } +} + +// The Tokens page: a full-page list, so a long list of clients scrolls on its own. struct MCPTokenListView: View { - let tokens: [MCPAuthToken] - let isStoreAvailable: Bool - let onGenerate: () -> Void - let onRevoke: (UUID) -> Void - let onDelete: (Set) -> Void + private struct Confirmation: Identifiable { + enum Kind { + case revoke + case delete + } + + let kind: Kind + let tokens: [MCPAuthToken] + + var id: [UUID] { tokens.map(\.id) } + } + + @ObservedObject var model: MCPSettingsModel + let configuredPort: () -> Int @State private var selection: Set = [] - @State private var deleteCandidates: [MCPAuthToken] = [] + @State private var confirmation: Confirmation? + @State private var tokenAlert: MCPTokenAlert? + @State private var showsCreateSheet = false var body: some View { - VStack(alignment: .leading, spacing: 8) { - if tokens.isEmpty { - emptyState - } else { - List(selection: $selection) { - ForEach(tokens) { token in - MCPTokenRow(token: token) - .tag(token.id) - .contextMenu { - contextMenu(for: token) - } - } + SettingsFullPageList { + List(selection: $selection) { + ForEach(rows) { token in + MCPTokenRow( + token: token, + onRevoke: token.isActive ? { requestRevoke([token]) } : nil, + onDelete: { requestDelete([token]) } + ) + .tag(token.id) } - .frame(minHeight: 160) - .onDeleteCommand(perform: deleteSelectionFromKeyboard) } - - HStack(spacing: 8) { - Button { - onGenerate() - } label: { - Label(String(localized: "Generate Token"), systemImage: "plus") + .accessibilityIdentifier("mcp-tokens-list") + .contextMenu(forSelectionType: UUID.self) { ids in + menu(for: ids) + } + .onDeleteCommand { + requestDelete(tokens(in: selection)) + } + .alert( + confirmationTitle, + isPresented: confirmationBinding, + presenting: confirmation + ) { confirmation in + switch confirmation.kind { + case .revoke: + Button(String(localized: "Revoke"), role: .destructive) { + revoke(confirmation.tokens) + } + case .delete: + Button(String(localized: "Delete"), role: .destructive) { + delete(confirmation.tokens) + } } - .buttonStyle(.borderedProminent) - .disabled(!isStoreAvailable) - .accessibilityLabel(String(localized: "Generate token")) - - Spacer() + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { confirmation in + Text(verbatim: Self.confirmationMessage(confirmation)) } + } emptyState: { + emptyState + } bar: { + SettingsListBar( + addLabel: String(localized: "Generate Token"), + removeLabel: String(localized: "Delete"), + canAdd: model.tokenStore != nil, + canRemove: !tokens(in: selection).isEmpty, + addHelp: String(localized: "Generate Token…"), + removeHelp: String(localized: "Delete…"), + addIdentifier: "mcp-token-add", + removeIdentifier: "mcp-token-remove", + onAdd: { showsCreateSheet = true }, + onRemove: { requestDelete(tokens(in: selection)) } + ) } - .alert( - deleteAlertTitle, - isPresented: deleteAlertBinding, - presenting: deleteCandidates.isEmpty ? nil : deleteCandidates - ) { candidates in - Button(String(localized: "Cancel"), role: .cancel) { - deleteCandidates = [] - } - Button(String(localized: "Delete"), role: .destructive) { - let ids = Set(candidates.map(\.id)) - onDelete(ids) - selection.subtract(ids) - deleteCandidates = [] + .sheet(isPresented: $showsCreateSheet) { + MCPTokenCreateSheet { request in + await model.generate(request, configuredPort: configuredPort()) } - } message: { candidates in - Text(verbatim: Self.deleteAlertMessage(for: candidates)) } + .alert(tokenAlert?.title ?? "", isPresented: tokenAlertBinding, presenting: tokenAlert) { _ in + Button(String(localized: "OK")) {} + } message: { alert in + Text(verbatim: alert.message) + } + .onChange(of: model.tokens.map(\.id)) { ids in + selection.formIntersection(ids) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier(SettingsPage.mcpTokens.pageIdentifier) + } + + // Tokens from a stopped server stay loaded but are not shown, since nothing can change them. + private var rows: [MCPAuthToken] { + model.tokenStore == nil ? [] : model.tokens } + private func tokens(in ids: Set) -> [MCPAuthToken] { + rows.filter { ids.contains($0.id) } + } + + @ViewBuilder private var emptyState: some View { - VStack(spacing: 8) { - Image(systemName: "key") - .font(.title) - .foregroundStyle(.tertiary) - Text(isStoreAvailable ? String(localized: "No tokens created") : String(localized: "Tokens are not available")) - .foregroundStyle(.secondary) - Text(isStoreAvailable - ? String(localized: "Generate a token so external clients can connect with their own credentials.") - : String(localized: "Tokens load while the MCP server is running.")) - .font(.caption) - .foregroundStyle(.tertiary) - .multilineTextAlignment(.center) + if model.tokenStore == nil { + UnavailableStateView( + String(localized: "Tokens Unavailable"), + systemImage: "key", + description: Text("Tokens load while the MCP server is running.") + ) + } else if model.hasLoadedTokens && model.tokens.isEmpty { + UnavailableStateView { + Label("No Tokens", systemImage: "key") + } description: { + Text("Generate a token so external clients can connect with their own credentials.") + } actions: { + Button(String(localized: "Generate Token…")) { + showsCreateSheet = true + } + .accessibilityIdentifier("mcp-token-generate-empty") + } } - .frame(maxWidth: .infinity) - .padding(.vertical, 24) } @ViewBuilder - private func contextMenu(for token: MCPAuthToken) -> some View { - if token.isActive { - Button(role: .destructive) { - onRevoke(token.id) - } label: { - Label(String(localized: "Revoke"), systemImage: "xmark.circle") + private func menu(for ids: Set) -> some View { + let targets = tokens(in: ids) + if !targets.isEmpty { + if targets.contains(where: { $0.isActive }) { + Button(String(localized: "Revoke…")) { + requestRevoke(targets) + } + } + if targets.count == 1, let token = targets.first { + Button(String(localized: "Copy ID")) { + ClipboardService.shared.writeText(token.id.uuidString) + } + } + Divider() + Button(String(localized: "Delete…"), role: .destructive) { + requestDelete(targets) } - } - Button { - copyTokenId(token.id) - } label: { - Label(String(localized: "Copy ID"), systemImage: "doc.on.doc") - } - Divider() - Button(role: .destructive) { - // A right-click inside a multiple selection acts on all of it, as in Finder. - deleteCandidates = selection.contains(token.id) ? selectedTokens : [token] - } label: { - Label(String(localized: "Delete…"), systemImage: "trash") } } - private var selectedTokens: [MCPAuthToken] { - tokens.filter { selection.contains($0.id) } + private func requestRevoke(_ targets: [MCPAuthToken]) { + let active = targets.filter { $0.isActive } + guard !active.isEmpty else { return } + confirmation = Confirmation(kind: .revoke, tokens: active) } - private func deleteSelectionFromKeyboard() { - deleteCandidates = selectedTokens + private func requestDelete(_ targets: [MCPAuthToken]) { + guard !targets.isEmpty else { return } + confirmation = Confirmation(kind: .delete, tokens: targets) } - private func copyTokenId(_ id: UUID) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(id.uuidString, forType: .string) + private func revoke(_ targets: [MCPAuthToken]) { + let ids = Set(targets.map(\.id)) + Task { + tokenAlert = await model.revoke(ids) + } } - private var deleteAlertTitle: String { - deleteCandidates.count > 1 - ? String(format: String(localized: "Delete %d tokens?"), deleteCandidates.count) - : String(localized: "Delete token?") + private func delete(_ targets: [MCPAuthToken]) { + let ids = Set(targets.map(\.id)) + selection.subtract(ids) + Task { + tokenAlert = await model.delete(ids) + } } - private static func deleteAlertMessage(for candidates: [MCPAuthToken]) -> String { - guard candidates.count > 1 else { - return String( - format: String(localized: "“%@” will be permanently deleted. External clients using this token will lose access immediately."), - candidates.first?.name ?? "" - ) + private var confirmationTitle: String { + guard let confirmation else { return "" } + let count = confirmation.tokens.count + let name = confirmation.tokens.first?.name ?? "" + switch confirmation.kind { + case .revoke: + return count > 1 + ? String(format: String(localized: "Revoke %d Tokens?"), count) + : String(format: String(localized: "Revoke “%@”?"), name) + case .delete: + return count > 1 + ? String(format: String(localized: "Delete %d Tokens?"), count) + : String(format: String(localized: "Delete “%@”?"), name) } - return String(localized: "These tokens will be permanently deleted. External clients using them will lose access immediately.") } - private var deleteAlertBinding: Binding { + private static func confirmationMessage(_ confirmation: Confirmation) -> String { + let isSingle = confirmation.tokens.count == 1 + switch confirmation.kind { + case .revoke: + return isSingle + ? String(localized: "Apps using it lose access now. This can't be undone.") + : String(localized: "Apps using them lose access now. This can't be undone.") + case .delete: + return isSingle + ? String(localized: "Apps using it lose access now, and the token leaves this list.") + : String(localized: "Apps using them lose access now, and the tokens leave this list.") + } + } + + private var confirmationBinding: Binding { + Binding( + get: { confirmation != nil }, + set: { isPresented in + if !isPresented { + confirmation = nil + } + } + ) + } + + private var tokenAlertBinding: Binding { Binding( - get: { !deleteCandidates.isEmpty }, + get: { tokenAlert != nil }, set: { isPresented in if !isPresented { - deleteCandidates = [] + tokenAlert = nil } } ) @@ -146,56 +250,79 @@ struct MCPTokenListView: View { private struct MCPTokenRow: View { let token: MCPAuthToken + let onRevoke: (() -> Void)? + let onDelete: () -> Void var body: some View { HStack(spacing: 10) { - VStack(alignment: .leading, spacing: 3) { - Text(token.name) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: token.name) + .lineLimit(1) - HStack(spacing: 8) { + HStack(spacing: 4) { Text(token.permissions.displayName) - .font(.caption) - .foregroundStyle(.secondary) - - Text(token.prefix + "…") - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(.secondary) - + Text(verbatim: "·") + connectionsText + Text(verbatim: "·") + Text(verbatim: token.prefix + "…") + .font(.subheadline.monospaced()) + Text(verbatim: "·") Text(lastUsedText) - .font(.caption) - .foregroundStyle(.tertiary) } + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) if token.extraScopes.contains(.connectionsDisplay) { - Text(String(localized: "Lists connections hidden from AI")) - .font(.caption) + Text("Lists connections hidden from AI") + .font(.subheadline) .foregroundStyle(.secondary) } } - Spacer() + Spacer(minLength: 8) - IntegrationStatusIndicator(status: tokenStatus) - .help(tokenStatus == .active - ? String(localized: "Active") - : tokenStatus == .expired - ? String(localized: "Expired") - : String(localized: "Revoked")) + status } .padding(.vertical, 2) + .accessibilityElement(children: .combine) + .accessibilityActions { + if let onRevoke { + Button(String(localized: "Revoke"), action: onRevoke) + } + Button(String(localized: "Delete"), action: onDelete) + } } - private var tokenStatus: IntegrationStatus { - if token.isExpired { return .expired } - return token.isActive ? .active : .revoked + @ViewBuilder + private var connectionsText: some View { + switch token.connectionAccess { + case .all: + Text("All connections") + case .limited(let ids): + Text("^[\(ids.count) connection](inflect: true)") + } + } + + @ViewBuilder + private var status: some View { + if !token.isActive { + IntegrationStatusIndicator(status: .revoked, label: String(localized: "Revoked")) + } else if token.isExpired { + IntegrationStatusIndicator(status: .expired, label: String(localized: "Expired")) + } else if let expiresAt = token.expiresAt { + Text(String(format: String(localized: "Expires %@"), expiresAt.formatted(date: .abbreviated, time: .omitted))) + .foregroundStyle(.secondary) + } else { + Text("Active") + .foregroundStyle(.secondary) + } } private var lastUsedText: String { guard let lastUsed = token.lastUsedAt else { return String(localized: "Never used") } - let formatter = RelativeDateTimeFormatter() - formatter.unitsStyle = .full - return formatter.localizedString(for: lastUsed, relativeTo: .now) + return String(format: String(localized: "Last used %@"), lastUsed.formatted(.relative(presentation: .named))) } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift index 7dd6d41913..9d131d582e 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift @@ -1,136 +1,113 @@ -import AppKit import SwiftUI +// Shown inside MCPTokenCreateSheet once the token exists; it has no cancel action, only Done. struct MCPTokenRevealSheet: View { - let plaintext: String - let port: Int - let configuredPort: Int - @Environment(\.dismiss) private var dismiss + let reveal: MCPTokenReveal + let onDone: () -> Void @State private var isTokenRevealed = false @State private var selectedClientID: String - private let setup: MCPHTTPClientSetup - - init(plaintext: String, port: Int, configuredPort: Int) { - self.plaintext = plaintext - self.port = port - self.configuredPort = configuredPort - let setup = MCPHTTPClientSetup(port: port) - self.setup = setup - _selectedClientID = State(initialValue: setup.choices.first?.id ?? MCPHTTPClientSetup.otherClientID) + init(reveal: MCPTokenReveal, onDone: @escaping () -> Void) { + self.reveal = reveal + self.onDone = onDone + _selectedClientID = State(initialValue: reveal.setup.choices.first?.id ?? MCPHTTPClientSetup.otherClientID) } var body: some View { VStack(spacing: 0) { - ScrollView { - VStack(alignment: .leading, spacing: 20) { - warningBanner - tokenDisplay - setupInstructions + Form { + Section { + NoticeLabel(String(localized: "Copy this token now. TablePro won't show it again."), severity: .warning) + + LabeledContent { + HStack(spacing: 8) { + Text(verbatim: displayedToken) + .font(.body.monospaced()) + .textSelection(.enabled) + .lineLimit(1) + .truncationMode(.middle) + + Button { + isTokenRevealed.toggle() + } label: { + Image(systemName: isTokenRevealed ? "eye.slash" : "eye") + } + .buttonStyle(.borderless) + .accessibilityLabel(isTokenRevealed + ? String(localized: "Hide token") + : String(localized: "Reveal token")) + .help(isTokenRevealed + ? String(localized: "Hide token") + : String(localized: "Reveal token")) + + Button(String(localized: "Copy")) { + ClipboardService.shared.writeSecretText(reveal.plaintext) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) + } + .accessibilityLabel(String(localized: "Copy token")) + .accessibilityIdentifier("mcp-token-copy") + } + } label: { + Text("Token") + } + } + + Section { + Picker(String(localized: "Client"), selection: $selectedClientID) { + ForEach(reveal.setup.choices) { choice in + Text(verbatim: choice.name).tag(choice.id) + } + } + .pickerStyle(.menu) + .accessibilityIdentifier("mcp-token-client-picker") + + if reveal.port != reveal.configuredPort { + NoticeLabel(String( + format: String(localized: "Port %d was in use, so this address changes when TablePro restarts."), + reveal.configuredPort + )) + } + + if selectedClientID == MCPHTTPClientSetup.otherClientID { + otherClientInstructions + } else { + clientInstructions + } + } header: { + Text("Set Up a Client") } - .padding(20) } + .formStyle(.grouped) Divider() - HStack { - Spacer() - Button(String(localized: "Done")) { dismiss() } + DialogFooter { + Button(String(localized: "Done"), action: onDone) .keyboardShortcut(.defaultAction) + .accessibilityIdentifier("mcp-token-done") } .padding() } - .frame(minWidth: 540, minHeight: 520) - } - - private var warningBanner: some View { - NoticeLabel(String(localized: "This token will not be shown again"), severity: .warning) - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var tokenDisplay: some View { - VStack(alignment: .leading, spacing: 8) { - Text(String(localized: "Token")) - .font(.headline) - - HStack(spacing: 8) { - Text(verbatim: displayedToken) - .font(.system(.body, design: .monospaced)) - .textSelection(.enabled) - .lineLimit(1) - .truncationMode(.middle) - - Spacer(minLength: 0) - - Button { - isTokenRevealed.toggle() - } label: { - Image(systemName: isTokenRevealed ? "eye.slash" : "eye") - } - .accessibilityLabel(isTokenRevealed - ? String(localized: "Hide token") - : String(localized: "Reveal token")) - .help(isTokenRevealed - ? String(localized: "Hide token") - : String(localized: "Reveal token")) - } - .padding(10) - .background(.quaternary) - .clipShape(RoundedRectangle(cornerRadius: 6)) - - Button { - ClipboardService.shared.writeSecretText(plaintext) - AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) - } label: { - Label(String(localized: "Copy Token"), systemImage: "doc.on.doc") - } - .accessibilityLabel(String(localized: "Copy token")) - } - } - - private var setupInstructions: some View { - VStack(alignment: .leading, spacing: 12) { - Text(String(localized: "Setup Instructions")) - .font(.headline) - - Picker(String(localized: "Client"), selection: $selectedClientID) { - ForEach(setup.choices) { choice in - Text(verbatim: choice.name).tag(choice.id) - } - } - .pickerStyle(.menu) - .fixedSize() - .accessibilityIdentifier("mcp-token-client-picker") - - if port != configuredPort { - NoticeLabel(String( - format: String(localized: "Port %d was in use, so this address changes when TablePro restarts."), - configuredPort - )) - } - - if selectedClientID == MCPHTTPClientSetup.otherClientID { - otherClientInstructions - } else { - clientInstructions - } - } } @ViewBuilder private var clientInstructions: some View { - if let copied = setup.render(clientID: selectedClientID, token: plaintext), - let shown = setup.render(clientID: selectedClientID, token: displayedToken) { + if let copied = reveal.setup.render(clientID: selectedClientID, token: reveal.plaintext), + let shown = reveal.setup.render(clientID: selectedClientID, token: displayedToken) { if let commandLine = copied.commandLine { - Text(String(localized: "Run this in Terminal:")) - CopyableCodeBlock(text: commandLine, displayText: shown.commandLine, isSecret: true) + VStack(alignment: .leading, spacing: 6) { + Text("Run this in Terminal:") + CopyableCodeBlock(text: commandLine, displayText: shown.commandLine, isSecret: true) + } } if let snippet = copied.snippet { - if let path = copied.displayConfigPath { - Text(String(format: String(localized: "Add this to %@:"), path)) + VStack(alignment: .leading, spacing: 6) { + if let path = copied.displayConfigPath { + Text(String(format: String(localized: "Add this to %@:"), path)) + } + CopyableCodeBlock(text: snippet, displayText: shown.snippet, isSecret: true) } - CopyableCodeBlock(text: snippet, displayText: shown.snippet, isSecret: true) } } else { otherClientInstructions @@ -138,11 +115,11 @@ struct MCPTokenRevealSheet: View { } private var otherClientInstructions: some View { - VStack(alignment: .leading, spacing: 8) { - Text(String(localized: "Give your client this address and header:")) - CopyableCodeBlock(text: setup.url) + VStack(alignment: .leading, spacing: 6) { + Text("Give your client this address and header:") + CopyableCodeBlock(text: reveal.setup.url) CopyableCodeBlock( - text: header(token: plaintext), + text: header(token: reveal.plaintext), displayText: header(token: displayedToken), isSecret: true ) @@ -154,10 +131,10 @@ struct MCPTokenRevealSheet: View { } private var displayedToken: String { - isTokenRevealed ? plaintext : maskedToken + isTokenRevealed ? reveal.plaintext : maskedToken } private var maskedToken: String { - String(plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) + String(reveal.plaintext.prefix(8)) + String(repeating: "\u{2022}", count: 24) } } diff --git a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift index 501dd6e6b9..247001ba1d 100644 --- a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift @@ -1,4 +1,3 @@ -import Combine import SwiftUI import TableProMCP @@ -9,7 +8,13 @@ struct PairingApproval: Sendable { let extraScopes: Set } +// Hosted by AlertHelper.runPairingApproval in its own window, so it works while Settings is closed. struct PairingApprovalSheet: View { + private enum Access: Hashable { + case all + case selected + } + let request: PairingRequest let codeExpiresAt: Date let allowsHiddenConnectionListing: Bool @@ -17,14 +22,12 @@ struct PairingApprovalSheet: View { @State private var permissions: TokenPermissions @State private var grantsHiddenConnections = false - @State private var connectionAccess: ConnectionAccessMode = .all + @State private var access: Access = .all @State private var selectedConnectionIds: Set = [] - @State private var expiry: ExpiryOption = .never + @State private var expiry: TokenExpiry = .never + @State private var customExpiry = TokenExpiry.defaultCustomDate() @State private var connections: [DatabaseConnection] = [] - @State private var connectionSearch: String = "" - @State private var now: Date = .now - - private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() + @State private var isExpired: Bool init( request: PairingRequest, @@ -37,8 +40,9 @@ struct PairingApprovalSheet: View { self.allowsHiddenConnectionListing = allowsHiddenConnectionListing self.onComplete = onComplete _permissions = State(initialValue: request.scopeRequest.permissions) + _isExpired = State(initialValue: codeExpiresAt <= .now) if let requested = request.requestedConnectionIds, !requested.isEmpty { - _connectionAccess = State(initialValue: .selected) + _access = State(initialValue: .selected) _selectedConnectionIds = State(initialValue: requested) } } @@ -49,7 +53,7 @@ struct PairingApprovalSheet: View { Divider() Form { permissionsSection - connectionAccessSection + connectionsSection if requestsHiddenConnections { hiddenConnectionsSection } @@ -65,12 +69,17 @@ struct PairingApprovalSheet: View { .frame(width: 520) .task { connections = ConnectionStorage.shared.loadConnections() - if connectionAccess == .all { + if access == .all { selectedConnectionIds = Set(connections.map(\.id)) } } - .onReceive(timer) { value in - now = value + .task { + let remaining = codeExpiresAt.timeIntervalSinceNow + if remaining > 0 { + try? await Task.sleep(for: .seconds(remaining)) + } + guard !Task.isCancelled else { return } + isExpired = true } } @@ -81,11 +90,13 @@ struct PairingApprovalSheet: View { .font(.headline) .lineLimit(2) .truncationMode(.tail) - Text(String(localized: "An external app is asking for an API token. Review the permissions before approving.")) - .font(.callout) + Text("An external app is asking for an API token. Review the permissions before approving.") + .font(.subheadline) .foregroundStyle(.secondary) destinationLabel - countdownLabel + TimelineView(.periodic(from: .now, by: 1)) { timeline in + countdownLabel(now: timeline.date) + } } .frame(maxWidth: .infinity, alignment: .leading) .padding() @@ -95,11 +106,11 @@ struct PairingApprovalSheet: View { private var destinationLabel: some View { HStack(spacing: 6) { Image(systemName: "arrow.up.forward.app") - .foregroundStyle(Color(nsColor: .secondaryLabelColor)) + .foregroundStyle(.secondary) .imageScale(.small) .accessibilityHidden(true) Text(String(format: String(localized: "Sends the code to %@"), request.redirectDisplayValue)) - .font(.caption) + .font(.subheadline) .foregroundStyle(.secondary) .lineLimit(2) .truncationMode(.middle) @@ -107,117 +118,66 @@ struct PairingApprovalSheet: View { } } - private var countdownLabel: some View { - HStack(spacing: 6) { - Image(systemName: isExpired ? "clock.badge.exclamationmark.fill" : "clock") - .foregroundStyle(isExpired ? .red : Color(nsColor: .secondaryLabelColor)) + private func countdownLabel(now: Date) -> some View { + let remaining = max(0, Int(codeExpiresAt.timeIntervalSince(now).rounded(.up))) + let expired = isExpired || remaining == 0 + return HStack(spacing: 6) { + Image(systemName: expired ? "clock.badge.exclamationmark.fill" : "clock") + .foregroundStyle(expired ? Color.red : Color.secondary) .imageScale(.small) .accessibilityHidden(true) - countdownText - .font(.caption) - .monospacedDigit() - .foregroundStyle(.secondary) - .contentTransition(.numericText()) - } - } - - private var remainingSeconds: Int { - let interval = codeExpiresAt.timeIntervalSince(now) - return max(0, Int(interval.rounded(.up))) - } - - private var isExpired: Bool { - remainingSeconds <= 0 - } - - private var countdownText: Text { - if isExpired { - return Text(String(localized: "Code expired")) + Group { + if expired { + Text("Code expired") + } else { + Text("Code expires in ^[\(remaining) second](inflect: true)") + } + } + .font(.subheadline) + .monospacedDigit() + .foregroundStyle(.secondary) + .contentTransition(.numericText()) } - return Text("Code expires in ^[\(remainingSeconds) second](inflect: true)") } private var permissionsSection: some View { - Section(String(localized: "Permission Level")) { - Picker(String(localized: "Permission"), selection: $permissions) { + Section { + Picker(selection: $permissions) { ForEach(TokenPermissions.allCases) { permission in Text(permission.displayName).tag(permission) } + } label: { + Text("Permissions") + Text(permissions.summary) } .pickerStyle(.segmented) - .labelsHidden() - - Text(permissionsDescription) - .font(.caption) - .foregroundStyle(.secondary) + .accessibilityIdentifier("pairing-permissions-picker") } } - private var connectionAccessSection: some View { - Section(String(localized: "Allowed Connections")) { - Picker(String(localized: "Access"), selection: $connectionAccess) { - Text(String(localized: "All Connections")).tag(ConnectionAccessMode.all) - Text(String(localized: "Select Connections")).tag(ConnectionAccessMode.selected) + private var connectionsSection: some View { + Section { + Picker(selection: $access) { + Text("All").tag(Access.all) + Text("Selected").tag(Access.selected) + } label: { + Text("Connections") } - .labelsHidden() - .onChange(of: connectionAccess) { newValue in - if newValue == .all { - selectedConnectionIds = Set(connections.map(\.id)) - } else if selectedConnectionIds.isEmpty { + .pickerStyle(.menu) + .accessibilityIdentifier("pairing-connections-picker") + .onChange(of: access) { newValue in + if newValue == .all || selectedConnectionIds.isEmpty { selectedConnectionIds = Set(connections.map(\.id)) } } - if connectionAccess == .selected { - connectionList - } - } - } - - @ViewBuilder - private var connectionList: some View { - if connections.isEmpty { - Text(String(localized: "No saved connections")) - .foregroundStyle(.secondary) - } else { - HStack { - NativeSearchField(text: $connectionSearch, placeholder: String(localized: "Search connections")) - Spacer() - Button(String(localized: "Select All")) { - selectedConnectionIds.formUnion(filteredConnections.map(\.id)) - } - Button(String(localized: "Deselect All")) { - selectedConnectionIds.subtract(filteredConnections.map(\.id)) - } - } - - ScrollView { - VStack(alignment: .leading, spacing: 0) { - ForEach(filteredConnections) { connection in - Toggle(isOn: connectionBinding(for: connection.id)) { - HStack(spacing: 6) { - Text(connection.name) - Text(connection.type.displayName) - .font(.caption) - .foregroundStyle(.secondary) - } - } - .toggleStyle(.checkbox) - .padding(.vertical, 2) - } - } + if access == .selected { + ConnectionAllowlistSection( + selection: $selectedConnectionIds, + connections: connections, + showsSelectAll: true + ) } - .frame(maxHeight: 200) - } - } - - private var filteredConnections: [DatabaseConnection] { - let trimmed = connectionSearch.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return connections } - let lowercased = trimmed.lowercased() - return connections.filter { connection in - connection.name.lowercased().contains(lowercased) - || connection.type.displayName.lowercased().contains(lowercased) } } @@ -227,32 +187,46 @@ struct PairingApprovalSheet: View { // Off even when allowed: an agent with a shell can pair to its own redirect, and one Approve must not hand it these. private var hiddenConnectionsSection: some View { - Section(String(localized: "Connections Hidden from AI")) { + Section { if allowsHiddenConnectionListing { - Toggle(String(localized: "List connections hidden from AI"), isOn: $grantsHiddenConnections) - .accessibilityIdentifier("pairing-hidden-connections-toggle") - // swiftlint:disable:next line_length - Text(String(localized: "Adds connections whose AI Policy is Never to this app's list, with each user name. The app still cannot query them. Blocked connections stay hidden.")) - .font(.caption) - .foregroundStyle(.secondary) + Toggle(isOn: $grantsHiddenConnections) { + Text("List connections hidden from AI") + Text("Adds connections whose AI Policy is Never to this app's list, with each user name. The app still cannot query them. Blocked connections stay hidden.") + } + .accessibilityIdentifier("pairing-hidden-connections-toggle") } else { // swiftlint:disable:next line_length - Text(String(localized: "This app also asks to list connections hidden from AI. To allow that, turn on “Allow apps to list connections hidden from AI” in Settings > MCP, then pair again.")) - .font(.caption) + Text("This app also asks to list connections hidden from AI. To allow that, turn on “Allow apps to list connections hidden from AI” in Settings > MCP, then pair again.") + .font(.subheadline) .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("pairing-hidden-connections-refusal") } + } header: { + Text("Connections Hidden from AI") } } private var expirySection: some View { - Section(String(localized: "Expiration")) { - Picker(String(localized: "Expires"), selection: $expiry) { - ForEach(ExpiryOption.allCases) { option in + Section { + Picker(selection: $expiry) { + ForEach(TokenExpiry.allCases) { option in Text(option.displayName).tag(option) } + } label: { + Text("Expires") + } + .pickerStyle(.menu) + .accessibilityIdentifier("pairing-expiry-picker") + + if expiry == .custom { + DatePicker( + String(localized: "Expiration date"), + selection: $customExpiry, + in: Date.now..., + displayedComponents: .date + ) } - .labelsHidden() } } @@ -261,8 +235,8 @@ struct PairingApprovalSheet: View { Button(String(localized: "Approve")) { let approval = PairingApproval( grantedPermissions: permissions, - allowedConnectionIds: connectionAccess == .selected ? selectedConnectionIds : nil, - expiresAt: expiry.resolvedDate, + allowedConnectionIds: access == .selected ? selectedConnectionIds : nil, + expiresAt: expiry.resolvedDate(custom: customExpiry), extraScopes: grantsHiddenConnections && allowsHiddenConnectionListing ? [.connectionsDisplay] : [] ) onComplete(.success(approval)) @@ -278,68 +252,7 @@ struct PairingApprovalSheet: View { private var approveDisabled: Bool { if isExpired { return true } - if connectionAccess == .selected && selectedConnectionIds.isEmpty { return true } + if access == .selected && selectedConnectionIds.isEmpty { return true } return false } - - private func connectionBinding(for id: UUID) -> Binding { - Binding( - get: { selectedConnectionIds.contains(id) }, - set: { isSelected in - if isSelected { - selectedConnectionIds.insert(id) - } else { - selectedConnectionIds.remove(id) - } - } - ) - } - - private var permissionsDescription: String { - switch permissions { - case .readOnly: - String(localized: "Read schema and run SELECT queries.") - case .readWrite: - String(localized: "Read schema and run any non-destructive query, including INSERT, UPDATE, and DELETE.") - case .fullAccess: - String(localized: "Full access including destructive DDL after explicit confirmation.") - } - } -} - -private enum ConnectionAccessMode: String, Identifiable, Sendable { - case all - case selected - - var id: String { rawValue } -} - -private enum ExpiryOption: String, CaseIterable, Identifiable, Sendable { - case never - case oneDay - case sevenDays - case thirtyDays - case ninetyDays - - var id: String { rawValue } - - var displayName: String { - switch self { - case .never: String(localized: "Never") - case .oneDay: String(localized: "1 day") - case .sevenDays: String(localized: "7 days") - case .thirtyDays: String(localized: "30 days") - case .ninetyDays: String(localized: "90 days") - } - } - - var resolvedDate: Date? { - switch self { - case .never: nil - case .oneDay: Calendar.current.date(byAdding: .day, value: 1, to: .now) - case .sevenDays: Calendar.current.date(byAdding: .day, value: 7, to: .now) - case .thirtyDays: Calendar.current.date(byAdding: .day, value: 30, to: .now) - case .ninetyDays: Calendar.current.date(byAdding: .day, value: 90, to: .now) - } - } } diff --git a/apple/TableProTests/Core/MCP/MCPSettingsTests.swift b/apple/TableProTests/Core/MCP/MCPSettingsTests.swift index 826a3409df..c6a1f36af3 100644 --- a/apple/TableProTests/Core/MCP/MCPSettingsTests.swift +++ b/apple/TableProTests/Core/MCP/MCPSettingsTests.swift @@ -184,4 +184,64 @@ struct MCPSettingsTests { #expect(decoded == original) } + + @Test("Lowering the maximum row limit pulls a higher default down in the same write") + func lowerMaximumPullsTheDefaultDown() { + let settings = MCPSettings(defaultRowLimit: 5_000, maxRowLimit: 10_000).withMaxRowLimit(1_000) + #expect(settings.maxRowLimit == 1_000) + #expect(settings.defaultRowLimit == 1_000) + } + + @Test("Raising the maximum row limit leaves the default alone") + func raisingTheMaximumKeepsTheDefault() { + let settings = MCPSettings(defaultRowLimit: 500, maxRowLimit: 10_000).withMaxRowLimit(20_000) + #expect(settings.maxRowLimit == 20_000) + #expect(settings.defaultRowLimit == 500) + } + + @Test("A maximum row limit outside the allowed range is clamped, and changes nothing else") + func maximumRowLimitIsClamped() { + let original = MCPSettings(enabled: true, port: 5_000, queryTimeoutSeconds: 45, logQueriesInHistory: false) + let lowest = original.withMaxRowLimit(0) + #expect(lowest.maxRowLimit == SettingsValidationRules.mcpRowLimitRange.lowerBound) + #expect(lowest.defaultRowLimit == SettingsValidationRules.mcpRowLimitRange.lowerBound) + + let highest = original.withMaxRowLimit(Int.max) + #expect(highest.maxRowLimit == SettingsValidationRules.mcpRowLimitRange.upperBound) + #expect(highest.defaultRowLimit == original.defaultRowLimit) + #expect(highest.port == original.port) + #expect(highest.queryTimeoutSeconds == original.queryTimeoutSeconds) + #expect(highest.logQueriesInHistory == original.logQueriesInHistory) + #expect(highest.enabled == original.enabled) + } + + @Test("Both token sheets offer the same expiry choices, Never first") + func tokenExpiryChoices() { + #expect(TokenExpiry.allCases.first == .never) + #expect(TokenExpiry.allCases.map { $0.days } == [nil, 1, 7, 30, 60, 90, nil]) + } + + @Test("A fixed expiry adds its days, Never has no date, and Custom keeps the picked date") + func tokenExpiryResolvesDates() throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = try #require(TimeZone(identifier: "UTC")) + let now = Date(timeIntervalSince1970: 1_700_000_000) + let picked = Date(timeIntervalSince1970: 1_800_000_000) + + #expect(TokenExpiry.never.resolvedDate(custom: picked, from: now, calendar: calendar) == nil) + #expect(TokenExpiry.custom.resolvedDate(custom: picked, from: now, calendar: calendar) == picked) + for option in TokenExpiry.allCases { + guard let days = option.days else { continue } + let expected = calendar.date(byAdding: .day, value: days, to: now) + #expect(option.resolvedDate(custom: picked, from: now, calendar: calendar) == expected) + } + } + + @Test("A custom expiry starts thirty days out") + func customExpiryDefault() throws { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = try #require(TimeZone(identifier: "UTC")) + let now = Date(timeIntervalSince1970: 1_700_000_000) + #expect(TokenExpiry.defaultCustomDate(from: now, calendar: calendar) == now.addingTimeInterval(30 * 86_400)) + } } diff --git a/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift b/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift index 1ed522539d..bc43b79279 100644 --- a/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift +++ b/apple/TableProTests/Core/MCP/MCPTokenStoreTests.swift @@ -1,8 +1,4 @@ -// Minting a token is a grant, so the store makes the caller state the grant: `generate` takes the -// connection scope and the expiry with no defaults, because the defaults it used to carry handed -// every caller that forgot them a token over every connection that never expired. Two tokens may -// share a name; pairing no longer revokes an existing token because a new client claimed the same -// one, which let any caller name an installed client and take its access away. +// generate has no default scope or expiry, and a shared name never revokes another client's token. import Foundation import TableProMCP @@ -890,6 +886,88 @@ struct MCPTokenStoreTests { #expect(access.allows(UUID()) == false) #expect(ConnectionAccess.all.allows(UUID())) } + + @Test("Only a token a person made is user managed") + func userManagedExcludesTableProsOwnTokens() { + #expect(makeToken().isUserManaged) + #expect(makeToken(isClaudeAgentCredential: true).isUserManaged == false) + let bridge = MCPAuthToken( + id: UUID(), + name: MCPTokenStore.stdioBridgeTokenName, + prefix: "tp_abc12", + tokenHash: "fakehash", + salt: "fakesalt", + permissions: .readWrite, + connectionAccess: .all, + createdAt: Date.now, + lastUsedAt: nil, + expiresAt: nil, + isActive: true, + isBridgeCredential: true + ) + #expect(bridge.isUserManaged == false) + } + + @Test("Every permission tier explains what it allows") + func permissionSummariesAreNotEmpty() { + for permissions in TokenPermissions.allCases { + #expect(!permissions.summary.isEmpty) + } + } + + @Test("Adding, revoking and deleting a client token each announce a membership change") + func membershipChangesAreAnnounced() async throws { + let store = makeStore() + var changes = store.membershipChanges.changes().makeAsyncIterator() + + let issued = try await store.generate( + name: "Raycast", + permissions: .readOnly, + connectionAccess: .all, + expiresAt: nil, + isBridgeCredential: false, + isClaudeAgentCredential: false, + extraScopes: [] + ) + let afterGenerate: Void? = await changes.next() + #expect(afterGenerate != nil) + + await store.revoke(tokenId: issued.token.id) + let afterRevoke: Void? = await changes.next() + #expect(afterRevoke != nil) + + await store.delete(tokenId: issued.token.id) + let afterDelete: Void? = await changes.next() + #expect(afterDelete != nil) + } + + @Test("An expired Claude Agent token left by a crashed turn is dropped at load, and a live one is kept") + func expiredAgentTokenIsDroppedAtLoad() async throws { + let expiredAgent = makeToken( + name: MCPTokenStore.claudeAgentTokenName, + expiresAt: Date.now.addingTimeInterval(-60), + isClaudeAgentCredential: true + ) + let liveAgent = makeToken( + name: MCPTokenStore.claudeAgentTokenName, + expiresAt: Date.now.addingTimeInterval(3_600), + isClaudeAgentCredential: true + ) + let expiredClient = makeToken(name: "Raycast", expiresAt: Date.now.addingTimeInterval(-60)) + let credentials = InMemoryCredentialStore( + seed: try MCPTokenStore.encodeStored(tokens: [expiredAgent, liveAgent, expiredClient], undecoded: []) + ) + + let store = makeStore(credentials) + await store.loadFromDisk() + + #expect(await store.token(id: expiredAgent.id) == nil) + #expect(await store.token(id: liveAgent.id) != nil) + #expect(await store.token(id: expiredClient.id) != nil) + let saved = MCPTokenStore.decodeStored(Data(credentials.storedText.utf8)).tokens.map { $0.id } + #expect(saved.contains(expiredAgent.id) == false) + #expect(saved.contains(expiredClient.id)) + } } private actor RevocationRecorder { diff --git a/apple/TableProTests/Core/MCP/Outside/MCPServerStoreTests.swift b/apple/TableProTests/Core/MCP/Outside/MCPServerStoreTests.swift index 4fbae967e0..66b8c0f5cf 100644 --- a/apple/TableProTests/Core/MCP/Outside/MCPServerStoreTests.swift +++ b/apple/TableProTests/Core/MCP/Outside/MCPServerStoreTests.swift @@ -1,8 +1,3 @@ -// -// MCPServerStoreTests.swift -// TableProTests -// - import Foundation @testable import TablePro import TableProMCP @@ -33,6 +28,25 @@ private final class LockedKeychain: KeychainStoring, @unchecked Sendable { func delete(forKey key: String) {} } +private final class SwitchableKeychain: KeychainStoring, @unchecked Sendable { + private var values: [String: String] = [:] + var refusesWrites = false + + func writeString(_ value: String, forKey key: String) -> Bool { + guard !refusesWrites else { return false } + values[key] = value + return true + } + + func readStringResult(forKey key: String) -> KeychainStringResult { + values[key].map { .found($0) } ?? .notFound + } + + func delete(forKey key: String) { + values.removeValue(forKey: key) + } +} + @MainActor struct MCPServerStoreTests { private let suite: EphemeralDefaults @@ -58,7 +72,7 @@ struct MCPServerStoreTests { token: "t" ) - #expect(error == .insecureEndpoint) + #expect(error == .invalid(.insecureEndpoint)) #expect(store.servers.isEmpty) } @@ -83,7 +97,7 @@ struct MCPServerStoreTests { #expect(reloaded.servers(allowedFor: connectionId).count == 1) } - /// A token left behind would be a live secret for a server the user believes they deleted. + // A token left behind would be a live secret for a server the user believes they deleted. @Test("Removing a server removes its token with it") func removingTakesTheTokenWithIt() { let keychain = FakeKeychain() @@ -98,8 +112,7 @@ struct MCPServerStoreTests { #expect(keychain.storedKeys.isEmpty) } - /// A token TablePro cannot read is a token it does not have, and the call that needs it fails - /// with the server unreachable rather than going out unauthenticated. + // A call that needs an unreadable token fails unreachable rather than going out unauthenticated. @Test("A locked Keychain reads as no token") func lockedKeychainReadsAsNoToken() { let store = MCPServerStore(defaults: makeDefaults(), keychain: LockedKeychain()) @@ -157,8 +170,7 @@ struct MCPServerStoreTests { #expect(store.server(id: configuration.id)?.allows(connectionId: connectionId) == false) } - /// A deleted connection's id must not sit in an allowlist forever. A new connection cannot - /// inherit it, but a stale entry makes the settings pane lie about how far a server reaches. + // A stale entry makes the settings pane overstate how far a server reaches. @Test("Forgetting a connection takes it off every allowlist") func forgettingAConnectionClearsIt() { let defaults = makeDefaults() @@ -196,4 +208,80 @@ struct MCPServerStoreTests { #expect(store.server(id: configuration.id)?.name == "Runbooks (staging)") #expect(store.token(for: configuration.id) == "secret") } + + @Test("A token the Keychain refuses leaves no new server behind") + func refusedTokenAddsNothing() { + let store = MCPServerStore(defaults: makeDefaults(), keychain: LockedKeychain()) + let configuration = MCPServerConfiguration(name: "Runbooks", endpoint: endpoint()) + + #expect(store.upsert(configuration, token: "secret") == .tokenNotSaved) + #expect(store.servers.isEmpty) + } + + @Test("A token the Keychain refuses on edit leaves the saved server and token as they were") + func refusedTokenKeepsTheSavedServer() { + let defaults = makeDefaults() + let keychain = SwitchableKeychain() + let store = MCPServerStore(defaults: defaults, keychain: keychain) + let original = MCPServerConfiguration(name: "Runbooks", endpoint: endpoint()) + #expect(store.upsert(original, token: "secret") == nil) + + keychain.refusesWrites = true + var edited = original + edited.name = "Runbooks (staging)" + edited.endpoint = endpoint("https://staging.example/mcp") + + #expect(store.upsert(edited, token: "new-secret") == .tokenNotSaved) + #expect(store.servers == [original]) + #expect(store.token(for: original.id) == "secret") + #expect(MCPServerStore(defaults: defaults, keychain: keychain).servers == [original]) + } + + @Test("A new server is refused without a token") + func newServerNeedsAToken() { + let store = MCPServerStore(defaults: makeDefaults(), keychain: FakeKeychain()) + let configuration = MCPServerConfiguration(name: "Runbooks", endpoint: endpoint()) + + #expect(store.upsert(configuration, token: nil) == .tokenRequired) + #expect(store.upsert(configuration, token: "") == .tokenRequired) + #expect(store.servers.isEmpty) + } + + @Test("Moving a saved server to another host needs a new token, and the old one stays put") + func movingToAnotherHostNeedsANewToken() { + let store = MCPServerStore(defaults: makeDefaults(), keychain: FakeKeychain()) + let original = MCPServerConfiguration(name: "Runbooks", endpoint: endpoint()) + #expect(store.upsert(original, token: "secret") == nil) + + var moved = original + moved.endpoint = endpoint("https://elsewhere.example/mcp") + #expect(store.upsert(moved, token: nil) == .tokenRequired) + #expect(store.server(id: original.id)?.endpoint == original.endpoint) + + #expect(store.upsert(moved, token: "elsewhere-secret") == nil) + #expect(store.server(id: original.id)?.endpoint == moved.endpoint) + #expect(store.token(for: original.id) == "elsewhere-secret") + } + + @Test("A new path on the same scheme, host and port keeps the saved token") + func samePathOriginKeepsTheToken() { + let store = MCPServerStore(defaults: makeDefaults(), keychain: FakeKeychain()) + var configuration = MCPServerConfiguration(name: "Runbooks", endpoint: endpoint()) + #expect(store.upsert(configuration, token: "secret") == nil) + + configuration.endpoint = endpoint("https://RUNBOOKS.example:443/v2/mcp") + #expect(store.upsert(configuration, token: nil) == nil) + #expect(store.token(for: configuration.id) == "secret") + } + + @Test("Two addresses share an origin only with the same scheme, host and port") + func originComparison() { + let base = endpoint("https://runbooks.example/mcp") + #expect(MCPServerStore.sharesOrigin(base, endpoint("https://runbooks.example:443/other"))) + #expect(MCPServerStore.sharesOrigin(base, endpoint("https://Runbooks.Example/mcp"))) + #expect(!MCPServerStore.sharesOrigin(base, endpoint("http://runbooks.example/mcp"))) + #expect(!MCPServerStore.sharesOrigin(base, endpoint("https://runbooks.example:8443/mcp"))) + #expect(!MCPServerStore.sharesOrigin(base, endpoint("https://runbooks.example.evil/mcp"))) + #expect(MCPServerStore.sharesOrigin(endpoint("http://localhost/mcp"), endpoint("http://localhost:80/x"))) + } } diff --git a/apple/TableProUITests/MCPConnectClientUITests.swift b/apple/TableProUITests/MCPConnectClientUITests.swift index e650ab8b3c..9e0b5592ee 100644 --- a/apple/TableProUITests/MCPConnectClientUITests.swift +++ b/apple/TableProUITests/MCPConnectClientUITests.swift @@ -38,6 +38,73 @@ final class MCPConnectClientUITests: UITestCase { XCTAssertTrue(waitForPredicate(timeout: 5) { !sheet.exists }, "Done should close the sheet") } + func testTokensPageGeneratesATokenAndRevealsItOnce() throws { + let app = try launchOpeningURL("tablepro://settings/mcp") + let settings = window("settings", in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "The settings link must open the settings window") + + let enable = settings.switches["mcp-enable-server-toggle"] + XCTAssertTrue(waitUntilHittable(enable, timeout: 10), "The MCP pane must offer its Enable switch") + if !isOn(enable) { + enable.click() + } + + let tokens = element("settings-drill-tokens", in: settings) + XCTAssertTrue(scrollUntilHittable(tokens, in: settings, timeout: 10), "An enabled server links to its Tokens page") + tokens.click() + + // The token store loads while the server starts, so + turns on a moment after the page opens. + let add = element("mcp-token-add", in: settings) + XCTAssertTrue(waitForPredicate(timeout: 20) { add.exists && add.isEnabled }, "Tokens offers + once the server runs") + add.click() + + let sheet = settings.sheets.firstMatch + XCTAssertTrue(sheet.waitToExist(timeout: 10), "+ must open the token sheet") + let name = element("mcp-token-name-field", in: sheet) + XCTAssertTrue(waitUntilHittable(name, timeout: 5)) + name.click() + name.typeText("UI Test Client") + + let generate = element("mcp-token-generate", in: sheet) + XCTAssertTrue(waitForPredicate(timeout: 5) { generate.isEnabled }, "A named token can be generated") + generate.click() + + let done = element("mcp-token-done", in: sheet) + XCTAssertTrue(waitUntilHittable(done, timeout: 10), "Generate turns the same sheet into the token it made") + XCTAssertTrue(element("mcp-token-client-picker", in: sheet).exists, "The reveal offers client setup") + done.click() + XCTAssertTrue(waitForPredicate(timeout: 5) { !sheet.exists }, "Done should close the sheet") + + let list = element("mcp-tokens-list", in: settings) + let row = list.descendants(matching: .any) + .matching(NSPredicate(format: "label CONTAINS %@ OR value CONTAINS %@", "UI Test Client", "UI Test Client")) + .firstMatch + XCTAssertTrue(row.waitToExist(timeout: 10), "The new token is listed on the Tokens page") + } + + func testAddServerSheetCancelsWithEscape() throws { + let app = try launchOpeningURL("tablepro://settings/mcp") + let settings = window("settings", in: app) + XCTAssertTrue(settings.waitToExist(timeout: 10), "The settings link must open the settings window") + + let add = element("mcp-outside-server-add", in: settings) + XCTAssertTrue(scrollUntilHittable(add, in: settings, timeout: 10), "Outside MCP Servers offers Add Server… with the server off") + add.click() + + let sheet = settings.sheets.firstMatch + XCTAssertTrue(sheet.waitToExist(timeout: 10), "Add Server… must open its sheet") + let save = element("mcp-outside-server-save", in: sheet) + XCTAssertTrue(save.waitToExist(timeout: 5)) + XCTAssertFalse(save.isEnabled, "A server with no name, address or token cannot be saved") + + sheet.typeKey(.escape, modifierFlags: []) + XCTAssertTrue(waitForPredicate(timeout: 5) { !sheet.exists }, "Escape cancels the sheet") + } + + private func element(_ identifier: String, in container: XCUIElement) -> XCUIElement { + container.descendants(matching: .any).matching(identifier: identifier).firstMatch + } + // SwiftUI text carries its string in `value` with no label, so a subscript by title finds nothing. private func text(_ value: String, in container: XCUIElement) -> XCUIElement { container.staticTexts.matching(NSPredicate(format: "value == %@", value)).firstMatch From 4b476db73052e715038b974bd93f2ce51e055dd1 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 19:45:59 +0700 Subject: [PATCH 39/48] feat(settings): Extensions pane with plugin pages, repair actions and reveal --- .../Plugins/BeancountDriverPlugin/Info.plist | 2 + apple/Plugins/BigQueryDriverPlugin/Info.plist | 2 + apple/Plugins/BigtableDriverPlugin/Info.plist | 2 + apple/Plugins/CSVExportPlugin/Info.plist | 2 + apple/Plugins/CSVImportPlugin/Info.plist | 2 + .../Plugins/CassandraDriverPlugin/Info.plist | 2 + .../Plugins/ClickHouseDriverPlugin/Info.plist | 2 + .../CloudflareD1DriverPlugin/Info.plist | 2 + .../CloudflareR2SQLDriverPlugin/Info.plist | 2 + apple/Plugins/DamengDriverPlugin/Info.plist | 2 + .../DataDictionaryExportPlugin/Info.plist | 2 + apple/Plugins/DuckDBDriverPlugin/Info.plist | 2 + apple/Plugins/DynamoDBDriverPlugin/Info.plist | 2 + .../ElasticsearchDriverPlugin/Info.plist | 2 + apple/Plugins/EtcdDriverPlugin/Info.plist | 2 + apple/Plugins/FirebaseDriverPlugin/Info.plist | 2 + apple/Plugins/HanaDriverPlugin/Info.plist | 2 + apple/Plugins/InfluxDBDriverPlugin/Info.plist | 2 + apple/Plugins/JSONExportPlugin/Info.plist | 2 + apple/Plugins/JSONImportPlugin/Info.plist | 2 + apple/Plugins/KafkaDriverPlugin/Info.plist | 2 + .../Plugins/KingbaseESDriverPlugin/Info.plist | 2 + apple/Plugins/LibSQLDriverPlugin/Info.plist | 2 + apple/Plugins/MQLExportPlugin/Info.plist | 2 + apple/Plugins/MSSQLDriverPlugin/Info.plist | 2 + apple/Plugins/MarkdownExportPlugin/Info.plist | 2 + .../Plugins/MemcachedDriverPlugin/Info.plist | 2 + apple/Plugins/MongoDBDriverPlugin/Info.plist | 2 + apple/Plugins/MySQLDriverPlugin/Info.plist | 2 + apple/Plugins/Neo4jDriverPlugin/Info.plist | 2 + apple/Plugins/OracleDriverPlugin/Info.plist | 2 + apple/Plugins/ParquetExportPlugin/Info.plist | 2 + .../Plugins/PostgreSQLDriverPlugin/Info.plist | 2 + apple/Plugins/QdrantDriverPlugin/Info.plist | 2 + apple/Plugins/RedisDriverPlugin/Info.plist | 2 + apple/Plugins/SQLExportPlugin/Info.plist | 2 + apple/Plugins/SQLImportPlugin/Info.plist | 2 + apple/Plugins/SQLiteDriverPlugin/Info.plist | 2 + .../Plugins/SnowflakeDriverPlugin/Info.plist | 2 + apple/Plugins/SpannerDriverPlugin/Info.plist | 2 + .../Plugins/StarRocksDriverPlugin/Info.plist | 2 + .../Plugins/SurrealDBDriverPlugin/Info.plist | 2 + apple/Plugins/TeradataDriverPlugin/Info.plist | 2 + apple/Plugins/TrinoDriverPlugin/Info.plist | 2 + .../Plugins/TypesenseDriverPlugin/Info.plist | 2 + apple/Plugins/WeaviateDriverPlugin/Info.plist | 2 + apple/Plugins/XLSXExportPlugin/Info.plist | 2 + apple/Plugins/XLSXImportPlugin/Info.plist | 2 + .../Plugins/PluginManager+AutoUpdate.swift | 20 +- .../Core/Plugins/PluginManager+Install.swift | 36 +- .../Plugins/PluginManager+Lifecycle.swift | 30 +- .../TablePro/Core/Plugins/PluginManager.swift | 76 +- .../Entries/ExtensionsSettingsEntry.swift | 26 +- .../Plugins/ExtensionsPaneModel.swift | 503 +++++++++++ .../Plugins/InstalledPluginsView.swift | 803 ++++++------------ .../Settings/Plugins/ModuleToggleRow.swift | 28 +- .../Settings/Plugins/PluginDetailPage.swift | 209 +++++ .../Settings/Plugins/PluginIconView.swift | 28 +- .../Plugins/PluginListSelection.swift | 12 +- .../Plugins/PluginsSettingsNavigation.swift | 31 - .../Plugins/RejectedPluginDetailPage.swift | 127 +++ .../Plugins/RejectedPluginRemovalTests.swift | 33 + .../Settings/ExtensionsPaneModelTests.swift | 357 ++++++++ .../Settings/PluginListSelectionTests.swift | 7 + apple/scripts/ci/check-plugin-provides.py | 27 +- 65 files changed, 1781 insertions(+), 668 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift create mode 100644 apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift delete mode 100644 apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift create mode 100644 apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift create mode 100644 apple/TableProTests/Views/Settings/ExtensionsPaneModelTests.swift diff --git a/apple/Plugins/BeancountDriverPlugin/Info.plist b/apple/Plugins/BeancountDriverPlugin/Info.plist index 8bb97777cc..9ddc59a0be 100644 --- a/apple/Plugins/BeancountDriverPlugin/Info.plist +++ b/apple/Plugins/BeancountDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Beancount Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/BigQueryDriverPlugin/Info.plist b/apple/Plugins/BigQueryDriverPlugin/Info.plist index d204d38817..4611353c04 100644 --- a/apple/Plugins/BigQueryDriverPlugin/Info.plist +++ b/apple/Plugins/BigQueryDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + BigQuery Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/BigtableDriverPlugin/Info.plist b/apple/Plugins/BigtableDriverPlugin/Info.plist index 6953716526..e1f508b75c 100644 --- a/apple/Plugins/BigtableDriverPlugin/Info.plist +++ b/apple/Plugins/BigtableDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Bigtable Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CSVExportPlugin/Info.plist b/apple/Plugins/CSVExportPlugin/Info.plist index 81a04239c9..f293006ad9 100644 --- a/apple/Plugins/CSVExportPlugin/Info.plist +++ b/apple/Plugins/CSVExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + CSV Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/CSVImportPlugin/Info.plist b/apple/Plugins/CSVImportPlugin/Info.plist index a09c94dbca..9167aba944 100644 --- a/apple/Plugins/CSVImportPlugin/Info.plist +++ b/apple/Plugins/CSVImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + CSV Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/CassandraDriverPlugin/Info.plist b/apple/Plugins/CassandraDriverPlugin/Info.plist index 7859b15635..7541863b74 100644 --- a/apple/Plugins/CassandraDriverPlugin/Info.plist +++ b/apple/Plugins/CassandraDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cassandra Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ClickHouseDriverPlugin/Info.plist b/apple/Plugins/ClickHouseDriverPlugin/Info.plist index 10fa22e650..9c3877768c 100644 --- a/apple/Plugins/ClickHouseDriverPlugin/Info.plist +++ b/apple/Plugins/ClickHouseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + ClickHouse Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CloudflareD1DriverPlugin/Info.plist b/apple/Plugins/CloudflareD1DriverPlugin/Info.plist index eb66596cb4..6aea4dd1db 100644 --- a/apple/Plugins/CloudflareD1DriverPlugin/Info.plist +++ b/apple/Plugins/CloudflareD1DriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cloudflare D1 Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist b/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist index 9625b89836..c86b10e02b 100644 --- a/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist +++ b/apple/Plugins/CloudflareR2SQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Cloudflare R2 SQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DamengDriverPlugin/Info.plist b/apple/Plugins/DamengDriverPlugin/Info.plist index 024e929450..b574bed77d 100644 --- a/apple/Plugins/DamengDriverPlugin/Info.plist +++ b/apple/Plugins/DamengDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Dameng Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DataDictionaryExportPlugin/Info.plist b/apple/Plugins/DataDictionaryExportPlugin/Info.plist index dfe303774b..8ba75b3ca8 100644 --- a/apple/Plugins/DataDictionaryExportPlugin/Info.plist +++ b/apple/Plugins/DataDictionaryExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Data Dictionary Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/DuckDBDriverPlugin/Info.plist b/apple/Plugins/DuckDBDriverPlugin/Info.plist index 001d3ff479..7f3aa3567e 100644 --- a/apple/Plugins/DuckDBDriverPlugin/Info.plist +++ b/apple/Plugins/DuckDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + DuckDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/DynamoDBDriverPlugin/Info.plist b/apple/Plugins/DynamoDBDriverPlugin/Info.plist index 750e2994e2..04616ec244 100644 --- a/apple/Plugins/DynamoDBDriverPlugin/Info.plist +++ b/apple/Plugins/DynamoDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + DynamoDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ElasticsearchDriverPlugin/Info.plist b/apple/Plugins/ElasticsearchDriverPlugin/Info.plist index 9e3a6cd5cc..1136a7812c 100644 --- a/apple/Plugins/ElasticsearchDriverPlugin/Info.plist +++ b/apple/Plugins/ElasticsearchDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Elasticsearch Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/EtcdDriverPlugin/Info.plist b/apple/Plugins/EtcdDriverPlugin/Info.plist index c79338b3ea..84124ee9fe 100644 --- a/apple/Plugins/EtcdDriverPlugin/Info.plist +++ b/apple/Plugins/EtcdDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + etcd Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/FirebaseDriverPlugin/Info.plist b/apple/Plugins/FirebaseDriverPlugin/Info.plist index 0a260443b2..60db2f8766 100644 --- a/apple/Plugins/FirebaseDriverPlugin/Info.plist +++ b/apple/Plugins/FirebaseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Firebase Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/HanaDriverPlugin/Info.plist b/apple/Plugins/HanaDriverPlugin/Info.plist index 37b21f2e8d..38d2fdf689 100644 --- a/apple/Plugins/HanaDriverPlugin/Info.plist +++ b/apple/Plugins/HanaDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SAP HANA Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/InfluxDBDriverPlugin/Info.plist b/apple/Plugins/InfluxDBDriverPlugin/Info.plist index a472fa3961..6193d36df8 100644 --- a/apple/Plugins/InfluxDBDriverPlugin/Info.plist +++ b/apple/Plugins/InfluxDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + InfluxDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/JSONExportPlugin/Info.plist b/apple/Plugins/JSONExportPlugin/Info.plist index 4077dfde3a..cd3c2a00e7 100644 --- a/apple/Plugins/JSONExportPlugin/Info.plist +++ b/apple/Plugins/JSONExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + JSON Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/JSONImportPlugin/Info.plist b/apple/Plugins/JSONImportPlugin/Info.plist index d0beb83840..7cd3012c3e 100644 --- a/apple/Plugins/JSONImportPlugin/Info.plist +++ b/apple/Plugins/JSONImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + JSON Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/KafkaDriverPlugin/Info.plist b/apple/Plugins/KafkaDriverPlugin/Info.plist index 2f105003d2..dac3c735c0 100644 --- a/apple/Plugins/KafkaDriverPlugin/Info.plist +++ b/apple/Plugins/KafkaDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Kafka Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/KingbaseESDriverPlugin/Info.plist b/apple/Plugins/KingbaseESDriverPlugin/Info.plist index 2a09d82f10..60b4b87ea8 100644 --- a/apple/Plugins/KingbaseESDriverPlugin/Info.plist +++ b/apple/Plugins/KingbaseESDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + KingbaseES Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/LibSQLDriverPlugin/Info.plist b/apple/Plugins/LibSQLDriverPlugin/Info.plist index 64fe9da34f..8bf48d7389 100644 --- a/apple/Plugins/LibSQLDriverPlugin/Info.plist +++ b/apple/Plugins/LibSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + libSQL / Turso Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MQLExportPlugin/Info.plist b/apple/Plugins/MQLExportPlugin/Info.plist index 7cc82fecc2..1111bf8a60 100644 --- a/apple/Plugins/MQLExportPlugin/Info.plist +++ b/apple/Plugins/MQLExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MQL Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/MSSQLDriverPlugin/Info.plist b/apple/Plugins/MSSQLDriverPlugin/Info.plist index 11d93c8982..da796d02a2 100644 --- a/apple/Plugins/MSSQLDriverPlugin/Info.plist +++ b/apple/Plugins/MSSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MSSQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MarkdownExportPlugin/Info.plist b/apple/Plugins/MarkdownExportPlugin/Info.plist index 9d9b33d127..020f6ad472 100644 --- a/apple/Plugins/MarkdownExportPlugin/Info.plist +++ b/apple/Plugins/MarkdownExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Markdown Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/MemcachedDriverPlugin/Info.plist b/apple/Plugins/MemcachedDriverPlugin/Info.plist index a9240bbf3f..4508b3c172 100644 --- a/apple/Plugins/MemcachedDriverPlugin/Info.plist +++ b/apple/Plugins/MemcachedDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Memcached Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MongoDBDriverPlugin/Info.plist b/apple/Plugins/MongoDBDriverPlugin/Info.plist index ad462443d3..a4ecc68ffa 100644 --- a/apple/Plugins/MongoDBDriverPlugin/Info.plist +++ b/apple/Plugins/MongoDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MongoDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/MySQLDriverPlugin/Info.plist b/apple/Plugins/MySQLDriverPlugin/Info.plist index e736a2c92e..557f35f946 100644 --- a/apple/Plugins/MySQLDriverPlugin/Info.plist +++ b/apple/Plugins/MySQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + MySQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/Neo4jDriverPlugin/Info.plist b/apple/Plugins/Neo4jDriverPlugin/Info.plist index 7293e94d0b..d2630185ac 100644 --- a/apple/Plugins/Neo4jDriverPlugin/Info.plist +++ b/apple/Plugins/Neo4jDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Neo4j Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/OracleDriverPlugin/Info.plist b/apple/Plugins/OracleDriverPlugin/Info.plist index bb2478ab96..a0b6894a6b 100644 --- a/apple/Plugins/OracleDriverPlugin/Info.plist +++ b/apple/Plugins/OracleDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Oracle Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/ParquetExportPlugin/Info.plist b/apple/Plugins/ParquetExportPlugin/Info.plist index 758650d5c3..a6000c7d0f 100644 --- a/apple/Plugins/ParquetExportPlugin/Info.plist +++ b/apple/Plugins/ParquetExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Parquet Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/PostgreSQLDriverPlugin/Info.plist b/apple/Plugins/PostgreSQLDriverPlugin/Info.plist index 4c5c2710c6..b25cf5ebe0 100644 --- a/apple/Plugins/PostgreSQLDriverPlugin/Info.plist +++ b/apple/Plugins/PostgreSQLDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + PostgreSQL Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/QdrantDriverPlugin/Info.plist b/apple/Plugins/QdrantDriverPlugin/Info.plist index a9c5f4eb04..1586112f04 100644 --- a/apple/Plugins/QdrantDriverPlugin/Info.plist +++ b/apple/Plugins/QdrantDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Qdrant Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/RedisDriverPlugin/Info.plist b/apple/Plugins/RedisDriverPlugin/Info.plist index 3bb3e5f4b7..5e6c28724d 100644 --- a/apple/Plugins/RedisDriverPlugin/Info.plist +++ b/apple/Plugins/RedisDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Redis Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SQLExportPlugin/Info.plist b/apple/Plugins/SQLExportPlugin/Info.plist index fd6dcc5ec1..d70d6a1dee 100644 --- a/apple/Plugins/SQLExportPlugin/Info.plist +++ b/apple/Plugins/SQLExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQL Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/SQLImportPlugin/Info.plist b/apple/Plugins/SQLImportPlugin/Info.plist index 262e0c28d1..b57054834a 100644 --- a/apple/Plugins/SQLImportPlugin/Info.plist +++ b/apple/Plugins/SQLImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQL Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/Plugins/SQLiteDriverPlugin/Info.plist b/apple/Plugins/SQLiteDriverPlugin/Info.plist index 5354fb9599..e44c913842 100644 --- a/apple/Plugins/SQLiteDriverPlugin/Info.plist +++ b/apple/Plugins/SQLiteDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SQLite Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SnowflakeDriverPlugin/Info.plist b/apple/Plugins/SnowflakeDriverPlugin/Info.plist index 8f3283d511..1bc2cbb831 100644 --- a/apple/Plugins/SnowflakeDriverPlugin/Info.plist +++ b/apple/Plugins/SnowflakeDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Snowflake Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SpannerDriverPlugin/Info.plist b/apple/Plugins/SpannerDriverPlugin/Info.plist index 36fa241b70..a47438724b 100644 --- a/apple/Plugins/SpannerDriverPlugin/Info.plist +++ b/apple/Plugins/SpannerDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Spanner Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/StarRocksDriverPlugin/Info.plist b/apple/Plugins/StarRocksDriverPlugin/Info.plist index 259ec20952..18f66f9ec1 100644 --- a/apple/Plugins/StarRocksDriverPlugin/Info.plist +++ b/apple/Plugins/StarRocksDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + StarRocks Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/SurrealDBDriverPlugin/Info.plist b/apple/Plugins/SurrealDBDriverPlugin/Info.plist index 34c7f92701..099bb24ee9 100644 --- a/apple/Plugins/SurrealDBDriverPlugin/Info.plist +++ b/apple/Plugins/SurrealDBDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + SurrealDB Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TeradataDriverPlugin/Info.plist b/apple/Plugins/TeradataDriverPlugin/Info.plist index 5bb701622c..a8e9f352f3 100644 --- a/apple/Plugins/TeradataDriverPlugin/Info.plist +++ b/apple/Plugins/TeradataDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Teradata Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TrinoDriverPlugin/Info.plist b/apple/Plugins/TrinoDriverPlugin/Info.plist index 79b7acc065..8dccae6cce 100644 --- a/apple/Plugins/TrinoDriverPlugin/Info.plist +++ b/apple/Plugins/TrinoDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Trino Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/TypesenseDriverPlugin/Info.plist b/apple/Plugins/TypesenseDriverPlugin/Info.plist index 0e0d2c4e6c..b6ec48e62a 100644 --- a/apple/Plugins/TypesenseDriverPlugin/Info.plist +++ b/apple/Plugins/TypesenseDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Typesense Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/WeaviateDriverPlugin/Info.plist b/apple/Plugins/WeaviateDriverPlugin/Info.plist index 153b6de197..c27dcfc388 100644 --- a/apple/Plugins/WeaviateDriverPlugin/Info.plist +++ b/apple/Plugins/WeaviateDriverPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + Weaviate Driver TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesDatabaseTypeIds diff --git a/apple/Plugins/XLSXExportPlugin/Info.plist b/apple/Plugins/XLSXExportPlugin/Info.plist index 661aa2ce9e..e44a235083 100644 --- a/apple/Plugins/XLSXExportPlugin/Info.plist +++ b/apple/Plugins/XLSXExportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + XLSX Export TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesExportFormatIds diff --git a/apple/Plugins/XLSXImportPlugin/Info.plist b/apple/Plugins/XLSXImportPlugin/Info.plist index a87e8e8ac3..6a7bf57fd2 100644 --- a/apple/Plugins/XLSXImportPlugin/Info.plist +++ b/apple/Plugins/XLSXImportPlugin/Info.plist @@ -2,6 +2,8 @@ + CFBundleDisplayName + XLSX Import TableProPluginKitVersion TABLEPRO_PLUGINKIT_VERSION TableProProvidesImportFormatIds diff --git a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift index 9d224a2a4a..2a8fbda7db 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift @@ -278,6 +278,10 @@ extension PluginManager { } func resolveRegistryId(for rejected: RejectedPlugin, manifest: RegistryManifest) -> String? { + Self.resolveRegistryId(for: rejected, in: manifest) + } + + nonisolated static func resolveRegistryId(for rejected: RejectedPlugin, in manifest: RegistryManifest) -> String? { if let id = rejected.registryId { return id } if let bundleId = rejected.bundleId, manifest.plugins.contains(where: { $0.id == bundleId }) { @@ -291,15 +295,23 @@ extension PluginManager { } func registryPlugin(for rejected: RejectedPlugin) -> RegistryPlugin? { - guard let manifest = RegistryClient.shared.manifest else { return nil } - guard let id = resolveRegistryId(for: rejected, manifest: manifest) else { return nil } + Self.registryPlugin(for: rejected, in: RegistryClient.shared.manifest) + } + + nonisolated static func registryPlugin(for rejected: RejectedPlugin, in manifest: RegistryManifest?) -> RegistryPlugin? { + guard let manifest, let id = resolveRegistryId(for: rejected, in: manifest) else { return nil } return manifest.plugins.first(where: { $0.id == id }) } func rejectedAction(for rejected: RejectedPlugin) -> RejectedPluginAction { + rejectedAction(for: rejected, manifest: RegistryClient.shared.manifest) + } + + // A surface that holds its own registry client passes that client's manifest, so its captions follow it. + func rejectedAction(for rejected: RejectedPlugin, manifest: RegistryManifest?) -> RejectedPluginAction { Self.rejectedAction( - registryPlugin: registryPlugin(for: rejected), - manifestLoaded: RegistryClient.shared.manifest != nil, + registryPlugin: Self.registryPlugin(for: rejected, in: manifest), + manifestLoaded: manifest != nil, kits: Self.compatibleKits ) } diff --git a/apple/TablePro/Core/Plugins/PluginManager+Install.swift b/apple/TablePro/Core/Plugins/PluginManager+Install.swift index 0fb022b0c6..f26d7767cb 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+Install.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+Install.swift @@ -154,8 +154,6 @@ extension PluginManager { ) } - // MARK: - Local bundle / zip install - // A file never puts back an older build than the one installed or staged. It drops the registry sidecar only at // or above the app's build, which the update pass never targets; below it the pass keeps the plugin current. nonisolated static func refuseOlderFile(build: Int, installedBuild: Int?) throws { @@ -183,8 +181,24 @@ extension PluginManager { .max() } + // Staging and replacing move the bundle they are given, so a file from elsewhere is copied first and stays put. + // The copy is what gets verified, so the file cannot change between the check and the install. + nonisolated static func copyLooseBundle(at url: URL, into workingDir: URL) throws -> URL { + try FileManager.default.createDirectory(at: workingDir, withIntermediateDirectories: true) + let copyURL = workingDir.appendingPathComponent(url.lastPathComponent, isDirectory: true) + try FileManager.default.copyItem(at: url, to: copyURL) + return copyURL + } + private func installLooseBundle(from url: URL) async throws -> PluginEntry { - guard let sourceBundle = Bundle(url: url) else { + let destURL = userPluginsDir.appendingPathComponent(url.lastPathComponent) + let isInPlace = url.standardizedFileURL == destURL.standardizedFileURL + let workingDir = PluginInstaller.stagingRoot(for: userPluginsDir) + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: workingDir) } + let bundleURL = try isInPlace ? url : Self.copyLooseBundle(at: url, into: workingDir) + + guard let sourceBundle = Bundle(url: bundleURL) else { throw PluginError.invalidBundle("Cannot create bundle from \(url.lastPathComponent)") } try PluginCodeSignatureVerifier.verify(bundle: sourceBundle) @@ -195,22 +209,16 @@ extension PluginManager { if let existing = plugins.first(where: { $0.id == bundleId }) { guard url.standardizedFileURL != existing.url.standardizedFileURL else { return existing } - try Self.refuseOlderFile(build: Self.bundleBuild(at: url), installedBuild: installedBuild(of: existing)) - PluginInstaller.stripQuarantine(at: url) - return try stageForNextLaunch(bundleAt: url, replacing: existing) + try Self.refuseOlderFile(build: Self.bundleBuild(at: bundleURL), installedBuild: installedBuild(of: existing)) + PluginInstaller.stripQuarantine(at: bundleURL) + return try stageForNextLaunch(bundleAt: bundleURL, replacing: existing) } - let fileBuild = Self.bundleBuild(at: url) + let fileBuild = Self.bundleBuild(at: bundleURL) let rejected = rejectedBuild(of: bundleId) try Self.refuseOlderFile(build: fileBuild, installedBuild: rejected) try FileManager.default.createDirectory(at: userPluginsDir, withIntermediateDirectories: true) - let destURL = userPluginsDir.appendingPathComponent(url.lastPathComponent) - let loadURL: URL - if url.standardizedFileURL != destURL.standardizedFileURL { - loadURL = try PluginInstaller.atomicReplace(stagedBundleURL: url, destURL: destURL) - } else { - loadURL = destURL - } + let loadURL = try isInPlace ? destURL : PluginInstaller.atomicReplace(stagedBundleURL: bundleURL, destURL: destURL) PluginInstaller.stripQuarantine(at: loadURL) if rejected == nil || fileBuild >= Bundle.main.buildNumber { removeRegistryMetadata(for: loadURL) diff --git a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift index b5067794fa..81c2e97c3b 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+Lifecycle.swift @@ -5,28 +5,29 @@ import SwiftUI import TableProPluginKit extension PluginManager { - func uninstallPlugin(id: String) async throws { - guard let index = plugins.firstIndex(where: { $0.id == id }) else { + // The bundle goes first, so a refused removal leaves the plugin listed and working. + func uninstallPlugin( + id: String, + removeBundle: (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) } + ) async throws { + guard let entry = plugins.first(where: { $0.id == id }) else { throw PluginError.notFound } - let entry = plugins[index] - guard entry.source == .userInstalled else { throw PluginError.cannotUninstallBuiltIn } + if FileManager.default.fileExists(atPath: entry.url.path) { + try removeBundle(entry.url) + } + unregisterCapabilities(pluginId: id) entry.bundle.unload() - plugins.remove(at: index) + plugins.removeAll { $0.id == id } + rebuildLazyRegistrations() removeRegistryMetadata(for: entry.url) - - let fm = FileManager.default - if fm.fileExists(atPath: entry.url.path) { - try fm.removeItem(at: entry.url) - } - PluginSettingsStorage(pluginId: id).removeAll() removeStagedUpdate(pluginId: id) @@ -46,7 +47,8 @@ extension PluginManager { return folder == userPluginsDir.standardizedFileURL.resolvingSymlinksInPath().path } - // To the Trash rather than deleted, so a mistaken removal can be put back. + // To the Trash rather than deleted, so a mistaken removal can be put back. A lazily registered copy of the + // same bundle goes with it, or the plugin would stay listed after its file is gone. func removeRejectedPlugin( _ plugin: RejectedPlugin, moveToTrash: (URL) throws -> Void = { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) } @@ -58,6 +60,10 @@ extension PluginManager { } catch CocoaError.fileNoSuchFile {} } removeFromRejected(url: plugin.url) + if plugins.contains(where: { $0.url == plugin.url }) { + plugins.removeAll { $0.url == plugin.url } + rebuildLazyRegistrations() + } Self.logger.info("Moved rejected plugin '\(plugin.name, privacy: .public)' to the Trash") } } diff --git a/apple/TablePro/Core/Plugins/PluginManager.swift b/apple/TablePro/Core/Plugins/PluginManager.swift index c4095f3e55..abe1c4e491 100644 --- a/apple/TablePro/Core/Plugins/PluginManager.swift +++ b/apple/TablePro/Core/Plugins/PluginManager.swift @@ -105,7 +105,7 @@ final class PluginManager: ObservableObject { private var lazyExportURLs: [String: URL] = [:] private var lazyImportURLs: [String: URL] = [:] private var activatedBundleIds: Set = [] - /// Bundles a connect already took through the load gate and loaded off the main actor. + // Bundles already taken through the load gate off the main actor, so activation skips a second check. private var gatedBundleURLs: Set = [] internal var registryUpdateTask: Task? @@ -151,8 +151,6 @@ final class PluginManager: ObservableObject { .appendingPathComponent("TablePro/Plugins", isDirectory: true) } - // MARK: - Registry Metadata - struct RegistryMetadata: Codable { let pluginId: String } @@ -190,8 +188,6 @@ final class PluginManager: ObservableObject { } } - // MARK: - Loading - func loadPlugins() { hasStartedInitialLoad = true Self.applyStagedUpdates(in: userPluginsDir) @@ -259,8 +255,6 @@ final class PluginManager: ObservableObject { } } - // MARK: - Lazy Plugin Activation - private func registerLazyManifest(at url: URL, source: PluginSource, manifest: PluginManifest) { guard let bundle = Bundle(url: url) else { return } let bundleId = manifest.bundleId @@ -278,6 +272,8 @@ final class PluginManager: ObservableObject { let info = bundle.infoDictionary ?? [:] let version = (info["CFBundleShortVersionString"] as? String) ?? "0.0.0" let displayName = registrySnapshot?.displayName + ?? Self.declaredDisplayName(in: info) + ?? Self.formatDisplayName(manifest: manifest) ?? bundleId.split(separator: ".").last.map(String.init) ?? bundleId let pluginIconName = Self.iconName(forPrimaryTypeId: primaryTypeId) @@ -319,8 +315,28 @@ final class PluginManager: ObservableObject { typeId.flatMap { PluginMetadataRegistry.shared.snapshot(forRegisteredTypeId: $0)?.iconName } ?? "puzzlepiece" } - /// Takes back everything `registerLazyManifest` published for this bundle, so a plugin the app - /// would refuse to activate stops being offered as an installed one. + // check-plugin-provides.py stamps pluginName here, so a plugin is named before its code loads. + nonisolated static func declaredDisplayName(in info: [String: Any]) -> String? { + guard let name = info["CFBundleDisplayName"] as? String else { return nil } + let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + + nonisolated static func formatDisplayName(manifest: PluginManifest) -> String? { + if let formatId = manifest.providedExportFormatIds.first { + return String(format: String(localized: "%@ Export"), formatId.uppercased()) + } + if let formatId = manifest.providedImportFormatIds.first { + return String(format: String(localized: "%@ Import"), formatId.uppercased()) + } + return nil + } + + nonisolated static func rejectedDisplayName(at url: URL) -> String { + declaredDisplayName(in: infoPlist(at: url)) ?? url.deletingPathExtension().lastPathComponent + } + + // A plugin the app would refuse to activate stops being offered as an installed one. internal func withdrawPlugin(at url: URL, reason: Error) { let manifest = Bundle(url: url).flatMap { PluginManifest(bundle: $0) } @@ -328,7 +344,7 @@ final class PluginManager: ObservableObject { rebuildLazyRegistrations() guard !rejectedPlugins.contains(where: { $0.url == url }) else { return } - let name = manifest?.bundleId ?? url.deletingPathExtension().lastPathComponent + let name = Self.declaredDisplayName(in: Self.infoPlist(at: url)) ?? manifest?.bundleId ?? url.deletingPathExtension().lastPathComponent let registryId = Self.readRegistryMetadata(for: url)?.pluginId rejectedPlugins.append(RejectedPlugin( url: url, @@ -341,12 +357,9 @@ final class PluginManager: ObservableObject { )) } - /// Rebuilt from the surviving manifests rather than filtered by URL. - /// - /// Two bundles may declare the same driver or format key, and the one registered - /// last owns it. Deleting the withdrawn bundle's keys would take the shared key with it and - /// leave the valid plugin listed but unreachable for the rest of the process. - private func rebuildLazyRegistrations() { + // Rebuilt rather than filtered by URL: two bundles may declare one key, and dropping the removed one's + // keys would leave the other listed but unreachable for the rest of the process. + internal func rebuildLazyRegistrations() { lazyDriverURLs = [:] gatedBundleURLs = [] lazyExportURLs = [:] @@ -394,17 +407,36 @@ final class PluginManager: ObservableObject { Array(lazyImportURLs.keys) } - // The signature check and dlopen of a driver plugin hold the thread for hundreds of milliseconds the - // first time a launch reads its file, so a connect does both here and leaves only registration to main. + // The signature check and dlopen of a plugin hold the thread for hundreds of milliseconds the first time + // a launch reads its file, so a connect or a Settings page does both here and leaves only registration to main. func loadLazyDriverExecutable(typeId: String) async { guard driverPlugins[typeId] == nil, let url = lazyDriverURLs[typeId], !gatedBundleURLs.contains(url) else { return } + guard await loadLazyBundleExecutable(at: url) else { return } + gatedBundleURLs.insert(url) + } + + // Only a driver load records the gate (plugin_gated_bundle_insert), so activation checks a format again, + // but the dlopen has already happened here. + func loadLazyExportExecutable(formatId: String) async { + guard exportPlugins[formatId] == nil, let url = lazyExportURLs[formatId] else { return } + await loadLazyBundleExecutable(at: url) + } + + func loadLazyImportExecutable(formatId: String) async { + guard importPlugins[formatId] == nil, let url = lazyImportURLs[formatId] else { return } + await loadLazyBundleExecutable(at: url) + } + + @discardableResult + private func loadLazyBundleExecutable(at url: URL) async -> Bool { let source = plugins.first(where: { $0.url == url })?.source ?? .userInstalled do { _ = try await Self.validateAndLoadBundleAsync(at: url, source: source) - gatedBundleURLs.insert(url) + return true } catch { // Activation runs the gate again on the main actor and records the rejection there. - Self.logger.error("Loading driver plugin '\(url.lastPathComponent)' ahead of activation failed: \(error.localizedDescription)") + Self.logger.error("Loading plugin '\(url.lastPathComponent)' ahead of activation failed: \(error.localizedDescription)") + return false } } @@ -569,7 +601,7 @@ final class PluginManager: ObservableObject { url: failure.url, bundleId: bundle?.bundleIdentifier, registryId: registryId, - name: failure.url.deletingPathExtension().lastPathComponent, + name: Self.rejectedDisplayName(at: failure.url), reason: failure.reason, isOutdated: false, providedDatabaseTypeIds: Self.databaseTypeIds(of: bundle, registryId: registryId) @@ -670,7 +702,7 @@ final class PluginManager: ObservableObject { url: winner.url, bundleId: bundle?.bundleIdentifier, registryId: registryId, - name: winner.url.deletingPathExtension().lastPathComponent, + name: Self.rejectedDisplayName(at: winner.url), reason: error.localizedDescription, isOutdated: (error as? PluginError)?.isOutdated ?? false, providedDatabaseTypeIds: Self.databaseTypeIds(of: bundle, registryId: registryId) diff --git a/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift index 35c552b48a..82f8a5c6b0 100644 --- a/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift +++ b/apple/TablePro/Views/Settings/Entries/ExtensionsSettingsEntry.swift @@ -4,23 +4,45 @@ internal struct ExtensionsSettingsEntry: View { internal let context: SettingsPaneContext internal var body: some View { - InstalledPluginsView(registryClient: context.registryClient) + InstalledPluginsView(context: context) } } internal struct ExtensionsSettingsPageEntry: View { internal let route: SettingsRoute internal let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel internal var body: some View { - SettingsPagePlaceholder(title: context.navigation.title(for: route)) + switch model.page(for: route) { + case .plugin(let entry, let isStaged): + PluginDetailPage(entry: entry, isStaged: isStaged, context: context) + case .rejected(let row): + RejectedPluginDetailPage(row: row, context: context, tracker: model.manager.installTracker) + case .unavailable: + UnavailableStateView( + String(localized: "Plugin Not Available"), + systemImage: "puzzlepiece.extension", + description: Text("It was removed or replaced.") + ) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("extensions-plugin-unavailable") + } } } +// The model sits above the stack, so the root and every pushed page share one view of the plugin manager. internal struct ExtensionsStackPresentations: ViewModifier { internal let context: SettingsPaneContext + @StateObject private var model: ExtensionsPaneModel + + internal init(context: SettingsPaneContext) { + self.context = context + _model = StateObject(wrappedValue: ExtensionsPaneModel(registryClient: context.registryClient)) + } internal func body(content: Content) -> some View { content + .environmentObject(model) } } diff --git a/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift b/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift new file mode 100644 index 0000000000..d78c5f4459 --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/ExtensionsPaneModel.swift @@ -0,0 +1,503 @@ +import AppKit +import Combine +import Foundation +import os +import TableProPluginKit + +internal enum ExtensionsPluginGroup: CaseIterable, Hashable, Sendable { + case drivers + case exports + case imports + case other + + // The first capability decides; none, or one this build does not know, lands in Other. + internal init(capabilities: [PluginCapability]) { + switch capabilities.first { + case .databaseDriver: self = .drivers + case .exportFormat: self = .exports + case .importFormat: self = .imports + default: self = .other + } + } + + internal var title: String { + switch self { + case .drivers: String(localized: "Database Drivers") + case .exports: String(localized: "Export Formats") + case .imports: String(localized: "Import Formats") + case .other: String(localized: "Other") + } + } +} + +internal struct ExtensionsPluginRow: Equatable, Identifiable, Sendable { + let id: String + let url: URL + let name: String + let iconName: String + let isBuiltIn: Bool + let version: String + let typeIds: [String] + let formatIds: [String] + let group: ExtensionsPluginGroup + let isStaged: Bool + + var isDriver: Bool { !typeIds.isEmpty } +} + +internal struct ExtensionsPluginSection: Equatable, Identifiable, Sendable { + let group: ExtensionsPluginGroup + let rows: [ExtensionsPluginRow] + + var id: ExtensionsPluginGroup { group } +} + +internal enum ExtensionsRejectedAction: Equatable, Sendable { + case update(registryId: String) + case appUpdate + case retry + case noAction +} + +internal struct ExtensionsRejectedRow: Equatable, Identifiable, Sendable { + let url: URL + let name: String + let iconName: String + let reason: String + let caption: String + let severity: NoticeSeverity + let action: ExtensionsRejectedAction + let canRemove: Bool + let bundleId: String? + // The tracker keys a repair by the registry id, so the row finds its own download. + let trackerId: String? + + var id: URL { url } +} + +internal enum ExtensionsRelaunchReason: Equatable, Sendable { + case removed + case updates + + var text: String { + switch self { + case .removed: String(localized: "Removed plugins stay loaded until TablePro relaunches.") + case .updates: String(localized: "Plugin updates install when TablePro relaunches.") + } + } +} + +internal enum ExtensionsPluginStatus: Equatable, Sendable { + case downloading + case installing + case failed + case staged + case builtIn + case version(String) + + init(phase: PluginInstallTracker.Phase?, isStaged: Bool, isBuiltIn: Bool, version: String) { + switch phase { + case .downloading?: self = .downloading + case .installing?: self = .installing + case .failed?: self = .failed + case .completed?, nil: + if isStaged { + self = .staged + } else if isBuiltIn { + self = .builtIn + } else { + self = .version(version) + } + } + } + + var text: String { + switch self { + case .downloading: String(localized: "Downloading update…") + case .installing: String(localized: "Installing update…") + case .failed: String(localized: "Update failed") + case .staged: String(localized: "Updates when TablePro relaunches") + case .builtIn: String(localized: "Built-in") + case .version(let version): String(format: String(localized: "Version %@"), version) + } + } +} + +internal enum ExtensionsPageStatus: Equatable, Sendable { + case running(PluginInstallTracker.Phase) + case failed(String) + case staged + + init?(phase: PluginInstallTracker.Phase?, isStaged: Bool) { + switch phase { + case .downloading?, .installing?: + guard let phase else { return nil } + self = .running(phase) + case .failed(let reason)?: + self = .failed(reason) + case .completed?, nil: + guard isStaged else { return nil } + self = .staged + } + } +} + +internal struct ExtensionsFilteredContent: Equatable { + let groups: [ExtensionsPluginSection] + let rejected: [ExtensionsRejectedRow] + let modules: [AppModule] + let isFiltering: Bool + + var isEmpty: Bool { groups.isEmpty && rejected.isEmpty && modules.isEmpty } +} + +internal struct ExtensionsSnapshot: Equatable, Sendable { + var groups: [ExtensionsPluginSection] = [] + var rejected: [ExtensionsRejectedRow] = [] + var relaunch: ExtensionsRelaunchReason? + + var rows: [ExtensionsPluginRow] { groups.flatMap(\.rows) } + + // Tracker entries a row already shows; any other running or failed entry gets an activity row. + var trackedIds: Set { + Set(rows.map(\.id)).union(rejected.compactMap(\.trackerId)).union(rejected.compactMap(\.bundleId)) + } + + func filtered(_ query: String, modules: [AppModule] = AppModule.allCases) -> ExtensionsFilteredContent { + let needle = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !needle.isEmpty else { + return ExtensionsFilteredContent(groups: groups, rejected: rejected, modules: modules, isFiltering: false) + } + let matches: (String) -> Bool = { $0.localizedStandardContains(needle) } + let filteredGroups = groups.compactMap { section -> ExtensionsPluginSection? in + let rows = matches(section.group.title) ? section.rows : section.rows.filter { row in + matches(row.name) || row.typeIds.contains(where: matches) || row.formatIds.contains(where: matches) + } + return rows.isEmpty ? nil : ExtensionsPluginSection(group: section.group, rows: rows) + } + return ExtensionsFilteredContent( + groups: filteredGroups, + rejected: rejected.filter { matches($0.name) || matches($0.caption) }, + modules: modules.filter { matches($0.title) || matches($0.summary) }, + isFiltering: true + ) + } + + static func activities( + in entries: [String: PluginInstallTracker.Entry], + excluding trackedIds: Set + ) -> [PluginInstallTracker.Entry] { + entries.values + .filter { entry in + guard !trackedIds.contains(entry.pluginId) else { return false } + if case .completed = entry.phase { return false } + return true + } + .sorted { $0.order < $1.order } + } +} + +internal enum ExtensionsPage { + case plugin(PluginEntry, isStaged: Bool) + case rejected(ExtensionsRejectedRow) + case unavailable +} + +// Owns the pane's view of the plugin manager for the window's lifetime, shared by the root and its pages. +@MainActor +internal final class ExtensionsPaneModel: ObservableObject { + private static let logger = Logger(subsystem: "com.TablePro", category: "ExtensionsPane") + + @Published private(set) var snapshot = ExtensionsSnapshot() + @Published private(set) var retrying: Set = [] + @Published private(set) var retryFailures: Set = [] + + let manager: PluginManager + let registryClient: RegistryClient + private(set) var plugins: [PluginEntry] = [] + private(set) var stagedPluginIds: Set = [] + private var subscription: AnyCancellable? + + init(manager: PluginManager = .shared, registryClient: RegistryClient) { + self.manager = manager + self.registryClient = registryClient + // @Published sends the new value before storing it, so the inputs come from the publishers, never the manager. + subscription = manager.$plugins + .combineLatest(manager.$rejectedPlugins, manager.$needsRestart, manager.$stagedPluginIds) + .combineLatest(registryClient.$manifest) + .sink { [weak self] inputs, manifest in + MainActor.assumeIsolated { + self?.apply( + plugins: inputs.0, + rejected: inputs.1, + needsRestart: inputs.2, + staged: inputs.3, + manifest: manifest + ) + } + } + } + + private func apply( + plugins: [PluginEntry], + rejected: [RejectedPlugin], + needsRestart: Bool, + staged: Set, + manifest: RegistryManifest? + ) { + self.plugins = plugins + stagedPluginIds = staged + let next = Self.makeSnapshot( + plugins: plugins, + rejected: rejected, + needsRestart: needsRestart, + staged: staged, + manifest: manifest, + isUpdatingEnabled: manager.isUpdatingEnabled, + canRemove: { [manager] in manager.canRemoveRejectedPlugin($0) } + ) + if next != snapshot { + snapshot = next + } + } + + static func makeSnapshot( + plugins: [PluginEntry], + rejected: [RejectedPlugin], + needsRestart: Bool, + staged: Set, + manifest: RegistryManifest?, + isUpdatingEnabled: Bool, + canRemove: (RejectedPlugin) -> Bool + ) -> ExtensionsSnapshot { + let rejectedURLs = Set(rejected.map(\.url)) + let rows = plugins + .filter { !rejectedURLs.contains($0.url) } + .map { row(for: $0, isStaged: staged.contains($0.id)) } + let groups = ExtensionsPluginGroup.allCases.compactMap { group -> ExtensionsPluginSection? in + let members = rows + .filter { $0.group == group } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + return members.isEmpty ? nil : ExtensionsPluginSection(group: group, rows: members) + } + let rejectedRows = rejected + .map { rejectedRow(for: $0, manifest: manifest, isUpdatingEnabled: isUpdatingEnabled, canRemove: canRemove($0)) } + .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } + let relaunch: ExtensionsRelaunchReason? + if needsRestart { + relaunch = .removed + } else if !staged.isEmpty { + relaunch = .updates + } else { + relaunch = nil + } + return ExtensionsSnapshot(groups: groups, rejected: rejectedRows, relaunch: relaunch) + } + + private static func row(for entry: PluginEntry, isStaged: Bool) -> ExtensionsPluginRow { + ExtensionsPluginRow( + id: entry.id, + url: entry.url, + name: entry.name, + iconName: entry.pluginIconName, + isBuiltIn: entry.source == .builtIn, + version: entry.version, + typeIds: (entry.databaseTypeId.map { [$0] } ?? []) + entry.additionalTypeIds, + formatIds: [entry.exportFormatId, entry.importFormatId].compactMap { $0 }, + group: ExtensionsPluginGroup(capabilities: entry.capabilities), + isStaged: isStaged + ) + } + + private static func rejectedRow( + for plugin: RejectedPlugin, + manifest: RegistryManifest?, + isUpdatingEnabled: Bool, + canRemove: Bool + ) -> ExtensionsRejectedRow { + let action = PluginManager.rejectedAction( + registryPlugin: PluginManager.registryPlugin(for: plugin, in: manifest), + manifestLoaded: manifest != nil, + kits: PluginManager.compatibleKits + ) + let status = RejectedPluginStatus(action: action) + let rowAction: ExtensionsRejectedAction + switch action { + case .updateAvailable(let registryPlugin): rowAction = .update(registryId: registryPlugin.id) + case .requiresAppUpdate: rowAction = .appUpdate + case .awaitingCompatibleBuild: rowAction = isUpdatingEnabled ? .retry : .noAction + case .notInRegistry: rowAction = .noAction + } + let resolvedId = manifest.flatMap { PluginManager.resolveRegistryId(for: plugin, in: $0) } + return ExtensionsRejectedRow( + url: plugin.url, + name: plugin.name, + iconName: PluginManager.iconName(forPrimaryTypeId: plugin.providedDatabaseTypeIds.first), + reason: plugin.reason, + caption: status.caption, + severity: status.severity, + action: rowAction, + canRemove: canRemove, + bundleId: plugin.bundleId, + trackerId: resolvedId ?? plugin.registryId ?? plugin.bundleId + ) + } + + // A plugin row whose bundle could not load shows that page; a rejected route whose bundle has since loaded shows it. + func page(for route: SettingsRoute) -> ExtensionsPage { + switch route { + case .plugin(let id): + guard let entry = plugins.first(where: { $0.id == id }) else { return .unavailable } + if let row = snapshot.rejected.first(where: { $0.url == entry.url }) { return .rejected(row) } + return .plugin(entry, isStaged: stagedPluginIds.contains(id)) + case .rejectedPlugin(let url): + if let row = snapshot.rejected.first(where: { $0.url == url }) { return .rejected(row) } + if let entry = plugins.first(where: { $0.url == url }) { + return .plugin(entry, isStaged: stagedPluginIds.contains(entry.id)) + } + return .unavailable + case .page, .aiProvider: + return .unavailable + } + } + + // Waits for the list, so a request made before it loaded still finds its plugin. + func revealPending(in context: SettingsPaneContext) async { + guard context.navigation.pendingPluginReveal != nil else { return } + await manager.waitForInitialLoad() + guard !Task.isCancelled, let request = context.navigation.consumePluginReveal() else { return } + guard context.isCurrent, context.navigation.location.routes.isEmpty, + let target = PluginListSelection.revealTarget( + pluginId: request.pluginId, + loadedIds: manager.plugins.map(\.id), + rejected: manager.rejectedPlugins + ) else { return } + context.filter?.query = "" + context.navigation.push(target.route, in: context.pane) + } + + nonisolated static func installableFiles(_ urls: [URL]) -> [URL] { + urls.filter { url in + url.isFileURL && ["zip", "tableplugin"].contains(url.pathExtension.lowercased()) + } + } + + // Returns false when no file is a plugin, so a drop of anything else is refused. + @discardableResult + func install(_ urls: [URL], context: SettingsPaneContext) -> Bool { + let files = Self.installableFiles(urls) + guard !files.isEmpty else { return false } + Task { await installFiles(files, context: context) } + return true + } + + private func installFiles(_ files: [URL], context: SettingsPaneContext) async { + var installed: [PluginEntry] = [] + for url in files { + do { + installed.append(try await manager.installPlugin(from: url)) + } catch { + Self.logger.info("A plugin file did not install: \(error.localizedDescription)") + } + } + // Several files, or a user who moved on, stay where they are. + guard files.count == 1, let entry = installed.first, context.navigation.location.routes.isEmpty else { return } + context.navigation.push(.plugin(id: entry.id), in: context.pane) + } + + func retryInstall(_ entry: PluginInstallTracker.Entry, context: SettingsPaneContext, replacing route: SettingsRoute? = nil) { + switch entry.retry { + case .registry(let registryPlugin): + update(registryPlugin, context: context, replacing: route) + case .file(let url): + install([url], context: context) + case nil: + break + } + } + + func registryPlugin(id: String) -> RegistryPlugin? { + registryClient.manifest?.plugins.first { $0.id == id } + } + + // A rejected plugin that installed is a loaded one now, so its page takes the loaded route. + func update(_ registryPlugin: RegistryPlugin, context: SettingsPaneContext, replacing route: SettingsRoute? = nil) { + Task { + let result = await manager.performRegistryUpdate(registryPlugin) + guard case .succeeded(let entry) = result, let route else { return } + Self.replace(route, with: .plugin(id: entry.id), in: context) + } + } + + func retryRejected(_ url: URL) { + guard !retrying.contains(url) else { return } + retrying.insert(url) + retryFailures.remove(url) + Task { + let reached = await manager.retryRejectedPluginRepairs(registryClient: registryClient) + retrying.remove(url) + if !reached { + retryFailures.insert(url) + } + } + } + + func uninstall(_ row: ExtensionsPluginRow, context: SettingsPaneContext) { + uninstall(id: row.id, name: row.name, isDriver: row.isDriver, context: context) + } + + func uninstall(id: String, name: String, isDriver: Bool, context: SettingsPaneContext) { + Task { + var message = String(localized: "The plugin moves to the Trash and its settings are deleted. It stays loaded until TablePro relaunches.") + if isDriver { + message += " " + String(localized: "Saved connections that use it stay in your library.") + } + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Uninstall “%@”?"), name), + message: message, + confirmButton: String(localized: "Uninstall"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + do { + try await manager.uninstallPlugin(id: id) { try FileManager.default.trashItem(at: $0, resultingItemURL: nil) } + } catch { + context.presentError(title: String(localized: "Couldn't Uninstall"), message: error.localizedDescription) + return + } + context.navigation.removeRoute(.plugin(id: id)) + } + } + + func moveToTrash(_ url: URL, context: SettingsPaneContext) { + guard let plugin = manager.rejectedPlugins.first(where: { $0.url == url }) else { return } + Task { + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Move “%@” to the Trash?"), plugin.name), + message: String(localized: "The plugin can't be loaded. You can put it back from the Trash."), + confirmButton: String(localized: "Move to Trash"), + cancelButton: String(localized: "Cancel") + ) + guard confirmed else { return } + do { + try manager.removeRejectedPlugin(plugin) + } catch { + context.presentError(title: String(localized: "Couldn't Move to Trash"), message: error.localizedDescription) + return + } + context.navigation.removeRoute(.rejectedPlugin(url)) + } + } + + func showInFinder(_ url: URL) { + NSWorkspace.shared.activateFileViewerSelecting([url]) + } + + private static func replace(_ old: SettingsRoute, with new: SettingsRoute, in context: SettingsPaneContext) { + let wasShown = context.isCurrent && context.navigation.location.routes.last == old + context.navigation.removeRoute(old) + if wasShown { + context.navigation.push(new, in: context.pane) + } + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index dc47fa79d9..cdd25f61ba 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -1,643 +1,348 @@ import AppKit import SwiftUI -import TableProPluginKit import UniformTypeIdentifiers +// The Extensions pane root. The toolbar filter narrows it; the pages are their own views in the pane's stack. struct InstalledPluginsView: View { - @ObservedObject private var pluginManager = PluginManager.shared - @ObservedObject private var registryClient: RegistryClient - // Install progress lives in the tracker, which the plugin manager does not republish. - @ObservedObject private var installTracker = PluginInstallTracker.shared - @ObservedObject private var navigation = PluginsSettingsNavigation.shared - @ObservedObject private var modules = AppModuleSettings.shared - @ObservedObject private var updates = UpdateCenter.shared - - @Binding private var path: NavigationPath - @State private var searchText = "" - @State private var showErrorAlert = false - @State private var errorAlertTitle = "" - @State private var errorAlertMessage = "" - @State private var isRetryingRejected = false - - init(registryClient: RegistryClient = .shared, path: Binding = .constant(NavigationPath())) { - self.registryClient = registryClient - self._path = path - } - - private var filteredPlugins: [PluginEntry] { - if searchText.isEmpty { return pluginManager.plugins } - return pluginManager.plugins.filter { $0.name.localizedCaseInsensitiveContains(searchText) } - } - - private var filteredModules: [AppModule] { - AppModule.allCases.filter { $0.matches(filter: searchText) } - } - - private var filteredRejected: [RejectedPlugin] { - if searchText.isEmpty { return pluginManager.rejectedPlugins } - return pluginManager.rejectedPlugins.filter { $0.name.localizedCaseInsensitiveContains(searchText) } + private static let importTypes: [UTType] = [.zip] + (UTType("com.tablepro.plugin").map { [$0] } ?? []) + + private let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel + @ObservedObject private var filter: SettingsPaneFilter + @ObservedObject private var reveal: SettingsPluginReveal + @ObservedObject private var visit: SettingsPaneVisit + @State private var isDropTargeted = false + @State private var isImporting = false + + init(context: SettingsPaneContext) { + self.context = context + _filter = ObservedObject(wrappedValue: context.filter ?? SettingsPaneFilter()) + _reveal = ObservedObject(wrappedValue: context.navigation.pluginReveal) + _visit = ObservedObject(wrappedValue: context.visit) } var body: some View { - pluginList - .task { - await registryClient.fetch(policy: .ifStale) + let content = model.snapshot.filtered(filter.query) + Group { + if content.isFiltering && content.isEmpty { + UnavailableStateView.search(text: filter.query) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("extensions-no-results") + } else { + form(content) + } } - .navigationDestination(for: PluginListSelection.self) { selection in - detailPage(for: selection) + .task(id: visit.count) { + _ = await model.registryClient.fetch(policy: .ifStale) } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in - guard let provider = providers.first, - provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) else { - return false - } - provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier) { data, _ in - guard let data = data as? Data, - let url = URL(dataRepresentation: data, relativeTo: nil) else { return } - let ext = url.pathExtension.lowercased() - guard ext == "zip" || ext == "tableplugin" else { return } - Task { @MainActor in - installPlugin(from: url) - } - } - return true + .task(id: reveal.pending?.id) { + await model.revealPending(in: context) } - .alert(errorAlertTitle, isPresented: $showErrorAlert) { - Button("OK") {} - } message: { - Text(errorAlertMessage) + .dropDestination(for: URL.self) { urls, _ in + model.install(urls, context: context) + } isTargeted: { isTargeted in + isDropTargeted = isTargeted } - } - - // MARK: - Relaunch Row - - private var relaunchRow: some View { - HStack(spacing: 8) { - Label { - Text("Relaunch to finish removing plugins.") - .lineLimit(2) - } icon: { - Image(systemName: "arrow.clockwise") - .foregroundStyle(.secondary) - } - Spacer(minLength: 4) - Button(String(localized: "Relaunch")) { updates.relaunch() } - .controlSize(.small) - .accessibilityIdentifier("plugins-relaunch-button") + .overlay { dropHighlight } + .fileImporter(isPresented: $isImporting, allowedContentTypes: Self.importTypes, allowsMultipleSelection: true) { result in + guard case .success(let urls) = result else { return } + model.install(urls, context: context) } - .padding(.vertical, 2) } - // MARK: - Rejected Plugins - - private func rejectedRow(_ plugin: RejectedPlugin) -> some View { - let status = RejectedPluginStatus(action: pluginManager.rejectedAction(for: plugin)) - return HStack(spacing: 8) { - PluginIconView(name: PluginManager.iconName(forPrimaryTypeId: plugin.providedDatabaseTypeIds.first)) - .font(.title3) - .frame(width: 24, height: 24) - .foregroundStyle(.tertiary) + private func form(_ content: ExtensionsFilteredContent) -> some View { + Form { + ExtensionsAttentionSection(snapshot: model.snapshot, context: context, tracker: model.manager.installTracker) - VStack(alignment: .leading, spacing: 2) { - Text(plugin.name) - .lineLimit(1) - Text(status.caption) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(1) + if !content.rejected.isEmpty { + Section(String(localized: "Couldn't Load")) { + ForEach(content.rejected) { row in + ExtensionsRejectedRowView(row: row, context: context, tracker: model.manager.installTracker) + } + } } - Spacer() - - Image(systemName: status.severity.symbolName) - .selectionAwareTint(status.severity.tint) - .accessibilityHidden(true) - } - .padding(.vertical, 2) - .accessibilityElement(children: .combine) - } - - private func rejectedDetail(_ plugin: RejectedPlugin) -> some View { - let action = pluginManager.rejectedAction(for: plugin) - let status = RejectedPluginStatus(action: action) - return ScrollView { - VStack(alignment: .leading, spacing: 16) { - Text(plugin.name) - .font(.title3.weight(.semibold)) - - NoticeLabel(plugin.reason, severity: status.severity) - .font(.callout) - - if let bundleId = plugin.bundleId { - Divider() - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { - GridRow { - Text("Bundle ID") - .foregroundStyle(.secondary) - Text(bundleId) - .textSelection(.enabled) - } + if !content.modules.isEmpty { + Section(String(localized: "Modules")) { + ForEach(content.modules, id: \.self) { module in + ModuleToggleRow(module: module) } - .font(.callout) } + } - Divider() - - HStack(spacing: 8) { - rejectedActionControl(for: plugin, action: action) - if pluginManager.canRemoveRejectedPlugin(plugin) { - Button(String(localized: "Remove")) { - removeRejectedPlugin(plugin) - } - .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) + ForEach(content.groups) { section in + Section(section.group.title) { + ForEach(section.rows) { row in + ExtensionsPluginRowView(row: row, context: context, tracker: model.manager.installTracker) } } } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - @ViewBuilder - private func rejectedActionControl(for plugin: RejectedPlugin, action: RejectedPluginAction) -> some View { - switch action { - case .updateAvailable(let registryPlugin): - Button(String(localized: "Update Now")) { - updatePlugin(registryPlugin) - } - .disabled(pluginManager.isInstalling) - .accessibilityLabel(String(format: String(localized: "Update %@"), plugin.name)) - case .requiresAppUpdate: - Button(updates.status.appUpdateTitle) { - updates.performAppUpdateAction() - } - .disabled(!updates.isAppUpdateActionEnabled) - .help(String(localized: "A newer TablePro is required to load this plugin.")) - case .awaitingCompatibleBuild: - if pluginManager.isUpdatingEnabled { - if isRetryingRejected { - ProgressView() - .controlSize(.small) - } else { - Button(String(localized: "Try Again")) { - retryRejectedPlugins() + // System Settings puts Add below its list. + if !content.isFiltering { + Section { + LabeledContent { + Button(String(localized: "Install from File…")) { + isImporting = true + } + .accessibilityIdentifier("extensions-install-from-file") + } label: { + Text("Install a plugin") + Text("Choose a .tableplugin bundle or a .zip archive, or drop one on this window.") } } } - case .notInRegistry: - EmptyView() } + .formStyle(.grouped) } - private func retryRejectedPlugins() { - isRetryingRejected = true - Task { - defer { isRetryingRejected = false } - await pluginManager.retryRejectedPluginRepairs(registryClient: registryClient) - } - } - - private func removeRejectedPlugin(_ plugin: RejectedPlugin) { - Task { - let confirmed = await AlertHelper.confirmDestructive( - title: String(format: String(localized: "Move “%@” to the Trash?"), plugin.name), - message: String(localized: "The plugin can't be loaded. You can put it back from the Trash."), - confirmButton: String(localized: "Move to Trash"), - cancelButton: String(localized: "Cancel") - ) - guard confirmed else { return } - do { - try pluginManager.removeRejectedPlugin(plugin) - } catch { - errorAlertTitle = String(localized: "Remove Failed") - errorAlertMessage = error.localizedDescription - showErrorAlert = true - return - } - if !path.isEmpty { path.removeLast() } + @ViewBuilder private var dropHighlight: some View { + if isDropTargeted { + RoundedRectangle(cornerRadius: 12) + .strokeBorder(.tint, lineWidth: 2) + .padding(8) + .allowsHitTesting(false) + .accessibilityHidden(true) } } +} - // MARK: - Plugin List - - private var pluginList: some View { - VStack(spacing: 0) { - NativeSearchField(text: $searchText, placeholder: String(localized: "Filter…")) - .padding(.horizontal, 8) - .padding(.vertical, 6) +// Unfiltered: a relaunch or an install in progress matters whatever the query. +private struct ExtensionsAttentionSection: View { + let snapshot: ExtensionsSnapshot + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel - List { - if pluginManager.needsRestart { - Section { - relaunchRow - } - } - if !filteredModules.isEmpty { - Section(String(localized: "Modules")) { - ForEach(filteredModules, id: \.self) { module in - ModuleToggleRow(module: module, settings: modules) - } - } - } - if !filteredRejected.isEmpty { - Section(String(localized: "Couldn't Load")) { - ForEach(filteredRejected, id: \.url) { plugin in - NavigationLink(value: PluginListSelection.rejected(plugin.url)) { - rejectedRow(plugin) - } + var body: some View { + let activities = ExtensionsSnapshot.activities(in: tracker.entries, excluding: snapshot.trackedIds) + if snapshot.relaunch != nil || !activities.isEmpty { + Section { + if let relaunch = snapshot.relaunch { + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() } + .accessibilityIdentifier("plugins-relaunch-button") + } label: { + Text("Relaunch TablePro to finish") + Text(verbatim: relaunch.text) } } - Section(String(localized: "Plugins")) { - ForEach(filteredPlugins) { plugin in - NavigationLink(value: PluginListSelection.plugin(plugin.id)) { - pluginRow(plugin) - } - } + ForEach(activities) { entry in + activityRow(entry) } } - .listStyle(.inset) - .safeAreaInset(edge: .bottom, spacing: 0) { - listBottomBar - } - .onAppear { revealRequestedPlugin() } - .onChange(of: navigation.pendingRequest) { _ in - revealRequestedPlugin() - } - } - } - - private var listBottomBar: some View { - VStack(alignment: .leading, spacing: 0) { - if let install = bottomBarInstall { - bottomBarStatus(install) - .padding(.horizontal, 10) - .padding(.top, 8) - } - listBottomButtons - } - } - - // A running install first; then a failure with no plugin row to show it. - private var bottomBarInstall: PluginInstallTracker.Entry? { - if let running = installTracker.runningEntries.first { - return running - } - return installTracker.failedEntries.last { install in - !pluginManager.plugins.contains { $0.id == install.pluginId } } } @ViewBuilder - private func bottomBarStatus(_ install: PluginInstallTracker.Entry) -> some View { - switch install.phase { + private func activityRow(_ entry: PluginInstallTracker.Entry) -> some View { + switch entry.phase { case .downloading, .installing: - let title = String(format: String(localized: "Installing %@…"), install.displayName) - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 6) { - Text(title) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(1) - .truncationMode(.middle) - Spacer(minLength: 4) - Button(String(localized: "Cancel")) { - installTracker.cancel(pluginId: install.pluginId) - } - .controlSize(.small) - .disabled(install.phase == .installing) - .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), install.displayName)) + let title = String(format: String(localized: "Installing %@…"), entry.displayName) + LabeledContent { + Button(String(localized: "Cancel")) { + tracker.cancel(pluginId: entry.pluginId) } - installProgress(install.phase) - .accessibilityLabel(Text(title)) + .disabled(entry.phase == .installing) + .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), entry.displayName)) + } label: { + Text(verbatim: title) + ExtensionsInstallProgress(phase: entry.phase) + .accessibilityLabel(Text(verbatim: title)) } case .failed(let reason): - VStack(alignment: .leading, spacing: 4) { - Text(String(format: String(localized: "%@ could not be installed"), install.displayName)) - .font(.callout) - .lineLimit(1) - .truncationMode(.middle) - installFailure(install, reason: reason) + LabeledContent { + HStack(spacing: 8) { + if entry.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(entry, context: context) + } + .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), entry.displayName)) + } + Button(String(localized: "Dismiss")) { + tracker.cancel(pluginId: entry.pluginId) + } + } + } label: { + Text(verbatim: String(format: String(localized: "%@ could not be installed"), entry.displayName)) + Text(verbatim: reason) } case .completed: EmptyView() } } +} - @ViewBuilder - private func installProgress(_ phase: PluginInstallTracker.Phase) -> some View { - if case .downloading(let fraction?) = phase { - ProgressView(value: fraction) - .controlSize(.small) - } else { - ProgressView() - .progressViewStyle(.linear) - .controlSize(.small) - } - } +private struct ExtensionsRejectedRowView: View { + let row: ExtensionsRejectedRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel - private func installFailure(_ install: PluginInstallTracker.Entry, reason: String) -> some View { - VStack(alignment: .leading, spacing: 4) { - HStack(alignment: .firstTextBaseline, spacing: 4) { - Image(systemName: "exclamationmark.triangle.fill") - .symbolRenderingMode(.multicolor) - .accessibilityHidden(true) - Text(reason) + var body: some View { + NavigationLink(value: SettingsRoute.rejectedPlugin(row.url)) { + HStack(spacing: 10) { + PluginIconView(name: row.iconName, size: 20) .foregroundStyle(.secondary) - .lineLimit(3) - .help(reason) - } - .font(.caption) - .accessibilityElement(children: .combine) - - HStack(spacing: 6) { - if install.retry != nil { - Button(String(localized: "Try Again")) { - retryInstall(install) - } - .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), install.displayName)) - } - Button(String(localized: "Dismiss")) { - installTracker.cancel(pluginId: install.pluginId) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: row.name) + .lineLimit(1) + Text(verbatim: caption) + .font(.subheadline) + .foregroundStyle(.secondary) + .lineLimit(1) } + Spacer(minLength: 8) + Image(systemName: row.severity.symbolName) + .selectionAwareTint(row.severity.tint) + .accessibilityHidden(true) } - .controlSize(.small) - } - } - - private var listBottomButtons: some View { - HStack(spacing: 4) { - Button { - installFromFile() - } label: { - Image(systemName: "plus") - .frame(width: 24, height: 20) - } - .buttonStyle(.borderless) - .disabled(pluginManager.isInstalling) - .accessibilityLabel(String(localized: "Install plugin from file")) - - Spacer() } - .padding(.horizontal, 8) - .padding(.vertical, 6) - } - - // MARK: - Plugin Row - - @ViewBuilder - private func pluginRow(_ plugin: PluginEntry) -> some View { - HStack(spacing: 8) { - PluginIconView(name: plugin.pluginIconName) - .font(.title3) - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) - - VStack(alignment: .leading, spacing: 2) { - Text(plugin.name) - .lineLimit(1) - - HStack(spacing: 8) { - Text("v\(plugin.version)") - if let capability = plugin.capabilities.first { - Text(capability.displayName) - } - } - .font(.caption) - .foregroundStyle(.secondary) - - if let install = installTracker.entries[plugin.id] { - pluginRowInstallCaption(install) - } else if pluginManager.stagedPluginIds.contains(plugin.id) { - Text("Updates when TablePro relaunches") - .font(.caption) - .foregroundStyle(.secondary) + .contextMenu { + if row.canRemove { + Button(String(localized: "Move to Trash…")) { + model.moveToTrash(row.url, context: context) } } - - Spacer() - - Text(plugin.source == .builtIn ? String(localized: "Built-in") : String(localized: "User")) - .font(.caption2) - .foregroundStyle(.secondary) + Button(String(localized: "Show in Finder")) { + model.showInFinder(row.url) + } } - .padding(.vertical, 2) + .modifier(ExtensionsOptionalAction(name: row.canRemove ? String(localized: "Move to Trash") : nil) { + model.moveToTrash(row.url, context: context) + }) + .accessibilityAction(named: Text("Show in Finder")) { + model.showInFinder(row.url) + } + .accessibilityIdentifier("extensions-rejected-row-\(row.url.lastPathComponent)") } - @ViewBuilder - private func pluginRowInstallCaption(_ install: PluginInstallTracker.Entry) -> some View { - switch install.phase { - case .downloading: - Text("Downloading update…") - .font(.caption) - .foregroundStyle(.secondary) - case .installing: - Text("Installing update…") - .font(.caption) - .foregroundStyle(.secondary) - case .completed: - if pluginManager.stagedPluginIds.contains(install.pluginId) { - Text("Updates when TablePro relaunches") - .font(.caption) - .foregroundStyle(.secondary) - } - case .failed(let reason): - installFailure(install, reason: reason) + private var caption: String { + switch row.trackerId.flatMap({ tracker.entries[$0]?.phase }) { + case .downloading?: String(localized: "Downloading update…") + case .installing?: String(localized: "Installing update…") + default: row.caption } } +} - // MARK: - Detail Pane +private struct ExtensionsPluginRowView: View { + let row: ExtensionsPluginRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel - @ViewBuilder - private func detailPage(for selection: PluginListSelection) -> some View { - switch selection { - case .rejected(let url): - if let rejected = pluginManager.rejectedPlugins.first(where: { $0.url == url }) { - rejectedDetail(rejected) - .settingsDrillIn(title: rejected.name) - } - case .plugin(let id): - if let selected = pluginManager.plugins.first(where: { $0.id == id }) { - pluginDetail(selected) - .settingsDrillIn(title: selected.name) + var body: some View { + let install = tracker.entries[row.id] + NavigationLink(value: SettingsRoute.plugin(id: row.id)) { + HStack(spacing: 10) { + PluginIconView(name: row.iconName, size: 20) + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: row.name) + .lineLimit(1) + ExtensionsPluginStatusLine( + status: ExtensionsPluginStatus( + phase: install?.phase, + isStaged: row.isStaged, + isBuiltIn: row.isBuiltIn, + version: row.version + ) + ) + } } } + .contextMenu { menu(install) } + .modifier(ExtensionsOptionalAction(name: row.isBuiltIn ? nil : String(localized: "Uninstall")) { + model.uninstall(row, context: context) + }) + .modifier(ExtensionsOptionalAction(name: row.isBuiltIn ? nil : String(localized: "Show in Finder")) { + model.showInFinder(row.url) + }) + .accessibilityIdentifier("extensions-plugin-row-\(row.id)") } - private func pluginDetail(_ selected: PluginEntry) -> some View { - ScrollView { - VStack(alignment: .leading, spacing: 16) { - Text(selected.name) - .font(.title3.weight(.semibold)) - - Text("v\(selected.version), \(selected.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed"))") - .font(.subheadline) - .foregroundStyle(.secondary) - - if !selected.pluginDescription.isEmpty { - Text(selected.pluginDescription) - .font(.callout) - .foregroundStyle(.secondary) + @ViewBuilder + private func menu(_ install: PluginInstallTracker.Entry?) -> some View { + if let install { + switch install.phase { + case .downloading, .installing: + Button(String(localized: "Cancel Update")) { + tracker.cancel(pluginId: row.id) } - - Divider() - - Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { - GridRow { - Text("Bundle ID") - .foregroundStyle(.secondary) - .gridColumnAlignment(.leading) - Text(selected.id) - .textSelection(.enabled) - .gridColumnAlignment(.leading) - } - - if !selected.capabilities.isEmpty { - GridRow { - Text("Capabilities") - .foregroundStyle(.secondary) - Text(selected.capabilities.map(\.displayName).joined(separator: ", ")) - } - } - - if let typeId = selected.databaseTypeId { - GridRow { - Text("Database Type") - .foregroundStyle(.secondary) - Text(typeId) - } - - if !selected.additionalTypeIds.isEmpty { - GridRow { - Text("Also handles") - .foregroundStyle(.secondary) - Text(selected.additionalTypeIds.joined(separator: ", ")) - } - } - - if let port = selected.defaultPort { - GridRow { - Text("Default Port") - .foregroundStyle(.secondary) - Text(verbatim: "\(port)") - } - } + .disabled(install.phase == .installing) + case .failed: + if install.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(install, context: context) } } - .font(.callout) - - if let settable = pluginManager.pluginInstances[selected.id] as? any SettablePluginDiscoverable, - let pluginSettings = settable.settingsView() { - Divider() - pluginSettings - } - - if selected.source == .userInstalled { - Divider() - Button("Uninstall", role: .destructive) { - uninstallPlugin(selected) - } + Button(String(localized: "Dismiss")) { + tracker.cancel(pluginId: row.id) } + case .completed: + EmptyView() } - .padding(20) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - - // A failure shows on the plugin's row or in the list's bottom bar, from the tracker. - private func updatePlugin(_ registryPlugin: RegistryPlugin) { - Task { - _ = await pluginManager.performRegistryUpdate(registryPlugin) - // A rejected plugin that updated is no longer rejected; pop its now-dead detail page. - if !path.isEmpty { path.removeLast() } } - } - - private func retryInstall(_ install: PluginInstallTracker.Entry) { - switch install.retry { - case .registry(let registryPlugin): - updatePlugin(registryPlugin) - case .file(let url): - installPlugin(from: url) - case nil: - break + if !row.isBuiltIn { + if install.map({ $0.phase != .completed }) == true { + Divider() + } + Button(String(localized: "Uninstall…")) { + model.uninstall(row, context: context) + } + Button(String(localized: "Show in Finder")) { + model.showInFinder(row.url) + } } } +} - // MARK: - Actions - - private func revealRequestedPlugin() { - guard let request = navigation.consumePendingRequest(), - let target = PluginListSelection.revealTarget( - pluginId: request.pluginId, - loadedIds: pluginManager.plugins.map(\.id), - rejected: pluginManager.rejectedPlugins - ) else { return } - searchText = "" - path.append(target) - } - - private func installFromFile() { - let panel = NSOpenPanel() - panel.title = String(localized: "Select Plugin") - panel.allowedContentTypes = [.zip] + (UTType("com.tablepro.plugin").map { [$0] } ?? []) - panel.allowsMultipleSelection = false - panel.canChooseDirectories = false - panel.treatsFilePackagesAsDirectories = false - - guard let window = NSApp.keyWindow else { return } - panel.beginSheetModal(for: window) { response in - guard response == .OK, let url = panel.url else { return } - self.installPlugin(from: url) - } - } +struct ExtensionsPluginStatusLine: View { + let status: ExtensionsPluginStatus - // A failure shows in the list's bottom bar, from the tracker. - private func installPlugin(from url: URL) { - Task { - guard let entry = try? await pluginManager.installPlugin(from: url) else { return } - path.append(PluginListSelection.plugin(entry.id)) + var body: some View { + Group { + if status == .failed { + NoticeLabel(status.text, severity: .warning) + } else { + Text(verbatim: status.text) + .foregroundStyle(.secondary) + } } + .font(.subheadline) + .lineLimit(1) } +} - private func uninstallPlugin(_ plugin: PluginEntry) { - Task { - let confirmed = await AlertHelper.confirmDestructive( - title: String(localized: "Uninstall Plugin?"), - message: String(format: String(localized: "\"%@\" will be removed from your system. This action cannot be undone."), plugin.name), - confirmButton: String(localized: "Uninstall"), - cancelButton: String(localized: "Cancel") - ) - - guard confirmed else { return } +struct ExtensionsInstallProgress: View { + let phase: PluginInstallTracker.Phase - do { - try await pluginManager.uninstallPlugin(id: plugin.id) - if !path.isEmpty { path.removeLast() } - } catch { - errorAlertTitle = String(localized: "Uninstall Failed") - errorAlertMessage = error.localizedDescription - showErrorAlert = true - } + var body: some View { + if case .downloading(let fraction?) = phase { + ProgressView(value: fraction) + .controlSize(.small) + } else { + ProgressView() + .progressViewStyle(.linear) + .controlSize(.small) } } } -// MARK: - PluginCapability Display Names +// VoiceOver gets every row action the context menu offers. +struct ExtensionsOptionalAction: ViewModifier { + let name: String? + let action: () -> Void -private extension PluginCapability { - var displayName: String { - switch self { - case .databaseDriver: String(localized: "Database Driver") - case .exportFormat: String(localized: "Export Format") - case .importFormat: String(localized: "Import Format") - case .documentInspector: String(localized: "Document Inspector") - @unknown default: String(localized: "Unknown") + @ViewBuilder + func body(content: Content) -> some View { + if let name { + content.accessibilityAction(named: Text(verbatim: name), action) + } else { + content } } } - -#Preview { - InstalledPluginsView() - .frame(width: 650, height: 500) -} diff --git a/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift b/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift index eb94ca5d06..e4275ee2fd 100644 --- a/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift +++ b/apple/TablePro/Views/Settings/Plugins/ModuleToggleRow.swift @@ -1,33 +1,23 @@ import SwiftUI -// A checkbox per module, the way Safari lists its extensions; this click is the only way a module turns on. +// This switch is the only way a module turns on (apple/AGENTS.md, Scope), and only module rows observe the settings. struct ModuleToggleRow: View { let module: AppModule - @ObservedObject var settings: AppModuleSettings + @ObservedObject private var settings: AppModuleSettings + + init(module: AppModule, settings: AppModuleSettings = .shared) { + self.module = module + self.settings = settings + } var body: some View { Toggle(isOn: Binding( get: { settings.isEnabled(module) }, set: { AppModuleActivation.setEnabled($0, for: module, settings: settings) } )) { - VStack(alignment: .leading, spacing: 2) { - Text(module.title) - Text(module.summary) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } + Text(verbatim: module.title) + Text(verbatim: module.summary) } - .toggleStyle(.checkbox) - .padding(.vertical, 2) .accessibilityIdentifier("module-toggle-\(module.rawValue)") } } - -extension AppModule { - func matches(filter: String) -> Bool { - filter.isEmpty - || title.localizedCaseInsensitiveContains(filter) - || summary.localizedCaseInsensitiveContains(filter) - } -} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift new file mode 100644 index 0000000000..83d0700433 --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift @@ -0,0 +1,209 @@ +import SwiftUI +import TableProPluginKit + +struct PluginDetailPage: View { + let entry: PluginEntry + let isStaged: Bool + let context: SettingsPaneContext + @EnvironmentObject private var model: ExtensionsPaneModel + @State private var loaded: PluginLoadedInstance? + + var body: some View { + Form { + Section { + PluginHeaderCard(iconName: entry.pluginIconName, name: entry.name, detail: headerDetail) + } + + PluginStatusSection( + trackerId: entry.id, + displayName: entry.name, + isStaged: isStaged, + route: .plugin(id: entry.id), + context: context, + tracker: model.manager.installTracker + ) + + Section(String(localized: "Details")) { + LabeledContent(String(localized: "Version"), value: entry.version) + LabeledContent( + String(localized: "Source"), + value: entry.source == .builtIn ? String(localized: "Built-in") : String(localized: "User-installed") + ) + if !entry.capabilities.isEmpty { + LabeledContent(String(localized: "Capabilities"), value: capabilityNames) + } + if let typeId = entry.databaseTypeId { + LabeledContent(String(localized: "Database type"), value: typeId) + if !entry.additionalTypeIds.isEmpty { + LabeledContent(String(localized: "Also handles"), value: entry.additionalTypeIds.joined(separator: ", ")) + } + if let port = entry.defaultPort { + LabeledContent(String(localized: "Default port"), value: String(port)) + } + } + LabeledContent(String(localized: "Bundle ID")) { + Text(verbatim: entry.id) + .textSelection(.enabled) + } + } + + if let loaded, let settable = loaded.settable, let options = settable.settingsView() { + Section(optionsTitle) { + options + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + if entry.source == .userInstalled { + Section { + LabeledContent { + Button(String(localized: "Uninstall…"), role: .destructive) { + model.uninstall(id: entry.id, name: entry.name, isDriver: entry.databaseTypeId != nil, context: context) + } + .accessibilityLabel(String(format: String(localized: "Uninstall %@"), entry.name)) + .accessibilityIdentifier("extensions-plugin-uninstall") + } label: { + Text("Uninstall this plugin") + Text("The plugin moves to the Trash and its settings are deleted.") + } + } + } + } + .formStyle(.grouped) + .task(id: entry.id) { + loaded = await PluginLoadedInstance.load(entry, manager: model.manager) + } + } + + private var capabilityNames: String { + entry.capabilities.map(\.settingsDisplayName).joined(separator: ", ") + } + + private var headerDetail: String { + let description = loaded?.description ?? entry.pluginDescription + return description.isEmpty ? capabilityNames : description + } + + private var optionsTitle: String { + if entry.exportFormatId != nil { return String(localized: "Export Options") } + if entry.importFormatId != nil { return String(localized: "Import Options") } + return String(localized: "Options") + } +} + +// A format's code loads off the main actor first, so opening its page never holds the window on a signature check. +struct PluginLoadedInstance { + let description: String + let settable: (any SettablePluginDiscoverable)? + + @MainActor + static func load(_ entry: PluginEntry, manager: PluginManager) async -> PluginLoadedInstance? { + if let formatId = entry.exportFormatId { + await manager.loadLazyExportExecutable(formatId: formatId) + _ = manager.exportPlugin(forFormat: formatId) + } else if let formatId = entry.importFormatId { + await manager.loadLazyImportExecutable(formatId: formatId) + _ = manager.importPlugin(forFormat: formatId) + } + // A driver's code is never loaded just to show its page. + guard let instance = manager.pluginInstances[entry.id] else { return nil } + return PluginLoadedInstance( + description: type(of: instance).pluginDescription, + settable: instance as? any SettablePluginDiscoverable + ) + } +} + +struct PluginHeaderCard: View { + let iconName: String + let name: String + let detail: String + + var body: some View { + HStack(spacing: 12) { + PluginIconView(name: iconName, size: 32) + .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: name) + .font(.headline) + if !detail.isEmpty { + Text(verbatim: detail) + .font(.subheadline) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + Spacer(minLength: 0) + } + .accessibilityElement(children: .combine) + } +} + +// Shown only while the tracker has this plugin or an update waits for a relaunch. +struct PluginStatusSection: View { + let trackerId: String? + let displayName: String + let isStaged: Bool + let route: SettingsRoute + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @EnvironmentObject private var model: ExtensionsPaneModel + + var body: some View { + let install = trackerId.flatMap { tracker.entries[$0] } + if let status = ExtensionsPageStatus(phase: install?.phase, isStaged: isStaged) { + Section { + switch status { + case .running(let phase): + LabeledContent { + Button(String(localized: "Cancel")) { + if let trackerId { tracker.cancel(pluginId: trackerId) } + } + .disabled(phase == .installing) + .accessibilityLabel(String(format: String(localized: "Cancel installing %@"), displayName)) + } label: { + Text(verbatim: ExtensionsPluginStatus(phase: phase, isStaged: false, isBuiltIn: false, version: "").text) + ExtensionsInstallProgress(phase: phase) + .accessibilityLabel(Text(verbatim: String(format: String(localized: "Installing %@…"), displayName))) + } + case .failed(let reason): + LabeledContent { + HStack(spacing: 8) { + if let install, install.retry != nil { + Button(String(localized: "Try Again")) { + model.retryInstall(install, context: context, replacing: route) + } + .accessibilityLabel(String(format: String(localized: "Try installing %@ again"), displayName)) + } + Button(String(localized: "Dismiss")) { + if let trackerId { tracker.cancel(pluginId: trackerId) } + } + } + } label: { + NoticeLabel(reason, severity: .error) + } + case .staged: + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() + } + } label: { + Text("Updates when TablePro relaunches") + } + } + } + } + } +} + +extension PluginCapability { + var settingsDisplayName: String { + switch self { + case .databaseDriver: String(localized: "Database Driver") + case .exportFormat: String(localized: "Export Format") + case .importFormat: String(localized: "Import Format") + case .documentInspector: String(localized: "Document Inspector") + @unknown default: String(localized: "Unknown") + } + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift b/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift index a56b020fa2..91685ceccd 100644 --- a/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift +++ b/apple/TablePro/Views/Settings/Plugins/PluginIconView.swift @@ -1,21 +1,39 @@ -// -// PluginIconView.swift -// TablePro - import AppKit import SwiftUI struct PluginIconView: View { let name: String + var size: CGFloat = 20 var body: some View { - if NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil { + icon + .frame(width: size + 4, height: size + 4) + .accessibilityHidden(true) + } + + @ViewBuilder private var icon: some View { + if PluginIconKind.isSymbol(name) { Image(systemName: name) + .font(.system(size: size * 0.8)) } else { Image(name) .renderingMode(.template) .resizable() .scaledToFit() + .frame(width: size, height: size) } } } + +// A symbol lookup costs tens of microseconds, and every row asks on each render. +@MainActor +private enum PluginIconKind { + private static var symbols: [String: Bool] = [:] + + static func isSymbol(_ name: String) -> Bool { + if let known = symbols[name] { return known } + let isSymbol = NSImage(systemSymbolName: name, accessibilityDescription: nil) != nil + symbols[name] = isSymbol + return isSymbol + } +} diff --git a/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift index 56ca05867d..7d8984ebef 100644 --- a/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift +++ b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift @@ -1,8 +1,3 @@ -// -// PluginListSelection.swift -// TablePro -// - import Foundation // A rejected bundle can carry the id of a loaded plugin, so rejected rows are told apart by URL. @@ -27,6 +22,13 @@ internal enum PluginListSelection: Hashable { let first = rejected.first(where: \.isOutdated) ?? rejected.first return first.map { .rejected($0.url) } } + + internal var route: SettingsRoute { + switch self { + case .plugin(let id): .plugin(id: id) + case .rejected(let url): .rejectedPlugin(url) + } + } } internal struct RejectedPluginStatus: Equatable { diff --git a/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift b/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift deleted file mode 100644 index 1d9bf2a889..0000000000 --- a/apple/TablePro/Views/Settings/Plugins/PluginsSettingsNavigation.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// PluginsSettingsNavigation.swift -// TablePro -// - -import Combine -import Foundation - -@MainActor -internal final class PluginsSettingsNavigation: ObservableObject { - internal struct Request: Equatable { - let id: UUID - let pluginId: String? - } - - internal static let shared = PluginsSettingsNavigation() - - @Published internal private(set) var pendingRequest: Request? - - internal init() {} - - internal func reveal(pluginId: String?) { - pendingRequest = Request(id: UUID(), pluginId: pluginId) - } - - internal func consumePendingRequest() -> Request? { - let request = pendingRequest - pendingRequest = nil - return request - } -} diff --git a/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift new file mode 100644 index 0000000000..48669d398b --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift @@ -0,0 +1,127 @@ +import AppKit +import SwiftUI + +struct RejectedPluginDetailPage: View { + let row: ExtensionsRejectedRow + let context: SettingsPaneContext + @ObservedObject var tracker: PluginInstallTracker + @ObservedObject private var updates = UpdateCenter.shared + @EnvironmentObject private var model: ExtensionsPaneModel + + var body: some View { + Form { + Section { + PluginHeaderCard(iconName: row.iconName, name: row.name, detail: caption) + } + + Section { + LabeledContent { + actionControl + } label: { + NoticeLabel(row.reason, severity: row.severity) + } + if model.retryFailures.contains(row.url) { + NoticeLabel( + String(localized: "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and try again."), + severity: .warning + ) + } + } + + PluginStatusSection( + trackerId: row.trackerId, + displayName: row.name, + isStaged: false, + route: .rejectedPlugin(row.url), + context: context, + tracker: tracker + ) + + Section(String(localized: "Details")) { + if let bundleId = row.bundleId { + LabeledContent(String(localized: "Bundle ID")) { + Text(verbatim: bundleId) + .textSelection(.enabled) + } + } + LabeledContent { + Button { + model.showInFinder(row.url) + } label: { + Image(systemName: "arrow.forward") + } + .buttonStyle(.borderless) + .help(String(localized: "Show in Finder")) + .accessibilityLabel(String(localized: "Show in Finder")) + } label: { + Text("Location") + Text(verbatim: location) + .lineLimit(1) + .truncationMode(.middle) + .help(location) + } + } + + if row.canRemove { + Section { + LabeledContent { + Button(String(localized: "Move to Trash…")) { + model.moveToTrash(row.url, context: context) + } + .accessibilityLabel(String(format: String(localized: "Move %@ to the Trash"), row.name)) + } label: { + Text("Remove this plugin") + Text("You can put it back from the Trash.") + } + } + } + } + .formStyle(.grouped) + } + + private var location: String { + (row.url.path as NSString).abbreviatingWithTildeInPath + } + + private var isOwnInstallRunning: Bool { + row.trackerId.flatMap { tracker.entries[$0]?.phase.isRunning } ?? false + } + + private var caption: String { + switch row.trackerId.flatMap({ tracker.entries[$0]?.phase }) { + case .downloading?: String(localized: "Downloading update…") + case .installing?: String(localized: "Installing update…") + default: row.caption + } + } + + @ViewBuilder private var actionControl: some View { + switch row.action { + case .update(let registryId): + Button(String(localized: "Update Now")) { + guard let registryPlugin = model.registryPlugin(id: registryId) else { return } + model.update(registryPlugin, context: context, replacing: .rejectedPlugin(row.url)) + } + .disabled(isOwnInstallRunning) + .accessibilityLabel(String(format: String(localized: "Update %@"), row.name)) + case .appUpdate: + Button(updates.status.appUpdateTitle) { + updates.performAppUpdateAction() + } + .disabled(!updates.isAppUpdateActionEnabled) + .help(String(localized: "A newer TablePro is required to load this plugin.")) + case .retry: + if model.retrying.contains(row.url) { + ProgressView() + .controlSize(.small) + .accessibilityLabel(String(localized: "Checking for a compatible build")) + } else { + Button(String(localized: "Try Again")) { + model.retryRejected(row.url) + } + } + case .noAction: + EmptyView() + } + } +} diff --git a/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift b/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift index 8d9ecce183..d00e2749c0 100644 --- a/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift +++ b/apple/TableProTests/Core/Plugins/RejectedPluginRemovalTests.swift @@ -1,5 +1,6 @@ import Foundation @testable import TablePro +import TableProPluginKit import Testing @MainActor @@ -42,6 +43,38 @@ struct RejectedPluginRemovalTests { #expect(manager.rejectedPlugins.isEmpty) } + @Test("Removing a rejected plugin also drops the listed copy of the same bundle") + func removalDropsTheListedCopy() throws { + defer { try? FileManager.default.removeItem(at: root) } + let userPlugins = root.appendingPathComponent("Plugins", isDirectory: true) + let plugin = try makeBundle(in: userPlugins) + let manager = PluginManager(builtInPluginsURL: nil, userPluginsDir: userPlugins) + manager.rejectedPlugins = [plugin] + manager.plugins = [PluginEntry( + id: "com.example.broken", + bundle: Bundle.main, + url: plugin.url, + source: .userInstalled, + name: "Broken", + version: "1.0", + pluginDescription: "", + capabilities: [.databaseDriver], + databaseTypeId: nil, + additionalTypeIds: [], + pluginIconName: "puzzlepiece", + defaultPort: nil, + exportFormatId: nil, + importFormatId: nil + )] + let recorder = TrashRecorder() + + try manager.removeRejectedPlugin(plugin) { recorder.trashed.append($0) } + + #expect(recorder.trashed == [plugin.url]) + #expect(manager.rejectedPlugins.isEmpty) + #expect(manager.plugins.isEmpty) + } + @Test("A rejected plugin outside the user's folder, such as one inside the app, is refused and kept") func bundledPluginIsRefused() throws { defer { try? FileManager.default.removeItem(at: root) } diff --git a/apple/TableProTests/Views/Settings/ExtensionsPaneModelTests.swift b/apple/TableProTests/Views/Settings/ExtensionsPaneModelTests.swift new file mode 100644 index 0000000000..fd1ff2ca23 --- /dev/null +++ b/apple/TableProTests/Views/Settings/ExtensionsPaneModelTests.swift @@ -0,0 +1,357 @@ +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct ExtensionsPaneModelTests { + private let root = FileManager.default.temporaryDirectory + .appendingPathComponent("ExtensionsPaneModelTests-\(UUID().uuidString)", isDirectory: true) + + private func entry( + _ id: String, + name: String? = nil, + capabilities: [PluginCapability] = [.databaseDriver], + typeIds: [String] = [], + exportFormatId: String? = nil, + source: PluginSource = .builtIn, + url: URL? = nil, + bundle: Bundle = .main + ) -> PluginEntry { + PluginEntry( + id: id, + bundle: bundle, + url: url ?? URL(fileURLWithPath: "/tmp/\(id).tableplugin"), + source: source, + name: name ?? id, + version: "1.0", + build: 1, + pluginDescription: "", + capabilities: capabilities, + databaseTypeId: typeIds.first, + additionalTypeIds: Array(typeIds.dropFirst()), + pluginIconName: "puzzlepiece", + defaultPort: nil, + exportFormatId: exportFormatId, + importFormatId: nil + ) + } + + private func rejected(_ name: String, bundleId: String? = nil, url: URL? = nil, isOutdated: Bool = true) -> RejectedPlugin { + RejectedPlugin( + url: url ?? URL(fileURLWithPath: "/tmp/\(UUID().uuidString).tableplugin"), + bundleId: bundleId, + registryId: nil, + name: name, + reason: "Built for an older PluginKit", + isOutdated: isOutdated, + providedDatabaseTypeIds: [] + ) + } + + private func snapshot( + _ plugins: [PluginEntry], + rejected: [RejectedPlugin] = [], + needsRestart: Bool = false, + staged: Set = [] + ) -> ExtensionsSnapshot { + ExtensionsPaneModel.makeSnapshot( + plugins: plugins, + rejected: rejected, + needsRestart: needsRestart, + staged: staged, + manifest: nil, + isUpdatingEnabled: false, + canRemove: { _ in false } + ) + } + + private func makeManager() -> PluginManager { + PluginManager(builtInPluginsURL: nil, userPluginsDir: root.appendingPathComponent("Plugins", isDirectory: true)) + } + + private func makeContext(_ navigation: SettingsNavigationModel, registry: OfflineRegistry) -> SettingsPaneContext { + SettingsPaneContext( + pane: .plugins, + settings: AppSettingsManager.shared, + navigation: navigation, + models: SettingsWindowModels(), + registryClient: registry.client, + presentError: { _, _ in } + ) + } + + @Test("Every plugin lands in exactly one group, and one with no known first capability lands in Other") + func everyPluginInOneGroup() { + let plugins = [ + entry("driver", capabilities: [.databaseDriver]), + entry("export", capabilities: [.exportFormat]), + entry("import", capabilities: [.importFormat]), + entry("inspector", capabilities: [.documentInspector]), + entry("none", capabilities: []), + entry("both", capabilities: [.exportFormat, .databaseDriver]), + ] + let groups = snapshot(plugins).groups + + #expect(groups.map(\.group) == [.drivers, .exports, .imports, .other]) + #expect(groups.flatMap(\.rows).map(\.id).sorted() == plugins.map(\.id).sorted()) + #expect(groups.first { $0.group == .exports }?.rows.map(\.id) == ["both", "export"]) + #expect(groups.first { $0.group == .other }?.rows.map(\.id) == ["inspector", "none"]) + } + + @Test("Rows sort by name the way Finder does, numbers by value and case ignored") + func rowsSortLikeFinder() { + let plugins = [ + entry("a", name: "PostgreSQL"), + entry("b", name: "mysql"), + entry("c", name: "Item 10"), + entry("d", name: "Item 9"), + ] + #expect(snapshot(plugins).rows.map(\.name) == ["Item 9", "Item 10", "mysql", "PostgreSQL"]) + } + + @Test("The filter matches a type id, a format id, a group title, a rejected caption and a module summary") + func filterMatchesEveryField() { + let content = snapshot( + [ + entry("pg", name: "PostgreSQL", typeIds: ["PostgreSQL", "Redshift"]), + entry("xlsx", name: "Spreadsheet", capabilities: [.exportFormat], exportFormatId: "xlsx"), + ], + rejected: [rejected("Old Driver")] + ) + + #expect(content.filtered("redshift").groups.flatMap(\.rows).map(\.id) == ["pg"]) + #expect(content.filtered("XLSX").groups.flatMap(\.rows).map(\.id) == ["xlsx"]) + #expect(content.filtered("Export Formats").groups.map(\.group) == [.exports]) + // With no manifest yet the caption reads "Waiting for a compatible build". + #expect(content.filtered("compatible").rejected.map(\.name) == ["Old Driver"]) + #expect(content.filtered("old").rejected.map(\.name) == ["Old Driver"]) + #expect(content.filtered("old").groups.isEmpty) + #expect(content.filtered("breakpoints").modules == [.routineDebugger]) + #expect(content.filtered("zzz").isEmpty) + #expect(content.filtered("zzz").isFiltering) + #expect(!content.filtered(" ").isFiltering) + } + + @Test("A plugin whose bundle also could not load is listed once, under Couldn't Load") + func doubleListedPluginShownOnce() throws { + let url = URL(fileURLWithPath: "/tmp/Broken.tableplugin") + let result = snapshot( + [entry("com.example.broken", url: url), entry("com.example.fine")], + rejected: [rejected("Broken", bundleId: "com.example.broken", url: url)] + ) + #expect(result.rows.map(\.id) == ["com.example.fine"]) + #expect(result.rejected.map(\.url) == [url]) + } + + @Test("A plugin route whose bundle could not load opens the Couldn't Load page") + func pluginRouteOfRejectedBundleShowsRejectedPage() throws { + let manager = makeManager() + let registry = try OfflineRegistry() + let model = ExtensionsPaneModel(manager: manager, registryClient: registry.client) + let url = URL(fileURLWithPath: "/tmp/Broken-\(UUID().uuidString).tableplugin") + manager.plugins = [entry("com.example.broken", url: url)] + manager.rejectedPlugins = [rejected("Broken", bundleId: "com.example.broken", url: url)] + + guard case .rejected(let row) = model.page(for: .plugin(id: "com.example.broken")) else { + Issue.record("expected the rejected page") + return + } + #expect(row.url == url) + guard case .unavailable = model.page(for: .plugin(id: "com.example.gone")) else { + Issue.record("expected the unavailable page") + return + } + } + + @Test("Relaunch explains removed plugins first, then staged updates") + func relaunchReason() { + #expect(snapshot([]).relaunch == nil) + #expect(snapshot([], staged: ["a"]).relaunch == .updates) + #expect(snapshot([], needsRestart: true).relaunch == .removed) + #expect(snapshot([], needsRestart: true, staged: ["a"]).relaunch == .removed) + } + + @Test("A row's status line shows the first state that applies") + func rowStatusPrecedence() { + #expect(ExtensionsPluginStatus(phase: .downloading(fraction: 0.5), isStaged: true, isBuiltIn: true, version: "1") == .downloading) + #expect(ExtensionsPluginStatus(phase: .installing, isStaged: true, isBuiltIn: true, version: "1") == .installing) + #expect(ExtensionsPluginStatus(phase: .failed("x"), isStaged: true, isBuiltIn: true, version: "1") == .failed) + #expect(ExtensionsPluginStatus(phase: .completed, isStaged: true, isBuiltIn: true, version: "1") == .staged) + #expect(ExtensionsPluginStatus(phase: nil, isStaged: false, isBuiltIn: true, version: "1") == .builtIn) + #expect(ExtensionsPluginStatus(phase: nil, isStaged: false, isBuiltIn: false, version: "1.2") == .version("1.2")) + #expect(ExtensionsPageStatus(phase: nil, isStaged: false) == nil) + #expect(ExtensionsPageStatus(phase: .completed, isStaged: true) == .staged) + } + + @Test("Only installs no row shows get an activity row, oldest first") + func activitiesSkipRowsAndFinishedInstalls() { + func install(_ id: String, order: Int, phase: PluginInstallTracker.Phase) -> PluginInstallTracker.Entry { + PluginInstallTracker.Entry( + pluginId: id, + displayName: id, + generation: UUID(), + order: order, + trigger: .user, + retry: nil, + phase: phase + ) + } + let entries = [ + "listed": install("listed", order: 1, phase: .installing), + "file:/a.zip": install("file:/a.zip", order: 3, phase: .installing), + "done": install("done", order: 2, phase: .completed), + "broken": install("broken", order: 4, phase: .failed("no")), + ] + let activities = ExtensionsSnapshot.activities(in: entries, excluding: ["listed"]) + #expect(activities.map(\.pluginId) == ["file:/a.zip", "broken"]) + } + + @Test("Only zip and tableplugin files install, whatever the case of the extension") + func onlyPluginFilesInstall() throws { + let urls = [ + URL(fileURLWithPath: "/tmp/a.zip"), + URL(fileURLWithPath: "/tmp/b.TablePlugin"), + URL(fileURLWithPath: "/tmp/c.txt"), + try #require(URL(string: "https://example.com/d.zip")), + ] + #expect(ExtensionsPaneModel.installableFiles(urls).map(\.lastPathComponent) == ["a.zip", "b.TablePlugin"]) + } + + @Test("A reveal asked for before the plugin loaded opens its page once the plugin is listed") + func revealBeforeLoadFinishes() async throws { + let manager = makeManager() + let registry = try OfflineRegistry() + let model = ExtensionsPaneModel(manager: manager, registryClient: registry.client) + let navigation = SettingsNavigationModel(initial: .root(.plugins), isRouteAvailable: { route in + guard case .plugin(let id) = route else { return true } + return manager.plugins.contains { $0.id == id } + }) + let context = makeContext(navigation, registry: registry) + + navigation.open(SettingsLocation(route: .plugin(id: "com.example.late")), recordsHistory: true) + #expect(navigation.location == .root(.plugins)) + #expect(navigation.pendingPluginReveal?.pluginId == "com.example.late") + + manager.plugins = [entry("com.example.late")] + context.filter?.query = "something" + await model.revealPending(in: context) + + #expect(navigation.location.routes == [.plugin(id: "com.example.late")]) + #expect(navigation.pendingPluginReveal == nil) + #expect(context.filter?.query == "") + } + + @Test("A reveal with no id opens the first plugin waiting for an update") + func revealWithoutIdOpensFirstOutdated() async throws { + let manager = makeManager() + let registry = try OfflineRegistry() + let model = ExtensionsPaneModel(manager: manager, registryClient: registry.client) + let broken = rejected("Broken", isOutdated: false) + let outdated = rejected("Outdated") + manager.rejectedPlugins = [broken, outdated] + let navigation = SettingsNavigationModel(initial: .root(.plugins)) + let context = makeContext(navigation, registry: registry) + + navigation.requestPluginReveal(nil) + await model.revealPending(in: context) + + #expect(navigation.location.routes == [.rejectedPlugin(outdated.url)]) + } + + @Test("A reveal is consumed but not pushed once the pane has moved into a page or away") + func revealDroppedWhenNotAtRoot() async throws { + let manager = makeManager() + let registry = try OfflineRegistry() + let model = ExtensionsPaneModel(manager: manager, registryClient: registry.client) + manager.rejectedPlugins = [rejected("Outdated")] + let navigation = SettingsNavigationModel(initial: .root(.plugins)) + let context = makeContext(navigation, registry: registry) + + navigation.push(.plugin(id: "com.example.open"), in: .plugins) + navigation.requestPluginReveal(nil) + await model.revealPending(in: context) + #expect(navigation.location.routes == [.plugin(id: "com.example.open")]) + #expect(navigation.pendingPluginReveal == nil) + + navigation.select(.general) + navigation.requestPluginReveal(nil) + await model.revealPending(in: context) + #expect(navigation.location == .root(.general)) + } + + @Test("An uninstall whose bundle cannot be removed keeps the plugin listed and asks for no relaunch") + func uninstallFailureKeepsTheEntry() async throws { + defer { try? FileManager.default.removeItem(at: root) } + let manager = makeManager() + let url = root.appendingPathComponent("Plugins/Driver.tableplugin", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let bundle = try #require(Bundle(url: url)) + manager.plugins = [entry("com.example.driver", source: .userInstalled, url: url, bundle: bundle)] + + await #expect(throws: CocoaError.self) { + try await manager.uninstallPlugin(id: "com.example.driver") { _ in throw CocoaError(.fileWriteNoPermission) } + } + + #expect(manager.plugins.map(\.id) == ["com.example.driver"]) + #expect(!manager.needsRestart) + #expect(FileManager.default.fileExists(atPath: url.path)) + } + + @Test("An uninstall hands the bundle to the remover before it unlists the plugin") + func uninstallRemovesTheBundleFirst() async throws { + defer { try? FileManager.default.removeItem(at: root) } + let manager = makeManager() + let url = root.appendingPathComponent("Plugins/Driver.tableplugin", isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let bundle = try #require(Bundle(url: url)) + manager.plugins = [entry("com.example.driver", source: .userInstalled, url: url, bundle: bundle)] + var listedWhileRemoving: [String] = [] + + try await manager.uninstallPlugin(id: "com.example.driver") { _ in + listedWhileRemoving = manager.plugins.map(\.id) + } + + #expect(listedWhileRemoving == ["com.example.driver"]) + #expect(manager.plugins.isEmpty) + #expect(manager.needsRestart) + } + + @Test("Installing a loose bundle works on a copy and leaves the user's file where it was") + func looseInstallLeavesTheSource() throws { + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("Downloads/Driver.tableplugin", isDirectory: true) + let contents = source.appendingPathComponent("Contents", isDirectory: true) + try FileManager.default.createDirectory(at: contents, withIntermediateDirectories: true) + try Data("".utf8).write(to: contents.appendingPathComponent("Info.plist")) + + let copy = try PluginManager.copyLooseBundle(at: source, into: root.appendingPathComponent("Staging/work", isDirectory: true)) + + #expect(copy.lastPathComponent == "Driver.tableplugin") + #expect(copy.standardizedFileURL != source.standardizedFileURL) + #expect(FileManager.default.fileExists(atPath: source.appendingPathComponent("Contents/Info.plist").path)) + #expect(FileManager.default.fileExists(atPath: copy.appendingPathComponent("Contents/Info.plist").path)) + } + + @Test("A declared display name is trimmed, and a blank one counts as none") + func declaredDisplayName() { + #expect(PluginManager.declaredDisplayName(in: ["CFBundleDisplayName": " CSV Export "]) == "CSV Export") + #expect(PluginManager.declaredDisplayName(in: ["CFBundleDisplayName": " "]) == nil) + #expect(PluginManager.declaredDisplayName(in: [:]) == nil) + } + + @Test("Every bundled plugin's Info.plist names it the way its class does, so the list shows it before its code loads") + func bundledPluginsDeclareTheirName() throws { + let plugIns = try #require(Bundle.main.builtInPlugInsURL) + let urls = try FileManager.default.contentsOfDirectory(at: plugIns, includingPropertiesForKeys: nil) + .filter { $0.pathExtension == "tableplugin" } + #expect(!urls.isEmpty) + + for url in urls { + let bundle = try #require(Bundle(url: url)) + let principal = try #require(bundle.principalClass as? any TableProPlugin.Type, "\(url.lastPathComponent)") + let declared = PluginManager.declaredDisplayName(in: PluginManager.infoPlist(at: url)) + #expect(declared == principal.pluginName, "\(url.lastPathComponent)") + } + } +} diff --git a/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift b/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift index 925cbfb29c..deb3036d84 100644 --- a/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift +++ b/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift @@ -59,6 +59,13 @@ struct PluginListSelectionTests { ) } + @Test("A reveal target pushes the route the Extensions pane draws its pages for") + func targetMapsToItsRoute() { + let url = URL(fileURLWithPath: "/tmp/Broken.tableplugin") + #expect(PluginListSelection.plugin("com.example.driver").route == .plugin(id: "com.example.driver")) + #expect(PluginListSelection.rejected(url).route == .rejectedPlugin(url)) + } + @Test("Only a plugin missing from the registry reads as an error") func statusSeverity() { #expect(RejectedPluginStatus(action: .awaitingCompatibleBuild).severity == .warning) diff --git a/apple/scripts/ci/check-plugin-provides.py b/apple/scripts/ci/check-plugin-provides.py index 2c6dd606a0..4daef93ff9 100755 --- a/apple/scripts/ci/check-plugin-provides.py +++ b/apple/scripts/ci/check-plugin-provides.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 -"""Fail when a plugin's TableProProvides* Info.plist keys differ from the ids its Swift class declares. +"""Fail when a plugin's TableProProvides* Info.plist keys or CFBundleDisplayName differ from its Swift class. The app registers a plugin from these keys without loading its code, and loads a plugin that has -none at launch. The first database type id is the plugin's primary one. +none at launch. The first database type id is the plugin's primary one. CFBundleDisplayName is the +class's pluginName, which Settings shows before the code loads. Usage: check-plugin-provides.py [--plugins ] # compare every Plugins/*/Info.plist - check-plugin-provides.py [--plugins ] --write # stamp the keys from the Swift ids + check-plugin-provides.py [--plugins ] --write # stamp the keys from the Swift ids and name """ import argparse @@ -21,11 +22,13 @@ EXPORT_KEY = "TableProProvidesExportFormatIds" IMPORT_KEY = "TableProProvidesImportFormatIds" KEYS = (DATABASE_KEY, EXPORT_KEY, IMPORT_KEY) +NAME_KEY = "CFBundleDisplayName" STATIC = r"^[ \t]*(?:[a-z]+[ \t]+)*static[ \t]+(?:let|var)[ \t]+" PRIMARY_ID = re.compile(STATIC + r"databaseTypeId(?:\s*:\s*String)?\s*=\s*\"([^\"]+)\"", re.M) EXTRA_IDS = re.compile(STATIC + r"additionalDatabaseTypeIds(?:\s*:\s*\[String\])?\s*=\s*\[([^\]]*)\]", re.M) FORMAT_ID = re.compile(STATIC + r"formatId(?:\s*:\s*String)?\s*=\s*\"([^\"]+)\"", re.M) +PLUGIN_NAME = re.compile(STATIC + r"pluginName(?:\s*:\s*String)?\s*=\s*\"([^\"]+)\"", re.M) EXPORTER = re.compile(r"\b(?:class|struct|enum|actor)\s+\w+\s*:[^{]*\bExportFormatPlugin\b") IMPORTER = re.compile(r"\b(?:class|struct|enum|actor)\s+\w+\s*:[^{]*\bImportFormatPlugin\b") STRING = re.compile(r"\"([^\"]*)\"") @@ -75,6 +78,13 @@ def provided_ids(directory): return expected +# None when pluginName is not a string literal; the name is then left to the class. +def plugin_name(directory): + sources = [(path, path.read_text(encoding="utf-8")) for path in sorted(directory.rglob("*.swift"))] + name = find_one(PLUGIN_NAME, sources, "pluginName") + return name.group(1) if name else None + + def read_plist(path): macros = {} @@ -101,6 +111,7 @@ def write_plist(path, info, macros): def problems_in(directory, write=False): expected = provided_ids(directory) + name = plugin_name(directory) info, macros = read_plist(directory / "Info.plist") problems = [] @@ -116,10 +127,16 @@ def problems_in(directory, write=False): else: problems.append(f"{directory.name}: Info.plist has {key} {declared}, the class provides {wanted}") + declared_name = info.get(NAME_KEY) + if name is not None and declared_name != name: + problems.append(f"{directory.name}: Info.plist has {NAME_KEY} {declared_name!r}, the class's pluginName is {name!r}") + if write and problems: for key in KEYS: info.pop(key, None) info.update(expected) + if name is not None: + info[NAME_KEY] = name write_plist(directory / "Info.plist", info, macros) return problems @@ -127,7 +144,7 @@ def problems_in(directory, write=False): def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--plugins", type=Path, default=PLUGINS_DIR) - parser.add_argument("--write", action="store_true", help="rewrite the keys from the Swift ids") + parser.add_argument("--write", action="store_true", help="rewrite the keys from the Swift ids and name") args = parser.parse_args(argv) directories = plugin_directories(args.plugins) @@ -154,7 +171,7 @@ def main(argv=None): print(f"\n{len(errors)} problem(s).{hint}", file=sys.stderr) return 1 if not args.write: - print(f"{len(directories)} plugin Info.plists declare the ids their classes provide") + print(f"{len(directories)} plugin Info.plists declare the ids and names their classes provide") return 0 From 931b2b16663dd283d625feebed5cb5952b7dedd2 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:18 +0700 Subject: [PATCH 40/48] refactor(settings): drop the subpage shims and the manager's slice forwarding --- .../Core/Storage/AppSettingsManager.swift | 28 +---- .../Settings/SettingsDrillInChrome.swift | 8 -- .../Views/Settings/SettingsNavigation.swift | 38 +++--- .../Views/Settings/SettingsPaneRouter.swift | 15 --- .../Views/Settings/SettingsSubpage.swift | 41 ------- .../Settings/SettingsTitleResolver.swift | 13 +- .../Core/Storage/SettingsSliceTests.swift | 4 +- .../Settings/SettingsNavigationTests.swift | 15 +++ .../Settings/SettingsTitleResolverTests.swift | 116 ++++++++++++++++++ 9 files changed, 166 insertions(+), 112 deletions(-) delete mode 100644 apple/TablePro/Views/Settings/SettingsDrillInChrome.swift delete mode 100644 apple/TablePro/Views/Settings/SettingsSubpage.swift create mode 100644 apple/TableProTests/Views/Settings/SettingsTitleResolverTests.swift diff --git a/apple/TablePro/Core/Storage/AppSettingsManager.swift b/apple/TablePro/Core/Storage/AppSettingsManager.swift index 2730e647c3..099dd9e848 100644 --- a/apple/TablePro/Core/Storage/AppSettingsManager.swift +++ b/apple/TablePro/Core/Storage/AppSettingsManager.swift @@ -4,7 +4,7 @@ import Foundation import TableProSyncTransport @MainActor -final class AppSettingsManager: ObservableObject { +final class AppSettingsManager { static let shared = AppSettingsManager() let generalSlice: SettingsSlice @@ -117,7 +117,6 @@ final class AppSettingsManager: ObservableObject { private let applyHistoryRetention: @MainActor () -> Void private let resetOutsideSettings: @MainActor () -> Void private var deferredDirtyCategories: [String]? - private var sliceChanges: AnyCancellable? init( storage: AppSettingsStorage = .shared, @@ -190,7 +189,6 @@ final class AppSettingsManager: ObservableObject { dateFormattingService.updateFormat(dataGridSlice.value.dateFormat) attachCommits() - forwardSliceChanges() } // Settings saved before there was an active provider would otherwise read as AI turned off. @@ -251,30 +249,6 @@ final class AppSettingsManager: ObservableObject { mcpSlice.attach { [weak self] old, new in self?.commitMCP(from: old, to: new) } } - // For views that still observe the whole manager. - private func forwardSliceChanges() { - let changes: [ObservableObjectPublisher] = [ - generalSlice.objectWillChange, - appearanceSlice.objectWillChange, - appearanceModeSlice.objectWillChange, - editorSlice.objectWillChange, - formatterSlice.objectWillChange, - typographySlice.objectWillChange, - notificationsSlice.objectWillChange, - dataGridSlice.objectWillChange, - valueColorsSlice.objectWillChange, - historySlice.objectWillChange, - tabsSlice.objectWillChange, - keyboardSlice.objectWillChange, - aiSlice.objectWillChange, - syncSlice.objectWillChange, - mcpSlice.objectWillChange, - ] - sliceChanges = Publishers.MergeMany(changes).sink { [weak self] _ in - self?.objectWillChange.send() - } - } - // A reset collects its categories and marks them once, after the whole reset is saved. private func markDirty(_ category: String) { if deferredDirtyCategories != nil { diff --git a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift b/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift deleted file mode 100644 index badb4e5198..0000000000 --- a/apple/TablePro/Views/Settings/SettingsDrillInChrome.swift +++ /dev/null @@ -1,8 +0,0 @@ -import SwiftUI - -// The shell titles pushed pages from their route; this stays only until the pane rewrites drop their calls. -extension View { - func settingsDrillIn(title: String) -> some View { - self - } -} diff --git a/apple/TablePro/Views/Settings/SettingsNavigation.swift b/apple/TablePro/Views/Settings/SettingsNavigation.swift index 617c5c9100..ec0a754340 100644 --- a/apple/TablePro/Views/Settings/SettingsNavigation.swift +++ b/apple/TablePro/Views/Settings/SettingsNavigation.swift @@ -208,7 +208,7 @@ extension SettingsPane { ] case .keyboard: [ - String(localized: "Keyboard shortcuts"), + String(localized: "Restore Defaults…"), ] case .connections: [ @@ -292,7 +292,7 @@ extension SettingsPane { String(localized: "Active provider"), String(localized: "Providers"), String(localized: "Add Provider"), - String(localized: "Apple Intelligence"), + AppleIntelligenceAvailability.displayName, String(localized: "Inline Suggestions"), String(localized: "Suggest SQL while typing"), String(localized: "Agent"), @@ -304,12 +304,15 @@ extension SettingsPane { ] case .mcp: [ + String(localized: "MCP server"), String(localized: "Status"), String(localized: "Clients"), - String(localized: "Connect a Client"), + String(localized: "Connect a Client…"), String(localized: "Activity"), String(localized: "Access"), String(localized: "Approval"), + String(localized: "Approved connections"), + String(localized: "Allow apps to list connections hidden from AI"), String(localized: "Server"), String(localized: "Port"), String(localized: "Default row limit"), @@ -317,6 +320,7 @@ extension SettingsPane { String(localized: "Query timeout"), String(localized: "Log MCP queries in history"), String(localized: "Outside MCP Servers"), + String(localized: "Add Server…"), ] case .plugins: [ @@ -324,7 +328,7 @@ extension SettingsPane { String(localized: "Database Drivers"), String(localized: "Export Formats"), String(localized: "Import Formats"), - String(localized: "Install from File"), + String(localized: "Install from File…"), String(localized: "Couldn't Load"), ] + AppModule.allCases.map(\.title) case .sync: @@ -335,20 +339,20 @@ extension SettingsPane { String(localized: "What Syncs"), String(localized: "Connections"), String(localized: "Passwords"), - String(localized: "Groups & tags"), - String(localized: "SSH profiles"), - String(localized: "Credential profiles"), - String(localized: "Table favorites"), - String(localized: "Table folders"), - String(localized: "Database favorites"), - String(localized: "Saved queries"), + String(localized: "Groups & Tags"), + String(localized: "SSH Profiles"), + String(localized: "Credential Profiles"), + String(localized: "Table Favorites"), + String(localized: "Table Folders"), + String(localized: "Database Favorites"), + String(localized: "Saved Queries"), ] case .account: [ String(localized: "Plan"), String(localized: "Sign In"), - String(localized: "Sign Out"), - String(localized: "Upgrade"), + String(localized: "Sign Out…"), + String(localized: "Upgrade…"), ] } } @@ -413,7 +417,7 @@ extension SettingsPane { case .sync: [ "icloud", "apple account", "keychain", "password", "connections", "saved queries", "favorites", "folders", - "credential", "device", "last synced", "sync now", "cloudkit", "backup", + "credential", "device", "last synced", "sync now", "cloudkit", ] case .account: [ @@ -435,8 +439,8 @@ extension SettingsPage { case .softwareUpdate: [String(localized: "Update channel"), String(localized: "What's New")] case .commandLineTool: [] case .manageThemes: [] - case .linkedFolders: [String(localized: "Shared connection files")] - case .trustedLinks: [String(localized: "Links that connect without asking")] + case .linkedFolders: [String(localized: "Add Folder…"), String(localized: "Show in Finder")] + case .trustedLinks: [String(localized: "Forget All…")] case .sqlFormatting: [ String(localized: "Indentation"), @@ -449,7 +453,7 @@ extension SettingsPage { ] case .queryHistory: [String(localized: "Clear query history")] case .dataRewind: [String(localized: "Clear saved changes")] - case .slashCommands: [String(localized: "Add Command")] + case .slashCommands: [String(localized: "Add Command…")] case .mcpApprovals: [] case .mcpTokens: [String(localized: "Generate Token")] case .accountFeatures, .accountDevices, .accountTeams, .accountOffline: [] diff --git a/apple/TablePro/Views/Settings/SettingsPaneRouter.swift b/apple/TablePro/Views/Settings/SettingsPaneRouter.swift index 7bfefff48f..50dc95922d 100644 --- a/apple/TablePro/Views/Settings/SettingsPaneRouter.swift +++ b/apple/TablePro/Views/Settings/SettingsPaneRouter.swift @@ -150,18 +150,3 @@ private struct SettingsPaneStack: View { ) } } - -// Stands in for a page whose pane has not moved to the route-based pages yet. -internal struct SettingsPagePlaceholder: View { - internal let title: String - - internal var body: some View { - Form { - Section { - Text(verbatim: title) - .foregroundStyle(.secondary) - } - } - .formStyle(.grouped) - } -} diff --git a/apple/TablePro/Views/Settings/SettingsSubpage.swift b/apple/TablePro/Views/Settings/SettingsSubpage.swift deleted file mode 100644 index 44e40da0bc..0000000000 --- a/apple/TablePro/Views/Settings/SettingsSubpage.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// SettingsSubpage.swift -// TablePro -// - -import Foundation - -// A drill-in page pushed onto a pane's NavigationStack in the Settings detail column. Payload-free -// so it is Hashable for navigationDestination and can carry a deep-link id later. Leaf editors that -// need an id (a plugin, a profile) stay sheets for now. -enum SettingsSubpage: String, Hashable, CaseIterable { - case softwareUpdate - case commandLine - case manageThemes - case sqlFormatting - case queryHistory - case dataRewind - case whatSyncs - - var parent: SettingsPane { - switch self { - case .softwareUpdate, .commandLine: .general - case .manageThemes: .appearance - case .sqlFormatting: .editor - case .queryHistory, .dataRewind: .data - case .whatSyncs: .sync - } - } - - var title: String { - switch self { - case .softwareUpdate: String(localized: "Software Update") - case .commandLine: String(localized: "Command Line Tool") - case .manageThemes: String(localized: "Manage Themes") - case .sqlFormatting: String(localized: "SQL Formatting") - case .queryHistory: String(localized: "Query History") - case .dataRewind: String(localized: "Data Rewind") - case .whatSyncs: String(localized: "What Syncs") - } - } -} diff --git a/apple/TablePro/Views/Settings/SettingsTitleResolver.swift b/apple/TablePro/Views/Settings/SettingsTitleResolver.swift index 4c5802f09d..115d730170 100644 --- a/apple/TablePro/Views/Settings/SettingsTitleResolver.swift +++ b/apple/TablePro/Views/Settings/SettingsTitleResolver.swift @@ -10,6 +10,8 @@ internal final class SettingsTitleResolver { internal var rejectedPlugins: @MainActor () -> [RejectedPlugin] internal var providers: @MainActor () -> [AIProviderConfig] internal var isSignedIn: @MainActor () -> Bool + internal var isAIEnabled: @MainActor () -> Bool + internal var isMCPEnabled: @MainActor () -> Bool internal var changes: @MainActor () -> [AnyPublisher] internal static var live: Sources { @@ -18,10 +20,13 @@ internal final class SettingsTitleResolver { rejectedPlugins: { PluginManager.shared.rejectedPlugins }, providers: { AppSettingsManager.shared.ai.providers }, isSignedIn: { FeatureAccess.shared.state.isSignedIn }, + isAIEnabled: { AppSettingsManager.shared.ai.enabled }, + isMCPEnabled: { AppSettingsManager.shared.mcp.enabled }, changes: { [ PluginManager.shared.objectWillChange.map { _ in () }.eraseToAnyPublisher(), AppSettingsManager.shared.aiSlice.objectWillChange.map { _ in () }.eraseToAnyPublisher(), + AppSettingsManager.shared.mcpSlice.objectWillChange.map { _ in () }.eraseToAnyPublisher(), FeatureAccess.shared.objectWillChange.map { _ in () }.eraseToAnyPublisher(), ] } @@ -36,10 +41,15 @@ internal final class SettingsTitleResolver { self.sources = sources } + // A page the pane root hides is unavailable, so Back, Forward and links never land on it. internal func isAvailable(_ route: SettingsRoute) -> Bool { switch route { case .page(.accountDevices), .page(.accountTeams): sources.isSignedIn() + case .page(.slashCommands): + sources.isAIEnabled() + case .page(.mcpApprovals), .page(.mcpTokens): + sources.isMCPEnabled() case .page: true case .plugin(let id): @@ -47,7 +57,7 @@ internal final class SettingsTitleResolver { case .rejectedPlugin(let url): sources.rejectedPlugins().contains { $0.url == url } case .aiProvider(let id): - sources.providers().contains { $0.id == id } + sources.isAIEnabled() && sources.providers().contains { $0.id == id } } } @@ -68,6 +78,7 @@ internal final class SettingsTitleResolver { let plugins = sources.plugins().map { SettingsSearchEntry(title: $0.name, location: SettingsLocation(route: .plugin(id: $0.id))) } + guard sources.isAIEnabled() else { return plugins } let providers = sources.providers().map { SettingsSearchEntry(title: $0.displayName, location: SettingsLocation(route: .aiProvider($0.id))) } diff --git a/apple/TableProTests/Core/Storage/SettingsSliceTests.swift b/apple/TableProTests/Core/Storage/SettingsSliceTests.swift index fe93481ec9..ce5891a879 100644 --- a/apple/TableProTests/Core/Storage/SettingsSliceTests.swift +++ b/apple/TableProTests/Core/Storage/SettingsSliceTests.swift @@ -181,21 +181,19 @@ struct SettingsSliceTests { #expect(received == [false, true]) } - @Test("A write through the manager publishes only its own slice, and the manager once") + @Test("A write through the manager publishes only its own slice") func facadeWritePublishesOnlyItsSlice() throws { let fixture = try ManagerFixture() let manager = fixture.manager let editor = PublishCounter(manager.editorSlice.objectWillChange) let general = PublishCounter(manager.generalSlice.objectWillChange) let dataGrid = PublishCounter(manager.dataGridSlice.objectWillChange) - let whole = PublishCounter(manager.objectWillChange) manager.editor.showLineNumbers.toggle() #expect(editor.count == 1) #expect(general.count == 0) #expect(dataGrid.count == 0) - #expect(whole.count == 1) } @Test("A change is saved, then marked for sync, before the assignment returns") diff --git a/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift index ad19c8b297..e75f22391b 100644 --- a/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsNavigationTests.swift @@ -90,6 +90,7 @@ struct SettingsNavigationTests { ("debugger", [.plugins]), ("long-running", [.notifications]), ("Sidebar & Tabs", [.sidebar]), + ("Apple Intelligence", [.ai]), ] @Test("Each unit's keywords find their pane", arguments: unitKeywordCases) @@ -97,6 +98,20 @@ struct SettingsNavigationTests { #expect(SettingsNavigation.panes(matching: query) == expected) } + @Test("A label the pane shows finds that pane or page") + func visibleLabelsFindTheirPaneOrPage() { + #expect(SettingsNavigation.panes(matching: "Saved Queries").contains(.sync)) + #expect(SettingsNavigation.panes(matching: "Approved connections").contains(.mcp)) + + let connections = SettingsNavigation.results(matching: "Forget All").first { $0.pane == .connections } + #expect(connections?.pages.contains { $0.location == SettingsLocation(page: .trustedLinks) } == true) + } + + @Test("Backup does not find iCloud Sync, which keeps no backup") + func backupDoesNotFindSync() { + #expect(!SettingsNavigation.panes(matching: "backup").contains(.sync)) + } + @Test("A page title lists the page under its pane") func pageTitlesProducePageResults() { let expected = SettingsSearchResult( diff --git a/apple/TableProTests/Views/Settings/SettingsTitleResolverTests.swift b/apple/TableProTests/Views/Settings/SettingsTitleResolverTests.swift new file mode 100644 index 0000000000..7377675079 --- /dev/null +++ b/apple/TableProTests/Views/Settings/SettingsTitleResolverTests.swift @@ -0,0 +1,116 @@ +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct SettingsTitleResolverTests { + @MainActor + private final class Switches { + var isAIEnabled = true + var isMCPEnabled = true + var isSignedIn = true + } + + private let provider = AIProviderConfig(name: "Work Claude") + + private func resolver(_ switches: Switches, providers: [AIProviderConfig] = []) -> SettingsTitleResolver { + SettingsTitleResolver(sources: SettingsTitleResolver.Sources( + plugins: { [] }, + rejectedPlugins: { [] }, + providers: { providers }, + isSignedIn: { switches.isSignedIn }, + isAIEnabled: { switches.isAIEnabled }, + isMCPEnabled: { switches.isMCPEnabled }, + changes: { [] } + )) + } + + @Test("With AI on and MCP on, every page and a listed provider are available") + func everythingAvailableWhenOn() { + let titles = resolver(Switches(), providers: [provider]) + + for page in SettingsPage.allCases { + #expect(titles.isAvailable(.page(page)), "\(page)") + } + #expect(titles.isAvailable(.aiProvider(provider.id))) + #expect(!titles.isAvailable(.aiProvider(UUID()))) + } + + @Test("With AI off, provider pages and Slash Commands are unavailable") + func aiPagesFollowTheAISwitch() { + let switches = Switches() + switches.isAIEnabled = false + let titles = resolver(switches, providers: [provider]) + + #expect(!titles.isAvailable(.aiProvider(provider.id))) + #expect(!titles.isAvailable(.page(.slashCommands))) + #expect(titles.isAvailable(.page(.mcpTokens))) + #expect(titles.title(for: .aiProvider(provider.id)) == "Work Claude") + } + + @Test("Search offers a provider page only while AI is on") + func providerSearchEntriesFollowTheAISwitch() { + let switches = Switches() + let titles = resolver(switches, providers: [provider]) + let entry = SettingsSearchEntry(title: "Work Claude", location: SettingsLocation(route: .aiProvider(provider.id))) + + #expect(titles.searchEntries == [entry]) + + switches.isAIEnabled = false + #expect(titles.searchEntries.isEmpty) + } + + @Test("With the MCP server off, Approved Connections and Tokens are unavailable") + func mcpPagesFollowTheServerSwitch() { + let switches = Switches() + switches.isMCPEnabled = false + let titles = resolver(switches, providers: [provider]) + + #expect(!titles.isAvailable(.page(.mcpApprovals))) + #expect(!titles.isAvailable(.page(.mcpTokens))) + #expect(titles.isAvailable(.page(.slashCommands))) + #expect(titles.isAvailable(.aiProvider(provider.id))) + } + + @Test("Devices and Teams follow sign-in, and the other Account pages stay") + func accountPagesFollowSignIn() { + let switches = Switches() + switches.isSignedIn = false + let titles = resolver(switches) + + #expect(!titles.isAvailable(.page(.accountDevices))) + #expect(!titles.isAvailable(.page(.accountTeams))) + #expect(titles.isAvailable(.page(.accountFeatures))) + #expect(titles.isAvailable(.page(.accountOffline))) + + switches.isSignedIn = true + #expect(titles.isAvailable(.page(.accountDevices))) + #expect(titles.isAvailable(.page(.accountTeams))) + } + + @Test("Back skips a Tokens entry while the MCP server is off and lands on the MCP root") + func backSkipsMCPPagesWhileTheServerIsOff() { + let switches = Switches() + let titles = resolver(switches) + let model = SettingsNavigationModel(initial: .root(.mcp), isRouteAvailable: { titles.isAvailable($0) }) + #expect(model.push(.page(.mcpTokens), in: .mcp)) + model.select(.general) + + switches.isMCPEnabled = false + model.goBack() + + #expect(model.location == .root(.mcp)) + } + + @Test("A link to a provider page while AI is off opens the AI root") + func providerLinkWithAIOffOpensTheRoot() { + let switches = Switches() + switches.isAIEnabled = false + let titles = resolver(switches, providers: [provider]) + let model = SettingsNavigationModel(initial: .root(.general), isRouteAvailable: { titles.isAvailable($0) }) + + model.open(SettingsLocation(route: .aiProvider(provider.id)), recordsHistory: true) + + #expect(model.location == .root(.ai)) + } +} From 74c63823359b51f14a6d4dafedeb764f7c582786 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:20 +0700 Subject: [PATCH 41/48] chore(settings): lint rules for colon labels and caption fonts in Settings --- apple/.swiftlint.yml | 19 +++++++++++++++++++ .../Components/AddRemoveControlGroup.swift | 8 +------- .../Components/CopyableCodeBlock.swift | 2 +- apple/scripts/ci/source-ratchets.json | 2 +- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.yml index 5d4d0ea84c..75f9a2dd45 100644 --- a/apple/.swiftlint.yml +++ b/apple/.swiftlint.yml @@ -634,3 +634,22 @@ custom_rules: excluded_match_kinds: [comment, doccomment] message: "Every top-level @Suite expansion walks every other one, so compile time grows with their square. Keep @Suite only to carry a trait such as .serialized." severity: error + + # Settings + # A line that introduces a CopyableCodeBlock keeps its colon. + settings_label_trailing_colon: + name: "Settings Label Colon" + included: ['.*/TablePro/Views/Settings/'] + regex: '\b(?:Text|Label|LabeledContent|Toggle|Picker|TextField|SecureField|Stepper|DatePicker|ColorPicker|Section|SettingsNumberField|SettingsTextField|SettingsDrillRow)\((?:\s*route:[^,\n]*,)?\s*(?:title:\s*)?(?:String\(\s*localized:\s*)?("(?!e\.g\.|i\.e\.)(?:\p{Lu}|\p{Ll}[^"\\\s]*[ \t])[^"\\\n]*?\p{L}[::][ \t]?")(?!(?:[^\n]*\n){0,3}[^\n]*\bCopyableCodeBlock\()' + capture_group: 1 + excluded_match_kinds: [comment, doccomment] + message: "A grouped Form draws the label column, so a label takes no trailing colon." + severity: error + # An SF Symbol sized by a text style is not text, so its chain is left alone. + settings_caption_font: + name: "Settings Caption Font" + included: ['.*/TablePro/Views/Settings/'] + regex: '(?: View { } extension View { - // An overlay, not a safe area inset: an inset shrinks a bordered list and leaves the bar outside its border. - // The caller's list height counts ListBarMetrics.height, so no row ever sits under the bar. + // An overlay for a fixed-height list whose height already counts ListBarMetrics.height; a scrolling list uses SettingsFullPageList's inset. func listBar(@ViewBuilder _ content: () -> Content) -> some View { overlay(alignment: .bottom) { ListBar(content: content) diff --git a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift index 9f9ffb0948..523292ce14 100644 --- a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift +++ b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift @@ -8,7 +8,7 @@ struct CopyableCodeBlock: View { var body: some View { HStack(alignment: .top) { Text(verbatim: displayText ?? text) - .font(.system(.caption, design: .monospaced)) + .font(.system(.callout, design: .monospaced)) .textSelection(.enabled) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/apple/scripts/ci/source-ratchets.json b/apple/scripts/ci/source-ratchets.json index 3471c7c20d..2dc827d8ea 100644 --- a/apple/scripts/ci/source-ratchets.json +++ b/apple/scripts/ci/source-ratchets.json @@ -1,4 +1,4 @@ { "engine-name-comparisons": 580, - "view-singleton-reads": 453 + "view-singleton-reads": 448 } From e0fe48f8ec1e44263f892438a54272afc1e3d4a0 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:20 +0700 Subject: [PATCH 42/48] fix(settings): follow-ups across AI, MCP, Profiles, Extensions, Account, Sync and Notifications --- .../Components/LicenseNoticeControls.swift | 10 ++-- .../Views/Settings/AISettingsView.swift | 2 + .../Account/LicensePresentation.swift | 13 +++-- .../Components/SettingsDrillRow.swift | 27 +++++++++-- .../Settings/NotificationsSettingsView.swift | 2 + .../Plugins/InstalledPluginsView.swift | 2 + .../Settings/Plugins/PluginDetailPage.swift | 2 + .../Plugins/RejectedPluginDetailPage.swift | 2 + .../Profiles/ProfilesSettingsView.swift | 2 + .../Views/Settings/Sections/MCPSection.swift | 22 ++++----- .../Views/Settings/SyncSettingsView.swift | 2 + .../Settings/LicensePresentationTests.swift | 47 +++++++++++++------ .../SettingsPaneURLIdentifierTests.swift | 1 + .../scripts/ci/test_check_plugin_provides.py | 37 +++++++++++++++ 14 files changed, 129 insertions(+), 42 deletions(-) diff --git a/apple/TablePro/Views/Components/LicenseNoticeControls.swift b/apple/TablePro/Views/Components/LicenseNoticeControls.swift index bfbe854ec8..ddce936471 100644 --- a/apple/TablePro/Views/Components/LicenseNoticeControls.swift +++ b/apple/TablePro/Views/Components/LicenseNoticeControls.swift @@ -16,8 +16,10 @@ struct LicenseNoticeActionButton: View { case .purchase, .upgrade, .renew: Link(action.title, destination: SupportLinks.pricing(referrer)) .countsUpgradeClicks(from: referrer) - case .openAccountSettings: - Button(action.title) { WindowOpener.shared.openSettings(tab: .account) } + case .openAccountSettings(let page): + Button(action.title) { + WindowOpener.shared.openSettings(page.map(SettingsLocation.init(page:)) ?? .root(.account)) + } case .retryValidation: HStack(spacing: 6) { Button(action.title) { @@ -99,8 +101,8 @@ extension LicenseNoticeAction { case .purchase, .upgrade, .renew: Telemetry.shared.upgradeClicked(from: referrer) WebPageOpener.open(SupportLinks.pricing(referrer), scope: .https) - case .openAccountSettings: - WindowOpener.shared.openSettings(tab: .account) + case .openAccountSettings(let page): + WindowOpener.shared.openSettings(page.map(SettingsLocation.init(page:)) ?? .root(.account)) case .retryValidation: WindowOpener.shared.openSettings(tab: .account) Task { await AccountServices.shared.checkNow() } diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 457a2f0fbe..b116673348 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -132,6 +132,8 @@ struct AISettingsView: View { privacySection } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-ai") .task(id: visit.count) { appleIntelligence = SystemOnDeviceLanguageModel().availability } diff --git a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift index 02698f0bae..03a3cdc590 100644 --- a/apple/TablePro/Views/Settings/Account/LicensePresentation.swift +++ b/apple/TablePro/Views/Settings/Account/LicensePresentation.swift @@ -6,7 +6,8 @@ internal enum LicenseNoticeAction: Equatable { case upgrade case renew case retryValidation - case openAccountSettings + // nil opens the Account pane itself. + case openAccountSettings(page: SettingsPage?) var title: String { switch self { @@ -55,7 +56,7 @@ internal enum LicensePresentation { return LicenseNotice( title: String(localized: "Your plan is in use on 3 other devices"), message: String(localized: "Remove one in Settings to use your plan on this Mac."), - action: .openAccountSettings + action: .openAccountSettings(page: .accountDevices) ) } return LicenseNotice(title: feature.paidPlanRequirement, message: feature.featureDescription, action: .upgrade) @@ -103,8 +104,12 @@ internal enum LicensePresentation { switch notice { case .expiringSoon(_, false), .expired(_, false), .verificationFailed: return .retryValidation - case .deviceLimit, .paymentProblem, .expiringSoon(_, true), .expired(_, true): - return .openAccountSettings + case .deviceLimit: + return .openAccountSettings(page: .accountDevices) + case .expiringSoon(_, true), .expired(_, true): + return .openAccountSettings(page: .accountOffline) + case .paymentProblem: + return .openAccountSettings(page: nil) case .canceling: return nil } diff --git a/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift index f99d8cbdcd..9f1316355c 100644 --- a/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift +++ b/apple/TablePro/Views/Settings/Components/SettingsDrillRow.swift @@ -7,21 +7,35 @@ protocol SettingsDrillIdentifying { struct SettingsDrillRow: View { private let route: Route private let title: Text + private let subtitle: LocalizedStringKey? private let value: String? private let identifier: String? - init(route: Route, title: LocalizedStringKey, value: String? = nil, identifier: String? = nil) { - self.init(route: route, titleText: Text(title), value: value, identifier: identifier) + init( + route: Route, + title: LocalizedStringKey, + value: String? = nil, + subtitle: LocalizedStringKey? = nil, + identifier: String? = nil + ) { + self.init(route: route, titleText: Text(title), value: value, subtitle: subtitle, identifier: identifier) } @_disfavoredOverload - init(route: Route, title: Title, value: String? = nil, identifier: String? = nil) { - self.init(route: route, titleText: Text(title), value: value, identifier: identifier) + init( + route: Route, + title: Title, + value: String? = nil, + subtitle: LocalizedStringKey? = nil, + identifier: String? = nil + ) { + self.init(route: route, titleText: Text(title), value: value, subtitle: subtitle, identifier: identifier) } - private init(route: Route, titleText: Text, value: String?, identifier: String?) { + private init(route: Route, titleText: Text, value: String?, subtitle: LocalizedStringKey?, identifier: String?) { self.route = route self.title = titleText + self.subtitle = subtitle self.value = value // Route stays any Hashable for NavigationLink, so the page id comes from a route that adopts the protocol. self.identifier = identifier ?? (route as? any SettingsDrillIdentifying)?.settingsDrillIdentifier @@ -36,6 +50,9 @@ struct SettingsDrillRow: View { } } label: { title + if let subtitle { + Text(subtitle) + } } } .accessibilityIdentifier(identifier ?? "") diff --git a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift index ce5b64ff8c..301d5b878a 100644 --- a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift +++ b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift @@ -40,6 +40,8 @@ struct NotificationsSettingsView: View { } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-notifications") .task(id: visit.count) { await permission.refresh() } diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index cdd25f61ba..f7df092897 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -94,6 +94,8 @@ struct InstalledPluginsView: View { } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-plugins") } @ViewBuilder private var dropHighlight: some View { diff --git a/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift index 83d0700433..d826e546ac 100644 --- a/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift +++ b/apple/TablePro/Views/Settings/Plugins/PluginDetailPage.swift @@ -70,6 +70,8 @@ struct PluginDetailPage: View { } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-plugin") .task(id: entry.id) { loaded = await PluginLoadedInstance.load(entry, manager: model.manager) } diff --git a/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift index 48669d398b..3cce81bf9c 100644 --- a/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift +++ b/apple/TablePro/Views/Settings/Plugins/RejectedPluginDetailPage.swift @@ -77,6 +77,8 @@ struct RejectedPluginDetailPage: View { } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-page-rejected-plugin") } private var location: String { diff --git a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift index 906820a6ad..c2c612aa80 100644 --- a/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift +++ b/apple/TablePro/Views/Settings/Profiles/ProfilesSettingsView.swift @@ -29,6 +29,8 @@ struct ProfilesSettingsView: View { sshSection } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-profiles") .sheet(item: $editor) { route in switch route { case .newCredential: diff --git a/apple/TablePro/Views/Settings/Sections/MCPSection.swift b/apple/TablePro/Views/Settings/Sections/MCPSection.swift index dcab3216aa..a63bc623fe 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPSection.swift @@ -63,20 +63,14 @@ struct MCPSection: View { .pickerStyle(.menu) .accessibilityIdentifier("mcp-approval-picker") - NavigationLink(value: SettingsRoute.page(.mcpApprovals)) { - LabeledContent { - if let approvalsValue { - Text(approvalsValue) - .foregroundStyle(.secondary) - } - } label: { - Text("Approved connections") - if settings.connectionApproval != .oncePerConnection { - Text("Used only with Ask Once for Each Connection.") - } - } - } - .accessibilityIdentifier(SettingsPage.mcpApprovals.drillIdentifier) + SettingsDrillRow( + route: SettingsRoute.page(.mcpApprovals), + title: "Approved connections", + value: approvalsValue, + subtitle: settings.connectionApproval != .oncePerConnection + ? "Used only with Ask Once for Each Connection." + : nil + ) SettingsDrillRow(route: SettingsRoute.page(.mcpTokens), title: "Tokens", value: tokensValue) diff --git a/apple/TablePro/Views/Settings/SyncSettingsView.swift b/apple/TablePro/Views/Settings/SyncSettingsView.swift index 453c1cb2d5..e9e58f220a 100644 --- a/apple/TablePro/Views/Settings/SyncSettingsView.swift +++ b/apple/TablePro/Views/Settings/SyncSettingsView.swift @@ -82,6 +82,8 @@ struct SyncSettingsView: View { } } .formStyle(.grouped) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("settings-pane-sync") } private func noticeRow(_ notice: SyncNotice) -> some View { diff --git a/apple/TableProTests/Views/Settings/LicensePresentationTests.swift b/apple/TableProTests/Views/Settings/LicensePresentationTests.swift index 98c1979f46..981bd75861 100644 --- a/apple/TableProTests/Views/Settings/LicensePresentationTests.swift +++ b/apple/TableProTests/Views/Settings/LicensePresentationTests.swift @@ -1,8 +1,3 @@ -// -// LicensePresentationTests.swift -// TableProTests -// - import Foundation @testable import TablePro import Testing @@ -45,8 +40,6 @@ struct LicensePresentationTests { return try #require(LegacyEntitlement(payload: payload)) } - // MARK: - Gates - @Test("An available feature has no gate") func availableHasNoGate() { let state = AccountState(isSignedIn: true, entitlement: Self.entitlement()) @@ -71,10 +64,10 @@ struct LicensePresentationTests { #expect(gate?.alternative == nil) } - @Test("Past the device limit the gate opens Settings instead of selling the plan this account holds") + @Test("Past the device limit the gate opens the Devices page instead of selling the plan this account holds") func deviceLimitGate() { let gate = Self.gate(.compareSync, AccountState(isSignedIn: true, refresh: .deviceLimitReached([]))) - #expect(gate?.action == .openAccountSettings) + #expect(gate?.action == .openAccountSettings(page: .accountDevices)) #expect(gate?.title != ProFeature.compareSync.paidPlanRequirement) } @@ -91,12 +84,40 @@ struct LicensePresentationTests { #expect(Self.gate(.dataRewind, state)?.action == .retryValidation) } - @Test("A lapsed offline file sends the person to Settings, where the file is imported") + @Test("A lapsed offline file opens the Offline File and License Key page, where the file is imported") func lapsedOfflineFileOpensSettings() { let state = AccountState(entitlement: Self.entitlement(expiresAt: Self.now.addingTimeInterval(-Self.day), isOffline: true)) let gate = Self.gate(.iCloudSync, state) #expect(gate?.title == AccountSettingsContent.Notice.expired(at: .now, isOfflineFile: true).title) - #expect(gate?.action == .openAccountSettings) + #expect(gate?.action == .openAccountSettings(page: .accountOffline)) + } + + @Test("A notice the pane fixes on a page opens that page; a payment problem opens the Account pane") + func noticeOpensItsPage() { + let plan = AccountSettingsContent.PlanRow( + id: "lic_1", title: "Pro", owner: "Ada", status: .paymentProblem, billing: nil + ) + let expected: [(AccountSettingsContent.Notice, SettingsPage?)] = [ + (.deviceLimit, .accountDevices), + (.expiringSoon(expiresAt: Self.now, isOfflineFile: true), .accountOffline), + (.expired(at: Self.now, isOfflineFile: true), .accountOffline), + (.paymentProblem(plan), nil), + ] + for (notice, page) in expected { + #expect(LicensePresentation.action(for: notice) == .openAccountSettings(page: page)) + } + } + + @Test("A notice this Mac can check again offers the check, not a trip to Settings") + func checkableNoticesRetry() { + let notices: [AccountSettingsContent.Notice] = [ + .expiringSoon(expiresAt: Self.now, isOfflineFile: false), + .expired(at: Self.now, isOfflineFile: false), + .verificationFailed(message: nil), + ] + for notice in notices { + #expect(LicensePresentation.action(for: notice) == .retryValidation) + } } @Test("Signed in with no entitlement after a failed refresh reads as the pane's failed check") @@ -130,8 +151,6 @@ struct LicensePresentationTests { #expect(Self.gate(.iCloudSync, AccountState(legacy: unchecked))?.action == .retryValidation) } - // MARK: - Welcome line - @Test("Welcome says nothing about a working plan, a free account or a key an older build left") func welcomeQuietWhenNothingIsNeeded() throws { #expect(Self.welcomeLine(AccountState(isSignedIn: true, entitlement: Self.entitlement())) == nil) @@ -168,8 +187,6 @@ struct LicensePresentationTests { #expect(Self.welcomeLine(state) == nil) } - // MARK: - Check failure - @Test("Only a failed check has a reason to show") func checkFailureMessage() { #expect(LicensePresentation.checkFailureMessage(.failed(.network("offline"))) == AccountError.network("offline").friendlyDescription) diff --git a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift index da64eda2d9..1fd6a01895 100644 --- a/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsPaneURLIdentifierTests.swift @@ -134,6 +134,7 @@ struct SettingsPaneURLIdentifierTests { #expect(SettingsPage.sqlFormatting.drillIdentifier == "settings-drill-sql-formatting") #expect(SettingsPage.commandLineTool.pageIdentifier == "settings-page-command-line-tool") #expect(SettingsRoute.page(.mcpTokens).settingsDrillIdentifier == "settings-drill-tokens") + #expect(SettingsRoute.page(.mcpApprovals).settingsDrillIdentifier == "settings-drill-approvals") #expect(SettingsRoute.plugin(id: "com.tablepro.postgresql").settingsDrillIdentifier == nil) } } diff --git a/apple/scripts/ci/test_check_plugin_provides.py b/apple/scripts/ci/test_check_plugin_provides.py index 2bb200d99a..dd5f7ad53c 100644 --- a/apple/scripts/ci/test_check_plugin_provides.py +++ b/apple/scripts/ci/test_check_plugin_provides.py @@ -45,12 +45,22 @@ """ +NAMED_DRIVER = DRIVER.replace("{\n", '{\n static let pluginName = "Example Driver"\n', 1) + +COMPUTED_NAME_DRIVER = DRIVER.replace("{\n", '{\n static var pluginName: String { "Example Driver" }\n', 1) + + def provides(key, values): items = "".join(f"\t\t{value}\n" for value in values) return f"\t{key}\n\t\n{items}\t\n" +def display_name(name): + return f"\t{check.NAME_KEY}\n\t{name}\n" + + DRIVER_PLIST = HEADER + provides(check.DATABASE_KEY, ["Example", "ExampleCloud", "ExampleLite"]) + FOOTER +NAMED_DRIVER_PLIST = DRIVER_PLIST.replace("\n", "\n" + display_name("Example Driver"), 1) class CheckPluginProvidesTests(unittest.TestCase): @@ -169,6 +179,33 @@ def test_write_fails_on_an_unreadable_plugin_and_leaves_its_plist(self): self.assertEqual((odd / "Info.plist").read_text(encoding="utf-8"), HEADER + FOOTER) self.assertEqual((driver / "Info.plist").read_text(encoding="utf-8"), DRIVER_PLIST) + def test_a_display_name_that_differs_from_the_plugin_name_is_reported(self): + missing = self.plugin("ExampleDriverPlugin", NAMED_DRIVER, DRIVER_PLIST) + stale = self.plugin("StaleDriverPlugin", NAMED_DRIVER, NAMED_DRIVER_PLIST.replace("Example Driver", "Old Name")) + named = self.plugin("NamedDriverPlugin", NAMED_DRIVER, NAMED_DRIVER_PLIST) + for directory in (missing, stale): + problems = check.problems_in(directory) + self.assertEqual(len(problems), 1) + self.assertIn(check.NAME_KEY, problems[0]) + self.assertIn("'Example Driver'", problems[0]) + self.assertEqual(check.problems_in(named), []) + + def test_write_stamps_the_plugin_name_as_the_display_name(self): + driver = self.plugin("ExampleDriverPlugin", NAMED_DRIVER, DRIVER_PLIST) + self.assertEqual(self.run_main("--write")[0], 0) + self.assertEqual((driver / "Info.plist").read_text(encoding="utf-8"), NAMED_DRIVER_PLIST) + self.assertEqual(self.run_main()[0], 0) + + def test_a_plugin_name_that_is_not_a_literal_leaves_the_display_name_alone(self): + plist = DRIVER_PLIST.replace("\n", "\n" + display_name("Hand Written"), 1) + driver = self.plugin("ExampleDriverPlugin", COMPUTED_NAME_DRIVER, plist) + unnamed = self.plugin("UnnamedDriverPlugin", COMPUTED_NAME_DRIVER, DRIVER_PLIST) + self.assertEqual(check.problems_in(driver), []) + self.assertEqual(check.problems_in(unnamed), []) + self.assertEqual(self.run_main("--write"), (0, "", "")) + self.assertEqual((driver / "Info.plist").read_text(encoding="utf-8"), plist) + self.assertEqual((unnamed / "Info.plist").read_text(encoding="utf-8"), DRIVER_PLIST) + def test_write_leaves_a_correct_plist_untouched(self): exporter = self.plugin("ExampleExportPlugin", EXPORTER, HEADER + provides(check.EXPORT_KEY, ["ex"]) + "\n" + FOOTER) before = (exporter / "Info.plist").read_text(encoding="utf-8") From a9dedc21b81638e5718754e5a22040432370b4a3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:21 +0700 Subject: [PATCH 43/48] test(settings): drill-in walk and an opt-in screenshot suite --- .../SettingsDrillInUITests.swift | 95 ++++++++++ .../SettingsScreenshotUITests.swift | 176 ++++++++++++++++++ .../SettingsWindowUITests.swift | 11 -- .../Support/UITestCase+Settings.swift | 4 + 4 files changed, 275 insertions(+), 11 deletions(-) create mode 100644 apple/TableProUITests/SettingsDrillInUITests.swift create mode 100644 apple/TableProUITests/SettingsScreenshotUITests.swift diff --git a/apple/TableProUITests/SettingsDrillInUITests.swift b/apple/TableProUITests/SettingsDrillInUITests.swift new file mode 100644 index 0000000000..2e9b55bbbf --- /dev/null +++ b/apple/TableProUITests/SettingsDrillInUITests.swift @@ -0,0 +1,95 @@ +import XCTest + +final class SettingsDrillInUITests: UITestCase { + private enum Leaf { + case hittable(String) + case disabled(String) + case present(String) + } + + private struct Drill { + let pane: String + let paneTitle: String + let page: String + let pageTitle: String + let leaf: Leaf? + + init(_ pane: String, _ paneTitle: String, page: String, title pageTitle: String, leaf: Leaf? = nil) { + self.pane = pane + self.paneTitle = paneTitle + self.page = page + self.pageTitle = pageTitle + self.leaf = leaf + } + } + + // The UI test target cannot import the app, so these mirror SettingsPage's parents, titles and URL ids. + private static let drills: [Drill] = [ + Drill("connections", "Connections", page: "linked-folders", title: "Linked Folders", leaf: .hittable("linked-folders-add-button")), + // A new sandbox trusts no link, so Forget All has nothing to forget. + Drill("connections", "Connections", page: "trusted-links", title: "Trusted Links", leaf: .disabled("trusted-links-forget-all-button")), + Drill("data", "Data", page: "query-history", title: "Query History"), + Drill("data", "Data", page: "data-rewind", title: "Data Rewind"), + Drill("ai", "AI", page: "slash-commands", title: "Slash Commands", leaf: .present("slash-command-add")), + Drill("editor", "Editor", page: "sql-formatting", title: "SQL Formatting"), + Drill("general", "General", page: "command-line-tool", title: "Command Line Tool"), + ] + + // One launch for every page: the UI plan pays for each launch. A page missing an environment object + // its pane hands down crashes on push, so the walk catches that too. + func testEveryPageOpensFromItsPaneAndBackReturnsThere() throws { + let app = try launchApp() + let settings = openSettings(in: app) + let back = settingsNavigationButton("Back", in: settings) + + for drill in Self.drills { + selectSettingsPane(drill.pane, page: drill.page, in: settings) + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == drill.pageTitle }, + "\(drill.pane)/\(drill.page) must title the window \(drill.pageTitle), it is \(settings.title)" + ) + XCTAssertTrue( + settingsPage(drill.page, in: settings).waitToExist(timeout: 5), + "\(drill.pageTitle) must show settings-page-\(drill.page)" + ) + if let leaf = drill.leaf { + check(leaf, on: drill, in: settings) + } + + XCTAssertTrue( + waitForPredicate(timeout: 5) { back.exists && back.isEnabled }, + "\(drill.pageTitle) must enable Back" + ) + back.click() + XCTAssertTrue( + waitForPredicate(timeout: 5) { settings.title == drill.paneTitle }, + "Back from \(drill.pageTitle) must return to \(drill.paneTitle), it is \(settings.title)" + ) + } + } + + private func check(_ leaf: Leaf, on drill: Drill, in settings: XCUIElement) { + switch leaf { + case .hittable(let identifier): + XCTAssertTrue( + waitUntilHittable(element(identifier, in: settings), timeout: 5), + "\(drill.pageTitle) must show \(identifier) on screen" + ) + case .disabled(let identifier): + let control = element(identifier, in: settings) + XCTAssertTrue( + waitForPredicate(timeout: 5) { control.exists && !control.isEnabled }, + "\(drill.pageTitle) must show \(identifier), turned off in an empty sandbox" + ) + case .present(let identifier): + XCTAssertTrue( + element(identifier, in: settings).waitToExist(timeout: 5), + "\(drill.pageTitle) must show \(identifier)" + ) + } + } + + private func element(_ identifier: String, in settings: XCUIElement) -> XCUIElement { + settings.descendants(matching: .any).matching(identifier: identifier).firstMatch + } +} diff --git a/apple/TableProUITests/SettingsScreenshotUITests.swift b/apple/TableProUITests/SettingsScreenshotUITests.swift new file mode 100644 index 0000000000..eb7988f40d --- /dev/null +++ b/apple/TableProUITests/SettingsScreenshotUITests.swift @@ -0,0 +1,176 @@ +import XCTest + +final class SettingsScreenshotUITests: UITestCase { + private enum Preparation { + // MCP's pages exist only while its server runs, and a new sandbox starts with it off. + case enableMCPServer + } + + private struct Location { + let url: String + let name: String + let title: String + let page: String? + let preparation: Preparation? + + // `pane` is the SettingsPane rawValue; `urlPane` is its link id where the two differ (Account is "license"). + // A prepared location links to its pane, since the page is not there until the preparation runs. + init(_ pane: String, urlPane: String? = nil, page: String? = nil, title: String, preparation: Preparation? = nil) { + let linkedPage = preparation == nil ? page : nil + url = "tablepro://settings/" + [urlPane ?? pane, linkedPage].compactMap { $0 }.joined(separator: "/") + name = [pane, page].compactMap { $0 }.joined(separator: "-") + self.title = title + self.page = page + self.preparation = preparation + } + } + + // Read by the app as AppAppearanceMode, which pins NSApp.appearance whatever this Mac's own mode is. + private enum Appearance: String { + case light, dark + } + + // The UI test target cannot import the app, so these mirror SettingsNavigation.sections and SettingsPage. + // Left out: Devices and Teams need a signed-in account, and AI provider and rejected plugin pages need + // records no fixture seeds. The SQLite driver is bundled, so its plugin page is always there. + private static let appSection: [Location] = [ + Location("general", title: "General"), + Location("general", page: "software-update", title: "Software Update"), + Location("general", page: "command-line-tool", title: "Command Line Tool"), + Location("appearance", title: "Appearance"), + Location("appearance", page: "themes", title: "Manage Themes"), + Location("notifications", title: "Notifications"), + Location("keyboard", title: "Keyboard"), + ] + + private static let workspaceSection: [Location] = [ + Location("connections", title: "Connections"), + Location("connections", page: "linked-folders", title: "Linked Folders"), + Location("connections", page: "trusted-links", title: "Trusted Links"), + Location("profiles", title: "Profiles"), + Location("sidebar", title: "Sidebar & Tabs"), + Location("editor", title: "Editor"), + Location("editor", page: "sql-formatting", title: "SQL Formatting"), + Location("data", title: "Data"), + Location("data", page: "query-history", title: "Query History"), + Location("data", page: "data-rewind", title: "Data Rewind"), + ] + + private static let integrationsSection: [Location] = [ + Location("ai", title: "AI"), + Location("ai", page: "slash-commands", title: "Slash Commands"), + Location("mcp", title: "MCP"), + Location("mcp", page: "approvals", title: "Approved Connections", preparation: .enableMCPServer), + Location("mcp", page: "tokens", title: "Tokens", preparation: .enableMCPServer), + Location("plugins", title: "Extensions"), + Location("plugins", page: "com.TablePro.SQLiteDriver", title: "SQLite"), + ] + + private static let accountSection: [Location] = [ + Location("sync", title: "iCloud Sync"), + Location("account", urlPane: "license", title: "Account"), + Location("account", urlPane: "license", page: "features", title: "Features"), + Location("account", urlPane: "license", page: "offline", title: "Offline File and License Key"), + ] + + // xcodebuild passes TEST_RUNNER_TABLEPRO_SETTINGS_SHOTS=1 to the runner as TABLEPRO_SETTINGS_SHOTS. + override internal func setUpWithError() throws { + try XCTSkipUnless( + ProcessInfo.processInfo.environment["TABLEPRO_SETTINGS_SHOTS"] == "1", + "56 launches, kept out of the UI plan: run with TEST_RUNNER_TABLEPRO_SETTINGS_SHOTS=1" + ) + try super.setUpWithError() + } + + // One case per section and appearance keeps each under the UI plan's per-case limit. + func testAppSectionInLight() throws { + try capture(Self.appSection, in: .light) + } + + func testAppSectionInDark() throws { + try capture(Self.appSection, in: .dark) + } + + func testWorkspaceSectionInLight() throws { + try capture(Self.workspaceSection, in: .light) + } + + func testWorkspaceSectionInDark() throws { + try capture(Self.workspaceSection, in: .dark) + } + + func testIntegrationsSectionInLight() throws { + try capture(Self.integrationsSection, in: .light) + } + + func testIntegrationsSectionInDark() throws { + try capture(Self.integrationsSection, in: .dark) + } + + func testAccountSectionInLight() throws { + try capture(Self.accountSection, in: .light) + } + + func testAccountSectionInDark() throws { + try capture(Self.accountSection, in: .dark) + } + + // A link reaches the app only at launch, so each location gets its own. + private func capture(_ locations: [Location], in appearance: Appearance) throws { + var running: XCUIApplication? + for location in locations { + running?.terminate() + let app = try launchApp(environment: [ + "TABLEPRO_UI_TEST_OPEN_URL": location.url, + "TABLEPRO_SCREENSHOT_APPEARANCE": appearance.rawValue, + ]) + running = app + + let settings = settingsWindow(in: app) + XCTAssertTrue(settings.waitToExist(timeout: 15), "\(location.url) must open the settings window") + if let preparation = location.preparation { + prepare(preparation, for: location, in: settings) + } + XCTAssertTrue( + waitForPredicate(timeout: 15) { settings.title == location.title }, + "\(location.url) must title the window \"\(location.title)\", it is \"\(settings.title)\"" + ) + + // A pointer left over a control shows its tooltip in the shot; the sidebar below its last row has none. + settings.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.97)).hover() + let attachment = XCTAttachment(screenshot: settledScreenshot(of: settings)) + attachment.name = "\(appearance.rawValue)-\(location.name)" + attachment.lifetime = .keepAlways + add(attachment) + } + } + + private func prepare(_ preparation: Preparation, for location: Location, in settings: XCUIElement) { + switch preparation { + case .enableMCPServer: + let enable = settings.switches["mcp-enable-server-toggle"] + XCTAssertTrue(waitUntilHittable(enable, timeout: 15), "\(location.url) must offer the MCP server switch") + if !isOn(enable) { + enable.click() + } + } + guard let page = location.page else { return } + let drill = settings.descendants(matching: .any).matching(identifier: "settings-drill-\(page)").firstMatch + XCTAssertTrue(scrollUntilHittable(drill, in: settings, timeout: 10), "\(location.url) must link to \(page) once prepared") + drill.click() + } + + // The window fades in and a plugin reveal pushes with an animation. A spinner never settles, so the + // last frame is kept when time runs out. + private func settledScreenshot(of element: XCUIElement, timeout: TimeInterval = 5) -> XCUIScreenshot { + var shot = element.screenshot() + let deadline = Date(timeIntervalSinceNow: timeout) + while Date() < deadline { + RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.25)) + let next = element.screenshot() + if next.pngRepresentation == shot.pngRepresentation { return next } + shot = next + } + return shot + } +} diff --git a/apple/TableProUITests/SettingsWindowUITests.swift b/apple/TableProUITests/SettingsWindowUITests.swift index c419d283f6..c5eab8a17d 100644 --- a/apple/TableProUITests/SettingsWindowUITests.swift +++ b/apple/TableProUITests/SettingsWindowUITests.swift @@ -63,15 +63,4 @@ final class SettingsWindowUITests: UITestCase { settings.typeKey("]", modifierFlags: [.command, .control]) XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Account" }, "View > Forward must return to Account") } - - func testDarkAppearanceScreenshots() throws { - let app = try launchApp(arguments: ["-AppleInterfaceStyle", "Dark"]) - let settings = openSettings(in: app) - XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "General" }, "Settings must open on General") - attachScreenshot(of: settings, named: "settings-general-dark") - - selectSettingsPane("appearance", in: settings) - XCTAssertTrue(waitForPredicate(timeout: 5) { settings.title == "Appearance" }, "Picking Appearance must title the window") - attachScreenshot(of: settings, named: "settings-appearance-dark") - } } diff --git a/apple/TableProUITests/Support/UITestCase+Settings.swift b/apple/TableProUITests/Support/UITestCase+Settings.swift index 01c09f85c5..287c5672e1 100644 --- a/apple/TableProUITests/Support/UITestCase+Settings.swift +++ b/apple/TableProUITests/Support/UITestCase+Settings.swift @@ -28,6 +28,10 @@ extension UITestCase { drill.click() } + internal func settingsPage(_ page: String, in settings: XCUIElement) -> XCUIElement { + settings.descendants(matching: .any).matching(identifier: "settings-page-\(page)").firstMatch + } + // The toolbar's navigation group publishes Back and Forward as buttons with their enabled state. internal func settingsNavigationButton(_ label: String, in settings: XCUIElement) -> XCUIElement { settings.toolbars.buttons.matching(NSPredicate(format: "label == %@", label)).firstMatch From f9252f4576f6eb03e71c47d61e415dafa26ccc79 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:22 +0700 Subject: [PATCH 44/48] chore(l10n): extract Settings strings and carry colon-key translations --- .../TablePro/Resources/Localizable.xcstrings | 1655 ++++++++++++++++- .../Appearance/ThemeLibraryModel.swift | 2 +- .../Views/Settings/EditorSettingsView.swift | 2 +- .../Settings/Sections/DataGridSection.swift | 5 +- .../Settings/Sections/FormatterSection.swift | 8 +- .../Models/GeneralSettingsTests.swift | 5 +- .../Settings/DataGridSettingsTests.swift | 8 + .../Settings/ThemeLibraryModelTests.swift | 16 + 8 files changed, 1690 insertions(+), 11 deletions(-) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 0e7072f1c6..0f35683d0e 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -749,6 +749,9 @@ } } } + }, + "“%@”" : { + }, "“%@” already has a column with that name." : { @@ -2315,6 +2318,16 @@ } } }, + "%@ (%@)" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ (%2$@)" + } + } + } + }, "%@ (%@@%@)" : { "localizations" : { "en" : { @@ -2469,6 +2482,9 @@ } } } + }, + "%@ (Not Installed)" : { + }, "%@ (reader)" : { "localizations" : { @@ -3237,6 +3253,9 @@ }, "%@ connects with a token from Settings > MCP > Authentication, which can limit what it reaches. TablePro leaves it as is." : { + }, + "%@ connects with a token from Settings > MCP > Tokens, which can limit what it reaches. TablePro leaves it as is." : { + }, "%@ contains characters Spanner does not allow." : { "extractionState" : "manual", @@ -3489,6 +3508,9 @@ } } } + }, + "%@ Export" : { + }, "%@ failed" : { "comment" : "Failure count, %@ is a count", @@ -3733,6 +3755,9 @@ "%@ holds values that cannot be compared, so the row cannot be found again." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ Import" : { + }, "%@ in the workbook expands to far more data than it holds, so it was not read." : { "extractionState" : "manual", @@ -4321,6 +4346,19 @@ } } } + }, + "%@ is used by “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ is used by “%2$@”." + } + } + } + }, + "%@ is used by macOS." : { + }, "%@ is using %@. Only one app can open a DuckDB file for writing." : { "extractionState" : "manual", @@ -4337,6 +4375,12 @@ "%@ isn't compiled for debugging." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ isn't installed. Grids use System Mono." : { + + }, + "%@ isn't installed. The editor uses System Mono." : { + }, "%@ kept changing while TablePro wrote it. Try again." : { @@ -7824,6 +7868,9 @@ } } } + }, + "%1$@, approved %2$@" : { + }, "%1$@, entry %2$lld: %3$@" : { "localizations" : { @@ -10939,6 +10986,9 @@ } } } + }, + "%lld active" : { + }, "%lld additional errors are in Copy Details." : { @@ -11007,6 +11057,12 @@ }, "%lld connections" : { + }, + "%lld connections use this profile. They keep these credentials as their own." : { + + }, + "%lld connections use this profile. They keep this configuration as their own SSH tunnel." : { + }, "%lld connections were imported." : { "extractionState" : "stale", @@ -11056,6 +11112,9 @@ "%lld constraint(s) removed" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%lld customized" : { + }, "%lld dims" : { @@ -11766,6 +11825,9 @@ } } } + }, + "%lld profiles were saved by a newer version of TablePro and can't be shown here." : { + }, "%lld properties" : { @@ -11773,6 +11835,9 @@ "%lld property value(s) set" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%lld pt" : { + }, "%lld relationship(s) created" : { "extractionState" : "manual", @@ -12825,6 +12890,9 @@ }, "^[%lld change](inflect: true)" : { + }, + "^[%lld character](inflect: true)" : { + }, "^[%lld check](inflect: true) could not run. Select one to see why." : { @@ -12880,6 +12948,9 @@ } } } + }, + "^[%lld connection](inflect: true)" : { + }, "^[%lld connection](inflect: true) use this profile. They keep these credentials as their own." : { "localizations" : { @@ -13020,6 +13091,9 @@ } } } + }, + "^[%lld space](inflect: true)" : { + }, "^[%lld table](inflect: true) to export" : { "localizations" : { @@ -13715,6 +13789,12 @@ } } } + }, + "1 connection uses this profile. It keeps these credentials as its own." : { + + }, + "1 connection uses this profile. It keeps this configuration as its own SSH tunnel." : { + }, "1 connection was imported." : { "localizations" : { @@ -14008,6 +14088,9 @@ } } } + }, + "1 profile was saved by a newer version of TablePro and can't be shown here." : { + }, "1 property" : { @@ -15462,6 +15545,9 @@ } } } + }, + "A .sql-formatter.json in a linked SQL folder replaces these rules for files opened from that folder." : { + }, "A .sql-formatter.json in a linked SQL folder replaces these rules for the files opened from that folder." : { @@ -15786,6 +15872,9 @@ } } } + }, + "A command named “/%@” already exists." : { + }, "A comment is never closed." : { @@ -16216,6 +16305,9 @@ }, "A failed write may have made additional changes." : { + }, + "A faint band behind the statement the cursor is in." : { + }, "A field named “%@” can only be changed on MongoDB 5.0 or later, which can address a dot or a leading $ in a name." : { "extractionState" : "manual", @@ -16539,6 +16631,9 @@ }, "A larger binary value stays on the server until you open, copy or export it. Applies to tables with a primary key." : { + }, + "A link you chose Always Allow for connects without asking again. Only connections on this Mac can be trusted." : { + }, "A local secondary index is part of its table and is removed only with the table." : { "extractionState" : "manual", @@ -16824,6 +16919,9 @@ } } } + }, + "A paid plan adds the features listed under Features." : { + }, "A paired app, such as a launcher, can ask when it pairs to show connections whose AI Policy is Never, with their user names. It still cannot query them. Turning this off stops every app at once." : { "localizations" : { @@ -16973,6 +17071,9 @@ "A point's id cannot change. Insert a new row with the new id instead." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "A profile needs a name." : { + }, "A publish to the team library is still running. Try again when it finishes." : { @@ -17282,6 +17383,9 @@ } } } + }, + "A run that returns more keeps only the newest. Pinned results always stay." : { + }, "A run that returns more results with rows keeps only the newest. Pinned results always stay." : { @@ -17361,6 +17465,9 @@ }, "A SELECT list, SET list or WHERE condition that fits in this width stays on one line." : { + }, + "A SELECT list, SET list or WHERE condition that fits stays on one line." : { + }, "A SELECT to export. Use instead of 'tables'." : { "localizations" : { @@ -17547,6 +17654,9 @@ } } } + }, + "A single cell still copies its value. Edit > Copy Special offers every format." : { + }, "A single click opens each table in the same preview tab. Double-click a table, or press Return, to keep it open." : { "localizations" : { @@ -17587,6 +17697,9 @@ } } } + }, + "A small query on each open connection catches a drop early. For a database that sleeps when idle or bills per query, pick Only when used: it checks when you next use the connection." : { + }, "A SQL condition, such as status = 'active'" : { "localizations" : { @@ -17701,6 +17814,9 @@ } } } + }, + "A strip on the window's leading edge with each open connection and database. It appears once more than one is open." : { + }, "A superuser bypasses all permission checks." : { "localizations" : { @@ -18902,6 +19018,9 @@ } } } + }, + "Actions for %@" : { + }, "Activate" : { "localizations" : { @@ -19305,6 +19424,9 @@ } } } + }, + "Active provider" : { + }, "Active Provider" : { "localizations" : { @@ -19913,6 +20035,9 @@ } } } + }, + "Add ⌘ or ⌃ to this shortcut." : { + }, "Add a connection first." : { "localizations" : { @@ -19950,6 +20075,9 @@ } } } + }, + "Add an API key to load this provider's models." : { + }, "Add Another SQL Folder…" : { "comment" : "Text for a menu item that adds a new linked SQL folder.", @@ -20250,6 +20378,9 @@ } } } + }, + "Add Command…" : { + }, "Add Connection" : { "localizations" : { @@ -20906,6 +21037,12 @@ }, "Add one row to a table on a saved connection. Provide the row as a JSON object or a CSV row." : { + }, + "Add one to reuse a prompt in the chat." : { + + }, + "Add one to use chat and Agent mode." : { + }, "Add plugin_debugger to shared_preload_libraries and restart the server." : { "extractionState" : "manual", @@ -21086,6 +21223,9 @@ } } } + }, + "Add SSH Profile…" : { + }, "Add SSH Server…" : { "localizations" : { @@ -21096,6 +21236,9 @@ } } } + }, + "Add TablePro to Claude, Cursor and other apps on this Mac." : { + }, "Add tags" : { "localizations" : { @@ -21572,6 +21715,9 @@ } } } + }, + "Adds a Recent section to the welcome window and the connection switcher." : { + }, "Adds a Recent section with the connections you opened lately to the welcome window and the connection switcher." : { "localizations" : { @@ -21989,6 +22135,9 @@ } } } + }, + "Agent mode pauses at the limit so you can continue. A higher limit uses more tokens per reply." : { + }, "Agent reply “%1$@” on %2$@" : { @@ -22458,6 +22607,9 @@ } } } + }, + "AI Policy applies to AI features and MCP clients. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, AppleScript, and Shortcuts. Effective scope is the minimum of the requesting token's scope and the External Clients level." : { + }, "AI Policy controls in-app AI agents. External Clients controls Raycast, Cursor, Claude Desktop, other MCP clients, and AppleScript. Effective scope is the minimum of the requesting token's scope and the External Clients level." : { "extractionState" : "stale", @@ -24291,6 +24443,9 @@ }, "already saved" : { + }, + "Also deletes saved changes kept for Data Rewind and earlier versions of query tabs." : { + }, "Also drop the columns, functions and other objects that use this type" : { @@ -24337,6 +24492,9 @@ }, "Also include global saved queries" : { + }, + "Also the direction of the first click on a column header." : { + }, "Also updating:" : { @@ -25688,6 +25846,9 @@ }, "And %lld more" : { + }, + "AND and OR" : { + }, "AND and OR:" : { @@ -25982,6 +26143,9 @@ } } } + }, + "Answered with ^[%lld tool](inflect: true)." : { + }, "Answered with 1 tool." : { "localizations" : { @@ -26979,9 +27143,15 @@ } } } + }, + "Applied when a table first opens." : { + }, "Applies to columns added later. Existing columns keep their character set." : { + }, + "Applies to connections set to Use Default, in AI features and for MCP clients." : { + }, "Applies to grid cells, the inspector, cell popovers and the row diff." : { @@ -27853,6 +28023,9 @@ } } } + }, + "Approval is set to “%@”, so these approvals are not used now. They apply again if you choose Ask Once for Each Connection." : { + }, "Approve" : { "extractionState" : "manual", @@ -27935,6 +28108,15 @@ } } } + }, + "Approved %@" : { + + }, + "Approved connections" : { + + }, + "Approved Connections" : { + }, "Approximate row count reported by the engine" : { "extractionState" : "manual", @@ -27989,6 +28171,18 @@ } } } + }, + "Apps using it lose access now, and the token leaves this list." : { + + }, + "Apps using it lose access now. This can't be undone." : { + + }, + "Apps using them lose access now, and the tokens leave this list." : { + + }, + "Apps using them lose access now. This can't be undone." : { + }, "Archive" : { "extractionState" : "manual", @@ -29054,6 +29248,9 @@ } } } + }, + "Asks for a value for each :name placeholder before the query runs." : { + }, "Assistant" : { "localizations" : { @@ -30537,6 +30734,9 @@ "Automatic does not work through a tunnel to %@. DuckDB would use HTTPS and check the certificate against 127.0.0.1, not against the server's name. Set SSL Mode to Verify Fingerprint or Required (skip verify), or to Disabled if the server serves plain HTTP." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Automatic Updates" : { + }, "Automatically check for updates" : { "localizations" : { @@ -34758,6 +34958,9 @@ } } } + }, + "Cancel Update" : { + }, "Canceling" : { @@ -35893,6 +36096,9 @@ } } } + }, + "Case" : { + }, "Case-insensitive substring to look for" : { "localizations" : { @@ -37532,6 +37738,36 @@ "state" : "translated", "value" : "Jeu de caractères" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "문자 집합" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Karakter Seti" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bảng mã" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "字符集" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "字集" + } } } }, @@ -37857,6 +38093,15 @@ } } } + }, + "Chat, Agent mode, inline suggestions and query actions such as Explain and Optimize." : { + + }, + "ChatGPT account" : { + + }, + "ChatGPT Account" : { + }, "ChatGPT did not return an access token." : { "localizations" : { @@ -38162,6 +38407,9 @@ }, "Check Now" : { + }, + "Check open connections" : { + }, "Check Skipped" : { @@ -38349,6 +38597,9 @@ "Checkered Flag" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Checking for a compatible build" : { + }, "Checking for the Claude Code command line tool…" : { "localizations" : { @@ -38636,6 +38887,9 @@ } } } + }, + "Choose a .tableplugin bundle or a .zip archive, or drop one on this window." : { + }, "Choose a %@ export file to import" : { "localizations" : { @@ -38977,6 +39231,16 @@ } } }, + "Choose a port from %d to %d." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Choose a port from %1$d to %2$d." + } + } + } + }, "Choose a private key file" : { "localizations" : { "fr" : { @@ -39451,6 +39715,9 @@ } } } + }, + "Choose an active provider or turn on Apple Intelligence first." : { + }, "Choose an AI provider in Settings to chat." : { @@ -40253,6 +40520,9 @@ } } } + }, + "Claude Agent" : { + }, "Claude Agent can't use this connection: TablePro couldn't create its access token. Try again." : { @@ -40488,6 +40758,9 @@ } } } + }, + "Clause items" : { + }, "Clause items:" : { @@ -40931,6 +41204,9 @@ } } } + }, + "Clear query history" : { + }, "Clear Query History?" : { "localizations" : { @@ -41011,6 +41287,9 @@ } } } + }, + "Clear Recent Connections" : { + }, "Clear Recent Tables" : { "localizations" : { @@ -41609,6 +41888,9 @@ } } } + }, + "Click + to add a theme, or drop a TablePro or VS Code theme file here." : { + }, "Click a table" : { "localizations" : { @@ -41717,6 +41999,9 @@ } } } + }, + "Clicking a table opens it in a preview tab that the next click reuses. Double-click a table or press Return to keep its tab." : { + }, "Client" : { "localizations" : { @@ -42173,6 +42458,12 @@ }, "Client: %@" : { + }, + "Clients" : { + + }, + "Clients ask again the next time they reach a connection." : { + }, "Clients can connect once the MCP server is running." : { @@ -46235,6 +46526,9 @@ } } } + }, + "Commas" : { + }, "Commas:" : { @@ -46436,6 +46730,9 @@ }, "Committed" : { + }, + "Committed saves stay committed. Their previous values can no longer be restored." : { + }, "Committing…" : { @@ -46992,6 +47289,9 @@ } } } + }, + "Compare what each plan includes." : { + }, "Compare With" : { @@ -47443,6 +47743,9 @@ } } } + }, + "Complete Word" : { + }, "Composite Type" : { "localizations" : { @@ -49435,6 +49738,9 @@ } } } + }, + "Connection history" : { + }, "Connection is read only for external clients" : { "localizations" : { @@ -50020,6 +50326,9 @@ } } } + }, + "Connection test" : { + }, "Connection test failed" : { "localizations" : { @@ -50654,6 +50963,15 @@ }, "Connections on this profile share one database user. TablePro renews its lease while in use, revokes it once the last connection disconnects or after 10 minutes unused, and never saves the generated password." : { + }, + "Connections set to Local only are left out." : { + + }, + "Connections that use a profile sign in with its username and password. Edit it once to update them all." : { + + }, + "Connections that use an SSH profile tunnel through its server. Changes reach every connection that uses it." : { + }, "Connections the client may use, ordered by name" : { "localizations" : { @@ -50694,6 +51012,9 @@ } } } + }, + "Connections without their own AI Policy use it. Clients cannot query a connection set to Never." : { + }, "Connections:" : { "extractionState" : "stale", @@ -51208,6 +51529,9 @@ } } } + }, + "Controls, sidebars and Settings follow this. Applies to this Mac." : { + }, "Conversation History" : { "localizations" : { @@ -53145,6 +53469,9 @@ } } } + }, + "Copy rows as" : { + }, "Copy rows as:" : { @@ -53340,6 +53667,9 @@ }, "Copy the setup into %@" : { + }, + "Copy this token now. TablePro won't show it again." : { + }, "Copy to" : { "localizations" : { @@ -55964,6 +56294,12 @@ } } } + }, + "Couldn't Clear Query History" : { + + }, + "Couldn't Clear Saved Changes" : { + }, "Couldn't connect" : { "extractionState" : "manual", @@ -55981,6 +56317,9 @@ }, "Couldn't Create the Token" : { + }, + "Couldn't Delete Profile" : { + }, "Couldn't Detach Partition" : { @@ -56000,6 +56339,9 @@ }, "Couldn't Drop Partition" : { + }, + "Couldn't Duplicate Profile" : { + }, "Couldn't Duplicate the Theme" : { @@ -56070,6 +56412,9 @@ }, "Couldn't Move the Theme to the Trash" : { + }, + "Couldn't Move to Trash" : { + }, "Couldn't Optimize Table" : { @@ -56348,6 +56693,9 @@ } } } + }, + "Couldn't Save the Command" : { + }, "Couldn't Save the Deletion" : { @@ -56357,6 +56705,9 @@ }, "Couldn't start" : { + }, + "Couldn't Uninstall" : { + }, "Couldn't update" : { @@ -57791,6 +58142,9 @@ }, "Credential profiles can't be read right now, so connections keep their own credentials." : { + }, + "Credential profiles couldn't be read, so none are shown. TablePro won't save over them." : { + }, "Credentials" : { "localizations" : { @@ -58579,6 +58933,9 @@ } } } + }, + "Cursor on my Mac" : { + }, "Cursor position %d exceeds SQL length (%d)" : { "localizations" : { @@ -58856,6 +59213,9 @@ } } } + }, + "Custom Provider" : { + }, "Custom Slash Commands" : { "localizations" : { @@ -59237,6 +59597,9 @@ }, "Dark theme" : { + }, + "Dark, in use" : { + }, "Dashboard" : { "extractionState" : "stale", @@ -59835,6 +60198,9 @@ } } } + }, + "Data types" : { + }, "database" : { @@ -60053,6 +60419,9 @@ } } } + }, + "Database Drivers" : { + }, "Database engine" : { "localizations" : { @@ -61419,6 +61788,9 @@ } } } + }, + "Database type" : { + }, "Database Type" : { "localizations" : { @@ -61832,6 +62204,46 @@ }, "Date and Time" : { + }, + "Date format" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Format de date" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "날짜 형식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tarih biçimi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Định dạng ngày" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "日期格式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "日期格式" + } + } + } }, "Date format:" : { "localizations" : { @@ -62583,6 +62995,19 @@ } } } + }, + "Default %@ is used by “%@”." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Default %1$@ is used by “%2$@”." + } + } + } + }, + "Default AI policy" : { + }, "Default collation" : { "localizations" : { @@ -62680,6 +63105,12 @@ } } } + }, + "Default JSON view" : { + + }, + "Default layout" : { + }, "Default layout for new connections:" : { "localizations" : { @@ -62807,6 +63238,9 @@ } } } + }, + "Default port" : { + }, "Default Port" : { "localizations" : { @@ -62970,6 +63404,9 @@ } } } + }, + "Default sort" : { + }, "Default sorting field: %@" : { "extractionState" : "manual", @@ -63333,6 +63770,9 @@ } } } + }, + "Delay" : { + }, "Delete" : { "localizations" : { @@ -63493,6 +63933,9 @@ }, "Delete %d tokens?" : { + }, + "Delete %d Tokens?" : { + }, "Delete %lld columns?" : { "localizations" : { @@ -63654,6 +64097,9 @@ } } } + }, + "Delete Backward" : { + }, "Delete Check Constraint" : { "localizations" : { @@ -63780,6 +64226,9 @@ } } } + }, + "Delete Command…" : { + }, "Delete Connection" : { "localizations" : { @@ -64019,6 +64468,9 @@ }, "Delete Foreign Key %@" : { + }, + "Delete Forward" : { + }, "Delete Group" : { "localizations" : { @@ -65595,6 +66047,36 @@ "state" : "translated", "value" : "Destination" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "대상" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hedef" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đích" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目标" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "目的地" + } } } }, @@ -68510,6 +68992,9 @@ } } } + }, + "Draws strings, numbers, dates and other typed values in the theme's Values colors." : { + }, "Driver Options" : { "comment" : "A section for driver-specific options.", @@ -70921,6 +71406,9 @@ }, "Each file below reports what happened to its changes." : { + }, + "Each link asks again before it connects. This applies only to this Mac." : { + }, "Each row takes a value that exists in the referenced table." : { @@ -70944,6 +71432,9 @@ } } } + }, + "Earlier versions of query tabs are kept this long too, up to 30 days." : { + }, "Earliest" : { "localizations" : { @@ -71034,6 +71525,9 @@ } } } + }, + "Edit %@" : { + }, "Edit %@ Connection" : { "localizations" : { @@ -72978,6 +73472,9 @@ } } } + }, + "Enable AI features" : { + }, "Enable AI Features" : { "localizations" : { @@ -73829,6 +74326,9 @@ } } } + }, + "Engines that match function and type names by exact case, such as ClickHouse, keep the case you typed." : { + }, "Engines that match function names by exact case, such as ClickHouse, keep the case you typed." : { @@ -74036,6 +74536,9 @@ }, "Enter a whole number from 1 to %@." : { + }, + "Enter a whole number." : { + }, "Enter an absolute path, as it appears on the SSH server." : { "localizations" : { @@ -74340,6 +74843,9 @@ } } } + }, + "Enter the code on GitHub" : { + }, "Enter the ElastiCache cache name (replication group ID) to use IAM authentication." : { "extractionState" : "manual", @@ -74603,6 +75109,9 @@ } } } + }, + "Enter where the password is read from." : { + }, "Enter whole numbers only." : { @@ -76436,6 +76945,9 @@ } } } + }, + "Every section returns to its default values. AI providers and their API keys, Enable AI features, Share usage data, linked folders, trusted links, connections and history are kept." : { + }, "Every shared column is generated, so there is nothing to write." : { "localizations" : { @@ -76476,6 +76988,9 @@ } } } + }, + "Every shortcut you changed goes back to its default." : { + }, "Every table needs at least one column. Click + to get started" : { "localizations" : { @@ -76625,6 +77140,9 @@ }, "Evictions" : { + }, + "Exact row count" : { + }, "Exact value" : { "localizations" : { @@ -79580,6 +80098,9 @@ } } } + }, + "Export Formats" : { + }, "Export multiple tables" : { "localizations" : { @@ -86283,6 +86804,9 @@ } } } + }, + "Font size" : { + }, "Font:" : { "extractionState" : "stale", @@ -86807,6 +87331,9 @@ }, "Forget %@" : { + }, + "Forget %1$@ for %2$@" : { + }, "Forget All" : { "localizations" : { @@ -86847,6 +87374,15 @@ } } } + }, + "Forget All Approvals?" : { + + }, + "Forget All Trusted Links?" : { + + }, + "Forget All…" : { + }, "Forgets which connections you opened and when. Sorting by Last Connected starts over." : { "localizations" : { @@ -86909,6 +87445,36 @@ "state" : "translated", "value" : "Format" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "형식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Biçim" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Định dạng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "格式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "格式" + } } } }, @@ -87111,6 +87677,9 @@ } } } + }, + "Formatted preview" : { + }, "Formatter" : { @@ -88169,6 +88738,9 @@ } } } + }, + "Generate Token…" : { + }, "Generate UUID" : { @@ -88774,6 +89346,12 @@ }, "Git stopped with the message below." : { + }, + "GitHub account" : { + + }, + "GitHub Account" : { + }, "GitHub Repository" : { "localizations" : { @@ -89959,6 +90537,9 @@ "Grid" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Grid cells, the inspector, cell popovers and the row diff. Applies to this Mac." : { + }, "Grid Line" : { "extractionState" : "manual", @@ -92510,6 +93091,9 @@ } } } + }, + "How plans, devices and offline files work." : { + }, "How to read value: percent is a fraction (0.25 means 25 percent), date is ISO 8601" : { @@ -94189,6 +94773,9 @@ } } } + }, + "Import Formats" : { + }, "Import from %@" : { "localizations" : { @@ -94460,6 +95047,36 @@ "state" : "translated", "value" : "Importer dans" } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "가져올 위치" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Şuraya içe aktar" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhập vào" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "导入到" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "匯入到" + } } } }, @@ -94605,6 +95222,9 @@ }, "Import Offline File…" : { + }, + "Import Options" : { + }, "Import rows into a table" : { "localizations" : { @@ -94762,6 +95382,9 @@ }, "Imported %d themes." : { + }, + "Imported ^[%lld Theme](inflect: true)" : { + }, "Imported 1 theme." : { @@ -95051,6 +95674,9 @@ } } } + }, + "In the sidebar, the inspector and data grid column header tooltips." : { + }, "In-memory data store and cache" : { "localizations" : { @@ -96076,12 +96702,21 @@ } } } + }, + "Indent width" : { + }, "Indent width:" : { + }, + "Indent with" : { + }, "Indent with:" : { + }, + "Indentation" : { + }, "Index" : { @@ -97165,6 +97800,9 @@ "INSERT needs a JSON object of cells, such as INSERT events/user#42 {\"profile:name\": \"Ann\"}." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Insert Non-Breaking Space" : { + }, "INSERT only sets cells. Leave %@ out, or delete it with PUT." : { "extractionState" : "manual", @@ -97461,6 +98099,9 @@ } } } + }, + "Insert Space" : { + }, "INSERT Statement(s)" : { "localizations" : { @@ -97807,9 +98448,15 @@ }, "Install %@…" : { + }, + "Install a plugin" : { + }, "Install adds TablePro to a client on this Mac. Select a client to see its settings and set it up by hand." : { + }, + "Install from File…" : { + }, "Install in %@" : { @@ -99820,6 +100467,19 @@ }, "It expires on %@. Create a new one in your account and import it." : { + }, + "It is used by “%@” in %@, which will have no shortcut." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "It is used by “%1$@” in %2$@, which will have no shortcut." + } + } + } + }, + "It is used by %@. They will have no shortcut." : { + }, "It stays on this Mac and never syncs, because it can name a command to run." : { @@ -99833,12 +100493,21 @@ "It supports these host key types: %@." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "It was changed outside TablePro and no longer loads. Settings > Appearance > Manage Themes lists it under Couldn't Load with the reason." : { + }, "It was changed outside TablePro and no longer loads. Settings > Appearance lists it under Not Loaded with the reason." : { }, "It was changed outside TablePro. The editor now shows the newer version." : { + }, + "It was copied to the clipboard and expires in 15 minutes." : { + + }, + "It was removed or replaced." : { + }, "Item count is approximate, updated about every six hours" : { "extractionState" : "manual", @@ -99984,10 +100653,22 @@ } } } + }, + "Its saved secrets couldn't be read or copied, so no copy was made." : { + + }, + "Its saved secrets or the connections that use it couldn't be updated, so nothing was deleted." : { + }, "Its server session may still be running and holding its locks." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Its settings are removed from every Mac that syncs settings, and its API key is deleted from the Keychain." : { + + }, + "Its settings are removed from every Mac that syncs settings." : { + }, "Its structure could not be read." : { "localizations" : { @@ -100019,6 +100700,9 @@ "JDWP error %d." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Join condition" : { + }, "Join condition:" : { @@ -100344,6 +101028,9 @@ }, "Jump host %1$@ failed: %2$@" : { + }, + "Jump Host %lld" : { + }, "Jump host configuration is invalid" : { "localizations" : { @@ -100732,6 +101419,46 @@ } } }, + "Keep entries for" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Conserver les entrées pendant" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "항목 보관 기간" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kayıtları saklama süresi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Giữ mục trong" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留记录" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留記錄" + } + } + } + }, "Keep entries for:" : { "localizations" : { "fr" : { @@ -101104,6 +101831,9 @@ } } } + }, + "Keep your connections and the items you choose the same on devices signed in to your Apple Account." : { + }, "Keeps the first row of each group of matching rows. Rows hidden by a filter or search are not compared." : { "localizations" : { @@ -101127,6 +101857,9 @@ }, "Keeps up to %1$d versions from the last %2$d days on this Mac." : { + }, + "Keeps what rows looked like before each save, for 7 days, on this Mac only. Encrypted and never synced." : { + }, "Keeps what rows looked like before each save, on this Mac only, for 7 days. It is encrypted, and never synced." : { "localizations" : { @@ -101368,6 +102101,9 @@ } } } + }, + "Key bindings" : { + }, "Key bindings:" : { @@ -102006,6 +102742,16 @@ } } }, + "Keyword case" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Casse des mots-clés" + } + } + } + }, "Keyword case:" : { "localizations" : { "fr" : { @@ -102096,6 +102842,9 @@ } } } + }, + "Keywords" : { + }, "killing a server session" : { "localizations" : { @@ -102383,6 +103132,46 @@ }, "Lakehouse analytics, MySQL protocol" : { + }, + "Language" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Langue" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "언어" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dil" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ngôn ngữ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "语言" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "語言" + } + } + } }, "Language %@" : { "localizations" : { @@ -102547,6 +103336,9 @@ } } } + }, + "Larger tables show an estimated count, which avoids a slow COUNT(*)." : { + }, "Largest INSERT written: %1$@ (%2$lld rows)." : { "extractionState" : "manual", @@ -103103,6 +103895,9 @@ }, "Last seen %@" : { + }, + "Last synced" : { + }, "Last Synced" : { "localizations" : { @@ -103459,6 +104254,9 @@ }, "Learn More About Licensing" : { + }, + "Learn More…" : { + }, "Lease can only be compared with a lease ID, such as 0x7b." : { "extractionState" : "manual", @@ -103531,6 +104329,12 @@ } } } + }, + "Leave blank to use Settings > Connections: %@." : { + + }, + "Leave blank to use Settings > Connections: no limit." : { + }, "Leave blank to use the global %d-second timeout. This setting applies only to database drivers that support it." : { "localizations" : { @@ -104072,6 +104876,9 @@ } } } + }, + "Lets AI apps such as Claude and Cursor work with your connections through TablePro." : { + }, "Library" : { "extractionState" : "manual", @@ -104945,6 +105752,9 @@ }, "Light theme" : { + }, + "Light, in use" : { + }, "Limit" : { "localizations" : { @@ -105271,6 +106081,9 @@ } } } + }, + "Line Breaks" : { + }, "Line Chart" : { "extractionState" : "manual", @@ -105357,9 +106170,15 @@ } } } + }, + "Line width" : { + }, "Line width:" : { + }, + "Lines up the AS of each SELECT item that sits on one line." : { + }, "Link" : { "extractionState" : "manual", @@ -107900,6 +108719,9 @@ } } } + }, + "Loading models…" : { + }, "Loading one sets the source, the target, the mode and these options. The Comparisons button in the toolbar lists them too." : { "localizations" : { @@ -108584,6 +109406,9 @@ } } } + }, + "Long values wrap onto up to 10 lines in new tabs. View > Wrap Text changes the open grid." : { + }, "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid." : { @@ -109849,6 +110674,9 @@ }, "Marked for deletion. Undo or Undo Delete brings it back." : { + }, + "Marks zero-width, control and special space characters in cells and value fields." : { + }, "Mask" : { "localizations" : { @@ -110476,6 +111304,9 @@ } } } + }, + "Match System follows Sidebar icon size in System Settings." : { + }, "Match what I type" : { @@ -111216,6 +112047,46 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "Maximum entries" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nombre maximal d’entrées" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "최대 항목 수" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maksimum kayıt" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Số mục tối đa" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大条目数" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "最大項目數" + } + } + } + }, "Maximum entries cannot be negative" : { "localizations" : { "fr" : { @@ -111415,6 +112286,9 @@ } } } + }, + "Maximum output tokens" : { + }, "Maximum row limit" : { "localizations" : { @@ -111535,6 +112409,9 @@ } } } + }, + "Maximum tables" : { + }, "Maximum tabs to return (1-500, default 20)" : { "localizations" : { @@ -111785,6 +112662,9 @@ } } } + }, + "MCP server" : { + }, "MCP Server" : { "extractionState" : "stale", @@ -113570,6 +114450,9 @@ } } } + }, + "Model list" : { + }, "Moderate cost" : { "comment" : "Accessibility label for a moderate cost.", @@ -114177,6 +115060,9 @@ }, "Move “%@” to the Trash?" : { + }, + "Move %@ to the Trash" : { + }, "Move Column Down" : { "localizations" : { @@ -115059,6 +115945,9 @@ } } } + }, + "Move to Trash…" : { + }, "Move Up" : { "localizations" : { @@ -115233,6 +116122,9 @@ } } } + }, + "ms" : { + }, "Multi-model database with SurrealQL" : { "localizations" : { @@ -116293,6 +117185,9 @@ }, "Needs attention" : { + }, + "Needs line numbers." : { + }, "Needs MySQL 8.0 or later." : { @@ -118631,6 +119526,9 @@ }, "No analyze recorded in the server's statistics, and this user cannot read the table's statistics to confirm it." : { + }, + "No approved connections. A connection a client may reach without asking again appears here." : { + }, "No Attached Databases" : { @@ -119469,6 +120367,9 @@ } } } + }, + "No credential profiles" : { + }, "No credential profiles yet." : { "localizations" : { @@ -119559,6 +120460,9 @@ } } } + }, + "No custom shortcuts" : { + }, "No Data" : { "localizations" : { @@ -120032,6 +120936,9 @@ } } } + }, + "No devices are signed in." : { + }, "No Differences" : { "localizations" : { @@ -120839,6 +121746,9 @@ } } } + }, + "No linked folders" : { + }, "No linked folders. Add a folder to watch for shared connection files." : { "localizations" : { @@ -121073,6 +121983,9 @@ } } } + }, + "No matching connections" : { + }, "No Matching Connections" : { "localizations" : { @@ -122079,6 +122992,9 @@ } } } + }, + "No providers" : { + }, "No providers configured" : { "localizations" : { @@ -122685,6 +123601,9 @@ } } } + }, + "No Results for “%@”" : { + }, "No results for \"%@\"." : { "localizations" : { @@ -123326,6 +124245,9 @@ }, "No sequences" : { + }, + "No servers" : { + }, "No servers yet." : { "localizations" : { @@ -123356,6 +124278,9 @@ } } } + }, + "No slash commands" : { + }, "No slow queries" : { "localizations" : { @@ -123466,6 +124391,9 @@ } } } + }, + "No SSH profiles" : { + }, "No SSH servers yet." : { "localizations" : { @@ -123930,6 +124858,9 @@ } } } + }, + "No Tokens" : { + }, "No tokens created" : { "localizations" : { @@ -124074,6 +125005,9 @@ } } } + }, + "No trusted links" : { + }, "No typed documents. Update the database driver, save changes and reload before exporting MQL." : { "extractionState" : "manual", @@ -125726,6 +126660,9 @@ } } } + }, + "Not included" : { + }, "Not installed" : { "localizations" : { @@ -126018,6 +126955,9 @@ } } } + }, + "Not set" : { + }, "Not signed in" : { "localizations" : { @@ -126402,6 +127342,9 @@ } } } + }, + "Not used" : { + }, "Not valid %@. %@ Showing the stored bytes." : { "localizations" : { @@ -127044,6 +127987,9 @@ } } } + }, + "Notifications are off in System Settings" : { + }, "Notifications are turned off for TablePro in System Settings." : { "localizations" : { @@ -127289,6 +128235,46 @@ } } }, + "NULL display" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Affichage de NULL" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 표시" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL görünümü" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hiển thị NULL" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 显示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "NULL 顯示" + } + } + } + }, "NULL display cannot be empty" : { "localizations" : { "fr" : { @@ -128536,6 +129522,12 @@ "Offline" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Offline file" : { + + }, + "Offline File and License Key" : { + }, "Offline file expired on %@" : { @@ -129879,6 +130871,9 @@ } } } + }, + "Only when used" : { + }, "open" : { @@ -134268,6 +135263,9 @@ } } } + }, + "Page size" : { + }, "Page Size" : { "extractionState" : "stale", @@ -134396,6 +135394,9 @@ } } } + }, + "Pages and Limits" : { + }, "Pagination" : { "localizations" : { @@ -134476,9 +135477,15 @@ } } } + }, + "Paid features stop on this Mac until you sign in again." : { + }, "Paid plan" : { + }, + "Paid plans" : { + }, "Paid plans add the features below." : { @@ -134788,6 +135795,9 @@ } } } + }, + "Part of the history couldn't be deleted. Try again." : { + }, "Partial files may remain on disk." : { "localizations" : { @@ -135940,6 +136950,9 @@ } } } + }, + "Password Source" : { + }, "password value" : { "localizations" : { @@ -137037,6 +138050,9 @@ } } } + }, + "Permissions" : { + }, "Person" : { "extractionState" : "manual", @@ -137292,6 +138308,9 @@ } } } + }, + "Pick a model to add this provider." : { + }, "Pick a model to save this provider." : { "localizations" : { @@ -137848,6 +138867,9 @@ } } } + }, + "Plans and devices" : { + }, "Plans are not saved for queries that carry parameters, because a database can print the values into its plan output." : { "localizations" : { @@ -138341,6 +139363,9 @@ } } } + }, + "Plugin Not Available" : { + }, "Plugin not found" : { "localizations" : { @@ -138685,6 +139710,9 @@ }, "Plugin updates are ready" : { + }, + "Plugin updates install when TablePro relaunches." : { + }, "Plugin was built for PluginKit version %d; this release of TablePro needs version %d." : { "localizations" : { @@ -139528,6 +140556,9 @@ } } } + }, + "Preferences and custom themes. Some settings, such as fonts and the appearance mode, stay on this Mac." : { + }, "Preferred" : { "extractionState" : "manual", @@ -140003,6 +141034,12 @@ } } } + }, + "Press Tab to accept, Escape to dismiss." : { + + }, + "Press to record a new shortcut. Delete removes it, Escape cancels." : { + }, "PrestoDB distributed SQL query engine" : { @@ -142434,6 +143471,9 @@ } } } + }, + "Profile, sign-in methods and billing" : { + }, "Profiles" : { "localizations" : { @@ -142713,6 +143753,9 @@ } } } + }, + "Prompt Template" : { + }, "Propose indexes for a slow query" : { "localizations" : { @@ -144632,6 +145675,9 @@ } } } + }, + "Query parameters" : { + }, "Query parameters (:name syntax)" : { "localizations" : { @@ -144714,6 +145760,9 @@ } } } + }, + "Query result limit" : { + }, "Query Result Row Cap" : { "localizations" : { @@ -147706,6 +148755,16 @@ } } }, + "Reassign %@ to “%@”?" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "Reassign %1$@ to “%2$@”?" + } + } + } + }, "Reassign owned objects" : { "localizations" : { "fr" : { @@ -147928,6 +148987,9 @@ } } } + }, + "Recent Connections" : { + }, "Recent Conversations" : { "localizations" : { @@ -148403,6 +149465,12 @@ } } } + }, + "Record Shortcut" : { + + }, + "Recording" : { + }, "Recording shortcut" : { "localizations" : { @@ -149642,6 +150710,9 @@ }, "Relaunch Now" : { + }, + "Relaunch TablePro to finish" : { + }, "Relaunch TablePro to finish removing plugins." : { @@ -151390,6 +152461,9 @@ } } } + }, + "Remove Jump Host" : { + }, "Remove Linked Folder?" : { "localizations" : { @@ -151430,6 +152504,9 @@ } } } + }, + "Remove old entries automatically" : { + }, "Remove one in Settings to use your plan on this Mac." : { @@ -151516,6 +152593,9 @@ } } } + }, + "Remove Provider…" : { + }, "Remove Rule" : { "localizations" : { @@ -151536,6 +152616,12 @@ } } } + }, + "Remove Server?" : { + + }, + "Remove Server…" : { + }, "Remove SET client_min_messages from the routine to debug it." : { "extractionState" : "manual", @@ -151544,6 +152630,9 @@ "Remove SET transaction_timeout from the routine to debug it." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Remove Shortcut" : { + }, "Remove TablePro from %@?" : { @@ -151665,6 +152754,9 @@ }, "Remove this change from the queue" : { + }, + "Remove this plugin" : { + }, "Remove this rule" : { "localizations" : { @@ -151738,6 +152830,12 @@ }, "Removed from the team library" : { + }, + "Removed plugins stay loaded until TablePro relaunches." : { + + }, + "Removes entries past these limits at launch, every 100 queries and when a limit changes. Removed entries can't be recovered." : { + }, "Removing" : { @@ -152842,6 +153940,9 @@ } } } + }, + "Requests go to" : { + }, "Requests to this host are sent unencrypted over http." : { "localizations" : { @@ -152852,6 +153953,9 @@ } } } + }, + "Requests, approvals and connected clients." : { + }, "Require authentication" : { "extractionState" : "stale", @@ -153167,6 +154271,12 @@ } } } + }, + "Reset %@ to default" : { + + }, + "Reset all settings" : { + }, "Reset All Settings" : { "localizations" : { @@ -153247,6 +154357,12 @@ } } } + }, + "Reset all settings?" : { + + }, + "Reset All Settings…" : { + }, "Reset All Shortcuts?" : { @@ -153530,6 +154646,9 @@ } } } + }, + "Reset to %@" : { + }, "Reset to default" : { "localizations" : { @@ -153570,6 +154689,9 @@ } } } + }, + "Reset to Default" : { + }, "Reset to Defaults" : { "localizations" : { @@ -153650,6 +154772,9 @@ } } } + }, + "Reset to None" : { + }, "Reset to System Default" : { "extractionState" : "stale", @@ -153731,6 +154856,9 @@ } } } + }, + "Reset…" : { + }, "Resident Memory" : { @@ -154139,9 +155267,18 @@ } } } + }, + "Restore default rules" : { + + }, + "Restore Default Shortcuts?" : { + }, "Restore Defaults" : { + }, + "Restore Defaults…" : { + }, "Restore Dump Cancelled" : { "comment" : "A title for a result sheet that indicates a restore operation was cancelled.", @@ -155249,6 +156386,9 @@ } } } + }, + "Results kept per run" : { + }, "Results kept per run:" : { @@ -155752,6 +156892,12 @@ } } } + }, + "Returns every rule on this page to its default." : { + + }, + "Returns every section to its defaults." : { + }, "Reuse Result For" : { @@ -156125,6 +157271,9 @@ } } } + }, + "Revoke %d Tokens?" : { + }, "Revoke All" : { "localizations" : { @@ -156205,6 +157354,9 @@ } } } + }, + "Revoke…" : { + }, "Revoked" : { "localizations" : { @@ -157444,6 +158596,46 @@ } } }, + "Row height" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hauteur des lignes" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "행 높이" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Satır yüksekliği" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chiều cao dòng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "行高" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "列高" + } + } + } + }, "Row height:" : { "localizations" : { "fr" : { @@ -157669,6 +158861,46 @@ } } }, + "Row size" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Taille des lignes" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "행 크기" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Satır boyutu" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cỡ hàng" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "行大小" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "列大小" + } + } + } + }, "Row size:" : { "comment" : "A label for the size of the sidebar rows.", "isCommentAutoGenerated" : true, @@ -157796,6 +159028,9 @@ } } } + }, + "Rows a query returns when the client sets no limit." : { + }, "Rows already transferred stay." : { @@ -158571,6 +159806,12 @@ } } } + }, + "Rules file" : { + + }, + "Rules File" : { + }, "Rules file:" : { @@ -159622,6 +160863,9 @@ } } } + }, + "Runs on this Mac and sends nothing over the network. Chat and Agent mode keep the active provider." : { + }, "Runs statements on the SSH server so a database file there can be read and written in place." : { "localizations" : { @@ -159713,6 +160957,9 @@ } } } + }, + "Runs the claude command line tool, so chat bills against your Claude subscription. Database tools need the MCP server, in Settings > MCP." : { + }, "Runs the Google Cloud SQL Auth Proxy against an instance connection name." : { "localizations" : { @@ -160021,6 +161268,9 @@ }, "Same as editor (%@)" : { + }, + "Same as editor (%lld)" : { + }, "same element" : { "localizations" : { @@ -161359,6 +162609,9 @@ } } } + }, + "Saved connections that use it stay in your library." : { + }, "Saved Customizations" : { "extractionState" : "stale", @@ -161410,6 +162663,9 @@ } } } + }, + "Saved in Keychain" : { + }, "Saved in the Keychain" : { "localizations" : { @@ -161420,6 +162676,9 @@ } } } + }, + "Saved in the Keychain once and used by every connection on this profile." : { + }, "Saved password" : { "localizations" : { @@ -164052,6 +165311,9 @@ } } } + }, + "Search Shortcuts" : { + }, "Search shortcuts…" : { "localizations" : { @@ -164240,6 +165502,9 @@ }, "Seat" : { + }, + "Seat assigned" : { + }, "Seats on a team license are managed on tablepro.app." : { "localizations" : { @@ -165688,6 +166953,9 @@ } } } + }, + "Select None" : { + }, "Select objects of the same kind to edit their privileges." : { "localizations" : { @@ -165811,6 +167079,9 @@ } } } + }, + "SELECT queries without their own LIMIT stop at this many rows. The editor text never changes. Fetch All and Execute Without Limit skip it once." : { + }, "Select Tab %d" : { "localizations" : { @@ -166255,6 +167526,9 @@ }, "Sending this Mac's environment variables to the server was not approved." : { + }, + "Sends one short request with this key and Base URL." : { + }, "Sends the code to %@" : { "localizations" : { @@ -168335,6 +169609,9 @@ }, "Set up" : { + }, + "Set Up a Client" : { + }, "Set up an app to use TablePro's MCP server" : { @@ -168505,6 +169782,9 @@ }, "Settings file" : { + }, + "Settings sections" : { + }, "Settings:" : { "extractionState" : "stale", @@ -169830,6 +171110,9 @@ } } } + }, + "Show comments" : { + }, "Show Completions" : { "localizations" : { @@ -170044,6 +171327,9 @@ } } } + }, + "Show Devices" : { + }, "Show edited fields only" : { "localizations" : { @@ -170165,6 +171451,9 @@ } } } + }, + "Show icons" : { + }, "Show Identical Objects" : { "localizations" : { @@ -170248,6 +171537,9 @@ } } } + }, + "Show in Theme Editor" : { + }, "Show Inspector" : { "localizations" : { @@ -170288,6 +171580,9 @@ } } } + }, + "Show inspector when a row is selected" : { + }, "Show invisible characters" : { "extractionState" : "manual", @@ -170506,6 +171801,9 @@ } } } + }, + "Show notifications" : { + }, "Show object comments" : { "localizations" : { @@ -170636,6 +171934,9 @@ } } } + }, + "Show passphrase" : { + }, "Show password" : { "localizations" : { @@ -171021,6 +172322,9 @@ }, "Show rows in %@" : { + }, + "Show secret" : { + }, "Show Sidebar" : { "localizations" : { @@ -171210,6 +172514,9 @@ }, "Show the messages that arrived while paused" : { + }, + "Show Themes Folder in Finder" : { + }, "Show Toolbar" : { "localizations" : { @@ -172009,6 +173316,9 @@ } } } + }, + "Shows UUIDs, Unix timestamps, JSON and serialized values in a readable form, judged from the first rows." : { + }, "Side" : { "localizations" : { @@ -172473,6 +173783,9 @@ }, "Sign In With" : { + }, + "Sign In With an Account" : { + }, "Sign In with Browser…" : { "localizations" : { @@ -172703,6 +174016,15 @@ } } } + }, + "Sign out of TablePro on this Mac?" : { + + }, + "Sign Out…" : { + + }, + "Sign this Mac in with a key from an older version of TablePro." : { + }, "Sign-in cancelled" : { "localizations" : { @@ -173236,6 +174558,9 @@ } } } + }, + "Signs in with your account" : { + }, "Silent" : { "localizations" : { @@ -173940,6 +175265,9 @@ } } } + }, + "Slash Commands" : { + }, "Slow" : { "extractionState" : "stale", @@ -175049,6 +176377,46 @@ } } }, + "Sort direction" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sens du tri" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "정렬 방향" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sıralama yönü" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hướng sắp xếp" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "排序方向" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "排序方向" + } + } + } + }, "Sort direction (default ascending)" : { "localizations" : { "fr" : { @@ -175236,6 +176604,9 @@ } } } + }, + "Sorting" : { + }, "Sorting will reload data and discard all unsaved changes." : { "localizations" : { @@ -177212,6 +178583,9 @@ } } } + }, + "SSH profiles couldn't be read, so none are shown. TablePro won't save over them." : { + }, "SSH Servers" : { "localizations" : { @@ -178398,7 +179772,44 @@ } }, "Statement" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Instruction" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "SQL 문" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Statement" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Câu lệnh" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "语句" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "陳述式" + } + } + } }, "Statement %1$d of %2$d failed: %3$@" : { "extractionState" : "manual", @@ -180302,6 +181713,9 @@ } } } + }, + "Stops longer queries on drivers that support it. A connection's own timeout overrides this. Applies to connections opened after a change." : { + }, "Storage engine" : { "localizations" : { @@ -180431,6 +181845,9 @@ }, "Store in Keychain" : { + }, + "Stored in iCloud Keychain, end-to-end encrypted. Applies to each password the next time you save it." : { + }, "Stored in the macOS Keychain and written to a temporary file only while the proxy runs." : { "localizations" : { @@ -181100,6 +182517,9 @@ } } } + }, + "Such as mysql and information_schema, in the sidebar and its database filter. The database switcher always lists them." : { + }, "Suggest indexes for a slow query from its plan and the indexes the tables already have" : { "localizations" : { @@ -181180,6 +182600,9 @@ } } } + }, + "Suggest SQL while typing" : { + }, "Suggested Actions" : { "localizations" : { @@ -183585,6 +185008,46 @@ } } }, + "Tab width" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Largeur de tabulation" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "탭 너비" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sekme genişliği" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Độ rộng tab" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "制表符宽度" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tab 寬度" + } + } + } + }, "Tab width (%d)" : { }, @@ -185302,10 +186765,16 @@ "TablePro can't read %@. Check that this account can see its source." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro can't read some saved connections, so it can't tell whether they use this profile." : { + }, "TablePro can't read this unit's source." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "TablePro can't show any notification until you allow it there." : { + }, "TablePro can't turn text into a %2$@ value for %1$@." : { "extractionState" : "manual", @@ -185584,6 +187053,9 @@ } } } + }, + "TablePro could not read the saved token. Type it to test." : { + }, "TablePro could not read the Table Health history: %@" : { @@ -185617,6 +187089,9 @@ }, "TablePro could not save the token to the Keychain, so it was not created. Try again." : { + }, + "TablePro could not save the token to the Keychain, so the server was not saved. Try again." : { + }, "TablePro could not tell how this Dameng server treats backslashes, so it will not send a value that contains one. Reconnect, then try again." : { "extractionState" : "manual", @@ -186355,6 +187830,9 @@ } } } + }, + "TablePro reads .tablepro files saved without a passphrase from these folders. Their connections appear read only in the sidebar." : { + }, "TablePro reads this file with a driver it downloads from the plugin registry." : { "localizations" : { @@ -187896,6 +189374,9 @@ } } } + }, + "Team library changes that were not sent yet are discarded." : { + }, "Team library updated %@" : { @@ -188536,6 +190017,9 @@ } } } + }, + "Testing…" : { + }, "text" : { "localizations" : { @@ -189818,6 +191302,9 @@ } } } + }, + "The API key could not be saved to the Keychain." : { + }, "The API key will be permanently deleted." : { "localizations" : { @@ -190492,6 +191979,9 @@ }, "The cache must be at least 1." : { + }, + "The case completions use. UPPERCASE and lowercase also change keywords as you type." : { + }, "The catalog location is not a folder: %@" : { "localizations" : { @@ -193406,6 +194896,9 @@ } } } + }, + "The first call asks. The answer is remembered for that client until you forget it." : { + }, "The first call asks. The answer is remembered for that client until you revoke it." : { "localizations" : { @@ -193707,6 +195200,9 @@ }, "the import's transaction was rolled back" : { + }, + "The imported offline file is removed." : { + }, "The increment cannot be zero." : { @@ -194815,6 +196311,9 @@ } } } + }, + "The most rows a client can ask for." : { + }, "The name a statement uses for this database, as in name.table." : { @@ -195616,6 +197115,12 @@ } } } + }, + "The plugin moves to the Trash and its settings are deleted." : { + + }, + "The plugin moves to the Trash and its settings are deleted. It stays loaded until TablePro relaunches." : { + }, "The plugin was built for an incompatible runtime." : { "localizations" : { @@ -195841,6 +197346,9 @@ } } } + }, + "The profile was saved, but its password couldn't be saved to the Keychain." : { + }, "The profile's region, or us-east-1" : { "extractionState" : "manual", @@ -196908,6 +198416,9 @@ }, "The save will fail: the rows listed below still reference rows this deletes, and their foreign key doesn't allow it." : { + }, + "The saved changes couldn't be deleted. Try again." : { + }, "The saved extension list is not in a format TablePro can read." : { "extractionState" : "manual", @@ -198413,6 +199924,9 @@ } } } + }, + "The SQL editor, the JSON viewer's Text mode and SQL previews. Applies to this Mac." : { + }, "The SQL Server Kerberos service principal name is not registered." : { "extractionState" : "manual", @@ -206187,6 +207701,9 @@ } } } + }, + "This provider was removed." : { + }, "This query belongs to another connection. Load it in the editor to run it there." : { "comment" : "A description of why the \"Load in Editor\" button is disabled.", @@ -209917,12 +211434,18 @@ } } } + }, + "Tokens" : { + }, "Tokens are not available" : { }, "Tokens load while the MCP server is running." : { + }, + "Tokens Unavailable" : { + }, "Too Large to Compare" : { @@ -210158,6 +211681,9 @@ } } } + }, + "Tool call limit" : { + }, "Tool call limit: %d" : { "localizations" : { @@ -211108,6 +212634,9 @@ }, "Transferring tables to %@" : { + }, + "Treat work as long-running after" : { + }, "Tree" : { "localizations" : { @@ -212450,6 +213979,9 @@ }, "Type @ in the message to find any other table" : { + }, + "Type / in the chat to run one. A template can use {{query}}, {{schema}}, {{database}} and {{body}}." : { + }, "Type %@ in the query to set where the cursor lands after keyword expansion." : { "extractionState" : "stale", @@ -212521,6 +214053,9 @@ } } } + }, + "Type Shortcut" : { + }, "Type shortcut…" : { "localizations" : { @@ -212561,6 +214096,9 @@ } } } + }, + "Type the server's token. A saved token stays with the address it was saved for." : { + }, "Type: %@" : { "localizations" : { @@ -212821,6 +214359,9 @@ } } } + }, + "Unavailable" : { + }, "unbalanced quotes" : { "extractionState" : "manual", @@ -212895,6 +214436,9 @@ }, "Uncommitted changes on %@ are rolled back when TablePro relaunches." : { + }, + "Under ^[%lld row](inflect: true)" : { + }, "Under MCP Servers click \"+ Add Custom Server\", select the Local tab, paste the JSON below, then click Add Server" : { "localizations" : { @@ -213386,6 +214930,9 @@ } } } + }, + "Uninstall “%@”?" : { + }, "Uninstall %@" : { "localizations" : { @@ -213546,6 +215093,12 @@ } } } + }, + "Uninstall this plugin" : { + + }, + "Uninstall…" : { + }, "Unique" : { "localizations" : { @@ -215274,6 +216827,9 @@ }, "Unused Indexes" : { + }, + "Up to %lld characters" : { + }, "Up to Date" : { "extractionState" : "manual", @@ -215377,6 +216933,9 @@ }, "Update changes the rows whose key is in the file. Insert or Update also adds the rest, and Insert, Skip Existing adds only rows whose key is not in the table. Columns not mapped keep their values." : { + }, + "Update channel" : { + }, "Update channel:" : { @@ -215392,6 +216951,9 @@ } } } + }, + "Update failed" : { + }, "Update in %@" : { @@ -216443,6 +218005,9 @@ } } } + }, + "Use ⌘ or ⌃, Space, or a function key." : { + }, "Use a license key" : { @@ -216999,9 +218564,18 @@ } } } + }, + "Used for chat context, {{schema}} commands and Copilot suggestions." : { + }, "Used Memory" : { + }, + "Used only with Ask Once for Each Connection." : { + + }, + "Used when a connection opens, unless you picked a layout for it from the View menu. For servers with a database tree." : { + }, "User" : { "localizations" : { @@ -217593,6 +219167,9 @@ } } } + }, + "Uses your Plus, Pro, Business or Enterprise subscription under OpenAI's terms. This interface is unofficial and may change." : { + }, "using %@" : { "localizations" : { @@ -217941,6 +219518,9 @@ } } } + }, + "Valid until %@" : { + }, "Validate" : { @@ -218990,6 +220570,9 @@ } } } + }, + "Verified %@" : { + }, "Verified %@, valid until %@" : { "localizations" : { @@ -219906,6 +221489,9 @@ } } } + }, + "View Plans…" : { + }, "View that was read" : { "localizations" : { @@ -220139,6 +221725,9 @@ } } } + }, + "Waiting for your browser…" : { + }, "Waiting for your password" : { "localizations" : { @@ -220396,6 +221985,9 @@ }, "Was %@" : { + }, + "Watch %@" : { + }, "Watch PostgreSQL notifications, Redis channels and Kafka topics as messages arrive." : { @@ -221190,6 +222782,49 @@ } } }, + "When long-running work finishes out of sight, an agent needs your answer or its reply fails, or an extension can't load or update." : { + + }, + "When TablePro starts" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Au démarrage de TablePro" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 시작 시" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro başlarken" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Khi TablePro khởi động" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 启动时" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 啟動時" + } + } + } + }, "When TablePro starts:" : { "localizations" : { "fr" : { @@ -221239,6 +222874,12 @@ } } } + }, + "When work this long finishes out of sight, its tab is marked and, with notifications on, a notification shows." : { + + }, + "When you last opened each connection, used by Recent and the Last Connected sort. Stays on this Mac." : { + }, "Where" : { "localizations" : { @@ -221249,6 +222890,9 @@ } } } + }, + "Where a broken SELECT, SET, WITH, WHERE or HAVING list starts. A single item stays beside its keyword." : { + }, "Where AND and OR go when a WHERE or HAVING condition breaks across lines." : { @@ -221295,6 +222939,9 @@ }, "Where the items of a SELECT list, SET list, WITH list, or WHERE or HAVING condition start once it breaks across lines. A single item stays beside its keyword." : { + }, + "Where they go when a WHERE or HAVING condition breaks." : { + }, "Whether a session is open" : { "localizations" : { @@ -224033,6 +225680,12 @@ } } } + }, + "You are not on a team." : { + + }, + "You can put it back from the Trash." : { + }, "You have %lld live links." : { "localizations" : { diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift index 1698d19d9c..b0c73aeee8 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibraryModel.swift @@ -88,7 +88,7 @@ internal struct ThemeImportReport: Equatable { } let title = imported.isEmpty ? String(localized: "No Themes Imported") - : String(format: String(localized: "Imported %lld Themes"), imported.count) + : String(AttributedString(localized: "Imported ^[\(imported.count) Theme](inflect: true)").characters) return ThemeLibraryAlert(title: title, message: lines.joined(separator: "\n")) } } diff --git a/apple/TablePro/Views/Settings/EditorSettingsView.swift b/apple/TablePro/Views/Settings/EditorSettingsView.swift index 5e8c62f3fb..98a67c32fc 100644 --- a/apple/TablePro/Views/Settings/EditorSettingsView.swift +++ b/apple/TablePro/Views/Settings/EditorSettingsView.swift @@ -57,7 +57,7 @@ struct EditorSettingsView: View { Picker("Tab width", selection: Self.tabWidthBinding($editor.value)) { SettingsChoiceItems(Self.tabWidths, including: editor.value.clampedTabWidth) { width in - Text("\(width) spaces") + Text("^[\(width) space](inflect: true)") } } .accessibilityIdentifier("editor-tab-width") diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 94710016e5..492a6dc32d 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -176,11 +176,12 @@ struct DataGridSection: View { } static func rowsTitle(_ count: Int) -> String { - String(localized: "\(count) rows") + String(AttributedString(localized: "^[\(count) row](inflect: true)").characters) } static func exactCountTitle(_ threshold: Int) -> String { - threshold == Int.max ? String(localized: "Always") : String(localized: "Under \(threshold) rows") + guard threshold != Int.max else { return String(localized: "Always") } + return String(AttributedString(localized: "Under ^[\(threshold) row](inflect: true)").characters) } static func resultSetsKeptTitle(_ count: Int) -> String { diff --git a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift index f72a9b7e45..00f39dd978 100644 --- a/apple/TablePro/Views/Settings/Sections/FormatterSection.swift +++ b/apple/TablePro/Views/Settings/Sections/FormatterSection.swift @@ -199,7 +199,9 @@ struct SQLFormattingPage: View { // A tab counts as indent width columns when a line's width is measured. private func indentWidthTitle(_ width: Int) -> Text { - settings.rules.indentStyle == .tabs ? Text("\(width) columns") : Text("\(width) spaces") + settings.rules.indentStyle == .tabs + ? Text("^[\(width) column](inflect: true)") + : Text("^[\(width) space](inflect: true)") } private var keywordCasePicker: some View { @@ -225,11 +227,11 @@ struct SQLFormattingPage: View { Text("One item per line").tag(0) Divider() ForEach(widths.fixed, id: \.self) { width in - Text("\(width) characters").tag(width) + Text("^[\(width) character](inflect: true)").tag(width) } if let extra = widths.extra { Divider() - Text("\(extra) characters").tag(extra) + Text("^[\(extra) character](inflect: true)").tag(extra) } } label: { Text("Line width") diff --git a/apple/TableProTests/Models/GeneralSettingsTests.swift b/apple/TableProTests/Models/GeneralSettingsTests.swift index 857025d5e5..b0e9200df4 100644 --- a/apple/TableProTests/Models/GeneralSettingsTests.swift +++ b/apple/TableProTests/Models/GeneralSettingsTests.swift @@ -29,12 +29,11 @@ struct AppLanguageTests { #expect(try JSONDecoder().decode(GeneralSettings.self, from: data).language == .french) } - /// The picker writes the choice to `AppleLanguages`, and a language the catalog does not carry - /// silently falls back to English, so offering one is a promise only the catalog can keep. + // A language the catalog does not carry falls back to English after the picker writes AppleLanguages. @Test("Every language the picker offers is translated in the app's catalog") func everyOfferedLanguageShipsInTheCatalog() throws { let catalog = try Self.catalogStrings() - let languageLabel = try #require(catalog["Language:"]?["localizations"] as? [String: Any]) + let languageLabel = try #require(catalog["Language"]?["localizations"] as? [String: Any]) for language in AppLanguage.allCases where language != .system && language != .english { #expect(languageLabel[language.rawValue] != nil, "\(language.rawValue) is offered but not translated") diff --git a/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift b/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift index c9290c403f..5622025216 100644 --- a/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift +++ b/apple/TableProTests/Models/Settings/DataGridSettingsTests.swift @@ -198,6 +198,14 @@ struct DataPaneChoiceTests { #expect(DataGridSection.exactCountTitle(100_000).contains(SettingsFormat.count(100_000))) #expect(DataGridSection.exactCountTitle(Int.max) == String(localized: "Always")) } + + @Test("A row count of one reads in the singular") + func rowTitlesAgreeWithTheCount() { + #expect(DataGridSection.rowsTitle(1) == "1 row") + #expect(DataGridSection.rowsTitle(2) == "2 rows") + #expect(DataGridSection.exactCountTitle(1) == "Under 1 row") + #expect(DataGridSection.exactCountTitle(2) == "Under 2 rows") + } } @MainActor diff --git a/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift b/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift index d29dd4afcb..7037dfbb3e 100644 --- a/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift +++ b/apple/TableProTests/Views/Settings/ThemeLibraryModelTests.swift @@ -170,6 +170,22 @@ struct ThemeLibraryModelTests { #expect(library.customThemes.map(\.name) == ["Ocean", "Paper"]) } + @Test("One imported theme beside a failure reads in the singular") + func importOneFileBesideAFailure() throws { + let fixture = try Fixture() + let library = fixture.makeLibrary() + let good = try fixture.writeIncoming( + "Ocean.json", + contents: ThemeFileFormat.encode(Fixture.theme("user.11111111", "Ocean")) + ) + let broken = try fixture.writeIncoming("Monokai.json", contents: Data("not json".utf8)) + + let report = library.importThemes(from: [good, broken], undoManager: nil) + + #expect(report.imported.count == 1) + #expect(library.alert?.title == "Imported 1 Theme") + } + @Test("A single file that fails names itself in the alert title") func singleFailedImport() throws { let fixture = try Fixture() From 9d0e7d081946cf737b76110b043248277055ab99 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:20:23 +0700 Subject: [PATCH 45/48] docs(changelog): Settings revamp fragments --- apple/changelog.d/4413.added.1.md | 1 + apple/changelog.d/4413.added.10.md | 1 + apple/changelog.d/4413.added.2.md | 1 + apple/changelog.d/4413.added.3.md | 1 + apple/changelog.d/4413.added.4.md | 1 + apple/changelog.d/4413.added.5.md | 1 + apple/changelog.d/4413.added.6.md | 1 + apple/changelog.d/4413.added.7.md | 1 + apple/changelog.d/4413.added.8.md | 1 + apple/changelog.d/4413.added.9.md | 1 + apple/changelog.d/4413.added.md | 1 + apple/changelog.d/4413.changed.1.md | 1 + apple/changelog.d/4413.changed.10.md | 1 + apple/changelog.d/4413.changed.11.md | 1 + apple/changelog.d/4413.changed.12.md | 1 + apple/changelog.d/4413.changed.13.md | 1 + apple/changelog.d/4413.changed.14.md | 1 + apple/changelog.d/4413.changed.15.md | 1 + apple/changelog.d/4413.changed.16.md | 1 + apple/changelog.d/4413.changed.2.md | 1 + apple/changelog.d/4413.changed.3.md | 1 + apple/changelog.d/4413.changed.4.md | 1 + apple/changelog.d/4413.changed.5.md | 1 + apple/changelog.d/4413.changed.6.md | 1 + apple/changelog.d/4413.changed.7.md | 1 + apple/changelog.d/4413.changed.8.md | 1 + apple/changelog.d/4413.changed.9.md | 1 + apple/changelog.d/4413.fixed.1.md | 1 + apple/changelog.d/4413.fixed.2.md | 1 + apple/changelog.d/4413.fixed.3.md | 1 + apple/changelog.d/4413.fixed.4.md | 1 + apple/changelog.d/4413.fixed.5.md | 1 + apple/changelog.d/4413.fixed.6.md | 1 + apple/changelog.d/4413.fixed.md | 1 + apple/changelog.d/4413.security.md | 1 + 35 files changed, 35 insertions(+) create mode 100644 apple/changelog.d/4413.added.1.md create mode 100644 apple/changelog.d/4413.added.10.md create mode 100644 apple/changelog.d/4413.added.2.md create mode 100644 apple/changelog.d/4413.added.3.md create mode 100644 apple/changelog.d/4413.added.4.md create mode 100644 apple/changelog.d/4413.added.5.md create mode 100644 apple/changelog.d/4413.added.6.md create mode 100644 apple/changelog.d/4413.added.7.md create mode 100644 apple/changelog.d/4413.added.8.md create mode 100644 apple/changelog.d/4413.added.9.md create mode 100644 apple/changelog.d/4413.added.md create mode 100644 apple/changelog.d/4413.changed.1.md create mode 100644 apple/changelog.d/4413.changed.10.md create mode 100644 apple/changelog.d/4413.changed.11.md create mode 100644 apple/changelog.d/4413.changed.12.md create mode 100644 apple/changelog.d/4413.changed.13.md create mode 100644 apple/changelog.d/4413.changed.14.md create mode 100644 apple/changelog.d/4413.changed.15.md create mode 100644 apple/changelog.d/4413.changed.16.md create mode 100644 apple/changelog.d/4413.changed.2.md create mode 100644 apple/changelog.d/4413.changed.3.md create mode 100644 apple/changelog.d/4413.changed.4.md create mode 100644 apple/changelog.d/4413.changed.5.md create mode 100644 apple/changelog.d/4413.changed.6.md create mode 100644 apple/changelog.d/4413.changed.7.md create mode 100644 apple/changelog.d/4413.changed.8.md create mode 100644 apple/changelog.d/4413.changed.9.md create mode 100644 apple/changelog.d/4413.fixed.1.md create mode 100644 apple/changelog.d/4413.fixed.2.md create mode 100644 apple/changelog.d/4413.fixed.3.md create mode 100644 apple/changelog.d/4413.fixed.4.md create mode 100644 apple/changelog.d/4413.fixed.5.md create mode 100644 apple/changelog.d/4413.fixed.6.md create mode 100644 apple/changelog.d/4413.fixed.md create mode 100644 apple/changelog.d/4413.security.md diff --git a/apple/changelog.d/4413.added.1.md b/apple/changelog.d/4413.added.1.md new file mode 100644 index 0000000000..86865d7880 --- /dev/null +++ b/apple/changelog.d/4413.added.1.md @@ -0,0 +1 @@ +General has Software Update and Command Line Tool pages, and the Software Update row shows a pending update. diff --git a/apple/changelog.d/4413.added.10.md b/apple/changelog.d/4413.added.10.md new file mode 100644 index 0000000000..c722f2f66e --- /dev/null +++ b/apple/changelog.d/4413.added.10.md @@ -0,0 +1 @@ +Picking a custom slash command that uses {{body}} puts it in the AI chat composer to finish before sending. diff --git a/apple/changelog.d/4413.added.2.md b/apple/changelog.d/4413.added.2.md new file mode 100644 index 0000000000..69590c14e0 --- /dev/null +++ b/apple/changelog.d/4413.added.2.md @@ -0,0 +1 @@ +Manage Themes is its own page in Appearance, and Undo of a theme change still works after going Back. diff --git a/apple/changelog.d/4413.added.3.md b/apple/changelog.d/4413.added.3.md new file mode 100644 index 0000000000..edcb018801 --- /dev/null +++ b/apple/changelog.d/4413.added.3.md @@ -0,0 +1 @@ +Each AI provider opens as its own page, with Edit Connection… for its name, Base URL and API key. diff --git a/apple/changelog.d/4413.added.4.md b/apple/changelog.d/4413.added.4.md new file mode 100644 index 0000000000..ece1510764 --- /dev/null +++ b/apple/changelog.d/4413.added.4.md @@ -0,0 +1 @@ +Custom slash commands have their own page in Settings > AI. diff --git a/apple/changelog.d/4413.added.5.md b/apple/changelog.d/4413.added.5.md new file mode 100644 index 0000000000..5a6ad4da13 --- /dev/null +++ b/apple/changelog.d/4413.added.5.md @@ -0,0 +1 @@ +Settings > MCP has Tokens and Approved Connections pages. diff --git a/apple/changelog.d/4413.added.6.md b/apple/changelog.d/4413.added.6.md new file mode 100644 index 0000000000..4a03aa9518 --- /dev/null +++ b/apple/changelog.d/4413.added.6.md @@ -0,0 +1 @@ +Extensions installs several plugins at once with Install from File…, or by dropping them on the pane. diff --git a/apple/changelog.d/4413.added.7.md b/apple/changelog.d/4413.added.7.md new file mode 100644 index 0000000000..b9043f41e2 --- /dev/null +++ b/apple/changelog.d/4413.added.7.md @@ -0,0 +1 @@ +SSH profiles can be duplicated, and SSH passwords, passphrases and TOTP secrets have Show toggles. diff --git a/apple/changelog.d/4413.added.8.md b/apple/changelog.d/4413.added.8.md new file mode 100644 index 0000000000..bd8cb1c8db --- /dev/null +++ b/apple/changelog.d/4413.added.8.md @@ -0,0 +1 @@ +Settings > Account has Devices, Teams, and Offline File and License Key pages, and Sign Out… asks first. diff --git a/apple/changelog.d/4413.added.9.md b/apple/changelog.d/4413.added.9.md new file mode 100644 index 0000000000..27248e240a --- /dev/null +++ b/apple/changelog.d/4413.added.9.md @@ -0,0 +1 @@ +Keyboard shortcut rows have a context menu with Record Shortcut, Remove Shortcut and Reset to Default. diff --git a/apple/changelog.d/4413.added.md b/apple/changelog.d/4413.added.md new file mode 100644 index 0000000000..5310ca0013 --- /dev/null +++ b/apple/changelog.d/4413.added.md @@ -0,0 +1 @@ +Settings pages keep Back and Forward history, and tablepro://settings links can open a page inside a pane. diff --git a/apple/changelog.d/4413.changed.1.md b/apple/changelog.d/4413.changed.1.md new file mode 100644 index 0000000000..63a8692b50 --- /dev/null +++ b/apple/changelog.d/4413.changed.1.md @@ -0,0 +1 @@ +The Settings window can be minimized, and its size resets once to fit the new layout. diff --git a/apple/changelog.d/4413.changed.10.md b/apple/changelog.d/4413.changed.10.md new file mode 100644 index 0000000000..e5a79beba7 --- /dev/null +++ b/apple/changelog.d/4413.changed.10.md @@ -0,0 +1 @@ +Sync is now iCloud Sync, with What Syncs on the same page and editable while sync is off. diff --git a/apple/changelog.d/4413.changed.11.md b/apple/changelog.d/4413.changed.11.md new file mode 100644 index 0000000000..66632ece78 --- /dev/null +++ b/apple/changelog.d/4413.changed.11.md @@ -0,0 +1 @@ +Settings > Data is regrouped, and Query result limit is one pop-up with a No limit choice. diff --git a/apple/changelog.d/4413.changed.12.md b/apple/changelog.d/4413.changed.12.md new file mode 100644 index 0000000000..bd726fd9dc --- /dev/null +++ b/apple/changelog.d/4413.changed.12.md @@ -0,0 +1 @@ +Clear Saved Changes in Data Rewind works without a license. diff --git a/apple/changelog.d/4413.changed.13.md b/apple/changelog.d/4413.changed.13.md new file mode 100644 index 0000000000..191221c7e4 --- /dev/null +++ b/apple/changelog.d/4413.changed.13.md @@ -0,0 +1 @@ +Show line numbers moved under Gutter in Editor settings, and SQL Formatting shows its preview first. diff --git a/apple/changelog.d/4413.changed.14.md b/apple/changelog.d/4413.changed.14.md new file mode 100644 index 0000000000..7b7c49204d --- /dev/null +++ b/apple/changelog.d/4413.changed.14.md @@ -0,0 +1 @@ +Settings labels lost their trailing colons, and help moved from tooltips into subtitles. diff --git a/apple/changelog.d/4413.changed.15.md b/apple/changelog.d/4413.changed.15.md new file mode 100644 index 0000000000..0937e2f2d1 --- /dev/null +++ b/apple/changelog.d/4413.changed.15.md @@ -0,0 +1 @@ +Lists in Settings have a native add and remove bar inside their border. diff --git a/apple/changelog.d/4413.changed.16.md b/apple/changelog.d/4413.changed.16.md new file mode 100644 index 0000000000..ab8c320db0 --- /dev/null +++ b/apple/changelog.d/4413.changed.16.md @@ -0,0 +1 @@ +The device limit and offline file notices open the matching page in Settings > Account. diff --git a/apple/changelog.d/4413.changed.2.md b/apple/changelog.d/4413.changed.2.md new file mode 100644 index 0000000000..abb81a1435 --- /dev/null +++ b/apple/changelog.d/4413.changed.2.md @@ -0,0 +1 @@ +Linked Folders and Trusted Links moved to Settings > Connections, and Forget All… asks first. diff --git a/apple/changelog.d/4413.changed.3.md b/apple/changelog.d/4413.changed.3.md new file mode 100644 index 0000000000..dd6fb06a97 --- /dev/null +++ b/apple/changelog.d/4413.changed.3.md @@ -0,0 +1 @@ +Keyboard settings search sits in the toolbar, and Restore Defaults… asks before resetting every shortcut. diff --git a/apple/changelog.d/4413.changed.4.md b/apple/changelog.d/4413.changed.4.md new file mode 100644 index 0000000000..fd969e7b35 --- /dev/null +++ b/apple/changelog.d/4413.changed.4.md @@ -0,0 +1 @@ +Reassigning a shortcut held by several actions names each one and clears them all in one step. diff --git a/apple/changelog.d/4413.changed.5.md b/apple/changelog.d/4413.changed.5.md new file mode 100644 index 0000000000..fd913e3bb4 --- /dev/null +++ b/apple/changelog.d/4413.changed.5.md @@ -0,0 +1 @@ +The long-running work threshold in Notifications can be changed while notifications are off. diff --git a/apple/changelog.d/4413.changed.6.md b/apple/changelog.d/4413.changed.6.md new file mode 100644 index 0000000000..60a9d3fb02 --- /dev/null +++ b/apple/changelog.d/4413.changed.6.md @@ -0,0 +1 @@ +The Default AI policy in Settings > AI and the connection form's AI Policy show while AI features are off. diff --git a/apple/changelog.d/4413.changed.7.md b/apple/changelog.d/4413.changed.7.md new file mode 100644 index 0000000000..444fbacca2 --- /dev/null +++ b/apple/changelog.d/4413.changed.7.md @@ -0,0 +1 @@ +Revoke… for MCP tokens and Forget All… for approved connections ask before they act. diff --git a/apple/changelog.d/4413.changed.8.md b/apple/changelog.d/4413.changed.8.md new file mode 100644 index 0000000000..c735c2c351 --- /dev/null +++ b/apple/changelog.d/4413.changed.8.md @@ -0,0 +1 @@ +Uninstalling an extension moves it to the Trash. diff --git a/apple/changelog.d/4413.changed.9.md b/apple/changelog.d/4413.changed.9.md new file mode 100644 index 0000000000..ed05b27fba --- /dev/null +++ b/apple/changelog.d/4413.changed.9.md @@ -0,0 +1 @@ +SSH Servers in Settings > Profiles is now SSH Profiles. diff --git a/apple/changelog.d/4413.fixed.1.md b/apple/changelog.d/4413.fixed.1.md new file mode 100644 index 0000000000..8867515608 --- /dev/null +++ b/apple/changelog.d/4413.fixed.1.md @@ -0,0 +1 @@ +A custom slash command typed with text after its name went to the model as plain text. diff --git a/apple/changelog.d/4413.fixed.2.md b/apple/changelog.d/4413.fixed.2.md new file mode 100644 index 0000000000..ed393e2fe2 --- /dev/null +++ b/apple/changelog.d/4413.fixed.2.md @@ -0,0 +1 @@ +After a slash command filled the AI chat composer, typed text landed before the command. diff --git a/apple/changelog.d/4413.fixed.3.md b/apple/changelog.d/4413.fixed.3.md new file mode 100644 index 0000000000..77729cb0f4 --- /dev/null +++ b/apple/changelog.d/4413.fixed.3.md @@ -0,0 +1 @@ +The query timeout field in the connection form read Global (0) instead of the time it inherits. diff --git a/apple/changelog.d/4413.fixed.4.md b/apple/changelog.d/4413.fixed.4.md new file mode 100644 index 0000000000..6dfc9d2ca6 --- /dev/null +++ b/apple/changelog.d/4413.fixed.4.md @@ -0,0 +1 @@ +Clearing Query History or Data Rewind could fail without showing an error. diff --git a/apple/changelog.d/4413.fixed.5.md b/apple/changelog.d/4413.fixed.5.md new file mode 100644 index 0000000000..a6d3dfa877 --- /dev/null +++ b/apple/changelog.d/4413.fixed.5.md @@ -0,0 +1 @@ +Saving an SSH profile while the Keychain was locked deleted its stored password, passphrase or TOTP secret. diff --git a/apple/changelog.d/4413.fixed.6.md b/apple/changelog.d/4413.fixed.6.md new file mode 100644 index 0000000000..e663cce19d --- /dev/null +++ b/apple/changelog.d/4413.fixed.6.md @@ -0,0 +1 @@ +Settings pop-ups were blank when a stored value, such as a page size or a removed font, was not on the list. diff --git a/apple/changelog.d/4413.fixed.md b/apple/changelog.d/4413.fixed.md new file mode 100644 index 0000000000..cb564c09fa --- /dev/null +++ b/apple/changelog.d/4413.fixed.md @@ -0,0 +1 @@ +TablePro notifications stayed silent when Play sound for notifications was on in System Settings. diff --git a/apple/changelog.d/4413.security.md b/apple/changelog.d/4413.security.md new file mode 100644 index 0000000000..4563a92e70 --- /dev/null +++ b/apple/changelog.d/4413.security.md @@ -0,0 +1 @@ +An outside MCP server's token must be entered again when its address moves to another scheme, host or port. From 1136dc2b9ad853a939766b9f6ca32779429ddc48 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:47:18 +0700 Subject: [PATCH 46/48] fix(ai): keep a menu-picked custom slash command when a built-in shares its name --- .../TablePro/ViewModels/AIChatViewModel.swift | 14 +++++++++ .../Views/AIChat/AIChatPanelView.swift | 1 + .../AIChatViewModelSlashTests.swift | 30 +++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/apple/TablePro/ViewModels/AIChatViewModel.swift b/apple/TablePro/ViewModels/AIChatViewModel.swift index 868534d720..058dc3c544 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel.swift @@ -117,6 +117,8 @@ final class AIChatViewModel: ObservableObject { var customSlashCommandNamed: @MainActor (String) -> CustomSlashCommand? = { CustomSlashCommandStorage.shared.command(named: $0) } + // A custom command picked from the menu keeps its identity, so Send runs it even when a built-in shares its name. + var composedCustomCommand: CustomSlashCommand? @Published var tableMentions = TableMentionIndex.empty var tableMentionSource: [TableInfo] = [] var tableMentionBuild: Task? @@ -197,6 +199,18 @@ final class AIChatViewModel: ObservableObject { let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty || !attachedImages.isEmpty else { return } + if let composed = composedCustomCommand, + let invocation = SlashCommand.invocation(in: text), + invocation.name.caseInsensitiveCompare(composed.name) == .orderedSame, + composed.isValid { + guard !isStreaming else { return } + composedCustomCommand = nil + inputText = "" + Task { await runCustomSlashCommand(composed, body: invocation.body) } + return + } + composedCustomCommand = nil + if let parsed = SlashCommand.parse(text) { runSlashCommand(parsed.command, body: parsed.body) return diff --git a/apple/TablePro/Views/AIChat/AIChatPanelView.swift b/apple/TablePro/Views/AIChat/AIChatPanelView.swift index 929cb3f0ca..1ddcda83ab 100644 --- a/apple/TablePro/Views/AIChat/AIChatPanelView.swift +++ b/apple/TablePro/Views/AIChat/AIChatPanelView.swift @@ -495,6 +495,7 @@ struct AIChatPanelView: View { switch CustomSlashCommandPick.resolve(command, draft: viewModel.inputText) { case .compose(let text): viewModel.inputText = text + viewModel.composedCustomCommand = command case .run: updateContext() Task { await viewModel.runCustomSlashCommand(command) } diff --git a/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift b/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift index 2f991531ac..4de6f77558 100644 --- a/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift +++ b/apple/TableProTests/ViewModels/AIChatViewModelSlashTests.swift @@ -118,6 +118,36 @@ struct AIChatViewModelSlashTests { #expect(firstUserTurn?.plainText == "/summarize last week's orders") } + @Test("A custom command picked from the menu runs even when a built-in shares its name") + func pickedCustomCommandWinsOverBuiltIn() async throws { + let vm = AIChatViewModel() + vm.customSlashCommandNamed = { _ in nil } + vm.composedCustomCommand = CustomSlashCommand(name: "help", promptTemplate: "Custom {{body}}") + vm.inputText = "/help orders" + + vm.sendMessage() + + #expect(vm.composedCustomCommand == nil) + try await waitUntil { + vm.messages.contains { turn in turn.plainText == "Custom orders" } + } + #expect(!vm.messages.contains { turn in turn.plainText.contains("Available commands") }) + } + + @Test("A picked custom command no longer applies once the composer names another command") + func pickedCustomCommandDropsWhenRenamed() { + let vm = AIChatViewModel() + vm.customSlashCommandNamed = { _ in nil } + vm.composedCustomCommand = CustomSlashCommand(name: "summarize", promptTemplate: "Custom {{body}}") + vm.inputText = "/help" + + vm.sendMessage() + + #expect(vm.composedCustomCommand == nil) + let assistant = vm.messages.last { turn in turn.role == .assistant } + #expect(assistant?.plainText.contains("Available commands") == true) + } + @Test("Typing a built-in name runs the built-in even when a custom command shares it") func typedBuiltInWinsOverCustom() { let vm = AIChatViewModel() From 133aa150ba621038cce93f3fa503d0263d7be1e7 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 22 Nov 2026 22:53:43 +0700 Subject: [PATCH 47/48] test(settings): scroll a drill row into its pane before hit-testing it --- .../Support/UITestCase+Settings.swift | 3 ++- apple/TableProUITests/Support/UITestCase.swift | 17 +++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/apple/TableProUITests/Support/UITestCase+Settings.swift b/apple/TableProUITests/Support/UITestCase+Settings.swift index 287c5672e1..822ec66880 100644 --- a/apple/TableProUITests/Support/UITestCase+Settings.swift +++ b/apple/TableProUITests/Support/UITestCase+Settings.swift @@ -24,7 +24,8 @@ extension UITestCase { row.click() guard let page else { return } let drill = settings.descendants(matching: .any).matching(identifier: "settings-drill-\(page)").firstMatch - XCTAssertTrue(scrollUntilHittable(drill, in: settings, timeout: 10), "The \(pane) pane must link to \(page)") + let content = settings.descendants(matching: .any).matching(identifier: "settings-pane-\(pane)").firstMatch + XCTAssertTrue(scrollUntilHittable(drill, in: content, timeout: 10), "The \(pane) pane must link to \(page)") drill.click() } diff --git a/apple/TableProUITests/Support/UITestCase.swift b/apple/TableProUITests/Support/UITestCase.swift index c45ae89162..66d3879487 100644 --- a/apple/TableProUITests/Support/UITestCase.swift +++ b/apple/TableProUITests/Support/UITestCase.swift @@ -217,16 +217,21 @@ internal class UITestCase: XCTestCase { } // A fixed step can carry a row past a short list, so each scroll centres the element. It posts inside the - // container because a window's own scroll lands on its title bar. + // container because a window's own scroll lands on its title bar. `isHittable` hit-tests the element's + // centre, and outside the container that asks whichever app is on screen there, which can stall for seconds. internal func scrollUntilHittable(_ element: XCUIElement, in container: XCUIElement, timeout: TimeInterval) -> Bool { let deadline = Date(timeIntervalSinceNow: timeout) guard element.waitToExist(timeout: timeout) else { return false } - while !(element.exists && element.isHittable) { - guard Date() < deadline, container.exists, element.exists else { return false } - container.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - .scroll(byDeltaX: 0, deltaY: container.frame.midY - element.frame.midY) + while container.exists, element.exists { + let visible = container.frame + let target = element.frame + if visible.contains(CGPoint(x: target.midX, y: target.midY)), element.isHittable { return true } + guard Date() < deadline else { return false } + // A frame XCUITest cannot read is CGRect.null, at infinity; the clamp keeps the step finite. + let offset = min(max(visible.midY - target.midY, -visible.height), visible.height) + container.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).scroll(byDeltaX: 0, deltaY: offset) } - return true + return false } // A grid enters the tree before its query returns, and a coordinate taken off an empty frame posts From 1e28c7c31733b95aa681707d5522f3f506fe609e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 01:05:48 +0700 Subject: [PATCH 48/48] fix(settings): put the shown pane host on top so accessibility hit tests reach it --- .../SettingsDetailViewController.swift | 2 + .../Settings/SettingsWindowTitleTests.swift | 80 +++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/apple/TablePro/Views/Settings/SettingsDetailViewController.swift b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift index 12d4beab3a..b37330b245 100644 --- a/apple/TablePro/Views/Settings/SettingsDetailViewController.swift +++ b/apple/TablePro/Views/Settings/SettingsDetailViewController.swift @@ -44,6 +44,8 @@ internal final class SettingsDetailViewController: NSViewController { host.view.frame = view.bounds host.view.autoresizingMask = [.width, .height] host.view.isHidden = false + // AX hit testing stops at the topmost subview under a point even when it is hidden. A reorder never leaves the window. + view.addSubview(host.view, positioned: .above, relativeTo: nil) shownPane = pane // A show before the window is key counts when it becomes key, so opening counts once. if view.window?.isKeyWindow == true { diff --git a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift index 53466a33bd..56c542124d 100644 --- a/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift +++ b/apple/TableProTests/Views/Settings/SettingsWindowTitleTests.swift @@ -1,4 +1,5 @@ import AppKit +import ApplicationServices @testable import TablePro import TableProTestSupport import Testing @@ -71,6 +72,64 @@ extension GlobalStateSuites { window.toolbar?.items.map { $0.itemIdentifier } ?? [] } + private static func attribute(_ name: String, of element: AXUIElement) -> CFTypeRef? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { return nil } + return value + } + + private static func element(_ identifier: String, under element: AXUIElement) -> AXUIElement? { + if attribute(kAXIdentifierAttribute, of: element) as? String == identifier { + return element + } + for child in attribute(kAXChildrenAttribute, of: element) as? [AXUIElement] ?? [] { + if let match = Self.element(identifier, under: child) { + return match + } + } + return nil + } + + private static func settingsElement(_ identifier: String) -> AXUIElement? { + let windows = attribute(kAXWindowsAttribute, of: AXUIElementCreateApplication(getpid())) as? [AXUIElement] ?? [] + guard let window = windows.first(where: { attribute(kAXIdentifierAttribute, of: $0) as? String == WindowIdentifier.settings }) else { + return nil + } + return element(identifier, under: window) + } + + private static func axValue(_ name: String, of element: AXUIElement) -> AXValue? { + guard let raw = attribute(name, of: element), CFGetTypeID(raw) == AXValueGetTypeID() else { return nil } + return unsafeDowncast(raw, to: AXValue.self) + } + + // In AX screen coordinates, y down from the top of the primary screen, as an AX client hit-tests. + private static func center(of element: AXUIElement) throws -> CGPoint { + let positionValue = try #require(axValue(kAXPositionAttribute, of: element)) + let sizeValue = try #require(axValue(kAXSizeAttribute, of: element)) + var position = CGPoint.zero + var size = CGSize.zero + let readPosition = AXValueGetValue(positionValue, .cgPoint, &position) + let readSize = AXValueGetValue(sizeValue, .cgSize, &size) + try #require(readPosition && readSize) + return CGPoint(x: position.x + size.width / 2, y: position.y + size.height / 2) + } + + // What VoiceOver and XCUITest's isHittable get at a point, with its ancestors' identifiers. + private static func identifiersHit(at point: CGPoint) -> [String] { + var hit: AXUIElement? + guard AXUIElementCopyElementAtPosition(AXUIElementCreateApplication(getpid()), Float(point.x), Float(point.y), &hit) == .success else { + return [] + } + var identifiers: [String] = [] + var current = hit + while let element = current { + identifiers.append(attribute(kAXIdentifierAttribute, of: element) as? String ?? "") + current = attribute(kAXParentAttribute, of: element).map { unsafeDowncast($0, to: AXUIElement.self) } + } + return identifiers + } + @Test("The sidebar order is every pane exactly once") func everyPaneIsReachableExactlyOnce() { #expect(SettingsNavigation.orderedPanes.count == SettingsPane.allCases.count) @@ -311,6 +370,27 @@ extension GlobalStateSuites { await host.tearDown() } + // A hidden host above the shown one took the hit test, which came back as the split view. + @Test("A pane shown again answers an accessibility hit test at its row") + func reshownPaneAnswersAccessibilityHitTests() async throws { + let host = try Host() + let (controller, window) = try host.makeController() + controller.prepareToShow(.root(.general)) + window.orderFront(nil) + let split = controller.split + + split.model.select(.editor) + split.model.select(.general) + window.layoutIfNeeded() + + let identifier = SettingsPage.commandLineTool.drillIdentifier + try await waitUntil { Self.settingsElement(identifier) != nil } + let row = try #require(Self.settingsElement(identifier)) + let center = try Self.center(of: row) + #expect(Self.identifiersHit(at: center).contains(identifier)) + await host.tearDown() + } + @Test("Only Keyboard and Extensions put a filter in the toolbar") func paneFilterFollowsThePane() async throws { let host = try Host()